def __CreateISLayer__(self, service): try: arcpy.AddMessage("Creating image service layer...") outislyr=os.path.join("in_memory",'ras_dsm') arcpy.AddMessage("image service layer: " + outislyr) arcpy.MakeImageServerLayer_management(service, outislyr, self.buffer, "", "CLOSEST_TO_CENTER", "", "", "", self.cellsize) return outislyr except arcpy.ExecuteError: EH = ErrorHandling.ErrorHandling() line, filename, err = EH.trace() m = "Python error on " + line + " of " + __file__ + \ " : with error - " + err arcpy.AddError(m)
def __CreateISLayer__(self, service): try: arcpy.AddMessage("Creating image service layer...") outislyr = os.path.join("in_memory", 'ras_dsm') #outislyr2 = os.path.join(r"C:\GEE\visibility", "outislyr2") arcpy.AddMessage("image service layer: " + outislyr) arcpy.MakeImageServerLayer_management(service, outislyr, self.buffer, "", "CLOSEST_TO_CENTER", "", "", "") #filteredraster = sa.FocalStatistics(outislyr, "", "MEAN", "") #newraster = Raster(outislyr) #newraster.save(outislyr2) #return filteredraster return outislyr except arcpy.ExecuteError: EH = ErrorHandling.ErrorHandling() line, filename, err = EH.trace() m = "Python error on " + line + " of " + __file__ + \ " : with error - " + err arcpy.AddError(m)
def RunTest(): try: arcpy.AddMessage("Starting Test: TestLocalPeaks") #TEST_IMPLEMENTED = False # #if not TEST_IMPLEMENTED : # arcpy.AddWarning("***Test Not Yet Implemented***") # return # TODO: once model has a version that works with local surface data # (rather than image service), then finish this test/implementation below # # alternately you can add an image service connection in Catalog and # fill in the parameter below if arcpy.CheckExtension("Spatial") == "Available": print("Checking out Spatial Analyst license...") arcpy.CheckOutExtension("Spatial") else: # Raise a custom exception raise Exception("LicenseError") if arcpy.CheckExtension("3D") == "Available": print("Checking out 3D Analyst license...") arcpy.CheckOutExtension("3D") else: raise Exception("LicenseError") try: print("Getting Advanced license...") import arcinfo except ImportError: print("Could not use ArcGIS Advanced license...") raise Exception arcpy.env.overwriteOutput = True arcpy.env.scratchWorkspace = TestUtilities.scratchGDB # WORKAROUND print("Creating New Scratch Workspace (Workaround)") TestUtilities.createScratch() # Getting inputs print("Getting inputs...") print("inputPolygonFC...") inputPolygonFC = os.path.join(TestUtilities.inputGDB, "samplePolygonArea") print("inputSurface...") inputSurface = TestUtilities.inputElevationURL print("outputPointsFC") outputPointsFC = os.path.join(TestUtilities.outputGDB, "LocalPeaks") print("ImportToolbox--MAoT...") arcpy.ImportToolbox(TestUtilities.toolbox, "MAoT") # mf - these have been tested # # Check For Valid Input # print("Checking valid inputs...") # objects2Check = [] # #objects2Check.extend([inputPolygonFC, inputSurface, toolbox]) # objects2Check.extend([inputPolygonFC, toolbox]) # for object2Check in objects2Check : # desc = arcpy.Describe(object2Check) # if desc == None : # raise Exception("Bad Input") # else : # print("Valid Object: " + desc.Name) # Set environment settings print("Running from: " + str(TestUtilities.currentPath)) print("Geodatabase path: " + str(TestUtilities.geodatabasePath)) inputFeatureCount = int( arcpy.GetCount_management(inputPolygonFC).getOutput(0)) print("Input FeatureClass: " + str(inputPolygonFC)) print("Input Feature Count: " + str(inputFeatureCount)) # if (inputFeatureCount < 1): # print("Invalid Input Polygon Feature Count: " + str(inputFeatureCount)) # Convert input elevation service to local dataset surface print("Converting input image service into a local raster surface") polygonExtent = arcpy.Describe(inputPolygonFC).extent print("Using extent: " + str(polygonExtent)) cellSize = CellSize(inputPolygonFC) print("Using cell size: " + str(cellSize)) localSurf = None srWGS84 = arcpy.SpatialReference(4326) # GCS_WGS_1984 srWebMerc = arcpy.SpatialReference( 3857) #Web_Mercator_Auxiliary_Sphere print("Reworking inputs from image service...") try: tempClipExtent = os.path.join(TestUtilities.scratchGDB, "tempClipExtent") localSurf = os.path.join(TestUtilities.scratchGDB, "localSurf") print(" projecting input clip to WGS 1984 to match service...") arcpy.Project_management(inputPolygonFC, tempClipExtent, srWGS84) tempCellSize = CellSize(tempClipExtent) #MakeImageServerLayer_management (in_image_service, out_imageserver_layer, {template}, #{band_index}, {mosaic_method}, {order_field}, #{order_base_value}, {lock_rasterid}, {cell_size}, #{where_clause}, {processing_template}) print(" getting image service layer with cell size " + str(tempCellSize) + "...") arcpy.MakeImageServerLayer_management(inputSurface, "inputSurface", tempClipExtent, "#", "#", "#", "#", "#", tempCellSize) print( " projecting image service layer to match target data...") arcpy.ProjectRaster_management("inputSurface", localSurf, srWebMerc) #arcpy.CopyRaster_management("inputSurface", localSurf) except arcpy.ExecuteError: print("Error converting image service...") msgs = arcpy.GetMessages() print(msgs) sys.exit(-1) numberOfPeaks = 3 ######################################################## # Execute the Model under test: arcpy.FindLocalPeaks_MAoT(inputPolygonFC, numberOfPeaks, localSurf, outputPointsFC) ######################################################## # Verify the results outputFeatureCount = int( arcpy.GetCount_management(outputPointsFC).getOutput(0)) print("Output FeatureClass: " + str(outputPointsFC)) print("Output Feature Count: " + str(outputFeatureCount)) if (outputPointsFC < 3): print("Invalid Output Feature Count: " + str(outputFeatureCount)) raise Exception("Test Failed") # WORKAROUND: delete scratch db print("Deleting Scratch Workspace (Workaround)") TestUtilities.deleteScratch() print("Test Successful") except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) # return a system error code sys.exit(-1) except Exception as e: # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str( sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n" # Return python error messages for use in script tool or Python Window arcpy.AddError(pymsg) arcpy.AddError(msgs) # return a system error code sys.exit(-1) finally: # Check in the 3D Analyst extension arcpy.CheckInExtension("Spatial") arcpy.CheckInExtension("3D")
def step1_get_dem_landuse(inUsername, inPassword, outGDB, wshedBoundary, bufferDi, outCS): """ :param inUsername: ArcGIS online Username :param inPassword: ArcGIS online password :param outGDB: geodatabase (or directory) where the downlaoded files will be saved :param wshedBoundary: polygon shapefile for which the DEM and landuse will be donwloaded :param bufferDi: Buffer distance in meters to download DEM and landuse. Serves as factor of safety :return: downloads and saves the DEM and landuse rasters. Also, projects them to a UTM zone 12 (for now) CS """ # defaulted, to make things easier if inUsername == "": inUsername = "******" if inPassword == "": inPassword = "******" if bufferDi == "": bufferDi = 100 # Set workspace environment arcpy.env.workspace = arcpy.env.scratchWorkspace = outGDB # = arcpy.env.scratchWorkspace arcpy.env.overwriteOutput = True # If no projection defined, assume the area is in Northen Utah, i.e. UTM 12N if outCS == "": outCS = arcpy.SpatialReference( "North America Albers Equal Area Conic" ) #arcpy.SpatialReference("WGS 1984 UTM Zone 12N") arcpy.env.outputCoordinateSystem = outCS arcpy.env.overwriteOutput = True arcpy.FeatureClassToFeatureClass_conversion(wshedBoundary, outGDB, "Boundary") arcpy.MakeFeatureLayer_management("Boundary", "Boundary") # Buffer arcpy.Buffer_analysis("Boundary", "Buffer", "%s Meters" % bufferDi, "FULL", "ROUND", "NONE", "", "PLANAR") # Connect to ArcGIS Servers out_folder_path = 'GIS Servers' out_landscape = 'Landscape.ags' server_landscape = 'https://landscape5.arcgis.com:443/arcgis/services/' out_elevation = 'Elevation.ags' server_elevation = 'https://elevation.arcgis.com:443/arcgis/services/' arcpy.mapping.CreateGISServerConnectionFile("USE_GIS_SERVICES", out_folder_path, out_landscape, server_landscape, "ARCGIS_SERVER", username=inUsername, password=inPassword, save_username_password=True) arcpy.mapping.CreateGISServerConnectionFile("USE_GIS_SERVICES", out_folder_path, out_elevation, server_elevation, "ARCGIS_SERVER", username=inUsername, password=inPassword, save_username_password=True) # Extract Image Server Data """ Land Use """ NLCD_ImageServer = "GIS Servers\\Landscape\\USA_NLCD_2011.ImageServer" arcpy.MakeImageServerLayer_management(NLCD_ImageServer, "NLCD_Layer") arcpy.gp.ExtractByMask_sa("NLCD_Layer", "Buffer", "Land_Use") """ Percent Impervious """ Imp_ImageServer = "GIS Servers\\Landscape\\USA_NLCD_Impervious_2011.ImageServer" arcpy.MakeImageServerLayer_management(Imp_ImageServer, "Impervious_Layer") arcpy.gp.ExtractByMask_sa("Impervious_Layer", "Buffer", "Impervious") # """ Soils HSG, USDA """ # Soils_ImageServer = "GIS Servers\\Landscape\\USA_Soils_Hydrologic_Group.ImageServer" # arcpy.MakeImageServerLayer_management(Soils_ImageServer, "Soils_Layer") # arcpy.gp.ExtractByMask_sa("Soils_Layer", "Buffer", "SoilsHSG") """ DEM, 30m NED """ NED30m_ImageServer = "GIS Servers\\Elevation\\NED30m.ImageServer" arcpy.MakeImageServerLayer_management(NED30m_ImageServer, "NED30m_Layer") arcpy.gp.ExtractByMask_sa("NED30m_Layer", "Buffer", "DEM") arcpy.AddMessage("DEM and Land Use data, i.e. NLCD , download complete") # Project the rasters arcpy.ProjectRaster_management(in_raster="DEM", out_raster="DEM_Prj", out_coor_system=outCS) arcpy.ProjectRaster_management(in_raster="Land_Use", out_raster="Land_Use_Prj", out_coor_system=outCS) arcpy.AddMessage("DEM and Land Use file projected")
Input_Image_Service = "http://stlpatrick.esri.com:6080/arcgis/services/ElevationServices/afghanistan/ImageServer" fc = wkid # Process: Buffer arcpy.Buffer_analysis(Observer_location, Buffer__2_, Distance__value_or_field_, "FULL", "ROUND", "NONE", "") # Process: Calculate Cell Size arcpy.CalculateValue_management("CalcCellSize(r\"%Buffer (2)%\")", "def CalcCellSize(ds):\\n width = arcpy.Describe(ds).extent.width\\n height = arcpy.Describe(ds).extent.height\\n cellsize = str(max(float(max(width,height))/2000.0,30.0))\\n #return cellsize + \" \" + cellsize\\n return cellsize", "Double") # Process: Calculate Value arcpy.CalculateValue_management("%Cell Size%", "", "Cell Size") # Process: Make Image Server Layer tempEnvironment0 = arcpy.env.cellSize arcpy.env.cellSize = "30" arcpy.MakeImageServerLayer_management(Input_Image_Service, ImageServer_Layer, Buffer__2_, "", "NORTH_WEST", "Name", "0", "", Cell_Size) arcpy.env.cellSize = tempEnvironment0 # Process: Copy Features arcpy.CopyFeatures_management(Observer_location, obs, "", "0", "0", "0") # Process: Add Field (2) arcpy.AddField_management(obs, "OFFSETA", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") # Process: Calculate Field (2) arcpy.CalculateField_management(Observer__2_, "OFFSETA", "%Height above surface (meters)%", "PYTHON", "") # Process: CreatePolygonMask arcpy.gp.toolbox = "C:/agsresources/visibility/VisibilityUtilities.tbx"; # Warning: the toolbox C:/agsresources/visibility/VisibilityUtilities.tbx DOES NOT have an alias. # Please assign this toolbox an alias to avoid tool name collisions
# Check the extent extentSize = inputExtent.width * inputExtent.height / 900.0 extentLimit = 24000 * 24000 if extentSize > extentLimit: msg("Extent is too big!", "warning") # Get the service layers scriptDir = os.path.dirname(sys.argv[0]) nlcdSvc = os.path.join(scriptDir, "LYRFiles", "ESRI Landscape 5", "USA_NLCD_2011.ImageServer") hydricSvc = os.path.join(scriptDir, "LYRFiles", "ESRI Landscape 4", "USA_Soils_Hydric_Classification.ImageServer") try: msg("Getting NLCD service layer") NLCDLyr = arcpy.MakeImageServerLayer_management(nlcdSvc, "NLCD_lyr", inputExtent) msg("Getting Hydric Soils service layer") hydricLyr = arcpy.MakeImageServerLayer_management(hydricSvc, "Soils_lyr", inputExtent) except: msg("Could not make image service layer.", "error") msg(arcpy.GetMessages()) sys.exit(1) # Set hydric soils to wetland, otherwise keep NLCD values msg("...converting all areas with hydric soils as wetlands") hydricNLCD = arcpy.sa.Con(hydricLyr, 90, NLCDLyr, "Value in (2)") # Createsa raster where urban areas are zero, otherwise hydric values msg("...reverting wetlands on developed areas back to developed")