def chazhi(a, b, d, CC, y=[]): cursor = arcpy.da.SearchCursor(a, [b]) for row in cursor: y.append(row[0]) del row, cursor if len(set(y)) == 1: arcpy.Idw_3d(a, b, d, CC) else: krig(a, b, d, CC)
def ShpToTif(shpPath, outRasterPath, zField="Value"): # Set local variables inPointFeatures = shpPath zField = zField outRaster = outRasterPath cell_size = 0.1 # Check out the ArcGIS 3D Analyst extension license arcpy.CheckOutExtension("3D") # Execute IDW arcpy.Idw_3d(inPointFeatures, zField, outRaster, cell_size) return outRasterPath
def interpolate_wle(self): """ Interpolates water level elevation, used as preliminary step for getting depth to groundwater and disconnected wetted areas. Args: self.method: 'Kriging', 'IDW', or 'Nearest Neighbor'. Determines the method used to interpolate WLE. Saves interpolated WLE raster to self.out_dir (also saves a WLE variance raster if Kriging method is used). """ try: arcpy.CheckOutExtension('Spatial') # check out license arcpy.gp.overwriteOutput = True arcpy.env.workspace = self.cache try: self.logger.info("Reading input rasters ...") ras_h = arcpy.Raster(self.path2h_ras) ras_dem = arcpy.Raster(self.path2dem_ras) arcpy.env.extent = ras_dem.extent cell_size = arcpy.GetRasterProperties_management( ras_dem, 'CELLSIZEX').getOutput(0) self.logger.info("OK") except: self.logger.info( "ERROR: Could not find / access input rasters.") return True try: self.logger.info("Making WSE raster ...") ras_wse = Con(ras_h > 0, (ras_dem + ras_h)) temp_dem = Con(((ras_dem > 0) & IsNull(ras_h)), ras_dem) ras_dem = temp_dem self.logger.info("OK") except: self.logger.info("ERROR: Input rasters contain invalid data.") return True try: self.logger.info("Converting WSE raster to points ...") pts_wse = arcpy.RasterToPoint_conversion( ras_wse, os.path.join(self.cache, "pts_wse.shp")) self.logger.info("OK") except arcpy.ExecuteError: self.logger.info(arcpy.AddError(arcpy.GetMessages(2))) return True except Exception as e: self.logger.info(arcpy.GetMessages(2)) self.logger.info(e.args[0]) return True if self.method == "Kriging": try: self.logger.info("Ordinary Kriging interpolation ...") # Spherical semivariogram using 12 nearest points to interpolate ras_wle_dem = Kriging(in_point_features=pts_wse, z_field="grid_code", kriging_model=KrigingModelOrdinary( "Spherical", lagSize=cell_size), cell_size=cell_size, search_radius="Variable 12") ras_wle_dem.save(os.path.join(self.cache, "ras_wle_dem")) # out_variance_prediction_raster=os.path.join(self.cache, "ras_wle_var") *** ras_wle_dem = arcpy.Raster( os.path.join(self.cache, "ras_wle_dem")) # ras_wle_var = arcpy.Raster(os.path.join(self.cache, "ras_wle_var")) *** self.logger.info("OK") except arcpy.ExecuteError: if "010079" in str(arcpy.GetMessages(2)): self.logger.info( "Could not fit semivariogram, increasing lag size and retrying..." ) empty_bins = True itr = 2 while empty_bins: try: ras_wle_dem = Kriging( in_point_features=pts_wse, z_field="grid_code", kriging_model=KrigingModelOrdinary( "Spherical", lagSize=cell_size * itr), cell_size=cell_size, search_radius="Variable 12") try: ras_wle_dem.save( os.path.join(self.cache, "ras_wle_dem")) # out_variance_prediction_raster=os.path.join(self.cache, "ras_wle_var") *** ras_wle_dem = arcpy.Raster( os.path.join(self.cache, "ras_wle_dem")) # ras_wle_var = arcpy.Raster(os.path.join(self.cache, "ras_wle_var")) *** self.logger.info("OK") empty_bins = False except: self.logger.info( "ERROR: Failed to produce interpolated raster." ) return True except: self.logger.info( "Still could not fit semivariogram, increasing lag and retrying..." ) itr *= 2 if itr > 16: break self.logger.info(arcpy.AddError(arcpy.GetMessages(2))) return True except Exception as e: self.logger.info(arcpy.GetMessages(2)) self.logger.info(e.args[0]) return True elif self.method == "IDW": try: self.logger.info("IDW interpolation...") # using IDW power of 2 with 12 nearest neighbors arcpy.Idw_3d(in_point_features=pts_wse, z_field="grid_code", out_raster=os.path.join( self.cache, "ras_wle_dem"), cell_size=cell_size, search_radius="Variable 12") ras_wle_dem = arcpy.Raster( os.path.join(self.cache, "ras_wle_dem")) self.logger.info("OK") except arcpy.ExecuteError: self.logger.info(arcpy.AddError(arcpy.GetMessages(2))) return True except Exception as e: self.logger.info(arcpy.GetMessages(2)) self.logger.info(e.args[0]) return True elif self.method == "Nearest Neighbor": try: self.logger.info("Nearest Neighbor interpolation...") # using IDW with 1 nearest neighbor arcpy.Idw_3d(in_point_features=pts_wse, z_field="grid_code", out_raster=os.path.join( self.cache, "ras_wle_dem"), cell_size=cell_size, search_radius="Variable 1") ras_wle_dem = arcpy.Raster( os.path.join(self.cache, "ras_wle_dem")) self.logger.info("OK") except arcpy.ExecuteError: self.logger.info(arcpy.AddError(arcpy.GetMessages(2))) return True except Exception as e: self.logger.info(arcpy.GetMessages(2)) self.logger.info(e.args[0]) return True elif self.method == "EBK": try: self.logger.info( "Empirical Bayesian Kriging interpolation...") search_nbrhood = arcpy.SearchNeighborhoodStandardCircular( nbrMin=12, nbrMax=12) arcpy.EmpiricalBayesianKriging_ga( in_features=pts_wse, z_field="grid_code", out_raster=os.path.join(self.cache, "ras_wle_dem"), cell_size=cell_size, transformation_type="EMPIRICAL", number_semivariograms=100, search_neighborhood=search_nbrhood, output_type="PREDICTION", semivariogram_model_type="EXPONENTIAL") ras_wle_dem = arcpy.Raster( os.path.join(self.cache, "ras_wle_dem")) self.logger.info("OK") except arcpy.ExecuteError: self.logger.info(arcpy.AddError(arcpy.GetMessages(2))) return True except Exception as e: self.logger.info(arcpy.GetMessages(2)) self.logger.info(e.args[0]) return True else: self.logger.info( "ERROR: invalid method for WSE interpolation: '%s'." % self.method) return True try: self.logger.info("Saving WLE raster to: %s" % os.path.join(self.out_dir, self.out_wle)) ras_wle_dem.save(os.path.join(self.out_dir, self.out_wle)) self.logger.info("OK") self.save_info_file(os.path.join(self.out_dir, self.out_wle)) """ *** if self.method == "Kriging": self.logger.info("Saving WLE Kriging variance raster (%s) ..." % os.path.join(self.out_dir, self.out_wle_var)) ras_wle_var.save(os.path.join(self.out_dir, self.out_wle_var)) self.logger.info("OK") """ arcpy.CheckInExtension('Spatial') except arcpy.ExecuteError: self.logger.info(arcpy.AddError(arcpy.GetMessages(2))) return True except Exception as e: self.logger.info(arcpy.GetMessages(2)) self.logger.info(e.args[0]) return True except arcpy.ExecuteError: self.logger.info("ExecuteERROR: (arcpy).") self.logger.info(arcpy.GetMessages(2)) return True except Exception as e: self.logger.info("ExceptionERROR: (arcpy).") self.logger.info(e.args[0]) return True self.clean_up() # return Boolean False if successful. return False
def DetrendDEM(output_workspace, flowline, flowline_points, dem, buffer_distance): # Check out the extension license arcpy.CheckOutExtension("3D") arcpy.CheckOutExtension("Spatial") # Set environment variables arcpy.env.overwriteOutput = True arcpy.env.workspace = output_workspace arcpy.env.extent = dem arcpy.env.snapRaster = dem arcpy.env.cellSize = arcpy.Describe(dem).meanCellHeight arcpy.env.compression = "LZ77" arcpy.env.outputCoordinateSystem = dem # List parameter values arcpy.AddMessage("Workspace: {}".format(arcpy.env.workspace)) arcpy.AddMessage("Flowline: " "{}".format(arcpy.Describe(flowline).baseName)) arcpy.AddMessage("Flowline Points: " "{}".format(arcpy.Describe(flowline_points).baseName)) arcpy.AddMessage("DEM: {}".format(arcpy.Describe(dem).baseName)) arcpy.AddMessage("Buffer Distance: {}".format(str(buffer_distance))) # Buffer the flowline_points flowline_buffer = os.path.join(output_workspace, "flowline_buffer") arcpy.Buffer_analysis(in_features=flowline, out_feature_class=flowline_buffer, buffer_distance_or_field=buffer_distance, line_side="FULL", line_end_type="ROUND", dissolve_option="ALL") arcpy.AddMessage("Buffering flowline complete.") # Set the environment mask to the flowline_buffer to clip all rasters arcpy.AddMessage("Setting mask to flowline_buffer...") arcpy.env.mask = flowline_buffer arcpy.AddMessage("Setting mask to flowline_buffer complete.") # Create the trend raster arcpy.AddMessage("Creating trend raster...") trend = os.path.join(output_workspace, "trend") arcpy.Idw_3d(in_point_features=flowline_points, z_field="Z", out_raster=trend, power=2, search_radius="VARIABLE") arcpy.AddMessage("Created trend raster.") # Smooth the trend raster trend_smooth = arcpy.sa.FocalStatistics(in_raster=trend, neighborhood=arcpy.sa.NbrCircle( 50, "CELL"), statistics_type="Mean") trend_smooth_path = os.path.join(output_workspace, "trend_smooth") arcpy.CopyRaster_management(in_raster=trend_smooth, out_rasterdataset=trend_smooth_path) arcpy.AddMessage("Smoothed trend raster.") # Create the detrended raster detrend = (Raster(dem) - Raster(trend_smooth_path)) + float(100) detrend_path = os.path.join(output_workspace, "detrend") arcpy.CopyRaster_management(in_raster=detrend, out_rasterdataset=detrend_path) arcpy.AddMessage("Created detrended raster.") # Calculate raster statistics and build pyramids arcpy.CalculateStatistics_management(detrend_path) arcpy.BuildPyramids_management(detrend_path) arcpy.AddMessage("Calculated raster statistics and pyramids.") # Return arcpy.SetParameter(5, detrend_path) # Cleanup arcpy.Delete_management(in_data=flowline_buffer) arcpy.Delete_management(in_data=trend) arcpy.Delete_management(in_data=trend_smooth_path)
# Check out 3D License arcpy.CheckOutExtension("3D") # Get parameters features = arcpy.GetParameter(0) cell_size = arcpy.GetParameter(1) power = arcpy.GetParameter(2) arcpy.AddMessage("CELL SIZE: " + str(cell_size)) arcpy.AddMessage("POWER: " + str(power)) # Do IDW Interpolation out_raster_name = arcpy.CreateUniqueName("output.tif", arcpy.env.scratchFolder) if cell_size > 0 and power != 0: arcpy.Idw_3d(features, "VALUE", out_raster_name, cell_size, power) elif cell_size > 0: arcpy.Idw_3d(features, "VALUE", out_raster_name, cell_size=cell_size) elif power != 0: arcpy.Idw_3d(features, "VALUE", out_raster_name, power=power) else: arcpy.Idw_3d(features, "VALUE", out_raster_name) # Write raster as result arcpy.SetParameter(3, out_raster_name) except Exception as e: arcpy.AddError(str(e)) finally: arcpy.Delete_management('in_memory')
if arcpy.CheckExtension("Spatial") == "Available": arcpy.CheckOutExtension("Spatial") arcpy.CheckOutExtension("3D") else: #Raise a custom exception raise LicenseError # Run Extract Values to Points Tool ExtractValuesToPoints(channelpoints, rasterSurface, channelpoints3d) print(arcpy.GetMessages()) # Create a "detrended" surface that approximates water surface/channel surface (ambiguous depending on raster creation) using inverse distance weighting. Must first check out 3D Analyst # NOTE: may have to run tool on test point features first to get one of IDW inputs - Z field. # Create detrended surface using IDW tool for both search radius. User can define power # arcpy.Idw_3d(channelpoints3d, "RASTERVALU", IDW1, outputCellSize, 2, idwSearchRadius1, IDWboundary1) arcpy.Idw_3d(channelpoints3d, "RASTERVALU", "IDW1", outputCellSize, 2, idwSearchRadius1) print(arcpy.GetMessages()) # IDW = arcpy.Idw(channelpoints3d,"RASTERVALU") # Create REM by subtracting detrended surface from elevation raster. Must first check out Spatial Analyst Extension # Complete map algebra geoprocessing outRaster = Raster(rasterSurface) - Raster("IDW1") outRaster.save("REM") print(arcpy.GetMessages()) # Extract REM from buffer extraction = ExtractByMask("REM", channelbufferdissolve) extraction.save = ("REM_final") print(arcpy.GetMessages())
# Import system modules import arcpy import os from arcpy import env # Set environment settings env.workspace = "E:/all_station_pre/point/day" resultpath = "e:/idw/idw_" #输出文件路径 filepath = env.workspace filelist = os.listdir(filepath) file_raw_list = filter(lambda filename: filename[-4:] == '.shp', filelist) #只选取文件夹中的.shp文件 arcpy.env.extent = "D:/zj/基础地理信息/太湖流域/太湖流域边界.shp" arcpy.env.outputCoordinateSystem = "E:/all_station_pre/TP/regions/PCSsample/11.shp" # Set local variables for i in range(len(file_raw_list)): infeatures = file_raw_list[i] zField = "pre" outRaster = resultpath + infeatures[0:8] cellSize = 10239.16639 power = 2 searchRadius = "" #searchRadius = 150000 # Check out the ArcGIS 3D Analyst extension license arcpy.CheckOutExtension("3D") # Execute IDW arcpy.Idw_3d(infeatures, zField, outRaster, cellSize, power, searchRadius)
def create_thematic_map(progressBar, mxd, input_files_path, i, btn_layer, btn_export_pdf,\ btn_export_png, administrative_layer_list, other_layer_list, \ graphic_list, btn_zoom_to_layer_list, btn_zoom_to_layer_attribute_list): #Acces to the list of layers dataframe = map.ListDataFrames(mxd)[0] layers = map.ListLayers(mxd,"",dataframe) if btn_layer.isChecked()==True: # Check out any necessary licenses arcpy.CheckOutExtension("3D") arcpy.CheckOutExtension('Spatial') arcpy.env.overwriteOutput=True #Join Input data progressBar.setValue(1) shp_path = str(input_files_path) inFeatures = shp_path weather_variables = ['temp_mit', 'temp_max', 'temp_min', 'prec', 'prec', 'hume', 'pres'] vble = weather_variables[i] Z_value = vble print Z_value outRaster = "interpolation_maps/"+str(vble) cellSize = 300 kModel = "Spherical 663.040376" for layer in layers: #(group of layer name is read as one layer else) if layer.name == administrative_layer_list[2].text(): arcpy.env.mask = layer.dataSource arcpy.env.extent = "626638.8673 4190956.536 815377.0266 4519162.5229" #arcpy.Kriging_3d(inFeatures, Z_value, outRaster, kModel, cellSize, "VARIABLE 12", "") arcpy.Idw_3d(inFeatures, Z_value, outRaster, cellSize, "2", "VARIABLE 12", "") #In order to automatically change the Source directory of the .shp inside the .mxd file i define the next code line this is assuming that the user doesn't change the directory manually in the .mxd last_workspace_path = str(arcpy.env.workspace) mxd.findAndReplaceWorkspacePaths(last_workspace_path,arcpy.env.workspace) #Enable weather layer progressBar.setValue(3) for layer in layers: #(group of layer name is read as one layer else) check_enable_layer (layer, btn_layer, True) #function created before #Enable other layers progressBar.setValue(4) for administrative_layer in administrative_layer_list: check_enable_layer(layer, administrative_layer, True) for other_layer in other_layer_list: check_enable_layer(layer, other_layer, True) #Draws graphic elements progressBar.setValue(5) draw_graphic_maps(mxd, graphic_list) #function created before #Zoom to progressBar.setValue(6) zoom_to_value(dataframe, btn_zoom_to_layer_list, layers, \ btn_zoom_to_layer_attribute_list) #function created before #Export map progressBar.setValue(7) export_maps(mxd, btn_layer, btn_export_pdf, \ btn_export_png) #function created before #Disable layers (It's important due to clean de template for the next map) for layer in layers: #(group of layer name is read as one layer else) check_enable_layer (layer, btn_layer, False) for administrative_layer in administrative_layer_list: check_enable_layer(layer, administrative_layer, False) for other_layer in other_layer_list: check_enable_layer(layer, other_layer, False)
del my_row,cursor1 for i in range(1,13): outputname1="trshidu%d.shp"%(i) outputkrigph1="trkrigph%d.tif"%(i) outputclip1="trclip%d.tif"%(i) print outputname1 exp='"MONTH"=%d'%(i) arcpy.Select_analysis("trsd.shp", outputname1, exp) cursor = arcpy.da.SearchCursor(outputname1, ["trsd"]) sdt=[] for row in cursor: sdt.append(row[0]) del row,cursor if len(set(sdt))==1: arcpy.Idw_3d(outputname1, "trsd", outputkrigph1,CC) else: chazhi(outputname1, "trsd", outputkrigph1,CC) arcpy.Clip_management(outputkrigph1,"",outputclip1,IN_CLIP,"", "ClippingGeometry") arcpy.Delete_management(outputname1) arcpy.Delete_management(outputkrigph1) WFF=0 for i in range(1,13): outputclip="clip%d.tif"%(i) outputclip1="trclip%d.tif"%(i) outputwf="wffinal%d.tif"%(i) if IN_XG =="99999": WF=arcpy.Raster(outputclip)*arcpy.Raster(outputclip1)*int(VAR_PP)/int(VAR_G) else: WF=arcpy.Raster(outputclip)*arcpy.Raster(outputclip1)*arcpy.Raster(IN_XG)*int(VAR_PP)/int(VAR_G)