def volume_computation(self): self.logger.info(" * calculating volume differences ...") # requires 3D extension arcpy.CheckOutExtension("3D") arcpy.env.extent = "MAXOF" for rn in self.reach_ids_applied: try: self.logger.info(" * calculating fill volume from " + str(self.rasters_for_pos_vol[rn])) self.logger.info(" *** takes time ***") feat_vol = arcpy.SurfaceVolume_3d(self.rasters_for_pos_vol[rn], "", "ABOVE", 0.0, 1.0) voltxt = feat_vol.getMessage(1).split("Volume=")[1] self.logger.info(" RESULT: " + str(float(voltxt)*self.convert_volume_to_cy) + self.unit_info + ".") self.volume_pos_dict[rn] = float(voltxt) * self.convert_volume_to_cy except: self.logger.info("ERROR: Calculation of volume from " + str(self.rasters_for_pos_vol[rn]) + " failed.") try: self.logger.info(" * calculating excavation volume from " + str(self.rasters_for_neg_vol[rn])) self.logger.info(" *** takes time ***") feat_vol = arcpy.SurfaceVolume_3d(self.rasters_for_neg_vol[rn], "", "ABOVE", 0.0, 1.0) voltxt = feat_vol.getMessage(1).split("Volume=")[1] self.logger.info(" RESULT: " + str(float(voltxt)*self.convert_volume_to_cy) + self.unit_info + ".") self.volume_neg_dict[rn] = float(voltxt) * self.convert_volume_to_cy except: self.logger.info("ERROR: Calculation of volume from " + str(self.rasters_for_neg_vol[rn]) + " failed.") # ALTERNATIVE OPTION IF arcpy.SurfaceVolume_3d FAILS # import numpy # myArray = arcpy.RasterToNumPyArray(outVol) # totVolume = numpy.sum(myArray) arcpy.CheckInExtension("3D")
ratio = int(ratio) except: arcpy.AddError( "The script could not read your ratio because it is not a number") quit() print(ratio) desc = arcpy.Describe(dem) # Get information from the DEM nombre = os.path.join(files, desc.baseName + ".txt") # Get the name from the DEM # Create a .txt file and populate it with the data from the Surface volume # calculation, given the thresholds and the interval with open(nombre, "w") as f: for plane in range(minalt, maxalt, interval): try: result = arcpy.SurfaceVolume_3d(dem, "", "ABOVE", plane) print(arcpy.GetMessage(0), file=f) print(arcpy.GetMessage(1), file=f) print(arcpy.GetMessage(2), file=f) print(arcpy.GetMessage(3), file=f) except Exception as e: print(e.message) f.close # Create list of altitudes and populate primervalor primervalor = [] start_altitude = minalt while start_altitude >= minalt and start_altitude < maxalt: primervalor.append(start_altitude) start_altitude = start_altitude + interval
#outputCSV = HomeDir + '/Python/AM_output/extracted_points_GCPs.csv' #with open(outputCSV, "w") as csvfile: # csvwriter = csv.writer(csvfile, delimiter=',', lineterminator='\n') # ## Write field name header line # fields = ['ObjectID', 'Shape', 'FID_GCPs', 'Field1', 'Field2', 'Field3', 'Field4', 'Field5', 'Field6', 'FID_beach_polygon', # 'walk_DEM', 'DEM_220ft_21GCP', 'DEM_300ft_21GCP', 'DEM_380ft_21GCP', 'DEM_220ft_15GCP', 'DEM_300ft_15GCP', 'DEM_380ft_15GCP', # 'diff_walk_DEM', 'diff_DEM_220ft_21GCP', 'diff_DEM_300ft_21GCP', 'diff_DEM_380ft_21GCP', 'diff_DEM_220ft_15GCP', # 'diff_DEM_300ft_15GCP', 'diff_DEM_380ft_15GCP'] # csvwriter.writerow(fields) # ## Write data rows # with arcpy.da.SearchCursor(GCPsOverlap, fields) as s_cursor: # for row in s_cursor: # csvwriter.writerow(row) # VOLUMES # extract by mask & surface volume tool (mask environment does not work, so need to first extract DEMs by mask) mask = Overlapping_Polygon #ExtractList = DEMsList[:] #ExtractList[0] = 'walk_DEM' for item in rastersList: extract_input = item extract_output = HomeDir + '/DealPostStorm.gdb/Extract_' + item arcpy.gp.ExtractByMask_sa(extract_input, mask, extract_output) volume_input = 'Extract_' + item volume_output = HomeDir + '/Python/AM_output/Volume/volume_' + item + '.txt' arcpy.SurfaceVolume_3d(volume_input, volume_output, "ABOVE", "-4", "1", "0") #mapdoc.save() #del mapdoc
Reference_Plane = "BELOW" plnHgt = MinElev + remainder outputText = tables + os.sep + "subbasin" + str(value) + ".txt" f = open(outputText, "w") f.write( "Dataset, Plane_heig, Reference, Z_Factor, Area_2D, Area_3D, Volume, Subbasin\n" ) f.close() while plnHgt <= maxValue: Plane_Height = plnHgt AddMsgAndPrint( "\tCalculating storage at elevation " + str(round(plnHgt, 1)), 0) arcpy.SurfaceVolume_3d(subGrid, outputText, Reference_Plane, Plane_Height, 1) plnHgt = 1 + plnHgt AddMsgAndPrint("\n\t\t\t\tConverting results...", 0) arcpy.CopyRows_management(outputText, storageTemp, "") arcpy.CalculateField_management(storageTemp, "Subbasin", value, "PYTHON") arcpy.Append_management(storageTemp, storageTable, "NO_TEST", "", "") arcpy.Delete_management(storageTemp) rows.updateRow(row) row = rows.next() del rows
AddMsgAndPrint("\nThe Max Elevation value specified is not within the elevation range of your watershed-pool area",2) AddMsgAndPrint("Elevation Range of your watershed-pool polygon is:",2) AddMsgAndPrint("\tMaximum Elevation: " + str(demTempMaxElev) + " " + zUnits + " ---- " + str(round(float(demTempMaxElev*convToFeetFactor),1)) + " Feet") AddMsgAndPrint("\tMinimum Elevation: " + str(demTempMinElev) + " " + zUnits + " ---- " + str(round(float(demTempMinElev*convToFeetFactor),1)) + " Feet") AddMsgAndPrint("Please enter an elevation value within this range.....Exiting!\n\n",2) exit() else: AddMsgAndPrint("\nSuccessfully clipped DEM to " + os.path.basename(inPool)) # --------------------------------------------------------------------------------- Set Elevations to calculate volume and surface area AddMsgAndPrint("\nCreating Pool at " + str(maxElev) + " FT") storageCSV = userWorkspace + os.sep + poolName + "_storageCSV.txt" arcpy.SurfaceVolume_3d(tempDEM, storageCSV, "BELOW", maxElevConverted, "1") if not createPool(maxElevConverted,storageCSV): AddMsgAndPrint("\nFailed To Create Pool at elevation: " + str(maxElevConverted),2) exit() arcpy.Delete_management(tempDEM) if arcpy.Exists(storageCSV): arcpy.Delete_management(storageCSV) # ------------------------------------------------------------------------------------------------ Compact FGDB arcpy.Compact_management(watershedGDB_path) AddMsgAndPrint("\nSuccessfully Compacted FGDB: " + os.path.basename(watershedGDB_path)) # ------------------------------------------------------------------------------------------------ Prepare to Add to ArcGIS Pro
# Passo para cálculo da CAV "1 = 1m; 0.1 = 10cm; 0.01 = 1cm" # y = 0.01 y = 0.1 # Cota do Fundo do Reservatório q = 723.68 print("please wait...this script is processing...(CAV processing)") #error handler try: if direction == "below": x = startingplane while x > q: arcpy.SurfaceVolume_3d(My_surface, My_txt, direction, x, z) x = x - y # if direction == "above": # x = startingplane # while x < q: # arcpy.SurfaceVolume_3d(My_surface, My_txt, direction, x, z) # x = x + y except: arcpy.AddMessage(arcpy.GetMessages(2)) print(arcpy.GetMessages(2)) end_time = datetime.now() print('FIM, PROCESSAMENTO CONCLUÍDO') print('TEMPO DE PROCESSAMENTO: {}'.format(end_time - start_time))
reservoir = arcpy.GetParameterAsText(3) volume = arcpy.GetParameterAsText(4) # Processsing Snap_Point_output = SnapPourPoint(pour_point, flow_accumulation, snap_distance, "OBJECTID") pourPointTest = Times(flow_accumulation, Snap_Point_output) majorStreamCondition = checkPourPoint(pourPointTest) if majorStreamCondition == True: Watershed_raster = Watershed(flow_direction, Snap_Point_output, "VALUE") arcpy.RasterToPolygon_conversion(Watershed_raster, watershedFT, "NO_SIMPLIFY", "VALUE") demCP = ExtractByMask(filled_dem, watershedFT) pointTest = Times(demCP, Snap_Point_output) initElev = getElev(pointTest) reservoirRS = Con(demCP <= float(initElev) + float(height), 1, "") arcpy.RasterToPolygon_conversion(reservoirRS, reservoir, "SIMPLIFY", "Value") reserElv = ExtractByMask(filled_dem, reservoir) arcpy.SurfaceVolume_3d(reserElv, volume, "BELOW", "", "1", "0") else: with open(volume, "w") as text_file: text_file.write( "Input point is not close enough to any major streams on record.\n" )
try: minalt= int(minimum.split('.')[0]) except: minalt= int(minimum.split(',')[0]) minalt=minalt-interval desc=arcpy.Describe(dem) # Get information from the DEM nombre=os.path.join(files,desc.baseName+".txt") # Get the name from the DEM # Create a .txt file and populate it with the data from the Surface volume # calculation, given the thresholds and the interval with open(nombre,"w") as f: try: for plane in range(minalt, maxalt, interval): result=arcpy.SurfaceVolume_3d(dem,"", "BELOW", plane) print (arcpy.GetMessage(0), file=f) print (arcpy.GetMessage(1), file=f) print (arcpy.GetMessage(2), file=f) print (arcpy.GetMessage(3), file=f) except Exception as e: print (e.message) f.close # Create a list of altitudes list_altitudes=[] start_altitude=minalt+(interval/2) while start_altitude > minalt and start_altitude < maxalt: list_altitudes.append(start_altitude) start_altitude=start_altitude+interval
) # Round to prevent deviations due to using floating point values. # Loop through elevations incrementally to calculate area and volume, writing results to screen and text file. # try: # Return a new output for every change of incElev elevation unit. # SurfaceVolume appends data if the file exists already. # while refElev_feet <= endElev_feet: refElev_meters = refElev_feet / 3.280833 # Reference plane elevation converted to meters. # arcpy.env.overwriteOutput = True # Needed to append each new record to the output file. # Run the SurfaceVolume_3d program with the user-defined values. # arcpy.SurfaceVolume_3d(inDEM, "", refPlane, refElev_meters, zFact) # Obtain the values or 2D Area, 3D Area, and Volume reported by SurfaceVolume_3d # by searching through the output message results string. # r = arcpy.GetMessage(2) area2d_m2 = float(r[r.find("2D Area=") + 8:r.find("3D Area=")]) area3d_m2 = float(r[r.find("3D Area=") + 8:r.find("Volume=")]) vol3d_m3 = float(r[r.find("Volume=") + 7:]) # Convert from units of square meters and cubic meters to acres and acre-ft, respectively area2d_ac = area2d_m2 / 4046.873 area3d_ac = area3d_m2 / 4046.873 vol3d_acft = vol3d_m3 / 1233.489 # Report the input and output values to the screen.
#Calculate differences for n in xrange(0, len(data)): dif = locdif + difs[n] difname = str(difs[n]) for y in xrange(1, compcount + 1): rowid = str(((n - 2) * compcount) + y) # Get COMP ID and set clause comp = loccomp + 'Compartments_KM_v3.shp' compnum = str(y) compid = str('"COMP" = ' + str(y)) temp1 = "in_memory/t2" + integ arcpy.MakeFeatureLayer_management( comp, "lyr", compid) # Create Mask for isolating compartment temp1 = ExtractByMask(dif, "lyr") # Get Raster for comp result = arcpy.SurfaceVolume_3d( temp1, "#", "ABOVE", "0", "1", "0") # Get Deposition Volume for compartment depvolp = str(arcpy.GetMessages()) volpos = depvolp.find('Volume=') depvol1 = str(depvolp[volpos + 7:volpos + 17]) # Get volume value from arcpy message try: depvol = float(depvol1) # Convert to float except: depvol = 0 result = arcpy.SurfaceVolume_3d( temp1, "#", "BELOW", "0", "1", "0") # Get Erosion Volume for compartment arcpy.GetMessages() erovolp = str(arcpy.GetMessages())
desc = arcpy.Describe(dem) demName = os.path.join(desc.path, desc.name) # Get information from the DEM nombre = os.path.join(files, desc.baseName + "AAR.txt") # Get the calculations .txt name from the DEM nombreOut = os.path.join(files, desc.baseName + "_output.txt") # Get output .txt name from the DEM nombreshp = os.path.join(files, desc.baseName + "ELAs.shp") listELAS = [] # Create a .txt file and populate it with the data from the Surface volume # calculation, given the thresholds and the interval with open(nombre, "w") as f: for plane in range(minalt, maxalt, interval): print(plane, file=f) try: arcpy.SurfaceVolume_3d(dem, "", "ABOVE", plane) print(arcpy.GetMessage(0), file=f) print(arcpy.GetMessage(1), file=f) print(arcpy.GetMessage(2), file=f) print(arcpy.GetMessage(3), file=f) except Exception as e: print(e.message) f.close # Create a list of altitudes for AAR primervalor = [] start_altitude = minalt while start_altitude >= minalt and start_altitude < maxalt: primervalor.append(start_altitude) start_altitude = start_altitude + interval
AddMsgAndPrint( "\tThe Pool Elevation Specified is not within the range of elevations within your input watershed!", 2) AddMsgAndPrint( "\tPlease specify a value between " + str(demTempMinElev) + " and " + str(demTempMaxElev) + ". Exiting...", 2) sys.exit() AddMsgAndPrint("\nCreating Pool at " + str(maxElev) + " feet", 0) # --------------------------------------------------------------------------------- Set Elevations to calculate volume and surface area AddMsgAndPrint("\nCreating Pool at " + str(maxElev) + " FT") arcpy.SurfaceVolume_3d(tempDEM, storageCSV, "BELOW", demElev, "1") if not createPool(demElev, storageCSV): pass if arcpy.Exists(tempDEM): arcpy.Delete_management(tempDEM) #------------------------------------------------------------------------ Convert StorageCSV to FGDB Table and populate fields arcpy.CopyRows_management(storageCSV, storageTable, "") arcpy.AddField_management(storageTable, "ELEV_FEET", "DOUBLE", "5", "1", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(storageTable, "POOL_ACRES", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(storageTable, "POOL_SQFT", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
#arcpy.env.workspace = "C:/HY-Data/ADHIHARI/PhD_Articles/6th_Paper/Data/FinalScans3D/Shapefiles/Rasterfiles" #outptConFol = r"C:\HY-Data\ADHIHARI\PhD_Articles\6th_Paper\Data\FinalScans3D\Shapefiles\Rasterfiles\RFI" arcpy.env.workspace = "C:/HY-Data/ADHIHARI/PhD_Articles/6th_Paper/Data/temp/FinalScans2andhalfD/PLYfolder/Shapefiles/Rasterfiles" outptConFol = r"C:\HY-Data\ADHIHARI\PhD_Articles\6th_Paper\Data\temp\FinalScans2andhalfD\PLYfolder\Shapefiles\Rasterfiles\RFI" # use r when you use \ symbol # CHECK OUT THE ARCGIS SPATIAL ANALYST EXTENSION LICENSE arcpy.CheckOutExtension("Spatial") arcpy.CheckOutExtension("3D") # FIND NECESSARY RASTER FILE # In a loop we will find all those raster files who ends with _0pt05.tif, as we are only intersted in those raster with original resolution # Make changes if you need different Contour Interval and Base Contour for tiff in arcpy.ListRasters("*_0pt05.tif"): in_surface = tiff out_text_file = os.path.join( outptConFol, os.path.splitext(os.path.basename(tiff))[0] + "_SV3D.txt" ) # Although the original resoultion is 0.05, it will be really messy reference_plane = "" base_z = "" z_factor = "" pyramid_level_resolution = "" arcpy.SurfaceVolume_3d(in_surface, out_text_file, reference_plane, base_z, z_factor, pyramid_level_resolution) # Execute Contour # arcpy.SurfaceVolume_3d (in_surface, {out_text_file}, {reference_plane}, {base_z}, {z_factor}, {pyramid_level_resolution})