Pkolommen = [Xkol, Ykol, Zkol, LnmKol, BGkol, Skol] afstandP = 0 ProfPunt = 0 # 1e punt uitlezen. sort = None, "ORDER BY " + Skol with arcpy.da.SearchCursor(PPfc, Pkolommen, where_clause=were, sql_clause=sort) as cursor2: row2 = cursor2.next() X = round(row2[0], 4) Y = round(row2[1], 4) Z = round(row2[2], 3) arcpy.AddMessage(" XYZ: " + str(row2[5]) + " - " + str(X) + "/" + str(Y) + "/" + str(Z)) ProfPunt = arcpy.PointGeometry(arcpy.Point(X, Y)) afstandP = DeLijn.measureOnLine(ProfPunt) arcpy.AddMessage( " Afstand 1e profielpunt tov begin dwarsprofiellijn: " + str(round(afstandP, 2))) row[6] = round(afstandP, 2) #--------------------------------------------------------- # Nu snijpunt van de lijnen vinden afstand = 0 afstandNEW = 0 SnijPunt = 0 GeenSpunt = 0 with arcpy.da.SearchCursor("in_memory/xxpipIN", ["SHAPE@"]) as Pcursor: for pip in Pcursor: # eerst kijken of de lijnen elkaar wel snijden. Zo niet dan is True en kan er geen intersect gedaan worden.
def MakeStopsFeatureClass(stopsfc, stoplist=None): '''Make a feature class of GTFS stops from the SQL table. Returns the path to the feature class and a list of stop IDs.''' stopsfc_path = os.path.dirname(stopsfc) stopsfc_name = os.path.basename(stopsfc) # If the output location is a feature dataset, we have to match the coordinate system desc = arcpy.Describe(stopsfc_path) if hasattr(desc, "spatialReference"): output_coords = desc.spatialReference else: output_coords = WGSCoords # Create a points feature class for the point pairs. StopsLayer = arcpy.management.CreateFeatureclass( stopsfc_path, stopsfc_name, "POINT", spatial_reference=output_coords) arcpy.management.AddField(StopsLayer, "stop_id", "TEXT") arcpy.management.AddField(StopsLayer, "stop_code", "TEXT") arcpy.management.AddField(StopsLayer, "stop_name", "TEXT") arcpy.management.AddField(StopsLayer, "stop_desc", "TEXT") arcpy.management.AddField(StopsLayer, "zone_id", "TEXT") arcpy.management.AddField(StopsLayer, "stop_url", "TEXT") if ".shp" in stopsfc_name: arcpy.management.AddField(StopsLayer, "loc_type", "TEXT") arcpy.management.AddField(StopsLayer, "parent_sta", "TEXT") else: arcpy.management.AddField(StopsLayer, "location_type", "TEXT") arcpy.management.AddField(StopsLayer, "parent_station", "TEXT") # Get the stop info from the GTFS SQL file if stoplist: StopTable = [] for stop_id in stoplist: selectstoptablestmt = "SELECT stop_id, stop_code, stop_name, stop_desc, stop_lat, stop_lon, zone_id, stop_url, location_type, parent_station FROM stops WHERE stop_id='%s';" % stop_id c.execute(selectstoptablestmt) StopInfo = c.fetchall() StopTable.append(StopInfo[0]) else: selectstoptablestmt = "SELECT stop_id, stop_code, stop_name, stop_desc, stop_lat, stop_lon, zone_id, stop_url, location_type, parent_station FROM stops;" c.execute(selectstoptablestmt) StopTable = c.fetchall() possiblenulls = [1, 3, 6, 7, 8, 9] # Make a list of stop_ids for use later. StopIDList = [] for stop in StopTable: StopIDList.append(stop[0]) if not ArcVersion: DetermineArcVersion() # Add the stops table to a feature class. if ".shp" in stopsfc_name: cur3 = arcpy.da.InsertCursor(StopsLayer, [ "SHAPE@", "stop_id", "stop_code", "stop_name", "stop_desc", "zone_id", "stop_url", "loc_type", "parent_sta" ]) else: cur3 = arcpy.da.InsertCursor(StopsLayer, [ "SHAPE@", "stop_id", "stop_code", "stop_name", "stop_desc", "zone_id", "stop_url", "location_type", "parent_station" ]) # Schema of stops table ## 0 - stop_id ## 1 - stop_code ## 2 - stop_name ## 3 - stop_desc ## 4 - stop_lat ## 5 - stop_lon ## 6 - zone_id ## 7 - stop_url ## 8 - location_type ## 9 - parent_station for stopitem in StopTable: stop = list(stopitem) pt = arcpy.Point() pt.X = float(stop[5]) pt.Y = float(stop[4]) # GTFS stop lat/lon is written in WGS1984 ptGeometry = arcpy.PointGeometry(pt, WGSCoords) if output_coords != WGSCoords: ptGeometry = ptGeometry.projectAs(output_coords) # Shapefile output can't handle null values, so make them empty strings. if ".shp" in stopsfc_name: for idx in possiblenulls: if not stop[idx]: stop[idx] = "" cur3.insertRow((ptGeometry, stop[0], stop[1], stop[2], stop[3], stop[6], stop[7], stop[8], stop[9])) del cur3 return stopsfc, StopIDList
def calculateDistance(x1, y1, x2, y2, ProjectionFile): # dist = math.sqrt((x2-x1)**2 +(y2-y1)**2) pnt_Geometry = arcpy.PointGeometry(arcpy.Point(x1, y1), arcpy.SpatialReference(ProjectionFile)) res = pnt_Geometry.angleAndDistanceTo( arcpy.PointGeometry(arcpy.Point(x2, y2), arcpy.SpatialReference(ProjectionFile))) return res
arcpy.AddField_management(savepath + '\\' + name + '.shp', 'STOPORDER', 'FLOAT') arcpy.AddField_management(savepath + '\\' + name + '.shp', 'LONGITUDE', 'FLOAT') arcpy.AddField_management(savepath + '\\' + name + '.shp', 'LATITUDE', 'FLOAT') arcpy.AddField_management(savepath + '\\' + name + '.shp', 'ROUTENAME', 'TEXT') rownum = sh.nrows # 获得表格的行数 # 接下来读取Excle表格的内容,利用插入游标给上面新建的点要素类插入数据(row) Insercur = arcpy.InsertCursor(savepath + '\\' + name + '.shp') for r in range(1, rownum): newpnt = arcpy.Point() # 新建一个点 # 获得点的xy坐标并赋值给点的XY属性 # sh.cell(r,c).value,这里的r,c索引要根据你自己表格的格式设置 newpnt.X = sh.cell(r, 10).value newpnt.Y = sh.cell(r, 11).value pointGeo = arcpy.PointGeometry(newpnt) newrow = Insercur.newRow() # 插入游标新建行row newrow.shape = pointGeo newrow.setValue('STOPNAME', sh.cell(r, 1).value) t = sh.cell(r, 8).value newrow.setValue('STOPORDER', sh.cell(r, 8).value) newrow.setValue('LONGITUDE', sh.cell(r, 10).value) newrow.setValue('LATITUDE', sh.cell(r, 11).value) newrow.setValue('ROUTENAME', sh.cell(r, 17).value) Insercur.insertRow(newrow) # 插入row except Exception as e: print e print u'%s文件已完成' % table
py = float(feature_dict[key - 1][6]) nx = float(feature_dict[key + 1][5]) ny = float(feature_dict[key + 1][6]) # find the angle between the initial point and the proceeding point angle = find_angle(px, nx, py, ny) # calculate the offset for the proceeding point offset1 = width_buffer(feature_dict[key][3], value_list, min_width, max_width) offset2 = width_buffer(feature_dict[key][3], value_list, min_width, max_width) # create a point geometry object based on the first point current_point = arcpy.PointGeometry(arcpy.Point( nx, ny), sr) # reconstruct geometry of selected point new_point1 = current_point # commit the coordinates of the first point as a point object variable del current_point # construct a pair of points based on the second last point and the calculated offset next_point = arcpy.PointGeometry( arcpy.Point(cx, cy), sr) # reconstruct geometry of the proceeding point new_point3 = next_point.pointFromAngleAndDistance( angle + 90, offset1, "GEODESIC") new_point2 = next_point.pointFromAngleAndDistance( angle - 90, offset1, "GEODESIC") del next_point # create a set of polygon coordinates from the 3 coordinate pairs new_pointList = [new_point1, new_point2, new_point3]
def Get_LatLon_BndBox( ): # Determine lat/long bounding coordinates for input dataset, when applicable ### Get extent and spatial reference of input dataset extent = desc.Extent Local_ExtentList = [float(extent.XMin), float(extent.YMin), \ float(extent.XMax), float(extent.YMax)] if float(extent.XMin) >= -180 and float(extent.XMax) <= 180 and \ float(extent.YMin) >= -90 and float(extent.YMax) <= 90: GCS_ExtentList = Local_ExtentList # Local extent is GCS so do not need to project coords in order to obtain GCS values return Local_ExtentList, GCS_ExtentList else: ### Create geographic bounding coordinates # Create 2 point list for LL and UR # For each axis, create a center point by (xmin + xmax)/2 and this would be coord (do not need to add or subtract) # And same for lat: (ymin + ymax)/2 and this would be coord (do not need to add or subtract) # Need total of 8 points x_mid6 = float(float(extent.XMin) + float(extent.XMax) / 2 * 0.25) x_mid7 = float(float(extent.XMin) + float(extent.XMax) / 2) x_mid8 = float(float(extent.XMin) + float(extent.XMax) / 2 * 0.75) y_mid2 = float(float(extent.YMin) + float(extent.YMax) / 2 * 0.25) y_mid3 = float(float(extent.YMin) + float(extent.YMax) / 2) y_mid4 = float(float(extent.YMin) + float(extent.YMax) * 0.75) # Point ID in list # 5 6 7 8 9 # # 4 10 # # 3 11 # # 2 12 # # 1 16 15 14 13 PtList = [[float(extent.XMin), float(extent.YMin)], [float(extent.XMin), y_mid2], [float(extent.XMin), y_mid3], [float(extent.XMin), y_mid4], [float(extent.XMin), float(extent.YMax)], [x_mid6, float(extent.YMax)], [x_mid7, float(extent.YMax)], [x_mid8, float(extent.YMax)], [float(extent.XMax), float(extent.YMax)], [float(extent.XMax), y_mid4], [float(extent.XMax), y_mid3], [float(extent.XMax), y_mid3], [float(extent.XMax), float(extent.YMin)], [x_mid8, float(extent.YMin)], [x_mid7, float(extent.YMin)], [x_mid6, float(extent.YMin)], [float(extent.XMin), float(extent.YMin)]] # Create an empty Point object point = arcpy.Point() array = arcpy.Array() # For each coordinate pair, populate the Point object and create # a new PointGeometry for pt in PtList: point.X = pt[0] point.Y = pt[1] pointGeometry = arcpy.PointGeometry(point, SR_InDS) array.add(point) # Create a Polygon object based on the array of points boundaryPolygon = arcpy.Polygon(array, SR_InDS) array.removeAll() # Instead of projecting point, project polygon OutSR = arcpy.SpatialReference(GCS_PrjFile) arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(GCS_PrjFile) # Return a list of geometry objects (we only have one polygon) using a geographic coordinate system boundaryPolygon2 = arcpy.CopyFeatures_management( boundaryPolygon, arcpy.Geometry()) # Each feature is list item which has its own geometry (therefore we pull the first and only polygon) GCSextent = boundaryPolygon2[0].extent # Get boundary extent GCS_XMin, GCS_YMin, GCS_XMax, GCS_YMax = float(GCSextent.XMin), float(GCSextent.YMin), \ float(GCSextent.XMax), float(GCSextent.YMax) #print "GCS_XMin, GCS_YMin, GCS_XMax, GCS_YMax:", GCS_XMin, GCS_YMin, GCS_XMax, GCS_YMax GCS_ExtentList = [GCS_XMin, GCS_YMin, GCS_XMax, GCS_YMax] del pointGeometry, PtList, point, OutSR, GCSextent, boundaryPolygon, boundaryPolygon2, array return Local_ExtentList, GCS_ExtentList
# Add bearing azimuth to plan profile line arcpy.AddGeometryAttributes_management(profileFC, 'LINE_BEARING', 'METERS', '#', sr) # Define cursor to loop the Structural Data Feature Layer cursor1 = arcpy.SearchCursor(strDataFC) # Loop the cursor and append the temporal line projections in outlines array for row1 in cursor1: Bz = (row1.getValue(dipField)) Az = (row1.getValue(azRumField)) Az2 = Az + 180 xi = (row1.getValue("POINT_X")) yi = (row1.getValue("POINT_Y")) start = arcpy.PointGeometry(arcpy.Point(xi, yi), sr) end = start.pointFromAngleAndDistance(Az, 5000, "PLANAR") end2 = start.pointFromAngleAndDistance(Az2, 5000, "PLANAR") outlines.append( arcpy.Polyline(arcpy.Array([start.centroid, end.centroid]), sr)) outlines.append( arcpy.Polyline(arcpy.Array([start.centroid, end2.centroid]), sr)) arcpy.CopyFeatures_management(outlines, 'in_memory\Aux1') del cursor1 # Define cursor to loop the Plan Profile Line Feature Layer cursor2 = arcpy.SearchCursor(profileFC) # Adjust the value in case the azimuth is greater than 180 for row in cursor2: azVal = row.BEARING
import arcpy point = arcpy.Point(5000, 2000) ptGeo = arcpy.PointGeometry(point) print(ptGeo)
def leastCostPath(Cost_Raster, anchors, Line_Processing_Radius): """ Calculate least cost path between two points Cost_Raster: cost raster anchors: list of two points: start and end points Line_Processing_Radius """ if not anchors[0] or not anchors[1]: print("Anchor points not valid") centerline = [None] return centerline lineNo = uuid.uuid4().hex # random line No. outWorkspaceMem = r"memory" arcpy.env.workspace = r"memory" fileClip = os.path.join(outWorkspaceMem, "FLM_VO_Clip_" + str(lineNo) + ".tif") fileCostDist = os.path.join(outWorkspaceMem, "FLM_VO_CostDist_" + str(lineNo) + ".tif") fileCostBack = os.path.join(outWorkspaceMem, "FLM_VO_CostBack_" + str(lineNo) + ".tif") fileCenterline = os.path.join(outWorkspaceMem, "FLM_VO_Centerline_" + str(lineNo)) # line from points # TODO: change the way to set spatial reference x1 = anchors[0][0] y1 = anchors[0][1] x2 = anchors[1][0] y2 = anchors[1][1] line = arcpy.Polyline( arcpy.Array([arcpy.Point(x1, y1), arcpy.Point(x2, y2)]), arcpy.SpatialReference(3400)) try: # Buffer around line lineBuffer = arcpy.Buffer_analysis([line], arcpy.Geometry(), Line_Processing_Radius, "FULL", "ROUND", "NONE", "", "PLANAR") # Clip cost raster using buffer SearchBox = str(lineBuffer[0].extent.XMin) + " " + str(lineBuffer[0].extent.YMin) + " " + \ str(lineBuffer[0].extent.XMax) + " " + str(lineBuffer[0].extent.YMax) arcpy.Clip_management(Cost_Raster, SearchBox, fileClip, lineBuffer, "", "ClippingGeometry", "NO_MAINTAIN_EXTENT") # Least cost path fileCostDist = CostDistance(arcpy.PointGeometry(arcpy.Point(x1, y1)), fileClip, "", fileCostBack) CostPathAsPolyline(arcpy.PointGeometry(arcpy.Point(x2, y2)), fileCostDist, fileCostBack, fileCenterline, "BEST_SINGLE", "") # get centerline polyline out of memory feature class fileCenterline centerline = [] with arcpy.da.SearchCursor(fileCenterline, ["SHAPE@"]) as cursor: for row in cursor: centerline.append(row[0]) except Exception as e: print("Problem with line starting at X " + str(x1) + ", Y " + str(y1) + "; and ending at X " + str(x2) + ", Y " + str(y2) + ".") print(e) centerline = [None] return centerline # Clean temporary files arcpy.Delete_management(fileClip) arcpy.Delete_management(fileCostDist) arcpy.Delete_management(fileCostBack) return centerline
def readSingleLayer(collection, singleparams, geometries, dbdestination, all_the_world, to_clip): filter = {} jsonParams = json.loads(singleparams.split("@")[1]) if singleparams.split(",")[1] == 'node': filter = {'osm_type': singleparams.split(",")[1]} elif singleparams.split(",")[1] == 'polyline': filter = {'geometry.type': {"$in": ['LineString', 'MultiLineString']}} elif singleparams.split(",")[1] == 'polygon': filter = {'geometry.type': {"$in": ['Polygon', 'MultiPolygon']}} arcpy.AddMessage("Create indexes for " + singleparams.split(",")[0]) for key in jsonParams.keys(): filter[key] = jsonParams[key] collection.create_index([(key, ASCENDING)], background=True) arcpy.AddMessage("Start data extraction from MongoDB for " + singleparams.split(",")[0]) if not all_the_world: for geometry in geometries: filter['geometry'] = {'$geoIntersects': {'$geometry': geometry}} arcpy.AddMessage("Insert data in " + singleparams.split(",")[2]) if (arcpy.Exists("in_memory/temp_fc")): arcpy.Delete_management("in_memory/temp_fc") arcfc = os.path.join(dbdestination, singleparams.split(",")[2]) arcpy.management.CreateFeatureclass( "in_memory", "temp_fc", template=arcfc, spatial_reference= "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 11258999068426.2;-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision" ) names = singleparams.split("[")[1] names = names.split("]")[0] flds = ['geometry'] for field in names.split(","): flds.append(field) mongocursor = collection.find(filter, projection=flds, no_cursor_timeout=True) #mongocursor.batch_size(10000) df = pandas.DataFrame(list(mongocursor)) arcpy.AddMessage("Array of data prepared") fieldnames = [] fieldosm = [] for field in names.split(","): if len(field.split("=>")) == 1: fieldnames.append(field.split("=>")[0]) else: fieldnames.append(field.split("=>")[1]) fieldosm.append(field.split("=>")[0].replace("'", "")) fieldnames.append("SHAPE@") arrive_fc = arcfc if not all_the_world and to_clip: arrive_fc = "in_memory/temp_fc" cursor = arcpy.da.InsertCursor(arrive_fc, fieldnames) arcpy.AddMessage("GDB cursor prepared") for index, document in df.iterrows(): #for document in mongocursor: valuesnames = [] for field in fieldosm: if field in document: valuesnames.append(document[field]) else: valuesnames.append('') if document['geometry']['type'] == 'Point': point = arcpy.Point(document['geometry']['coordinates'][0], document['geometry']['coordinates'][1]) geom_tosave = arcpy.PointGeometry(point, arcpy.SpatialReference(4326)) valuesnames.append(geom_tosave) elif document['geometry']['type'] == 'LineString': geom_tosave = arcpy.Polyline( arcpy.Array([ arcpy.Point(*coords) for coords in document['geometry']['coordinates'] ]), arcpy.SpatialReference(4326)) valuesnames.append(geom_tosave) elif document['geometry']['type'] == 'Polygon': geom_tosave = arcpy.Polygon( arcpy.Array([ arcpy.Point(*coords) for coords in document['geometry']['coordinates'][0] ]), arcpy.SpatialReference(4326)) valuesnames.append(geom_tosave) elif document['geometry']['type'] == 'MultiPolygon': lst_part = [] for pts in document['geometry']['coordinates']: for part in pts: lst_pnt = [] for pnt in part: lst_pnt.append( arcpy.Point(float(pnt[0]), float(pnt[1]))) lst_part.append(arcpy.Array(lst_pnt)) array = arcpy.Array(lst_part) geom_tosave = arcpy.Polygon(array, arcpy.SpatialReference(4326)) valuesnames.append(geom_tosave) else: #MultilineString arcpy.AddMessage(document['geometry']['type']) arcpy.AddMessage(document['geometry']['coordinates']) try: cursor.insertRow(valuesnames) except: continue del cursor if not all_the_world and to_clip: arcpy.AddMessage("Clip and append data to database") source_fc = r"in_memory/polygon_selection" arcpy.Clip_analysis("in_memory/temp_fc", source_fc, arcfc) del mongocursor del df if (arcpy.Exists("in_memory/temp_fc")): arcpy.Delete_management("in_memory/temp_fc")
# crt_date= datetime.strptime(row[6],"%m/%d/%y %H:%M") # strt_date= datetime.strptime(row[7],"%m/%d/%y %H:%M") or '' # comp_date= datetime.strptime(row[8],"%m/%d/%y %H:%M") or '' crt_date = row[6] strt_date = row[7] comp_date = row[8] likes = row[9] type = row[10] #x,y coordinates in Lat/Long (x = longitude, y = latitude) #Latitude lat = float(row[2].strip()) #Longitude long = float(row[3].strip()) #Create points #Append points to the pointList point = arcpy.Point(long, lat) point_obj = arcpy.PointGeometry(point, sr) print point # insert attriubtes into the attribute table row = [ point_obj, problem_ID, username, descr, type, crt_date, strt_date, comp_date, status, likes ] insertcursor.insertRow(row) del insertcursor arcpy.CheckInExtension('Spatial')
#coding=utf-8 import arcpy arcpy.env.workspace = r'C:\Data' coordlist = [[17.0, 20.0], [125.0, 32.0], [4.0, 87.0]] pointlist = [] for x, y in coordlist: point = arcpy.Point(x, y) pointgeometry = arcpy.PointGeometry(point) pointlist.append(pointgeometry) arcpy.Buffer_analysis(pointlist, "buffer1.shp", "10 METERS")
#!/usr/bin/env python # -*- coding: utf-8 -*- import arcpy #Création de la référence spatiale referenceSpatiale = arcpy.SpatialReference(4326) #Création d'une classe d'entités avec l'outil arcpy.CreateFeatureclass_management("in_memory", "pt_collecte", "POINT", spatial_reference=referenceSpatiale) #Création d'un point ptGeom = arcpy.PointGeometry(arcpy.Point(-71,46), referenceSpatiale) #Création d'un champ avec l'outil arcpy.AddField_management("in_memory/pt_collecte", "nom", "TEXT", field_length=20) #Ajout d'un enregistrement avec UpdateCursor curseur = arcpy.da.InsertCursor("in_memory/pt_collecte", ['SHAPE@', 'nom']) curseur.insertRow([ptGeom, "Quebec"]) #Copy la classe d'entités de la mémoire vers le disque dur arcpy.CopyFeatures_management("in_memory/pt_collecte", "C:/Temp/donnees.gdb/pt_collecte")
def ProjectPoint(x, y, sr, srOut): point = arcpy.Point(x, y) pg = arcpy.PointGeometry(point, sr) pp = pg.projectAs(srOut) part = pp.getPart() return part
def polylines(fcLineFeatures, listfcPointFeatures): TempPoints = "in_memory\\ZSnap_tempPoints" lyrTempPointsLineIntersect = "ZsnapTempPointsLineIntersect" lyrLines = "ZsnapLines" ## Preprocessing if arcpy.Exists(TempPoints): arcpy.Delete_management(TempPoints) arcpy.Merge_management(listfcPointFeatures, TempPoints) if arcpy.Exists(lyrTempPointsLineIntersect): arcpy.Delete_management(lyrTempPointsLineIntersect) if arcpy.Exists(lyrLines): arcpy.Delete_management(lyrLines) arcpy.MakeFeatureLayer_management(TempPoints, lyrTempPointsLineIntersect) arcpy.MakeFeatureLayer_management(fcLineFeatures, lyrLines, "") arcpy.SelectLayerByLocation_management(lyrTempPointsLineIntersect, "INTERSECT", lyrLines) TempPointGeometry = arcpy.CopyFeatures_management( lyrTempPointsLineIntersect, arcpy.Geometry()) ## Run with arcpy.da.UpdateCursor(fcLineFeatures, ["OID@", "SHAPE@"], '', '', "True") as ucLines: for line in ucLines: if line[1] is not None: # Do not process lines with "Null Geometry" arcpy.AddMessage("Line Feature: " + str(line[0])) arcpy.AddMessage(" Point Count: " + str(line[1].pointCount)) vertexCount = 0 vertexArray = [] arcpy.SelectLayerByAttribute_management( lyrLines, "NEW_SELECTION", '"FID" = ' + str(line[0])) arcpy.SelectLayerByLocation_management( lyrTempPointsLineIntersect, "INTERSECT", lyrLines, "", "NEW_SELECTION") if arcpy.Exists(TempPointGeometry): arcpy.Delete_management(TempPointGeometry) TempPointGeometry = arcpy.CopyFeatures_management( lyrTempPointsLineIntersect, arcpy.Geometry()) for lineVertex in line[1].getPart(vertexCount): arcpy.AddMessage(" Vertex: " + str(vertexCount) + " X:" + str(lineVertex.X) + " Y: " + str(lineVertex.Y)) vertexPoint = arcpy.Point(lineVertex.X, lineVertex.Y) vertexPointGeometry = arcpy.PointGeometry( vertexPoint, fcLineFeatures) for pointGeom in TempPointGeometry: intersect = pointGeom.intersect(vertexPointGeometry, 1) if intersect.firstPoint: arcpy.AddMessage(" Point Intersect: X: " + str(intersect.firstPoint.X) + " Y: " + str(intersect.firstPoint.Y)) arcpy.AddMessage(" Old Z: " + str(lineVertex.Z)) lineVertex.Z = intersect.firstPoint.Z arcpy.AddMessage(" New Z: " + str(lineVertex.Z)) #if intersect.pointCount == 0: # arcpy.AddWarning(" No Intersecting Point Found.") vertexArray.append( [lineVertex.X, lineVertex.Y, lineVertex.Z]) vertexCount = vertexCount + 1 line[1] = vertexArray ucLines.updateRow(line) else: arcpy.AddWarning("Line Feature: " + str(line[0]) + " Has no Geometry.") return
def linevertex_point(): """ メソッド名 : linevertex_point メソッド 概要 : ラインの頂点からポイントへ変換 """ try: arcpy.AddMessage(u"処理開始:") in_line_fc = arcpy.GetParameterAsText(0) out_pt_fc = arcpy.GetParameterAsText(1) # ワークスペース wstype = arcpy.Describe(os.path.dirname(out_pt_fc)).workspacetype # ワークスペースにすでに同一のフィーチャクラス名がないかチェック if arcpy.Exists(out_pt_fc): raise AlreadyExistError # カーソル作成に使用するフィールド情報を create_fieldinfo 関数を用いて取得 search_fields_name, search_fields_type, use_fields_name, spref = create_fieldinfo( in_line_fc, out_pt_fc) # フィーチャクラスの検索カーソル作成 incur = arcpy.da.SearchCursor(in_line_fc, search_fields_name) # フィーチャクラスの挿入カーソル作成 outcur = arcpy.da.InsertCursor(out_pt_fc, use_fields_name) i = 0 num = int(arcpy.GetCount_management(in_line_fc).getOutput(0)) # フィーチャ(ジオメトリ)の数 for inrow in incur: i = i + 1 if (i == 1) or (i == num) or (i % 1000 == 1): s = u"{0}/{1}の処理中・・・".format(i, num) arcpy.AddMessage(s) newValue = [] # 出力がShape ファイルの場合、NULL 値を格納できないため # フィールドのタイプに合わせて、空白や 0 を格納する if wstype == "FileSystem": for j, value in enumerate(inrow): if value == None: if search_fields_type[j] == "String": newValue.append("") elif search_fields_type[j] in [ "Double", "Integer", "Single", "SmallInteger" ]: newValue.append(0) else: newValue.append(value) else: newValue.append(value) # GDB は NULL 値を格納可能 else: newValue = list(inrow) # パートの数 for part in inrow[-1]: # 頂点座標の数 for pnt in part: # ジオメトリにラインの頂点のポイントを格納 newValue[-1] = arcpy.PointGeometry( arcpy.Point(pnt.X, pnt.Y), spref) # リストからタプルに変換してインサート outcur.insertRow(tuple(newValue)) # 後始末 del outcur del incur arcpy.AddMessage(u"処理終了:") except AlreadyExistError: arcpy.AddError(u"{0}はすでに存在しています".format(out_pt_fc)) except arcpy.ExecuteError: arcpy.AddError(arcpy.GetMessages(2)) except Exception as e: arcpy.AddError(e.args[0])
def copy_metadata(input_db, sde_conn): # Expected Paramters targets = ['FootprintRaster', 'BoundaryRaster', 'BoundaryLASDataset', 'FootprintLASFile'] proj_id = os.path.basename(input_db)[:-4] # Logging arcpy.AddMessage('Running A05_D_UpdateCMDRMetaData') arcpy.AddMessage('Input DB: {}'.format(input_db)) arcpy.AddMessage('SDE File: {}'.format(sde_conn)) arcpy.AddMessage('Proj ID: {}'.format(proj_id)) # Move Features for target in targets: sde_fc = os.path.join(sde_conn, 'LDM_CMDR.DBO.' + target) der_fc = os.path.join(input_db, target) if not arcpy.Exists(sde_fc) or not arcpy.Exists(der_fc): arcpy.AddMessage('Target Feature Class Not Found In Both Databases: {}'.format(target)) continue else: arcpy.AddMessage('Moving: {}'.format(target)) arcpy.AddMessage('Records: {}'.format(arcpy.GetCount_management(der_fc))) # Describe FC Fields To Mitigate Schema Conflicts der_desc = arcpy.Describe(der_fc) sde_desc = arcpy.Describe(sde_fc) der_fields = [f.name for f in der_desc.fields if f.name != der_desc.OIDFieldName if f.name != 'Shape'] sde_fields = [f.name for f in sde_desc.fields if f.name != sde_desc.OIDFieldName if f.name != 'Shape'] handled = list(set(der_fields) & set(sde_fields)) # Add Fields Needing Specific Attention To End For Access if target in ['FootprintRaster', 'BoundaryRaster']: der_handled = handled + ['area', 'nodata', 'SHAPE@'] sde_handled = handled + ['src_area', 'nodata', 'SHAPE@'] else: der_handled = handled + ['area', 'SHAPE@'] sde_handled = handled + ['src_area', 'SHAPE@'] # Remove Existing Records with arcpy.da.UpdateCursor(sde_fc, ['OBJECTID'], "Project_ID = '{}'".format(proj_id)) as u_cursor: arcpy.AddMessage('Deleting Existing Records') for row in u_cursor: u_cursor.deleteRow() # Insert Incoming Records with arcpy.da.SearchCursor(der_fc, der_handled) as s_cursor: with arcpy.da.InsertCursor(sde_fc, sde_handled) as i_cursor: arcpy.AddMessage('Inserting Incoming Records') for row in s_cursor: # Pull Centroid If Working With Footprints if target in ['FootprintRaster', 'FootprintLASFile']: centroid = row[-1].projectAs(arcpy.SpatialReference(3857)).centroid geom = arcpy.PointGeometry(arcpy.Point(centroid.X, centroid.Y)) else: geom = row[-1].projectAs(arcpy.SpatialReference(3857)) # Convert No Data to String & Insert Row if target in ['FootprintRaster', 'BoundaryRaster']: no_d = str(row[-2]) i_cursor.insertRow(row[:-2] + (no_d, geom,)) else: i_cursor.insertRow(row[:-1] + (geom,))
miny = extent.YMin maxy = extent.YMax temppoints = "temporarypoints12343" arcpy.CreateFeatureclass_management(work, temppoints, "POINT", '', '', '', spatialref) #create insert cursor inserter = arcpy.InsertCursor(temppoints) #pick random x,y and add that point to the point file for i in range(1, realnumpoints): x = random.uniform(minx, maxx) y = random.uniform(miny, maxy) point = arcpy.Point(x, y) newrow = inserter.newRow() newrow.shape = arcpy.PointGeometry(point) inserter.insertRow(newrow) ############################################################################## #intersect points with boundshp and limit to the specified number ############################################################################## #create feature layer temppoints_fl = "temp_fl" arcpy.MakeFeatureLayer_management(temppoints, temppoints_fl) #select all the points that intersect the bounding shape arcpy.SelectLayerByLocation_management(temppoints_fl, "INTERSECT", boundshp, '', 'NEW_SELECTION') temppoints2 = "temporarypoints123435" #copy the intersected features
def Feature_FN_overlay(FN_areas, feature_type, features, field_team, op_area, ID_field, dem): """Returns a dictionnary containing the intersection results of blocks/roads against FN consultative areas""" arcpy.AddMessage('Performing the analysis...') # Count of features in the input layer feat_count = arcpy.GetCount_management(features).getOutput(0) # Create a Dict that will hold the data val_dict = {} val_dict['Type'] = [] val_dict['Field Team'] = [] val_dict['Op Area'] = [] val_dict['Name'] = [] val_dict['Elevation'] = [] if feature_type == 'Block': measure = 'Area (ha)' val_dict['Type'].extend('Block' for i in range(int(feat_count))) elif feature_type == 'Road': measure = 'Length (m)' val_dict['Type'].extend('Road' for i in range(int(feat_count))) val_dict[measure] = [] # Get Field Team info arcpy.SpatialJoin_analysis(features, field_team, 'in_memory\st_inter', 'JOIN_ONE_TO_ONE') val_dict['Field Team'] = [ row[0] for row in arcpy.da.SearchCursor('in_memory\st_inter', ['FIELD_TEAM']) ] # Get Op Area info arcpy.SpatialJoin_analysis(features, op_area, 'in_memory\op_area', 'JOIN_ONE_TO_ONE') val_dict['Op Area'] = [ row[0] for row in arcpy.da.SearchCursor('in_memory\op_area', ['OPAREA_NAM']) ] # Initialize a counter proc_count = 1 # Add the rest of data to the dict fields = [ID_field, "SHAPE@AREA", "SHAPE@Length", "SHAPE@XY"] sr = arcpy.Describe(dem).spatialReference cursor = arcpy.da.SearchCursor(features, fields, '', sr) for row in cursor: arcpy.AddMessage('Processing feature {} of {}'.format( proc_count, feat_count)) proc_count += 1 # add Name, Type and Area/Length data for each block/road val_dict['Name'].append(str(row[0])) if feature_type == 'Block': val_dict[measure].append((round(row[1] / 10000, 2))) elif feature_type == 'Road': val_dict[measure].append((int(row[2]))) # add Elevation data for each feature #get feature centroid pt pnt = arcpy.Point(row[3][0], row[3][1]) ptGeometry = arcpy.PointGeometry(pnt) #clip TRIM DEM based on buffer around the centroid pt arcpy.Buffer_analysis(ptGeometry, 'in_memory\ptBuf', 100) extent = arcpy.Describe('in_memory\ptBuf').extent arcpy.Clip_management(dem, str(extent), 'in_memory\dem') #convert the dem to numpy array rast = arcpy.Raster('in_memory\dem') desc = arcpy.Describe(rast) ulx = desc.Extent.XMin uly = desc.Extent.YMax rstArray = arcpy.RasterToNumPyArray(rast) #get the row/col position of the centroid pt deltaX = pnt.X - ulx deltaY = uly - pnt.Y arow = int(deltaY / rast.meanCellHeight) acol = int(deltaX / rast.meanCellWidth) #extract the elevation from array and add it to the Dict elevation = rstArray[arow, acol] val_dict['Elevation'].append(elevation) arcpy.Delete_management("in_memory") # Spatial Join of feaures and FN territories arcpy.AddMessage('Populating FN overlay results...') intersect = 'in_memory\intersect' arcpy.SpatialJoin_analysis(FN_areas, features, intersect, 'JOIN_ONE_TO_MANY') # Add referral requirement of each feature to the dict based on the spatial overlay for row in arcpy.da.SearchCursor(intersect, ['CONTACT_ORGANIZATION_NAME', ID_field]): if str(row[0]) not in val_dict: val_dict[str(row[0])] = [] val_dict[str(row[0])].extend('n/r' for i in range(int(feat_count))) for i in range(0, int(feat_count)): if str(row[1]) == val_dict['Name'][i]: val_dict[str(row[0])][i] = 'required' else: pass #print ({k:len(v) for k, v in val_dict.items()}) return val_dict
featureln = [] for feature in feature_info: # Create a Polygon object based on the array of points # Append to the list of Polygon objects features.append( arcpy.Polygon( arcpy.Array([arcpy.Point(*coords) for coords in feature]), spatialref)) pnt = arcpy.Point() for i in feature_info: for j in range(len(i)): pnt.X = i[j][0] pnt.Y = i[j][1] featuresp.append(arcpy.PointGeometry(pnt, spatialref)) # #ary = arcpy.Array() # #for feature in feature_info: # for x,y in feature: # pnt = arcpy.Point(x,y) # ary.add(pnt) # features.append(arcpy.Polygon(ary,spatialref)) # Persist a copy of the Polyline objects using CopyFeatures feature_class = arcpy.CopyFeatures_management(features, arcpy.GetParameterAsText(6)) arcpy.CopyFeatures_management(featuresp, arcpy.GetParameterAsText(7)) #arcpy.CopyFeatures_management(featuresp, arcpy.GetParameterAsText(6))
arcpy.DeleteField_management(input + "_break1", "FID_" + inputName + "_dissolve1") # Break all line segments greater than the defined value 'divLength' -- # by creating points and using them to Split Line At Point cursor = arcpy.SearchCursor(input + "_break1") ptGeoms = [] divLength = 200 for feature in cursor: divisions = int(feature.SHAPE_length / divLength) pointCount = 0 while pointCount < divisions: division = feature.shape.positionAlongLine( divLength + (divLength * pointCount), False).firstPoint pt = arcpy.Point(division.X, division.Y) ptGeoms.append(arcpy.PointGeometry(pt)) pointCount += 1 arcpy.CopyFeatures_management(ptGeoms, workspace + "\\splitPoints_" + str(divLength)) dsc = arcpy.Describe(input) coord_sys = dsc.spatialReference arcpy.DefineProjection_management( workspace + "\\splitPoints_" + str(divLength), coord_sys) arcpy.SplitLineAtPoint_management( input + "_break1", workspace + "\\splitPoints_" + str(divLength), input + "_split1", "1 Foot") # Provide all line segments with an Avg Slope field arcpy.ddd.AddSurfaceInformation(input + "_split1", DEM_loc, "AVG_SLOPE", "LINEAR", "", 1, "")
#line geom is shape in search fields #use it to get length of line line_geom = row[0] length = float(line_geom.length) distance = 0 #oid is OID@ in search fields #insert value into point field oid = str(row[1]) #stream order is stream order in search fields #insert value into point field streamorder = row[2] #creates a point at the start and end of line for final point that is less then the userdistance away start_of_line = arcpy.PointGeometry(line_geom.firstPoint) end_of_line = arcpy.PointGeometry(line_geom.lastPoint) #returns a point on the line at a specific distance from the beginning point = line_geom.positionAlongLine(distance, False) #insert point at every userdistance while distance <= length: point = line_geom.positionAlongLine(distance, False) #insert rows for each point insert.insertRow((point, oid, float(distance), streamorder)) distance += float(userdistance) insert.insertRow((end_of_line, oid, length, streamorder)) del search
def main(oicpath, oicparas, inputParams, defValues, log=None): try: # Get the Spatial reference to the input OIC. outPathSRS = arcpy.Describe(oicpath).spatialReference count = int(arcpy.GetCount_management(oicpath)[0]) if not count: maxObjectID = 0 else: maxObjectID = arcpy.da.SearchCursor( oicpath, "OBJECTID", sql_clause=(None, "ORDER BY OBJECTID DESC")).next()[0] inPath = oicparas['InputFile'] imgPath = oicparas['PathToImage'] if log: log.Message("Input file: {}".format(inPath), log.const_general_text) log.Message("Input folder: {}".format(imgPath), log.const_general_text) ps_microns = oicparas['PixelSize(Microns)'] avght_meters = oicparas['AverageTerrainHeight(Meters)'] h_wkid = oicparas['HorizontalWKID'] v_wkid = oicparas['VeritcalWKID'] inChkFldsList = [ 'ImageName', 'ShotDate', 'ImageRows', 'ImageCols', 'PPx', 'PPy', 'CameraX', 'CameraY', 'CameraZ', 'Omega', 'Phi', 'Kappa', 'BalancedFL', 'BalancedK0', 'BalancedK1', 'BalancedK2', 'BalancedK3', 'Units' ] missingFldList = [] for mFldName in inChkFldsList: mFldList = arcpy.ListFields(inPath, mFldName) if len(mFldList) == 0: missingFldList.append(mFldName) if len(missingFldList) >= 1: errorMsg = 'Error: The following fields were required and could not be found in the input table:' + '\n' + ( ','.join(missingFldList)) log.Message( 'Error: The following fields were required and could not be found in the input table:' + '\n' + (','.join(missingFldList)), log.const_critical_text) return (errorMsg) #Get the SRS #start, ext = os.path.splitext(inPath) inFileDesc = arcpy.Describe(inPath) if hasattr(inFileDesc, "spatialReference"): inPathSRS = arcpy.Describe(inPath).spatialReference else: inPathSRS = arcpy.SpatialReference(int(h_wkid)) #build a list of input fields ## stringfields = arcpy.ListFields(inPath) ## inputFields = [] ## for fld in stringfields: ## if ('FID' in fld.name) or ('Shape' in fld.name): ## pass ## else: ## inputFields.append(fld.name) #Add missing fiedls to the OIC Table. arcpy.AddMessage("Adding Fields:") log.Message("Adding Fields:", log.const_general_text) #for infldName in inChkFldsList: for infld in arcpy.ListFields(inPath): if ('FID' in infld.name) or ('Shape' in infld.name): pass else: chkFldName = infld.name fieldChkList = arcpy.ListFields(oicpath, chkFldName) try: if len(fieldChkList) == 0: if chkFldName in inChkFldsList: arcpy.AddField_management(oicpath, infld.name, infld.type, infld.precision, infld.scale, infld.length, infld.aliasName) log.Message('Adding field {}'.format(infld.name), log.const_general_text) else: arcpy.AddMessage("The field name: " + infld.name + " already exists.") log.Message( 'The field name: {} already exists.'.format( infld.name), log.const_general_text) except: log.Message('Could not add field {}'.format(infld.name), log.const_general_text) continue #build the input list of output fields. outFldList = arcpy.ListFields(oicpath) outFldNameList = [] for outfld in outFldList: if ('OBJECTID' in outfld.name) or ('Shape' in outfld.name): pass else: outFldNameList.append(outfld.name) outFldNameList.insert(0, 'SHAPE@') inputFields = inChkFldsList[:] #if useShapeFld == True: # inputFields.insert(0,'SHAPE@') outCursor = arcpy.da.InsertCursor(oicpath, outFldNameList) arcpy.AddMessage('Importing Records') log.Message('Importing Records', log.const_general_text) with arcpy.da.SearchCursor(inPath, inputFields) as inCursor: for inRec in inCursor: valueList = [] valueList = [None] * (len(outFldNameList)) ## if useShapeFld == True: ## aPoint = inRec[0] ## ## aPtGeometry = aPoint.projectAs(outPathSRS) ## aPoint = aPtGeometry.centroid ## valueList[0] = aPoint ## else: #use the shape fields xindx = inputFields.index('CameraX') yindx = inputFields.index('CameraY') inX = inRec[xindx] inY = inRec[yindx] aPoint = arcpy.Point() aPoint.X = inX aPoint.Y = inY aPtGeometry = arcpy.PointGeometry( aPoint, inPathSRS).projectAs(outPathSRS) aPoint = aPtGeometry.centroid valueList[0] = aPoint #Set all the default values. defKeys = defValues.keys() for aKey in defKeys: if aKey in outFldNameList: keyindex = outFldNameList.index(aKey) tdefVal = defValues[aKey] try: if tdefVal is not None: defValAsNum = float(tdefVal) valueList[keyindex] = defValAsNum else: #Assign default as none, if user defined default value is none. valueList[keyindex] = None except Exception as valueError: #arcpy.AddMessage ('Value Error:'+str(valueError)) valueList[keyindex] = defValues[aKey][0] #read and set the values from the input table. for x in range(0, len(inputFields)): infldName = inputFields[x] if ('OBJECTID' in infldName) or ('Shape' in infldName): #handle things. continue else: aValue = inRec[x] #arcpy.AddMessage(infldName) outindex = outFldNameList.index(infldName) valueList[outindex] = aValue #add records #arcpy.AddMessage(outFldNameList) #arcpy.AddMessage(valueList) outCursor.insertRow(valueList) del inCursor del outCursor del inRec #Calculate additional values. ## chkFldList = arcpy.ListFields(oicpath,'X') ## if len(chkFldList) == 1: ## arcpy.AddMessage('Calculating X') ## arcpy.CalculateField_management(oicpath, 'X', ## "!SHAPE.CENTROID.X!", ## "PYTHON3") ## chkFldList = arcpy.ListFields(oicpath,'Y') ## if len(chkFldList) == 1: ## arcpy.AddMessage('Calculating Y') ## arcpy.CalculateField_management(oicpath, 'Y', ## "!SHAPE.CENTROID.Y!", ## "PYTHON3") arcpy.MakeFeatureLayer_management( oicpath, out_layer='lyr_selection', where_clause='"OBJECTID" > {}'.format(maxObjectID)) chkFldList = arcpy.ListFields(oicpath, 'Point') if len(chkFldList) == 1: arcpy.AddMessage('Calculating Point') log.Message('Calculating Point', log.const_general_text) arcpy.CalculateField_management( 'lyr_selection', 'Point', "str(!SHAPE.CENTROID.X!)+','+str(!SHAPE.CENTROID.Y!)", "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'ImageName') if len(chkFldList) == 1: arcpy.AddMessage("Calculating Name") log.Message('Calculating Name', log.const_general_text) arcpy.CalculateField_management('lyr_selection', 'Name', '!ImageName!', "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'AcquisitionDate') if len(chkFldList) == 1: arcpy.AddMessage("Calculating Date") log.Message('Calculating Date', log.const_general_text) arcpy.CalculateField_management('lyr_selection', 'AcquisitionDate', '!ShotDate!', "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'HFOV') if len(chkFldList) == 1: arcpy.AddMessage("Calculating HFOV") log.Message('Calculating HFOV', log.const_general_text) arcpy.CalculateField_management( 'lyr_selection', 'HFOV', 'math.degrees(2 * math.atan(!BalancedFL!/(!ImageCols!*' + ps_microns + '/2000)))', "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'VFOV') if len(chkFldList) == 1: arcpy.AddMessage("Calculating VFOV") log.Message('Calculating VFOV', log.const_general_text) arcpy.CalculateField_management( 'lyr_selection', 'VFOV', 'math.degrees(2 * math.atan(!BalancedFL!/(!ImageRows!*' + ps_microns + '/2000)))', "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'SRS') if len(chkFldList) == 1: arcpy.AddMessage('Calculating SRS') log.Message('Calculating SRS', log.const_general_text) arcpy.CalculateField_management('lyr_selection', 'SRS', outPathSRS.factoryCode, "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'CameraZ') if len(chkFldList) == 1: arcpy.AddMessage('Calculating AvgHtag') log.Message('Calculating AvgHtag', log.const_general_text) arcpy.CalculateField_management('lyr_selection', 'AvgHtAG', '!CameraZ! - ' + avght_meters, "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'Name') if len(chkFldList) == 1: #arcpy.AddMessage('Calculating Name') arcpy.CalculateField_management('lyr_selection', 'Name', "!ImageName!", "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'ImageName') if len(chkFldList) == 1: #imgPath = os.path.normpath(imgPath) imageCodeBlock = "def makeImgPath(imagePath,imgName):\n import os\n fullimageName = os.path.join(imagePath,imgName+'.jpg') \n return (fullimageName)" arcpy.AddMessage('Calculating Image Path') log.Message('Calculating Image Path', log.const_general_text) arcpy.CalculateField_management( 'lyr_selection', 'Image', 'makeImgPath(r"' + imgPath + '",!Name!)', "PYTHON3", imageCodeBlock) #if omega phi and kappa values are available use it to caluclate camheading, campitch and camroll. if outFldNameList.count('Omega') == 1 and outFldNameList.count( 'Phi') == 1 and outFldNameList.count('Kappa') == 1: camHeadingFormula = '(math.atan2(-1 * (math.sin(!Phi! * (math.pi/180))), (-1 * (-math.sin(!Omega! * (math.pi/180))*math.cos(!Phi!)))) * 180) / math.pi' arcpy.CalculateField_management('lyr_selection', 'CamHeading', camHeadingFormula, "PYTHON3") camPitchFormula = 'math.acos(math.cos(!Omega! * (math.pi/180))*math.cos(!Phi! * (math.pi/180))) * 180 / math.pi' arcpy.CalculateField_management('lyr_selection', 'CamPitch', camPitchFormula, "PYTHON3") camRollFormula = '(math.atan2((-1 * ((math.sin(!Omega! * (math.pi/180))*math.sin(!Kappa! * (math.pi/180))) - (math.cos(!Omega! * (math.pi/180))*math.sin(!Phi! * (math.pi/180))* math.cos(!Kappa! * (math.pi/180))))), (math.sin(!Omega! * (math.pi/180))*math.cos(!Kappa! * (math.pi/180))) + (math.cos(!Omega! * (math.pi/180))* math.sin(!Phi! * (math.pi/180))* math.sin(!Kappa! * (math.pi/180)))) * 180) / math.pi' arcpy.CalculateField_management('lyr_selection', 'CamRoll', camRollFormula, "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'FarDist') if len(chkFldList) == 1: farDistCodeBlock = "def retAvgHt(VFOV,AvgHtAG,Pitch):\n FarDist = AvgHtAG*math.sin(Pitch+(VFOV/2))\n if FarDist > (AvgHtAG*4.0):\n FarDist=AvgHtAG*4.0\n return (FarDist)" arcpy.AddMessage('Calculating FarDist') log.Message('Calculating FarDist', log.const_general_text) arcpy.CalculateField_management( 'lyr_selection', 'FarDist', "retAvgHt(!VFOV!,!AvgHtAG!,!CamPitch!)", "PYTHON3", farDistCodeBlock) chkFldList = arcpy.ListFields(oicpath, 'NearDist') if len(chkFldList) == 1: arcpy.AddMessage('Calculating NearDist') log.Message('Calculating NearDist', log.const_general_text) arcpy.CalculateField_management( 'lyr_selection', 'NearDist', "!AvgHtAG!*math.sin(!CamPitch!-(!VFOV!/2))", "PYTHON3") chkFldList = arcpy.ListFields(oicpath, 'CamOri') if len(chkFldList) == 1: camORiExp = "returnCO(+" + h_wkid + "," + v_wkid + ",!CameraX!,!CameraY!,!CameraZ!,!Omega!,!Phi!,!Kappa!,!ImageCols!,!ImageRows!," + ps_microns + ",!BalancedFL!,!PPx!,!PPy!,!BalancedK0!,!BalancedK1!,!BalancedK2!,!Units!)" camORICodeBlock = "def returnCO(WKID_H,WKID_V,X,Y,Z,O,P,K,cols,rows,psm,FL,ppx,ppy,K1,K2,K3,units):\n \n if 'feet' in units.lower():\n SC = 0.3048\n else:\n SC = 1 \n Z = Z*SC\n A0 = cols/2\n A1 = 1/psm\n A2 = 0\n B0 = rows/2\n B1 = 0\n B2 = A1\n PPAX = ppx*psm\n PPAY = ppx*psm\n \n camoristr = 'T|'+str(WKID_H)+'|'+str(WKID_V)+'|'+str(X)+'|'+str(Y)+'|'+str(Z)+'|'+str(O)+'|'+str(P)+'|'+str(K)+'|'+str(A0)+'|'+str(A1)+'|'+str(A2)+'|'+str(B0)+'|'+str(B1)+'|'+str(B2)+'|'+str(FL)+'|'+str(PPAX)+'|'+str(PPAY)+'|'+str(K1)+'|'+str(K2)+'|'+str(K3)\n return(camoristr) " arcpy.AddMessage('Calculating Camera Orientation Parameters') log.Message('Calculating Camera Orientation Parameters', log.const_general_text) arcpy.CalculateField_management('lyr_selection', 'CamOri', camORiExp, "PYTHON3", camORICodeBlock) arcpy.AddMessage('Cleaning up Oriented Imagery Catalog') log.Message('Cleaning up Oriented Imagery Catalog', log.const_general_text) arcpy.DeleteField_management(oicpath, inChkFldsList) return ("Completed.") except Exception as e: if log: log.Message("Error in type pictometry. {}".format(str(e)), log.const_critical_text) return ("Error in type pictometry. {}".format(str(e)))
def createSegments(contour_at_mean_high_water, contour_at_surge): # Start a timer time1 = time.clock() arcpy.AddMessage("\nSegmentation of the coastline started at "+str(datetime.now())) # Specify a tolerance distance or minimum length of a seawall # Users are not yet given control of this th = 150 # Create random points along the lines (mean high water and the surge of choice) # The numbers used are just my choice based on iterative observations random0 = arcpy.CreateRandomPoints_management(out_path= arcpy.env.workspace, \ out_name= "random0", \ constraining_feature_class= contour_at_mean_high_water, \ number_of_points_or_field= long(1600), \ minimum_allowed_distance = "{0} Feet".format(th)) random1 = arcpy.CreateRandomPoints_management(out_path= arcpy.env.workspace, \ out_name= "random1", \ constraining_feature_class= contour_at_surge, \ number_of_points_or_field= long(1600), \ minimum_allowed_distance = "{0} Feet".format(th)) # Perform a proximity analysis with the NEAR tool arcpy.Near_analysis(random0, random1) # Give each point a fixed unique ID # Create the ID field arcpy.AddField_management (random0, "UniqueID", "SHORT") arcpy.AddField_management (random1, "UniqueID", "SHORT") # Add Unique IDs arcpy.CalculateField_management(random0, "UniqueID", "[FID]") arcpy.CalculateField_management(random1, "UniqueID", "[FID]") # Categorize/Separate each feature based on their near feature # Crate a table view of random0 table0 = arcpy.MakeTableView_management(random0, "random0_table") #table1 = arcpy.MakeTableView_management(random1, "random1_table") # Sort the near feature for each points in random0 random0_sorted = arcpy.Sort_management(table0, "random0_sorte.dbf", [["NEAR_FID", "ASCENDING"]]) # Create "long enough" lists for each of the field of interests: ID, NEAR_ID, and NEAR_DIST # (distance to closest point). I added [99999] here to extend the list length and avoid IndexError list_fid = [r.getValue("UniqueID") for r in arcpy.SearchCursor(random0_sorted, ["UniqueID"])] +[99999] list_nearid = [r.getValue("NEAR_FID") for r in arcpy.SearchCursor(random0_sorted, ["NEAR_FID"])]\ +[99999] list_neardist = [r.getValue("NEAR_DIST") for r in arcpy.SearchCursor(random0_sorted, ["NEAR_DIST"])]\ +[99999] del r # Only take points with near feature within the specified threshold. If it's too far, it's not better # than the others for a segment point list_fid_filtered = [i for i in list_neardist if i < th] # Then initiate a list o contain their Unique ID and Near ID first_unique_id = [] first_near_id = [] # Get NEAR_ID and Unique ID for each of these points for i in list_fid_filtered: first_unique_id.append(list_fid[list_neardist.index(i)]) first_near_id.append(list_nearid[list_neardist.index(i)]) # Only take the unique values in case there are duplicates. This shoudn't happen. Just to make sure. first_unique_id = [i for i in set(first_unique_id)] first_near_id = [i for i in set(first_near_id)] # Now create a new feature out of these points # Frist let's create a Feature Layer arcpy.MakeFeatureLayer_management("random0.shp", "random0_lyr") # Let's select all points and export them into a new feature random0_points = arcpy.SearchCursor(random0, ["UniqueID"]) point0 = random0_points.next() for point0 in random0_points: for i in range(len(first_unique_id)): if point0.getValue("UniqueID") == first_unique_id[i]: selector0 = arcpy.SelectLayerByAttribute_management(\ "random0_lyr", "ADD_TO_SELECTION", '"UniqueID" = {0}'.format(first_unique_id[i])) del point0, random0_points new_random0 = arcpy.CopyFeatures_management(selector0, "new_random0") arcpy.Delete_management('random0_lyr') # Now for the new point feature, remove clusters of points around them and take only the ones # with minimum NEAR_DIST # First, get the geometry attributes of the new points arcpy.AddGeometryAttributes_management(new_random0, "POINT_X_Y_Z_M", "", "", "") # Create long enough list of the field of interest (same as the previous) pointx = [r.getValue("POINT_X") for r in arcpy.SearchCursor(new_random0, ["POINT_X"])] +[99999] pointy = [r.getValue("POINT_Y") for r in arcpy.SearchCursor(new_random0, ["POINT_Y"])] +[99999] new_list_fid = [r.getValue("UniqueID") for r in arcpy.SearchCursor(new_random0, ["UniqueID"])]\ +[99999] new_list_nearid = [r.getValue("NEAR_FID") for r in arcpy.SearchCursor(new_random0, ["NEAR_FID"])]\ +[99999] new_list_neardist = [r.getValue("NEAR_DIST") for r in arcpy.SearchCursor(new_random0, ["NEAR_DIST"])]\ +[99999] del r # Initiate a list of every points that has already been compared to the near points garbage = [] # Also initiate a list for the new Unique ID and NEAR ID new_unique_ID = [] new_near_ID = [] # Then, check if the points are right next to them. If so, add them to a temporary list # and find the one with closest near ID (or find minimum of their NEAR_DIST) for i in range(len(pointx)): if i+1 < len(pointx): # If not within the th range if not calculateDistance(pointx[i], pointy[i], pointx[i+1], pointy[i+1]) < float(th)*1.5: # Skip if it's in garbage if new_list_nearid[i] in garbage: continue else: new_unique_ID.append(new_list_fid[i]) new_near_ID.append(new_list_nearid[i]) # If within the range else: # Skip if it's in garbage if new_list_nearid[i] in garbage: continue else: temp_ID = [] temp_NEAR = [] temp_DIST = [] while True: temp_ID.append(new_list_fid[i]) temp_NEAR.append(new_list_nearid[i]) temp_DIST.append(new_list_neardist[i]) garbage.append(new_list_nearid[i]) i = i+1 # Stop when within the range again. And add the last point within the range if not calculateDistance(pointx[i], pointy[i], pointx[i+1], pointy[i+1]) < 200: temp_ID.append(new_list_fid[i]) temp_NEAR.append(new_list_nearid[i]) temp_DIST.append(new_list_neardist[i]) garbage.append(new_list_nearid[i]) # Calculate the minimum and get the Unique ID and Near ID minD = min(temp_DIST) new_unique_ID.append(new_list_fid[new_list_neardist.index(minD)]) new_near_ID.append(new_list_nearid[new_list_neardist.index(minD)]) del temp_ID, temp_NEAR, temp_DIST break # Now select these final points export them into new feature. # These are the end points for the segments to be created # First, make a layer out of all the random points arcpy.MakeFeatureLayer_management("random0.shp", "random0_lyr") arcpy.MakeFeatureLayer_management("random1.shp", "random1_lyr") # Then select and export the end points into feature0 and feature1 # Based on new_unique_ID for random0 random0_points = arcpy.SearchCursor(random0, ["UniqueID"]) point0 = random0_points.next() for point0 in random0_points: for i in range(len(new_unique_ID)): if point0.getValue("UniqueID") == new_unique_ID[i]: selected0 = arcpy.SelectLayerByAttribute_management(\ "random0_lyr", "ADD_TO_SELECTION", '"UniqueID" = {0}'.format(new_unique_ID[i])) feature0 = arcpy.CopyFeatures_management(selected0, "feature0") # Based on new_near_ID for random1 random1_points = arcpy.SearchCursor(random1, ["UniqueID"]) point1 = random1_points.next() for point1 in random1_points: for k in range(len(new_near_ID)): if point1.getValue("UniqueID") == new_near_ID[k]: selected1 = arcpy.SelectLayerByAttribute_management(\ "random1_lyr", "ADD_TO_SELECTION", '"UniqueID" = {0}'.format(new_near_ID[k])) feature1 = arcpy.CopyFeatures_management(selected1, "feature1") del point0, point1, random0_points, random1_points arcpy.Delete_management('random0_lyr') arcpy.Delete_management('random1_lyr') # Now for the actual create of the coastal segments # Which include creation of polygon and splitting the contours as the corresponding points # STEPS NECESSARY FOR POLYGON CREATION # Let's first add geometry attributes to these points arcpy.AddGeometryAttributes_management(feature0, "POINT_X_Y_Z_M", "", "", "") arcpy.AddGeometryAttributes_management(feature1, "POINT_X_Y_Z_M", "", "", "") # Let's create lines that connects points from feature0 to feature1 # Initiate a POLYLINE feature class for these lines arcpy.CreateFeatureclass_management (arcpy.env.workspace, "connector_lines.shp", "POLYLINE") # Then for each of the points in feature0, get the correspondingin feature1 # And create a line for each of the two points with arcpy.da.SearchCursor(feature0, ["NEAR_FID", "POINT_X", "POINT_Y"]) as features0: for feat0 in features0: with arcpy.da.SearchCursor(feature1, ["UniqueID", "POINT_X", "POINT_Y"]) as features1: x=0 for feat1 in features1: x = x+1 theseTwoPoints = [] if feat0[0] == feat1[0]: # Get coordinates X0, Y0 = feat0[1], feat0[2] X1, Y1 = feat1[1], feat1[2] # Append coordinates theseTwoPoints.append(arcpy.PointGeometry(arcpy.Point(X0, Y0))) theseTwoPoints.append(arcpy.PointGeometry(arcpy.Point(X1, Y1))) # Create line from the coordinates subline = arcpy.PointsToLine_management(theseTwoPoints, "subline"+str(x)+".shp") # Append all lines into one feature lines = arcpy.Append_management(["subline"+str(x)+".shp"], "connector_lines.shp") # Then delete subline as it's now unnecessary arcpy.Delete_management(subline) continue del feat0, feat1, features0, features1 # Now that the connectors are created, let's split the segments # Before splitting contours into segments, let's integrate the points and the segments # Just in case, there are misalignment arcpy.Integrate_management([contour_at_mean_high_water, feature0]) arcpy.Integrate_management([contour_at_surge, feature1]) segments0 = arcpy.SplitLineAtPoint_management(contour_at_mean_high_water, feature0, "segments0.shp", "10 Feet") segments1 = arcpy.SplitLineAtPoint_management(contour_at_surge, feature1, "segments1.shp", "10 Feet") # And let's give fixed unique ID for each segment arcpy.CalculateField_management(segments0, "Id", "[FID]") arcpy.CalculateField_management(segments1, "Id", "[FID]") # Now with the split segments and connector lines, let's make segment polygon of the segments almost_segment_polygons = arcpy.FeatureToPolygon_management([segments0, segments1, lines],\ "almost_segment_polygons.shp") # Adding unique ID to the segment polygons arcpy.CalculateField_management(almost_segment_polygons, "Id", "[FID]") # The Feature to Polygon process also created polygons that are surrounded by polygons # These are because these areas are surrounded by flooded areas at surge. # They are above the surge and technically safe. So, let's remove them. arcpy.MakeFeatureLayer_management(almost_segment_polygons, 'almost_segment_polygons_lyr') arcpy.MakeFeatureLayer_management(segments0, 'segments0_lyr') # Only the polygons within the mean_high_water segments are at risk arcpy.SelectLayerByLocation_management('almost_segment_polygons_lyr', 'INTERSECT', 'segments0_lyr') final_without_length = arcpy.CopyFeatures_management('almost_segment_polygons_lyr', 'final.shp') arcpy.Delete_management('segments0_lyr') arcpy.Delete_management('almost_segment_polygons_lyr') # For the new polygons, let's add the corresponding seawall length # Let's add Length field to both first arcpy.AddField_management(final_without_length, "Length", "SHORT") arcpy.AddField_management(segments0, "Length", "SHORT") # Calculation of the length with arcpy.da.UpdateCursor(segments0, ["SHAPE@LENGTH", "Length"]) as segments_0: for segment_0 in segments_0: length = segment_0[0] segment_0[1] = length segments_0.updateRow(segment_0) del segment_0, segments_0 # With spatial join, let's add these results to the segment polygons final = spatialJoin(final_without_length, segments0, "Length", "Length", "max", "joined_segment.shp") # Delete the created but now unnecessary files arcpy.Delete_management(random0) arcpy.Delete_management(random1) # Stop the timer time2 = time.clock() arcpy.AddMessage("Seawall segments and regions successfully created. It took "\ +str(time2-time1)+" seconds") return final
def __init__(self, name, country, point): self.name = name self.country = country self.point = arcpy.PointGeometry(arcpy.Point(point[0], point[1]))
def execute(self, parameters, messages): """The source code of the tool.""" distance = float(parameters[2].valueAsText) azi = float(parameters[3].valueAsText) report = parameters[4].valueAsText latit_sp = float(parameters[1].valueAsText) longit_sp = float(parameters[0].valueAsText) #Calculates Angular Distance ang_distance = distance / 6371 #Calculate the ending point latitude p1 = math.sin(math.radians(latit_sp)) * math.cos(ang_distance) p2 = math.cos( math.radians(latit_sp)) * math.sin(ang_distance) * math.cos( math.radians(azi)) lat_ep = math.degrees(math.asin(p1 + p2)) #Calculate the ending point longitude p3 = math.sin(math.radians(azi)) * math.sin(ang_distance) * math.cos( math.radians(latit_sp)) p4 = math.cos(ang_distance) - (math.sin(math.radians(latit_sp)) * math.sin(math.radians(lat_ep))) long_ep = longit_sp + math.degrees(math.atan2(p3, p4)) outshp = os.path.splitext(report)[0] + '.shp' point = arcpy.Point(latit_sp, longit_sp) end_point = arcpy.Point(lat_ep, long_ep) ptGeometry = arcpy.PointGeometry(point) ptGeometry2 = arcpy.PointGeometry(end_point) degree = int(latit_sp) r1 = 0 minutes = 0 seconds = 0 report_h = open(report, "w") report_h.write("SP_Lat_DD" + "\n" + latit_sp) # report_h.write("\nStarting Point Latitude: ") #report_h.write(str(getDegree(latit_sp)) + "? " + str(getMinute(latit_sp)) + " minutes " + str(getSecond(latit_sp)) + " seconds") report_h.write("SP_Lon_DD" + "\n" + longit_sp) # report_h.write("\nStarting Point Longitude: ") report_h.write( str(getDegree(longit_sp)) + "? " + str(getMinute(longit_sp)) + " minutes " + str(getSecond(longit_sp)) + " seconds") report_h.write("\nYour Range in Kilometers: " + str(distance)) report_h.write("\nYour Range in Nautical Miles: " + str(distance * 0.539957)) report_h.write("\nYour Range in Miles: " + str(distance * 0.621371)) report_h.write("\nYour Range in Yards: " + str(distance * 1093.61)) report_h.write("\nYour Range in Feet: " + str(distance * 3280.84)) report_h.write("\nYour Range in Meters: " + str(distance * 1000)) report_h.write("\nYour Azimuth in Degrees: " + str(azi)) report_h.write("\nEnding Point Latitude: " + str(lat_ep)) report_h.write("\nEnding Point Latitude: ") report_h.write( str(getDegree(lat_ep)) + "? " + str(getMinute(lat_ep)) + " minutes " + str(getSecond(lat_ep)) + " seconds") report_h.write("\nEnding Point Latitude: " + str(long_ep)) report_h.write("\nEnding Point Longitude: ") report_h.write( str(getDegree(long_ep)) + "? " + str(getMinute(long_ep)) + " minutes " + str(getSecond(long_ep)) + " seconds") report_h.close() return
arcpy.mapping.AddLayerToGroup(DF, grplyr, lyr4, "BOTTOM") #---------------------------------------------------------- arcpy.RefreshActiveView() arcpy.RefreshTOC() else: arcpy.AddWarning( "- er liggen geen profielen op het betreffende vak!") #---------------------------------------------------------- # Als laatste dichtsbijzijnde HRD locatie opzoeken tov middelpunt van het vak. # XY middelpunt vak bepalen. arcpy.AddMessage( "--------------------------\nDichtsbijzijnde HRD opzoeken...") feat = row[4] x = feat.positionAlongLine(0.5, True).firstPoint.X y = feat.positionAlongLine(0.5, True).firstPoint.Y midP = arcpy.PointGeometry(arcpy.Point(x, y), spatial_ref) # Nu een near met dit punt tov de HRD locaties naam = '' afst = 100000 for hr in HRDpntLijst: dist = midP.distanceTo(hr[1]) if (dist < afst): afst = dist naam = hr[2] arcpy.AddMessage("HRD: " + naam + " afstand: " + str(round(afst, 2)) + "m") row[5] = naam #---------------------------------------------------------- # Nu statistics opzoeken in array en toevoegen aan het vak. arcpy.AddMessage("\nStatistieken van het vak bepalen...") for st in StatsLijst:
#print (tagID,obsDate,obsTime,obsLC,"Lat:"+obsLat,"Long:"+obsLon) #Create a point object obsPoint = arcpy.Point() obsPoint.X = obsLon obsPoint.Y = obsLat #Handle any error except Exception as e: pass #error_count += 1 #print(f"Error adding record {tagID} to the output") #Convert the point to a point geometry object with spatial reference inputSR = arcpy.SpatialReference(4326) obsPointGeom = arcpy.PointGeometry(obsPoint, inputSR) #Add a feature using our insert cursor feature = cur.insertRow( (obsPointGeom, tagID, obsLC, obsDate.replace(".", "/") + " " + obsTime)) #increment the total counter #total_counter += 1 # Move to the next line so the while loop progresses lineString = inputFileObj.readline() #Close the file object inputFileObj.close()
location_type = stop[8] parent_station = stop[9] wheelchair_boarding = unicode(stop[10]) if location_type == 1 and stop_id not in used_parent_stations: # Skip this stop because it's an unused parent station # since these will just make useless standalone junctions. continue if location_type == 2 and parent_station not in used_parent_stations: # Remove station entrances that don't have a valid parent_station # since these serve no purpose continue pt = arcpy.Point() pt.X = float(stop_lon) pt.Y = float(stop_lat) # GTFS stop lat/lon is written in WGS1984 ptGeometry = arcpy.PointGeometry(pt, WGSCoords) # But the stops fc must be in the user's FD coordinate system ptGeometry_projected = ptGeometry.projectAs(outFD_SR) stoplatlon_dict[stop_id] = ptGeometry_projected cur3.insertRow( (ptGeometry_projected, stop_id, stop_code, stop_name, stop_desc, zone_id, stop_url, location_type, parent_station, wheelchair_boarding)) # ----- Obtain schedule info from the stop_times.txt file and convert it to a line-based model ----- arcpy.AddMessage( "Obtaining and processing transit schedule and line information...") arcpy.AddMessage("(This will take a few minutes for large datasets.)") # If there are multiple GTFS datasets, handle each one separately to keep memory usage as low as possible
scircle = (cperimeter / perimeter) pointList = [] #calculate circle buf = row[1].buffer(0.01) for part in buf: for coord in part: try: pointList.append((coord.X, coord.Y)) except: print "Bad Point" c = SEC.make_circle(pointList) print c circlearea = math.pi * c[2] * c[2] ccircle = area / circlearea print ptoa, shapeindex, scircle, ccircle cp = arcpy.PointGeometry(arcpy.Point(c[0],c[1])) polygonbuf = row[1].buffer(100) row[1] = polygonbuf.difference(row[1]) row[2] = ptoa row[3] = shapeindex row[4] = ccircle row[5] = scircle cursor.updateRow(row)