def run_viewshed(processs_list): #arg = ProcessList.split(',') #in_fc = arg[0] in_fc = processs_list out_gdb = r'C:\Users\greg6750\Documents\IPython Notebooks\Advanced_Python_for_GIS_and_RS\Week 13\results.gdb' dem = r'C:\Users\greg6750\Downloads\USGS_NED_13_n48w122_ArcGrid\grdn48w122_13' out_fc = os.path.join(out_gdb, in_fc[-5:] + '_' + uuid.uuid4().hex) print(out_fc) arcpy.Viewshed_3d(dem, in_fc, out_fc)
count += 1 print(row[1]) PointNameList.append(row[1]) arcpy.env.overwriteOutput = True env.workspace = scratchGDB filenameList = [] for n in PointNameList: filename = n.replace(" ", "_").replace(".", "_").replace(",", "_") print("**********************\n", filename) outfc = os.path.join(scratchGDB, filename) where_clause = '"RES_NAME" = \'%s\'' % n arcpy.Select_analysis(PointLayer, outfc, where_clause) viewshed_RasterFC = 'ViewshedRaster_' + filename print("Running ViewShed Analysis") arcpy.Viewshed_3d(DEM, outfc, viewshed_RasterFC) print("Running Raster to Polygon") viewshed_PolyFC = 'ViewshedPoly_' + filename arcpy.RasterToPolygon_conversion(viewshed_RasterFC, viewshed_PolyFC, "SIMPLIFY", "Value", "MULTIPLE_OUTER_PART") print("Extract viewshed polygons") positive_viewshed = "PositiveViewshed_" + filename where_clause = '"gridcode" = 1' arcpy.Select_analysis(viewshed_PolyFC, positive_viewshed, where_clause) filenameList.append(os.path.join(scratchGDB, positive_viewshed)) print("Adding SITE_ID field, calculating values") arcpy.AddField_management(positive_viewshed, "SITE_ID", "TEXT", field_length=50)
def createViewshed(inputObserverPoints, elevationRaster, outerRadiusInput, \ leftAzimuthInput, rightAzimuthInput, observerOffsetInput, \ innerRadiusInput, viewshed, sectorWedge, fullWedge): # Error Checking: if arcpy.CheckExtension("3D") != "Available": arcpy.AddError("3D license is not available.") return if not arcpy.Exists(inputObserverPoints): arcpy.AddError('Dataset does not exist: ' + str(inputObserverPoints)) return if not arcpy.Exists(elevationRaster): arcpy.AddError('Dataset does not exist: ' + str(elevationRaster)) return inputPointsCount = int( arcpy.GetCount_management(inputObserverPoints).getOutput(0)) if inputPointsCount == 0: arcpy.AddError('No features in input feature set: ' + str(inputObserverPoints)) return elevDesc = arcpy.Describe(elevationRaster) elevationSR = elevDesc.spatialReference if not elevationSR.type == "Projected": msgErrorNonProjectedSurface = \ "Error: Input elevation raster must be in a projected coordinate system. Existing elevation raster is in {0}.".format(elevationSR.name) arcpy.AddError(msgErrorNonProjectedSurface) return # Done error checking, do processing: arcpy.env.outputCoordinateSystem = elevationSR donutWedges = [] pieWedges = [] tempObserverPoints = r"in_memory\tempPoints" copyFeaturesAndProject(inputObserverPoints, tempObserverPoints, elevationSR) # Check if points falls within surface extent isWithin = surfaceContainsPoints(tempObserverPoints, elevationRaster) if not isWithin: msgErrorPointNotInSurface = \ "Error: Input Observer(s) does not fall within the extent of the input surface: {0}!".format(os.path.basename(elevationRaster)) arcpy.AddError(msgErrorPointNotInSurface) return addViewshedFields(tempObserverPoints, innerRadiusInput, outerRadiusInput, \ leftAzimuthInput, rightAzimuthInput, observerOffsetInput, \ 0) # Set Target Height to 0 arcpy.AddMessage("Buffering observers...") arcpy.Buffer_analysis(tempObserverPoints, \ r"in_memory\OuterBuffer", "RADIUS2", "FULL", "ROUND", "NONE", "", "GEODESIC") desc = arcpy.Describe(r"in_memory\OuterBuffer") xMin = desc.Extent.XMin yMin = desc.Extent.YMin xMax = desc.Extent.XMax yMax = desc.Extent.YMax Extent = str(xMin) + " " + str(yMin) + " " + str(xMax) + " " + str(yMax) arcpy.env.extent = Extent # TODO: investigate why this doesn't work in ArcGIS Pro (setting mask to in_memory or %scatchGDB%) # This output is clipped to the wedge below, so not entirely necessary if arcpy.GetInstallInfo()['ProductName'] != 'ArcGISPro': arcpy.env.mask = r"in_memory\OutBuffer" arcpy.AddMessage("Clipping image to observer buffer...") arcpy.Clip_management(elevationRaster, Extent, r"in_memory\clip") arcpy.AddMessage("Calculating viewshed...") arcpy.Viewshed_3d("in_memory\clip", tempObserverPoints, r"in_memory\intervis", "1", "FLAT_EARTH", "0.13") arcpy.AddMessage("Creating features from raster...") arcpy.RasterToPolygon_conversion( in_raster=r"in_memory\intervis", out_polygon_features=r"in_memory\unclipped", simplify="NO_SIMPLIFY") fields = ["SHAPE@XY", "RADIUS1", "RADIUS2", "AZIMUTH1", "AZIMUTH2"] ## get the attributes from the input point with arcpy.da.SearchCursor(tempObserverPoints, fields) as cursor: for row in cursor: centerX = row[0][0] centerY = row[0][1] radiusInner = row[1] radiusOuter = row[2] startBearing = row[3] endBearing = row[4] # TODO/IMPORTANT: radius must be in map units donutWedge = drawWedge(centerX, centerY, radiusInner, radiusOuter, startBearing, endBearing) donutWedges.append(donutWedge) pieWedge = drawWedge(centerX, centerY, 0, radiusOuter, startBearing, endBearing) pieWedges.append(pieWedge) arcpy.CopyFeatures_management(donutWedges, sectorWedge) arcpy.CopyFeatures_management(pieWedges, fullWedge) arcpy.AddMessage("Finishing output features...") arcpy.Clip_analysis(r"in_memory\unclipped", sectorWedge, r"in_memory\dissolve") arcpy.Dissolve_management(r"in_memory\dissolve", viewshed, "gridcode", "", "MULTI_PART", "DISSOLVE_LINES") # Output Symbol layer requires the field to be "VISIBILITY" arcpy.AddField_management(viewshed, "VISIBILITY", "LONG") arcpy.CalculateField_management(viewshed, "VISIBILITY", '!gridcode!', "PYTHON_9.3")
def main(): elevDesc = arcpy.Describe(elevation) Output_CS = elevDesc.spatialReference if not Output_CS.type == "Projected": msgErrorNonProjectedSurface = "Error: Input elevation raster must be in a projected coordinate system. Existing elevation raster is in {0}.".format(Output_CS.name) arcpy.AddError(msgErrorNonProjectedSurface) raise Exception(msgErrorNonProjectedSurface) arcpy.env.outputCoordinateSystem = Output_CS polylist = [] wedges = [] #### ########End of Script Parameters################## #### Point_Input = "in_memory\\tempPoints" arcpy.CopyFeatures_management(inputPoints, Point_Input) #Check if point extent falls within surface extent isWithin = surfaceContainsPoint(Point_Input, elevation) if not isWithin: msgErrorPointNotInSurface = "Error: Input Observer(s) does not fall within the extent of the input surface: {0}!".format(os.path.basename(elevation)) arcpy.AddError(msgErrorPointNotInSurface) raise Exception(msgErrorPointNotInSurface) arcpy.CalculateField_management(Point_Input, "OFFSETB", "0", "PYTHON_9.3", "") arcpy.CalculateField_management(Point_Input, "RADIUS2", Radius2_Input, "PYTHON_9.3", "") arcpy.CalculateField_management(Point_Input, "AZIMUTH1", Azimuth1_Input, "PYTHON_9.3", "") arcpy.CalculateField_management(Point_Input, "AZIMUTH2", Azimuth2_Input, "PYTHON_9.3", "") arcpy.CalculateField_management(Point_Input, "OFFSETA", OffsetA_Input, "PYTHON_9.3", "") arcpy.CalculateField_management(Point_Input, "RADIUS1", Radius1_Input, "PYTHON_9.3", "") arcpy.AddMessage("Buffering observers...") arcpy.Buffer_analysis(Point_Input, "in_memory\OuterBuffer", "RADIUS2", "FULL", "ROUND", "NONE", "", "GEODESIC") desc = arcpy.Describe("in_memory\OuterBuffer") xMin = desc.Extent.XMin yMin = desc.Extent.YMin xMax = desc.Extent.XMax yMax = desc.Extent.YMax Extent = str(xMin) + " " + str(yMin) + " " + str(xMax) + " " + str(yMax) # Call image service a second time to get corrected extents arcpy.env.extent = Extent arcpy.env.mask = "in_memory\\OutBuffer" arcpy.AddMessage("Clipping image to observer buffer...") # arcpy.MakeImageServerLayer_management(elevation, "elevation", Extent, "#", "#", "#", "#", "#", elevDesc.meanCellWidth) arcpy.Clip_management(elevation, Extent, "in_memory\clip") arcpy.AddMessage("Calculating viewshed...") arcpy.Viewshed_3d("in_memory\clip", Point_Input, "in_memory\intervis", "1", "FLAT_EARTH", "0.13") arcpy.AddMessage("Creating features from raster...") arcpy.RasterToPolygon_conversion(in_raster="in_memory\intervis", out_polygon_features="in_memory\unclipped",simplify="NO_SIMPLIFY") fields = ["SHAPE@XY","RADIUS1","RADIUS2","AZIMUTH1","AZIMUTH2"] ## get the attributes from the input point with arcpy.da.SearchCursor(Point_Input,fields) as cursor: for row in cursor: cx = row[0][0] cy = row[0][1] r1 = row[1] r2 = row[2] start = math.radians(90 - row[3]) if row[3] > row[4]: end = row[4] + 360 end = math.radians(90 - end) else: end = math.radians(90 - row[4]) poly = drawWedge(cx,cy,r1,r2,start,end) polylist.append(poly) fullWedge = drawWedge(cx,cy,0,r2,start,end) wedges.append(fullWedge) arcpy.CopyFeatures_management(polylist,wedge) arcpy.CopyFeatures_management(wedges,fullwedge) arcpy.AddMessage("Finishing output features...") arcpy.Clip_analysis("in_memory\unclipped", wedge, "in_memory\\dissolve") arcpy.Dissolve_management("in_memory\\dissolve", viewshed, "gridcode", "", "MULTI_PART", "DISSOLVE_LINES")
def DegViewshed (FLOOR, HEIGHT): """Calculates a parcels viewshed, in degrees""" #Select Record arcpy.SelectLayerByAttribute_management(PointsFL,"NEW_SELECTION",SQL) #Set Observer Height (OffSETA) arcpy.CalculateField_management(PointsFL,"OFFSETA",HEIGHT,"PYTHON_9.3") #perform viewshed analysis arcpy.SetProgressorLabel("Performing Viewshed Analysis for point "+str(value)) outViewshed = IntermediateFiles+"\\vs_"+str(FLOOR)+"_"+str(value).split(".")[0] arcpy.Viewshed_3d(outCon,PointsFL,outViewshed) #convert viewshed to polygon arcpy.SetProgressorLabel("Converting viewshed"+str(value)+" on floor "+str(FLOOR)+" to polygon.") OutPoly = IntermediateFiles+"\\"+os.path.basename(outViewshed).split(".")[0]+"_poly.shp" arcpy.RasterToPolygon_conversion(outViewshed,OutPoly) #Intersect viewshed polygon with buffer clip #This will allow the viewshed poly to inherit attribute fields needed for later analysis FinalView = Final_Floor_Viewsheds+"\\FinalViewshed_"+str(FLOOR)+"_"+str(value)+".shp" arcpy.Intersect_analysis([BufferClip,OutPoly],FinalView) #Select features in viewshed polygon with Gridcode = 1 #If no records with grid = 1 exist, scriptwill skip to setting viewshed in degrees to 0 #Convert viewshed polygon to layer ViewshedLayer = outName(FinalView,"lyr") arcpy.MakeFeatureLayer_management(FinalView,ViewshedLayer) #Select records with gridcode = 1 arcpy.SelectLayerByAttribute_management(ViewshedLayer,"NEW_SELECTION","GRIDCODE ="+str(1)+"") #Get count of the # of records selected in viewshed poly layer VsLyrCount = int(arcpy.GetCount_management(ViewshedLayer).getOutput(0)) NoView = SummaryTables+"\\summary_"+str(FLOOR)+"_"+str(value)+".dbf" YesView = SummaryTables+"\\summary_"+str(FLOOR)+"_"+str(value)+".dbf" StatsField0 = [["GRIDCODE","SUM"]] CaseField0 = ["ID","SPOT",FloorField] StatsField1 = [["LENGTH","SUM"]] CaseField1 = ["GRIDCODE","ID","SPOT",FloorField] VsArcLengths = ArcLengths+"\\ArcLength_"+str(FLOOR)+"_"+str(value)+".shp" if VsLyrCount == 0: #no viewable areas exist arcpy.SelectLayerByAttribute_management(ViewshedLayer,"CLEAR_SELECTION") arcpy.SetProgressorLabel("Calculating viewshed statistics for parcel "+str(value)) arcpy.Statistics_analysis(ViewshedLayer,NoView, StatsField0,CaseField0) #Add field to summary table to hold viewshed value of 0 #Add field to note which floor viewshed corresponds to arcpy.AddField_management(NoView, "FLR_RAN","SHORT") arcpy.AddField_management(NoView, "VIEW_"+Year,"DOUBLE") arcpy.AddField_management(NoView,"OFFSETA","SHORT") arcpy.CalculateField_management(NoView,"FLR_RAN",FLOOR) arcpy.CalculateField_management(NoView,"VIEW_"+Year,0) arcpy.CalculateField_management(NoView,"OFFSETA",HEIGHT) else: #Calculate viewshed, in degrees, for selected records arcpy.SetProgressorLabel("Getting arc length for parcel"+str(value)+" at the "+str(FLOOR)+" floor.") arcpy.Intersect_analysis([BufferLine,ViewshedLayer],VsArcLengths,"",10,"LINE")#Intersect with any line within 10 ft. arcpy.AddField_management(VsArcLengths, "Length","DOUBLE") arcpy.CalculateField_management(VsArcLengths,"Length","!SHAPE.length@miles!","PYTHON_9.3") arcpy.Statistics_analysis(VsArcLengths,YesView,StatsField1,CaseField1) #Add fields to output summary table arcpy.AddField_management(YesView,"FLR_RAN","SHORT") arcpy.AddField_management(YesView,"VIEW_"+Year,"DOUBLE") arcpy.AddField_management(YesView,"OFFSETA","SHORT") arcpy.CalculateField_management(YesView,"FLR_RAN",FLOOR) arcpy.CalculateField_management(YesView,"OFFSETA",HEIGHT) arcpy.CalculateField_management(YesView,"VIEW_"+Year,"((!SUM_LENGTH!/3.14)*180)","PYTHON_9.3") arcpy.SelectLayerByAttribute_management(ViewshedLayer,"CLEAR_SELECTION")
arcpy.env.extent = dem_20k arcpy.env.snapRaster = dem_20k arcpy.env.outputCoordinateSystem = dem_20k arcpy.env.overwriteOutput = True print "processing: " + output_dir for row in arcpy.da.SearchCursor(points_20k, ["SHAPE@", "FID"]): # Print x,y coordinates of each point feature # pnt_obj = row[0] #dist=row[1] fid = row[1] if fid >= 145 and fid < 146: start_time = time.time() fname = str(fid) + '.shp' pnt = arcpy.CreateFeatureclass_management( point_dir, fname, "POINT", "D:/oceanview/other_data/sea_point.shp", "", "", dem_20k) arcpy.AddField_management(pnt, "Dist_Coast", "FLOAT") cursor = arcpy.da.InsertCursor(pnt, ["SHAPE@"]) cursor.insertRow([pnt_obj]) viewshed_output = output_dir + "view" + str(fid) arcpy.Viewshed_3d(dem_20k, pnt, viewshed_output, "", "CURVED_EARTH") #arcpy.Delete_management(output_dir+"view"+str(fid)) print "processing time for " + str(fid) + "th point is " + str( time.time() - start_time)