def f7(): for i in range(1, 13): input_features = "F:/SA/RAIN/RAIN3/ELLIPSE/" + 'I' + 'CES' + str( i) + '.shp' # output data output_feature_class = r"F:/SA/RAIN/RAIN3/ELLIPSE/CC/" + 'I' + 'CES' + str( i) + '.shp' # create a spatial reference object for the output coordinate system out_coordinate_system = arcpy.SpatialReference(32649) # run the tool arcpy.Project_management(input_features, output_feature_class, out_coordinate_system) layer = 'I' + 'CES' + str(i) + '.shp' arcpy.MakeFeatureLayer_management(output_feature_class, layer) arcpy.AddXY_management(layer) for i in range(1, 13): input_features = "F:/SA/RAIN/RAIN3/ELLIPSE/" + 'T' + 'CES' + str( i) + '.shp' # output data output_feature_class = r"F:/SA/RAIN/RAIN3/ELLIPSE/CC/" + 'T' + 'CES' + str( i) + '.shp' # create a spatial reference object for the output coordinate system out_coordinate_system = arcpy.SpatialReference(32649) # run the tool arcpy.Project_management(input_features, output_feature_class, out_coordinate_system) layer = 'T' + 'CES' + str(i) + '.shp' arcpy.MakeFeatureLayer_management(output_feature_class, layer) arcpy.AddXY_management(layer)
def AddCoordinates(Dataset): ''' Adds and populates X and Y fields in the newly created feature class from the ExportView function. This function requires the location of the feature class to run correctly. ''' arcpy.AddXY_management(Dataset)
def finddist(clatoshad_14, dir, path): path2 = path # Local variables: points_shp = "{}\\points.shp".format(path2) dist1 = "{}\\dist1".format(path2) # Process: Raster to Point arcpy.RasterToPoint_conversion(clatoshad_14, points_shp, "VALUE") # Process: Add XY Coordinates arcpy.AddXY_management(points_shp) # Process: Add Field arcpy.AddField_management(points_shp, "distfield", "FLOAT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") xlist = [] ylist = [] finames = ['POINT_X', 'POINT_Y', 'distfield'] rows = arcpy.da.UpdateCursor(points_shp, finames) for row in rows: xlist.append(row[0]) ylist.append(row[1]) rows.reset() for row in rows: if dir == 'e': changex = row[0] - min(xlist) changey = row[1] - min(ylist) row[2] = math.sqrt(changex * changex + changey * changey) if dir == 'w': changex = row[0] - max(xlist) changey = row[1] - min(ylist) row[2] = math.sqrt(changex * changex + changey * changey) rows.updateRow(row) del row del rows arcpy.PointToRaster_conversion(points_shp, "distfield", dist1, "MOST_FREQUENT", "NONE", clatoshad_14) return dist1
def addStopDataToRoutes(routes): """ add stop data to the non-bus route data already collected """ arcpy.env.workspace = WORKING_GDB arcpy.env.overwriteOutput = True tempStops = 'temp_stops' tempStopsSp = 'temp_stops_sp' if arcpy.Exists(tempStops): arcpy.Delete_management(tempStops) if arcpy.Exists(tempStopsSp): arcpy.Delete_management(tempStopsSp) arcpy.CopyFeatures_management(TRANSIT_STOPS, tempStops) out_coordinate_system = os.path.join(arcpy.GetInstallInfo()['InstallDir'], NAD_83_DIRECTORY) arcpy.Project_management(tempStops, tempStopsSp, out_coordinate_system, 'NAD_1983_To_WGS_1984_1') arcpy.AddXY_management(tempStopsSp) for route in routes: qry = 'SCH_ROUTEID = ' + str( routes[route][0]) + ' AND SCH_PATTERNID = ' + str(routes[route][1]) stops = arcpy.SearchCursor( tempStopsSp, qry, '', 'CPT_STOPPOINTID;SCH_STOPPOINTSEQNO;SCH_ROUTEID;SCH_PATTERNID;POINT_X;POINT_Y', 'SCH_STOPPOINTSEQNO A') for row in stops: routes[route][2].append((row.POINT_X, row.POINT_Y))
def extract_hydro_points(drain, show, folder, gdb): gp = arcgisscripting.create() gp.CheckOutExtension("Spatial") gp.SetProgressor('default', 'starting vertex extraction...') arcpy.env.overwriteOutput = True arcpy.env.addOutputsToMap = show if not os.path.exists(os.path.join(folder, '{}.gdb'.format(gdb))): arcpy.CreateFileGDB_management(out_folder_path=folder, out_name='{}.gdb'.format(gdb)) gp.AddMessage('Processing Extract Vertex ...') arcpy.Intersect_analysis(in_features='{} #'.format(drain), out_feature_class=os.path.join( folder, 'temp', 'hydro_multi_points.shp'), join_attributes='ALL', cluster_tolerance='-1 Unknown', output_type='POINT') arcpy.AddXY_management( in_features=os.path.join(folder, 'temp', 'hydro_multi_points.shp')) arcpy.DeleteIdentical_management(in_dataset=os.path.join( folder, 'temp', 'hydro_multi_points.shp'), fields="POINT_X;POINT_Y", xy_tolerance="", z_tolerance="0") arcpy.MultipartToSinglepart_management( in_features=os.path.join(folder, 'temp', 'hydro_multi_points.shp'), out_feature_class=os.path.join(folder, '{}.gdb'.format(gdb), 'hydro_points')) gp.AddMessage('Finish')
def shape_creator(): pt = arcpy.Point() ptGeoms = [] for p in shp_list: pt.X = p[0] pt.Y = p[1] ptGeoms.append(arcpy.PointGeometry(pt, spatial_ref)) arcpy.CopyFeatures_management(ptGeoms, out_shapefile) arcpy.AddXY_management(out_shapefile) arcpy.AddField_management(out_shapefile, "timestamp", "TEXT", 9, "", "", "refcode", "NULLABLE", "REQUIRED") arcpy.AddField_management(out_shapefile, "img_path", "TEXT", 9, "", "", "refcode", "NULLABLE", "REQUIRED") count = 0 with arcpy.da.UpdateCursor(out_shapefile, ["timestamp", "img_path"]) as our_cursor: for c in our_cursor: c[0] = shp_list[count][3] c[1] = shp_list[count][2] count += 1 our_cursor.updateRow(c)
def origins_to_lines(self): """ joins origins to lines and adds POINT_X, POINT_Y fields """ print('method origins to lines'.upper()) if not self.__solve: print('run solve first') raise TypeError descr = arcpy.da.Describe(self.odcost_layer) self.lines_path = self.__get_na_layer_path__(descr, 'Lines') self.origings_path = self.__get_na_layer_path__(descr, 'Origins') self.origings_path_path = pathlib.Path(self.origings_path) self.origings_path_name = self.origings_path_path.name arcpy.AddXY_management(self.origings_path) #adding x and y fields to lines print('joining x and y to line'.upper()) joins.join_1one1(self.origings_path, 'ObjectID', self.outgdb, self.lines_path, 'OriginID', ['Name', 'POINT_X', 'POINT_Y']) print(f'joining {self.origins} to {self.lines_path}'.upper()) joins.join_1one1(self.origins, self.origins_identifierfield, self.outgdb, self.lines_path, f'Name_{self.origings_path_name}', from_fields='all')
def destinations_to_lines(self): """ joins destinations to lines and adds POINT_X, POINT_Y fields """ if not self.__solve: print('run solve first') raise TypeError descr = arcpy.da.Describe(self.odcost_layer) self.lines_path = self.__get_na_layer_path__(descr, 'Lines') self.destinations_path = self.__get_na_layer_path__( descr, 'Destinations') self.destinations_path_path = pathlib.Path(self.destinations_path) self.destinations_path_name = self.destinations_path_path.name arcpy.AddXY_management(self.destinations_path) joins.join_1one1(self.destinations_path, 'ObjectID', self.outgdb, self.lines_path, 'DestinationID', ['Name', 'POINT_X', 'POINT_Y']) joins.join_1one1(self.destinations, self.destinations_identifierfield, self.outgdb, self.lines_path, f'Name_{self.destinations_path_name}', from_fields='all')
def planarizeAndGetArcEndPoints(fds,caf,mup,fdsToken): # returns a feature class of endpoints of all caf lines, two per planarized line segment addMsgAndPrint('Planarizing '+os.path.basename(caf)+' and getting segment endpoints') # add LineID (so we can recover lines after planarization) arcpy.AddField_management(caf,'LineID','LONG') arcpy.CalculateField_management(caf,'LineID','!OBJECTID!','PYTHON_9.3') # planarize CAF by FeatureToLine addMsgAndPrint(' planarizing caf') planCaf = caf+'_xxx_plan' testAndDelete(planCaf) arcpy.FeatureToLine_management(caf,planCaf) # planarize CAF (by IDENTITY with MUP) addMsgAndPrint(' IDENTITYing caf with mup') cafp = caf+'_planarized' testAndDelete(cafp) arcpy.Identity_analysis(planCaf,mup,cafp,'ALL','','KEEP_RELATIONSHIPS') # delete extra fields addMsgAndPrint(' deleting extra fields') fns = fieldNameList(cafp) deleteFields = [] for f in fieldNameList(mup): if f != 'MapUnit': for hf in ('RIGHT_'+f,'LEFT_'+f): if hf in fns: deleteFields.append(hf) arcpy.DeleteField_management(cafp,deleteFields) # calculate azimuths startDir and endDir addMsgAndPrint(' adding StartAzimuth and EndAzimuth') for f in ('LineDir','StartAzimuth','EndAzimuth'): arcpy.AddField_management(cafp,f,'FLOAT') arcpy.AddField_management(cafp,'ToFrom','TEXT','','',4) fields = ['SHAPE@','StartAzimuth','EndAzimuth'] with arcpy.da.UpdateCursor(cafp,fields) as cursor: for row in cursor: lineSeg = row[0].getPart(0) row[1],row[2] = startEndGeogDirections(lineSeg) cursor.updateRow(row) # make endpoint feature class addMsgAndPrint(' converting line ends to points') arcEndPoints = fds+'/'+fdsToken+'xxx_EndPoints' # will be a feature class in fds arcEndPoints2 = arcEndPoints+'_end' testAndDelete(arcEndPoints) arcpy.FeatureVerticesToPoints_management(cafp,arcEndPoints, 'START') arcpy.CalculateField_management(arcEndPoints,'LineDir','!StartAzimuth!','PYTHON') arcpy.CalculateField_management(arcEndPoints,'ToFrom','"From"','PYTHON') testAndDelete(arcEndPoints2) arcpy.FeatureVerticesToPoints_management(cafp,arcEndPoints2,'END') arcpy.CalculateField_management(arcEndPoints2,'LineDir','!EndAzimuth!','PYTHON') arcpy.CalculateField_management(arcEndPoints2,'ToFrom','"To"','PYTHON') arcpy.Append_management(arcEndPoints2,arcEndPoints) testAndDelete(arcEndPoints2) # delete some more fields deleteFields = ['EndAzimuth','StartAzimuth','LEFT_MapUnitPolys','RIGHT_MapUnitPolys'] arcpy.DeleteField_management(arcEndPoints,deleteFields) addMsgAndPrint(' adding POINT_X and POINT_Y') arcpy.AddXY_management(arcEndPoints) testAndDelete(planCaf) return cafp, arcEndPoints
def getDestination(pt): try: destination = arcpy.Select_analysis( pt, os.path.join(basePath, r"Trash", r"destination.shp"), '"SYMBOL" = 706') arcpy.AddXY_management(destination) except: print("Failed to getStart()") return destination
def getStart(pt): try: start = arcpy.Select_analysis( pt, os.path.join(basePath, r"Trash", r"start.shp"), '"SYMBOL" = 701 AND "ANGLE" = 0') arcpy.AddXY_management(start) except: print("Failed to getStart()") return start
def GenerateNetworkFormDEM(DEMbuf, FlowDirFile, FlowAccFile, threshold, folder): env.workspace = folder arcpy.gp.overwriteOutput = 1 arcpy.CheckOutExtension("Spatial") if float(threshold) < MINI_VALUE: threshold = float( str(arcpy.GetRasterProperties_management(FlowAccFile, "MAXIMUM"))) / 100 Exec = "Con(\"%s\" > %s,1)" % (FlowAccFile, threshold) arcpy.gp.RasterCalculator_sa(Exec, "streamnet") Stream_shp = "streamnet.shp" arcpy.sa.StreamToFeature("streamnet", FlowDirFile, Stream_shp, "NO_SIMPLIFY") StreamLinks = arcpy.sa.StreamLink("streamnet", FlowDirFile) StreamLinks.save("streamlinks") StreamLinks_shp = "streamnet.shp" arcpy.sa.StreamToFeature("streamlinks", FlowDirFile, StreamLinks_shp, "NO_SIMPLIFY") StreamOrder = arcpy.sa.StreamOrder("streamnet", FlowDirFile, "STRAHLER") StreamOrder.save("streamorder") StreamOrder_shp = "StreamOrder.shp" arcpy.sa.StreamToFeature("streamorder", FlowDirFile, StreamOrder_shp, "NO_SIMPLIFY") arcpy.FeatureVerticesToPoints_management(StreamOrder_shp, "StreamNDsStart.shp", "START") arcpy.FeatureVerticesToPoints_management(StreamOrder_shp, "StreamNDsEnd.shp", "END") arcpy.AddXY_management("StreamNDsStart.shp") arcpy.AddXY_management("StreamNDsEnd.shp") arcpy.sa.ExtractValuesToPoints("StreamNDsStart.shp", DEMbuf, "StreamNDsElevStart.shp", "NONE", "VALUE_ONLY") arcpy.sa.ExtractValuesToPoints("StreamNDsEnd.shp", DEMbuf, "StreamNDsElevEnd.shp", "NONE", "VALUE_ONLY") Watershed = arcpy.sa.Watershed(FlowDirFile, "streamlinks", "VALUE") Watershed.save("watershed") arcpy.RasterToPolygon_conversion("watershed", "Watershed.shp", "NO_SIMPLIFY", "VALUE") WatershedFile = folder + os.sep + "watershed" StreamFile = folder + os.sep + "streamlinks" return (StreamFile, WatershedFile)
def processShapefile(shapeName, defaultPath, record, extraDir, option = None): if option == 0: pass elif option == 1: shapeName = validateInput("shapeName", "Shapefile name: ", defaultPath, record, extraDir) else: record = validateInput("record","Record Number: ", defaultPath) extraDir = validateInput("extraDir", "Extra directory: ", defaultPath, record) shapeName = validateInput("shapeName", "Shapefile name: ", defaultPath, record, extraDir) shpExt = shapeName+'.shp' if extraDir == '': inlayer = os.path.join(defaultPath,record,shpExt) outBoundingBox = os.path.join(defaultPath,record,shapeName+'_BB.shp') outBoundingBoxVertices = os.path.join(defaultPath,record,shapeName+'_BB_Vert.shp') else: inlayer = os.path.join(defaultPath,record,extraDir,shpExt) outBoundingBox = os.path.join(defaultPath,record,extraDir,shapeName+'_BB.shp') outBoundingBoxVertices = os.path.join(defaultPath,record,extraDir,shapeName+'_BB_Vert.shp') print 'Deleting BB if found' if arcpy.Exists(outBoundingBox): arcpy.Delete_management(outBoundingBox) if arcpy.Exists(outBoundingBoxVertices): arcpy.Delete_management(outBoundingBoxVertices) print 'Creating bounding box' # Use MinimumBoundingGeometry function to get an envelop area arcpy.MinimumBoundingGeometry_management(inlayer, outBoundingBox, "ENVELOPE") print 'Convert vertices to points' # Convert vertices to points arcpy.FeatureVerticesToPoints_management(outBoundingBox, outBoundingBoxVertices, 'All') print 'Calculate X/Y for vertices' # Calculate X/Y for vertices arcpy.AddXY_management(outBoundingBoxVertices) xField = "Point_X" xMinValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", xField + " A").next().getValue(xField) #Get 1st row in ascending cursor sort xMaxValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", xField + " D").next().getValue(xField) #Get 1st row in descending cursor sort yField = "Point_Y" yMinValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", yField + " A").next().getValue(yField) #Get 1st row in ascending cursor sort yMaxValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", yField + " D").next().getValue(yField) #Get 1st row in descending cursor sort if arcpy.Exists(outBoundingBox): arcpy.Delete_management(outBoundingBox) if arcpy.Exists(outBoundingBoxVertices): arcpy.Delete_management(outBoundingBoxVertices) return {'xMin':xMinValue, 'xMax':xMaxValue,'yMin':yMinValue, 'yMax':yMaxValue}
def CreateRefID(in_feature): communicateResults("Creating reference ID...") communicateResults("in_feature is: " + in_feature) arcpy.AddXY_management(in_feature) arcpy.AddField_management(in_feature, Ref_id, "TEXT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.CalculateField_management( in_feature, Ref_id, "str(int(!POINT_X!))+\"-\"+str(int(!POINT_Y!))", "PYTHON", "") communicateResults("Successfully added " + Ref_id + " to " + in_feature + ".\n")
def makeNodeName2ArcsDict(caf, fields): # takes arc fc, list of fields (e.g. [Left_MapUnit, Right_MapUnit] ) # makes to and from node fcs, concatenates, sorts, finds arc-ends # that share common XY values # returns dictionary of arcs at each node, keyed to nodename # i.e., dict[nodename] = [[arc1 fields], [arc2 fields],...] fv1 = os.path.dirname(caf) + '/xxxNfv1' fv2 = os.path.dirname(caf) + '/xxxNfv12' lenFields = len(fields) addMsgAndPrint(' making endpoint feature classes') testAndDelete(fv1) arcpy.FeatureVerticesToPoints_management(caf, fv1, 'BOTH_ENDS') addMsgAndPrint(' adding XY values and sorting by XY') arcpy.AddXY_management(fv1) testAndDelete(fv2) arcpy.Sort_management(fv1, fv2, [["POINT_X", "ASCENDING"], ["POINT_Y", "ASCENDING"]]) ##fix fields statement and following field references fields.append('SHAPE@XY') indexShape = len(fields) - 1 isFirst = True nArcs = 0 nodeList = [] with arcpy.da.SearchCursor(fv2, fields) as cursor: for row in cursor: x = row[indexShape][0] y = row[indexShape][1] arcFields = row[0:lenFields] if isFirst: isFirst = False lastX = x lastY = y arcs = [arcFields] elif abs(x - lastX) < searchRadius and abs(y - lastY) < searchRadius: arcs.append(arcFields) else: nodeList.append([nodeName(lastX, lastY), arcs]) lastX = x lastY = y arcs = [arcFields] nodeList.append([nodeName(lastX, lastY), arcs]) addMsgAndPrint(' ' + str(len(nodeList)) + ' distinct nodes') addMsgAndPrint(' cleaning up') for fc in fv1, fv2: testAndDelete(fc) nodeDict = {} for n in nodeList: nodeDict[n[0]] = n[1] return nodeDict
def snap_transfers_to_network(transfer_shp_f, node_shp): arcpy.AddXY_management(node_shp) arcpy.TableToTable_conversion(node_shp, "C:/GIS/", "node.dbf", "", "", "") arcpy.TableToTable_conversion(transfer_shp, "C:/GIS/", "transfer.dbf", "", "", "") arcpy.JoinField_management("C:/GIS/transfer.dbf", "nearNID", "C:/GIS/node.dbf", "ID", ["POINT_X", "POINT_Y"]) # arcpy.Delete_management(transfer_shp_snapped) arcpy.MakeXYEventLayer_management("C:/GIS/transfer.dbf", "POINT_X", "POINT_Y", "new_transfer") arcpy.CopyFeatures_management("new_transfer", transfer_shp)
def RillIndexCalc(StreamOrderFile, DEMbuf, tempDir, StatsDir): print "Calculating rill indexes..." #input StreamOrderFile and DEMbuf,output CSV files. env.workspace = tempDir arcpy.gp.overwriteOutput = 1 arcpy.CheckOutExtension("Spatial") dem_des = arcpy.gp.describe(DEMbuf) env.extent = dem_des.Extent arcpy.FeatureVerticesToPoints_management(StreamOrderFile, "StreamNDsStart.shp", "START") arcpy.FeatureVerticesToPoints_management(StreamOrderFile, "StreamNDsEnd.shp", "END") arcpy.AddXY_management("StreamNDsStart.shp") arcpy.AddXY_management("StreamNDsEnd.shp") arcpy.sa.ExtractValuesToPoints("StreamNDsStart.shp", DEMbuf, "StreamNDsElevStart.shp", "NONE", "VALUE_ONLY") arcpy.sa.ExtractValuesToPoints("StreamNDsEnd.shp", DEMbuf, "StreamNDsElevEnd.shp", "NONE", "VALUE_ONLY")
def getbbox(polygonfeat, itemgeo, isprj): try: ''' Find the intersection between footprint polygon and clipping feature ''' #Create point list to hold the point object point = arcpy.Point() array = arcpy.Array() itempoly = [] #Construct polygon feature from points for coordPair in itemgeo: point.X = coordPair[0] point.Y = coordPair[1] array.add(point) itempoly.append(arcpy.Polygon(array)) arcpy.env.overwriteOutput = 1 fpfeat = "in_memory/fpfeat" #fpfeat = r"e:\temp\clipandship\fpfeat.shp" arcpy.CopyFeatures_management(itempoly, fpfeat) arcpy.DefineProjection_management(fpfeat, isprj) #Find intersection between clipping polygon and footprint #Note: if two features class are in different projection, output should be # in image service projection interfeat = "in_memory/interfeat" #interfeat = r"e:\temp\clipandship\interfeat.shp" arcpy.Intersect_analysis(fpfeat + ";" + polygonfeat, interfeat) #Convert the intersecting polygon to vertice points verticespnt = "in_memory/verpnt" arcpy.FeatureVerticesToPoints_management(interfeat, verticespnt) #Get intersection polygon vertices to a list arcpy.AddXY_management(verticespnt) verticesxy = [] fieldNames = ["POINT_X", "POINT_Y"] with arcpy.da.SearchCursor(verticespnt, fieldNames) as rows: for row in rows: verticesxy.append([row[0], row[1]]) desc = arcpy.Describe(interfeat) bbox = [] bbox.append(desc.extent.XMin) bbox.append(desc.extent.YMin) bbox.append(desc.extent.XMax) bbox.append(desc.extent.YMax) return bbox except: arcpy.AddError("ERROR: Failure in get bounding box")
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 plot_junction_points(line_lyr, network_type): """ Dissolves a network polyline feature class into single part features, intersects the dissolved network with itself, and returns a junction point (i.e. tributary confluence) feature class. :param fc: network polyline feature class :return: point feature class """ line_dslv = "in_memory\\line_dslv" gis_tools.newGISDataset("in_memory", line_dslv) arcpy.Dissolve_management(line_lyr, line_dslv, "#", "#", "SINGLE_PART") pnt_junctions = "in_memory\\{0}_pnt_junctions".format(network_type) gis_tools.newGISDataset("in_memory", pnt_junctions) arcpy.Intersect_analysis(line_dslv, pnt_junctions, output_type="POINT") arcpy.AddXY_management(pnt_junctions) return pnt_junctions
def getQueryFields(serviceURL, polygonfeat): try: arcpy.AddMessage("Getting raster IDs and attributes by location...") # Convert polygon feature class to JSON geometry # Step 1: convert polygon to points arcpy.env.overwriteOutput = 1 verticespnt = "in_memory/verpnt" arcpy.FeatureVerticesToPoints_management(polygonfeat, verticespnt) # Step 2: add coordinates of point to the feature class arcpy.AddXY_management(verticespnt) # Step 3: Read the point coordinate from feature class to an array verticesxy = [] fieldNames = ["POINT_X", "POINT_Y"] with arcpy.da.SearchCursor(verticespnt, fieldNames) as rows: for row in rows: verticesxy.append([row[0], row[1]]) # Get the spatial reference code of the polygon feature desc = arcpy.Describe(polygonfeat) factcode = desc.SpatialReference.FactoryCode # Constructing Query REST request geometry = "&geometry={ 'rings': [" + str( verticesxy) + "],'spatialReference':{'wkid':" + str( factcode) + "}}&geometryType=esriGeometryPolygon" content = "where=CATEGORY=1" + geometry + "&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&f=json" post_data = unicode(content, "utf-8") headers = {} headers["Content-Type"] = "application/x-www-form-urlencoded" serviceURL = serviceURL.replace("arcgis/services", "arcgis/rest/services") + "/query" # Send Query request to get item attributes req = urllib2.Request(serviceURL, post_data, headers) response_stream = urllib2.urlopen(req) response = response_stream.read() jsondict = json.loads(response) itemfields = jsondict["fields"] itemfeatures = jsondict["features"] return itemfields, itemfeatures except: arcpy.AddError("Failure in getQueryFields function")
def snap_junction_points(from_line_lyr, to_line_lyr, search_distance): """ Shifts junction points (i.e. tributary confluences) in the 'From' network to same coordinates of junction points in the 'To' network, found within a user-specified search distance. :param from_line_lyr: polyline layer representing 'From' stream network :param to_line_lyr: polyline layer representing 'To' stream network :param search_distance: buffer distance around each 'To' junction point, in meters :return: line feature class """ tempWorkspace = "in_memory" arcpy.AddMessage("GNAT TLA: snapping junction points in 'From' network to 'To' network") snapped_from_line = gis_tools.newGISDataset(tempWorkspace, "snapped_from_line") arcpy.CopyFeatures_management(from_line_lyr, snapped_from_line) snap_line_lyr = gis_tools.newGISDataset("Layer", "snap_line_lyr") arcpy.MakeFeatureLayer_management(snapped_from_line, snap_line_lyr) list_field_objects = arcpy.ListFields(snap_line_lyr) list_from_fields = [f.name for f in list_field_objects if f.type != "OID" and f.type != "Geometry"] # Plot junction points for 'From' and 'To' stream networks from_junction_pnts = plot_junction_points(snap_line_lyr, "from") to_junction_pnts = plot_junction_points(to_line_lyr, "to") lyr_from_junc_pnts = gis_tools.newGISDataset("Layer", "lyr_from_junc_pnts") arcpy.MakeFeatureLayer_management(from_junction_pnts, lyr_from_junc_pnts) from_line_oidfield = arcpy.Describe(snap_line_lyr).OIDFieldName from_vrtx = gis_tools.newGISDataset(tempWorkspace, "from_vrtx") arcpy.FeatureVerticesToPoints_management(snap_line_lyr, from_vrtx, point_location="ALL") arcpy.AddXY_management(from_vrtx) from_vrtx_lyr = gis_tools.newGISDataset("Layer", "from_vrtx_lyr") arcpy.MakeFeatureLayer_management(from_vrtx, from_vrtx_lyr) arcpy.Near_analysis(from_vrtx_lyr, to_junction_pnts, search_distance, "LOCATION") arcpy.SelectLayerByLocation_management(from_vrtx_lyr, "INTERSECT", lyr_from_junc_pnts, "#", "NEW_SELECTION") update_xy_coord(from_vrtx_lyr) arcpy.MakeXYEventLayer_management(from_vrtx_lyr, "POINT_X", "POINT_Y", "xy_events", from_vrtx_lyr) xy_events_pnt = gis_tools.newGISDataset(tempWorkspace, "xy_events_pnt") arcpy.CopyFeatures_management("xy_events", xy_events_pnt) arcpy.MakeFeatureLayer_management(xy_events_pnt, "xy_events_lyr") xy_line = gis_tools.newGISDataset(tempWorkspace, "xy_line") arcpy.PointsToLine_management("xy_events_lyr", xy_line, "ORIG_FID") arcpy.JoinField_management(xy_line, "ORIG_FID", snap_line_lyr, from_line_oidfield, list_from_fields) arcpy.DeleteFeatures_management(snap_line_lyr) arcpy.Append_management(xy_line, snap_line_lyr, "NO_TEST") return snap_line_lyr
def buildPointGrids(inFeature, tempRaster, cell_size, outShapefile): # Convert from polygon to raster and raster to point to create point grid arcpy.PolygonToRaster_conversion(inFeature, "OBJECTID", tempRaster, "CELL_CENTER", "NONE", cell_size) # Determine if raster contains only NoData values noData = int(arcpy.GetRasterProperties_management(tempRaster, 'ALLNODATA')[0]) if noData == 0: # Convert raster to point grid arcpy.RasterToPoint_conversion(tempRaster, outShapefile, "VALUE") # Add XY Coordinates to feature class in the NAD_1983_Alaska_Albers projection arcpy.AddXY_management(outShapefile) # Delete intermediate files arcpy.Delete_management(tempRaster) elif noData == 1: arcpy.AddMessage("All values for this watershed are nodata...") # Delete intermediate files arcpy.Delete_management(tempRaster)
def centreFromPolygon(self, polygonSHP, coordinate_system): arcpy.AddField_management(polygonSHP, "xCentroid", "DOUBLE", 18, 11) arcpy.AddField_management(polygonSHP, "yCentroid", "DOUBLE", 18, 11) arcpy.CalculateField_management(in_table=polygonSHP, field="xCentroid", expression="!SHAPE.CENTROID.X!", expression_type="PYTHON_9.3", code_block="") arcpy.CalculateField_management(in_table=polygonSHP, field="yCentroid", expression="!SHAPE.CENTROID.Y!", expression_type="PYTHON_9.3", code_block="") in_rows = arcpy.SearchCursor(polygonSHP) outPointFileName = "polygonCentre" centreSHP = os.path.join(cfg.scratch, cfg.scratchgdb, outPointFileName) point1 = arcpy.Point() array1 = arcpy.Array() featureList = [] arcpy.CreateFeatureclass_management( os.path.join(cfg.scratch, cfg.scratchgdb), outPointFileName, "POINT", "", "DISABLED", "DISABLED", coordinate_system) cursor = arcpy.InsertCursor(centreSHP) feat = cursor.newRow() for in_row in in_rows: # Set X and Y for start and end points point1.X = in_row.xCentroid point1.Y = in_row.yCentroid array1.add(point1) centerpoint = arcpy.Multipoint(array1) array1.removeAll() featureList.append(centerpoint) feat.shape = point1 cursor.insertRow(feat) del feat del in_rows del cursor del point1 del array1 arcpy.AddXY_management(centreSHP) return centreSHP
def UploadSystems(): # Get the value of the input parameter inTable = arcpy.GetParameterAsText(0) X_field = arcpy.GetParameterAsText(1) Y_field = arcpy.GetParameterAsText(2) # Local variable: gpTempPlace = arcpy.env.scratchGDB XY_event_lyr = "SystemsXY" out_Name = "Telecoupling Systems" arcpy.SetProgressorLabel('Creating System Components ...') arcpy.AddMessage('Creating System Components ...') if inTable or inTable != "#": try: # Process: Make XY Event Layer (temporary) arcpy.MakeXYEventLayer_management(table=inTable, in_x_field=X_field, in_y_field=Y_field, out_layer=XY_event_lyr) # Process: Create temporary copy of XY event layer in memory out_layer_temp = os.path.join(gpTempPlace, "SystemsXY_fc") arcpy.CopyFeatures_management(XY_event_lyr, out_layer_temp) # Process: Add XY coordinates using GP environ settings arcpy.AddXY_management(out_layer_temp) # Process: After adding XY to the temporary feature class (in memory or local GDB), create a feature layer # to send back as output to GP tools out_fl = arcpy.MakeFeatureLayer_management(out_layer_temp, out_Name) except Exception: e = sys.exc_info()[1] arcpy.AddError('An error occurred: {}'.format(e.args[0])) else: arcpy.AddError('No Features Uploaded to the Map!') #### Set Parameters #### arcpy.SetParameter(3, out_fl) arcpy.ResetProgressor()
def calculateBearingAngel(): outPointSHP = os.path.join(scratch, "outPointSHP.shp") #r'in_memory/outPointSHP' arcpy.CreateFeatureclass_management(scratch, r"outPointSHP.shp", "POINT", "", "DISABLED", "DISABLED", srGCS83) arcpy.AddField_management(outPointSHP, "BearingD", 'DOUBLE', 10) arcpy.AddField_management(outPointSHP, "Angle", 'DOUBLE', 10) arcpy.AddField_management(outPointSHP, "Angle1", 'DOUBLE', 10) fields = ['SHAPE@XY', r'BearingD', r'Angle', r'Angle1'] cursor = arcpy.da.InsertCursor(outPointSHP, fields) result = FittlingB(degree, OrderCoord) templist = [] for key in result.keys(): if degree < 180: if key == 'max': Angle = degree - UpperRange / 2 Angle1 = degree - UpperRange / 2 - sideRange elif key == 'min': Angle = degree + UpperRange / 2 Angle1 = degree + UpperRange / 2 + sideRange else: if key == 'max': Angle = degree + UpperRange / 2 Angle1 = degree + UpperRange / 2 + sideRange elif key == 'min': Angle = degree - UpperRange / 2 Angle1 = degree - UpperRange / 2 - sideRange if Angle == 0 or Angle == 360: Angle += 1 if Angle1 == 0 or Angle1 == 360: Angle1 += 1 print Angle, Angle1 templist.append((Angle) % 360) templist.append((Angle1) % 360) cursor.insertRow(((result[key][0], result[key][1]), BearingD, Angle % 360, Angle1 % 360)) del cursor arcpy.DefineProjection_management(outPointSHP, srGCS83) arcpy.AddXY_management(outPointSHP) if len(list(set(templist))) == 3: global mark mark = 1 return outPointSHP
def UploadSystems(): # Get the value of the input parameter inTable = arcpy.GetParameterAsText(0) X_field = arcpy.GetParameterAsText(1) Y_field = arcpy.GetParameterAsText(2) # Local variable: out_layer = "Systems_lyr" arcpy.SetProgressorLabel('Creating System Components ...') arcpy.AddMessage('Creating System Components ...') if inTable or inTable != "#": try: # Process: Make XY Event Layer (temporary) arcpy.MakeXYEventLayer_management(table=inTable, in_x_field=X_field, in_y_field=Y_field, out_layer=out_layer) # Process: Create Feature Class from Feature Layer outSystems_fc = os.path.join(arcpy.env.scratchGDB, "Systems") arcpy.CopyFeatures_management(out_layer, outSystems_fc) # Process: Add XY Coordinates arcpy.SetProgressorLabel('Adding XY Coordinates ...') arcpy.AddMessage('Adding XY Coordinates ...') # Process: Add Coordinates arcpy.AddXY_management(outSystems_fc) except Exception: e = sys.exc_info()[1] arcpy.AddError('An error occurred: {}'.format(e.args[0])) else: arcpy.AddError('No Features Uploaded to the Map!') #### Set Parameters #### arcpy.SetParameterAsText(3, outSystems_fc) arcpy.ResetProgressor()
def getNetworkNodes(inStreamNetwork, scratchWorkspace="in_memory"): # Preprocess network fcNetworkDissolved = gis_tools.newGISDataset(scratchWorkspace, "GNAT_SO_NetworkDissolved") arcpy.Dissolve_management(inStreamNetwork, fcNetworkDissolved, multi_part="SINGLE_PART", unsplit_lines="DISSOLVE_LINES") fcNetworkIntersectPoints = gis_tools.newGISDataset( scratchWorkspace, "GNAT_SO_NetworkIntersectPoints") arcpy.Intersect_analysis(fcNetworkDissolved, fcNetworkIntersectPoints, "ALL", output_type="POINT") arcpy.AddXY_management(fcNetworkIntersectPoints) fcNetworkNodes = gis_tools.newGISDataset(scratchWorkspace, "GNAT_SO_NetworkNodes") arcpy.Dissolve_management(fcNetworkIntersectPoints, fcNetworkNodes, ["POINT_X", "POINT_Y"], "#", "SINGLE_PART") del fcNetworkDissolved del fcNetworkIntersectPoints return fcNetworkNodes
# -*- coding: utf-8 -*- # --------------------------------------------------------------------------- # redefine_xy.py # Created on: 2015-12-18 15:05:59.00000 # (generated by ArcGIS/ModelBuilder) # Description: # --------------------------------------------------------------------------- # Import arcpy module import arcpy # Local variables: uat_cen_point_0 = "uat_cen_point_0" uat_cen_point = "C:\\Users\\mmiller\\Documents\\ArcGIS\\Default.gdb\\uat_cen_point" uat_cen_point__2_ = uat_cen_point # Process: Project out_gcs = arcpy.SpatialReference('WGS_1984') arcpy.Project_management( uat_cen_point_0, uat_cen_point, "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]", "WGS_1984_(ITRF00)_To_NAD_1983", "PROJCS['NAD_1983_UTM_Zone_18N',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['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-75.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]", "NO_PRESERVE_SHAPE", "") # Process: Add XY Coordinates arcpy.AddXY_management(uat_cen_point)
data_type="FeatureClass", workspace="in_memory") arcpy.MakeRouteEventLayer_lr(routes, "ID", stationTable, "ID POINT STATION", stationEvents, "", "NO_ERROR_FIELD", "NO_ANGLE_FIELD", "NORMAL", "ANGLE", "LEFT", "POINT") arcpy.AddField_management(stationEvents, "STATIONID", "TEXT", "", "", "25", "", "NULLABLE", "NON_REQUIRED") arcpy.CalculateField_management(stationEvents, "STATIONID", "str(!STATION!) + '_' + str(!ID!)", "PYTHON3") stationTemp = watershedFD_path + os.sep + "stations" arcpy.CopyFeatures_management(stationEvents, stationTemp) arcpy.AddXY_management(stationTemp) arcpy.AddField_management(stationTemp, "POINT_Z", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.MakeFeatureLayer_management(stationTemp, stationLyr) AddMsgAndPrint( "\tSuccessfuly created a total of " + str(int(arcpy.GetCount_management(stationLyr).getOutput(0))) + " stations", 0) AddMsgAndPrint( "\tfor the " + str(int(arcpy.GetCount_management(lineTemp).getOutput(0))) + " line(s) provided\n") # --------------------------------------------------------------------- Retrieve Elevation values AddMsgAndPrint("\nRetrieving station elevations")