def __init__(self, dtm_path, manning_path, cellsize=5, radius=2000, nodata=-99, mute=True): self.dtm_ds = gtif.openf(dtm_path) self.dtm_gt = self.dtm_ds.GetGeoTransform() self.mannings_ds = gtif.openf(manning_path) self.mannings_gt = self.mannings_ds.GetGeoTransform() Matrix.__init__(self, gtif.as_array(self.dtm_ds)) self.cellsize = cellsize self.radius = radius self.nodata = nodata self.dtm = rd.rdarray(self.dtm, no_data=nodata) rd.FillDepressions(self.dtm, in_place=True) self.mannings = self.array(gtif.as_array(self.mannings_ds)) self.mannings = GeoTransformFit(self.mannings, self.mannings_gt, self.dtm_gt) self.mute = mute
def main(): """ RichDEM depression filling """ # lazy import RICHDEM try: import richdem as rd except: g.message( flags="e", message=("RichDEM not detected. Install pip3 and " + "then type at the command prompt: " + '"pip3 install richdem".'), ) _input = options["input"] _output = options["output"] _epsilon = options["epsilon"] _topology = options["topology"] if _epsilon == "true": epsilon = True else: epsilon = False dem = garray.array(_input, null=np.nan) rd_inout = rd.rdarray(dem, no_data=np.nan) rd.FillDepressions(dem=rd_inout, epsilon=epsilon, in_place=True, topology=_topology) dem[:] = rd_inout[:] dem.write(_output, overwrite=gscript.overwrite())
def main(): """ RichDEM depression filling """ # lazy import RICHDEM try: import richdem as rd except: g.message(flags='e', message=('RichDEM not detected. Install pip3 and ' + 'then type at the command prompt: ' + '"pip3 install richdem".')) _input = options['input'] _output = options['output'] _epsilon = options['epsilon'] _topology = options['topology'] if _epsilon == 'true': epsilon = True else: epsilon = False dem = garray.array() dem.read(_input, null=np.nan) rd_inout = rd.rdarray(dem, no_data=np.nan) rd.FillDepressions(dem=rd_inout, epsilon=epsilon, in_place=True, topology=_topology) dem[:] = rd_inout[:] dem.write(_output, overwrite=gscript.overwrite())
def main(): """ RichDEM depression filling """ options, flags = gscript.parser() _input = options['input'] _output = options['output'] _epsilon = options['epsilon'] _topology = options['topology'] if _epsilon == 'true': epsilon = True else: epsilon = False dem = garray.array() dem.read(_input, null=np.nan) rd_inout = rd.rdarray(dem, no_data=np.nan) rd.FillDepressions(dem=rd_inout, epsilon=epsilon, in_place=True, topology=_topology) dem[:] = rd_inout[:] dem.write(_output, overwrite=gscript.overwrite())
def RichFlow(bassin, zone, root, flowdir, overwrite): """ Calcule le plan de drainage en utilisant RichDEM : FillDepressions + ResolveFlats """ raster_template = os.path.join(root, bassin, zone, 'DEM5M.tif') flow_raster = os.path.join(root, bassin, zone, flowdir) if os.path.exists(flow_raster) and not overwrite: click.secho('Output already exists : %s' % flow_raster, fg=WARNING) return dem = rd.LoadGDAL(raster_template) filled = rd.FillDepressions(dem) rd.ResolveFlats(filled, True) flow = ta.flowdir(filled, filled.no_data) ds = rio.open(raster_template) profile = ds.profile.copy() profile.update(dtype=np.int16, nodata=-1, compress='deflate') with rio.open(flow_raster, 'w', **profile) as dst: dst.write(flow, 1) click.secho('Saved to %s' % flow_raster, fg=SUCCESS)
def processDEM(fileloc): """ computes hydrologically sound DEM by filling pits and also computes flow accumulation """ pitremovedDEM = rd.FillDepressions(rd.LoadGDAL(fileloc)) accumDEM = rd.FlowAccumulation(pitremovedDEM, method='Dinf') return pitremovedDEM, accumDEM
def filled_dem(ctx, cropped_dem_fp, filled_dem_fp): logger = ctx.obj['LOGGER'] logger.info("Cropping DEM to watershed extent") with rasterio.open(cropped_dem_fp) as dataset: dem = dataset.read(1) rdem = richdem.rdarray(dem, no_data=dataset.nodata) filled_dem = richdem.FillDepressions(rdem) logger.info("Filled {} pixels".format(np.sum(filled_dem != rdem))) out_meta = dataset.meta with rasterio.open(filled_dem_fp, 'w', **out_meta) as out_dataset: out_dataset.write(filled_dem, indexes=1) logger.info("DONE")
def DepressionFilling(): parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description='RichDEM Depression Filling') parser.add_argument('dem', type=str, help='Elevation model') parser.add_argument('outname', type=str, help='Name of output file') parser.add_argument('-g', '--gradient', action='store_true', help='Ensure that all cells are at least an epsilon above their downstream cell. This ensures that each cell has a defined flow direction.') parser.add_argument('-v', '--version', action='version', version=rd._RichDEMVersion()) args = parser.parse_args() dem = rd.LoadGDAL(args.dem) rd._AddAnalysis(dem, ' '.join(sys.argv)) rd.FillDepressions(dem, epsilon=args.gradient, in_place=True) rd.SaveGDAL(args.outname, dem)
def terrain(elvDs, variable="elevation", fillDem=True, flowMethod='D8'): out = elvDs.copy() zScales = { 0: 0.00000898, 10: 0.00000912, 20: 0.00000956, 30: 0.00001036, 40: 0.00001171, 50: 0.00001395, 60: 0.00001792, 70: 0.00002619, 80: 0.00005156 } # calculat the geospatial information from the dataset elvDim = [elvDs.dims['lon'], elvDs.dims["lat"]] xres = float((elvDs.lon[1] - elvDs.lon[0]).values) yres = float((elvDs.lat[1] - elvDs.lat[0]).values) xinit = float((elvDs.lon[0]).values) - (xres / 2) yinit = float((elvDs.lat[0]).values) + (yres / 2) # get elevation values as np.ndarray elvVals = np.squeeze(elvDs[variable].values) rdem = rd.rdarray(elvVals, no_data=np.nan) rdem.projection = '''GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.0174532925199433, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]] ''' rdem.geotransform = (xinit, xres, 0, yinit, 0, yres) if fillDem: filled = rd.FillDepressions(rdem, epsilon=True, in_place=False, topology='D8') rdem = rd.ResolveFlats(filled, in_place=False) zScale = zScales[np.around(yinit, decimals=-1)] slope = rd.TerrainAttribute(rdem, attrib='slope_percentage', zscale=zScale) accum = rd.FlowAccumulation(rdem, method=flowMethod) out["slope"] = (('time', 'lat', 'lon'), slope[np.newaxis, :, :]) out["flowAcc"] = (('time', 'lat', 'lon'), accum[np.newaxis, :, :]) return out
def drain_area(dem, drain_area_out): """ Creates a raster where each pixel represents the contributing upstream drainage area in km2. DEM should be in a desired projected coordinate system. PARAMS :dem: string - path to dem raster file :drain_area_out: string - path to output drainage area raster file """ dem_in = rd.LoadGDAL(dem) rd.FillDepressions(dem_in, epsilon=True, in_place=True) accum_d8 = rd.FlowAccumulation(dem_in, method='D8') da = accum_d8 * (accum_d8.geotransform[1]**2 / 1000000) rd.SaveGDAL(drain_area_out, da) return
def runoff(): # return 788 dem_path = os.path.join(os.getcwd(), 'Konambe_dem_clipped.tif') village_dem = rd.LoadGDAL(dem_path, no_data=-9999) rd.FillDepressions(village_dem, epsilon=False, in_place=False) arr = rd.TerrainAttribute(village_dem, attrib='slope_percentage', zscale=1 / 111120) np.save('out.npy', arr) demnp = np.load('out.npy') dem = copy.copy(arr) dem[np.where((arr > 0) & (arr < 5))] = 1 dem[np.where((arr >= 5) & (arr < 20))] = 2 dem[np.where((arr >= 20))] = 3 c1 = np.count_nonzero(dem == 1) c2 = np.count_nonzero(dem == 2) c3 = np.count_nonzero(dem == 3) area_m2_1 = c1 * 900 area_m2_2 = c2 * 900 area_m2_3 = c3 * 900 area_ha1 = area_m2_1 * 0.0001 area_ha2 = area_m2_2 * 0.0001 area_ha3 = area_m2_3 * 0.0001 #print('area',area_ha1+area_ha2) worthy_area = area_ha1 + area_ha2 #coeff for rainfall 775mm runoff1 = area_ha1 * 1.0791 runoff2 = area_ha2 * 1.6186 runoff3 = area_ha3 * 2.1583 #coeff for rainfall 725mm #runoff1=area_ha1*1.0791 #runoff2=area_ha2*1.3878 #runoff3=area_ha3*1.8496 tot_runoff = runoff1 + runoff2 + runoff3 return tot_runoff, worthy_area #r=runoff()
def ExtractSinks(in_dem, min_size, out_dir): """Extract sinks (e.g., maximum depression extent) from a DEM. Args: in_dem (str): File path to the input DEM. min_size (int): The minimum number of pixels to be considered as a sink. out_dir (str): File path to the output directory. Returns: object: The richDEM array containing sinks. """ start_time = time.time() out_dem = os.path.join(out_dir, "dem.tif") out_dem_filled = os.path.join(out_dir, "dem_filled.tif") out_dem_diff = os.path.join(out_dir, "dem_diff.tif") out_sink = os.path.join(out_dir, "sink.tif") out_region = os.path.join(out_dir, "region.tif") out_depth = os.path.join(out_dir, "depth.tif") out_csv_file = os.path.join(out_dir, "regions_info.csv") out_vec_file = os.path.join(out_dir, "regions.shp") # create output folder if nonexistent if not os.path.exists(out_dir): os.mkdir(out_dir) # load the dem and get dem info print("Loading data ...") dem = rd.LoadGDAL(in_dem) no_data = dem.no_data projection = dem.projection geotransform = dem.geotransform cell_size = np.round(geotransform[1], decimals=2) # get min and max elevation of the dem max_elev = np.float(np.max(dem)) min_elev = np.float(np.min(dem[dem > 0])) print("min = {:.2f}, max = {:.2f}, no_data = {}, cell_size = {}".format( min_elev, max_elev, no_data, cell_size)) # depression filling print("Depression filling ...") dem_filled = rd.FillDepressions(dem, in_place=False) dem_diff = dem_filled - dem dem_diff.no_data = 0 print("Saving filled dem ...") rd.SaveGDAL(out_dem_filled, dem_filled) rd.SaveGDAL(out_dem_diff, dem_diff) # nb_labels is the total number of objects. 0 represents background object. print("Region grouping ...") label_objects, nb_labels = regionGroup(dem_diff, min_size, no_data) dem_diff[label_objects == 0] = 0 depth = np2rdarray(dem_diff, no_data=0, projection=projection, geotransform=geotransform) rd.SaveGDAL(out_depth, depth) del dem_diff, depth print("Computing properties ...") # objects = measure.regionprops(label_objects, dem, coordinates='xy') objects = measure.regionprops(label_objects, dem) dep_list = get_dep_props(objects, cell_size) write_dep_csv(dep_list, out_csv_file) del objects, dep_list # convert numpy to richdem data format region = np2rdarray(label_objects, no_data=0, projection=projection, geotransform=geotransform) del label_objects print("Saving sink dem ...") sink = np.copy(dem) sink[region == 0] = 0 sink = np2rdarray(sink, no_data=0, projection=projection, geotransform=geotransform) rd.SaveGDAL(out_sink, sink) # del sink print("Saving refined dem ...") dem_refined = dem_filled dem_refined[region > 0] = dem[region > 0] dem_refined = np2rdarray(dem_refined, no_data=no_data, projection=projection, geotransform=geotransform) rd.SaveGDAL(out_dem, dem_refined) rd.SaveGDAL(out_region, region) del dem_refined, region, dem print("Converting raster to vector ...") polygonize(out_region, out_vec_file) end_time = time.time() print("Total run time:\t\t\t {:.4f} s\n".format(end_time - start_time)) return out_sink
def ExtractSinks(in_dem, min_size, out_dir): start_time = time.time() out_dem = os.path.join(out_dir, "dem.tif") out_dem_filled = os.path.join(out_dir, "dem_filled.tif") out_dem_diff = os.path.join(out_dir, "dem_diff.tif") out_sink = os.path.join(out_dir, "sink.tif") out_region = os.path.join(out_dir, "region.tif") out_depth = os.path.join(out_dir, "depth.tif") out_csv_file = os.path.join(out_dir, "depressions_info.csv") out_vec_file = os.path.join(out_dir, "depressions.shp") # delete contents in output folder if existing if not os.path.exists(out_dir): os.mkdir(out_dir) # load the dem and get dem info print("Loading data ...") dem = rd.LoadGDAL(in_dem) no_data = dem.no_data projection = dem.projection geotransform = dem.geotransform cell_size = geotransform[1] # get min and max elevation of the dem max_elev = np.float(np.max(dem)) min_elev = np.float(np.min(dem[dem > 0])) print("min = {:.2f}, max = {:.2f}, no_data = {}, cell_size = {}".format(min_elev, max_elev, no_data, cell_size)) # depression filling print("Depression filling ...") dem_filled = rd.FillDepressions(dem, in_place=False) dem_diff = dem_filled - dem dem_diff.no_data = 0 print("Saving filled dem ...") rd.SaveGDAL(out_dem_filled, dem_filled) rd.SaveGDAL(out_dem_diff, dem_diff) # nb_labels is the total number of objects. 0 represents background object. print("Region grouping ...") label_objects, nb_labels = regionGroup(dem_diff, min_size, no_data) # regions = measure.regionprops(label_objects, dem_diff) dem_diff[label_objects == 0] = 0 depth = np2rdarray(dem_diff, no_data=0, projection=projection, geotransform=geotransform) rd.SaveGDAL(out_depth, depth) del dem_diff, depth print("Computing properties ...") objects = measure.regionprops(label_objects, dem) dep_list = get_dep_props(objects, cell_size) write_dep_csv(dep_list, out_csv_file) del objects, dep_list # convert numpy to richdem data format region = np2rdarray(label_objects, no_data=0, projection=projection, geotransform=geotransform) del label_objects print("Saving sink dem ...") sink = np.copy(dem) sink[region == 0] = 0 sink = np2rdarray(sink, no_data=0, projection=projection, geotransform=geotransform) rd.SaveGDAL(out_sink, sink) # del sink print("Saving refined dem ...") dem_refined = dem_filled dem_refined[region > 0] = dem[region > 0] dem_refined = np2rdarray(dem_refined, no_data=no_data, projection=projection, geotransform=geotransform) rd.SaveGDAL(out_dem, dem_refined) rd.SaveGDAL(out_region, region) del dem_refined, region, dem print("Converting raster to vector ...") polygonize(out_region, out_vec_file) # # plot dems # demfig = rd.rdShow(dem, ignore_colours=[0], axes=False, cmap='jet', figsize=(8, 5.5)) # demfig_filled = rd.rdShow(dem_filled, ignore_colours=[0], axes=False, cmap='jet', vmin=demfig['vmin'], # vmax=demfig['vmax'], figsize=(8, 5.5)) # demfig_diff = rd.rdShow(dem_diff, ignore_colours=[0], axes=False, cmap='jet', figsize=(8, 5.5)) end_time = time.time() print("Total run time:\t\t\t {:.4f} s".format(end_time - start_time)) return sink
import richdem as rd import numpy as np import subprocess from osgeo import gdal, ogr dem = rd.LoadGDAL("chro_extent_lowRes.tif") dem = dem.astype(np.float32, copy=False) #Fill depressions with epsilon gradient to ensure drainage rd.FillDepressions(dem, epsilon=True, in_place=True) #Get flow accumulation with no explicit weighting. The default will be 1. accum = rd.FlowAccumulation(dem, method='Dinf') # accum[ accum >= 500] = 1 # accum[ accum < 500] = 0 # d8_fig = rd.rdShow(accum, zxmin=450, zxmax=550, zymin=550, zymax=450, figsize=(8,5.5), axes=False, cmap='jet') rd.SaveGDAL('flow_accumulation.tif', accum) # tmp_raster = 'd8.tif' # base_dir='' # plgs_shp='rivernetwork.shp' # subprocess.check_call(['gdal_polygonize.py %s -b 1 -mask %s -f "ESRI Shapefile" %s' % (tmp_raster, tmp_raster, # base_dir + # plgs_shp)], shell=True) # exec_string = 'ogr2ogr -overwrite %s %s -nlt LINESTRING' % ('line_' + plgs_shp, base_dir + plgs_shp) # # if simplify: # simplify_tol=50 # exec_string = exec_string + ' -simplify ' + str(simplify_tol)
def get_delineated_watershed(dem_data, basin_data, tif_data, discharge_file, output_fname): dem = 1 try: dem = loadmat(dem_data)['DEM_filled'] except: DEM = rd.LoadGDAL("DEM_clipped.tif") DEM1 = rd.FillDepressions(DEM, epsilon=False, in_place=False) DEM1_EPS = rd.FillDepressions(DEM1, epsilon=True, in_place=False) dem = np.asarray(DEM1_EPS) INCR_ROW, INCR_COL = [0, 1, 1, 1, -1, -1, -1, 0], [1, 0, -1, 1, -1, 1, 0, -1] D8_SIZE = 8 NUM_ROWS, NUM_COLS = dem.shape[0], dem.shape[1] def is_inside(row, col): ''' check if the cell (row,col) is a valid cell or not''' if row < NUM_ROWS and row >= 0 and col < NUM_COLS and col >= 0: return True else: return False # load the basin, latitude-longitude limits, # precipitation .mats , these are to be custom inputs basin_mat = loadmat(basin_data)['rev_new'] flow_grid = np.ones((NUM_ROWS, NUM_COLS)) * -1 prev = -1 for r in range(NUM_ROWS): if prev == -1: prev = (r / NUM_ROWS) * 100 print("%d%% processing done" % (prev)) else: curr = (r / NUM_ROWS) * 100 if curr - prev >= 1: print("%d%% processing done" % (curr)) prev = curr for c in range(NUM_COLS): ''' iterate through each grid of DEM data''' if math.isnan(dem[r, c]): continue max_flow = -1 for i in range(D8_SIZE): new_r, new_c = r + INCR_ROW[i], c + INCR_COL[i] if is_inside(new_r, new_c): cur_flow = (dem[r, c] - dem[new_r, new_c] ) / math.sqrt(INCR_ROW[i]**2 + INCR_COL[i]**2) if cur_flow >= max_flow: max_flow = cur_flow if max_flow > 0: flow_grid[r, c] = i else: flow_grid[r, c] = -2 if max_flow == -1: flow_grid[r, c] = -1 # save the flow grid as a CSV file np.savetxt('flow_dir.csv', flow_grid, delimiter=',') # read the discharge location as a csv file, CUSTOM INPUT disch_loc = pd.read_csv(discharge_file) # get the latitude and longitude limits from the .tif file # the tif file is supposed to be USER INPUT ds = gdal.Open(tif_data) width = ds.RasterXSize height = ds.RasterYSize gt = ds.GetGeoTransform() minx = gt[0] miny = gt[3] + width * gt[4] + height * gt[5] maxx = gt[0] + width * gt[1] + height * gt[2] maxy = gt[3] longitude_range, latitude_range = np.linspace(minx, maxx, NUM_COLS), np.linspace( miny, maxy, NUM_ROWS) def locate_sink(lat, long): ''' locate sinks manually ''' temp = 25 x = deepcopy(dem[lat - temp:lat + temp, long - temp:long + temp]) y = deepcopy(flow_grid[lat - temp:lat + temp, long - temp:long + temp]) d_lat, d_long = np.where(y == -2) a = [(d_lat[i], d_long[i]) for i in range(len(d_lat))] min_alt = x[temp, temp] for i in a: if min_alt >= x[i] and not math.isnan(x[i]): min_alt = x[i] m_lat, m_long = np.where(x == min_alt) b = [(m_lat[i], m_long[i]) for i in range(len(m_lat))] c = [np.asarray(i) for i in list(set(a).intersection(b))] if len(c) > 0: return [ tuple(i + np.array([-temp + lat, -temp + long])) for i in c ] else: return [(lat, long)] sink_list = [] for index, row in disch_loc.iterrows(): curr_lat, curr_long = row['latitude'], row['longitude'] lat_row = (np.abs(latitude_range - curr_lat)).argmin() long_col = (np.abs(longitude_range - curr_long)).argmin() sink_list.append(locate_sink(lat_row, long_col)) # FOR DFS, we initialize the visited array and watershed masks visited = np.zeros((NUM_ROWS, NUM_COLS)) watershed = np.zeros((NUM_ROWS, NUM_COLS)) def DFS(curr_row, curr_col, index): visited[curr_row, curr_col] = 1 watershed[curr_row, curr_col] = index for i in range(D8_SIZE): new_row, new_col = curr_row + INCR_ROW[i], curr_col + INCR_COL[i] if is_inside(new_row, new_col): # If the water flows from the new cell to the this cell if (flow_grid[new_row, new_col] == 7 - i or flow_grid[new_row, new_col] == -2) and visited[new_row, new_col] == 0: DFS(new_row, new_col, index) # iterate through all sink locations, backtracking for each of them to the highest point. for i, sink_list in enumerate(sink_list): for start_node in sink_list: try: DFS(start_node[0], start_node[1], i + 1) except RecursionError as re: print("Could not compute for (%d, %d)" % (start_node[0], start_node[1])) # store the delineated watershed basin_mat_x, basin_mat_y = basin_mat.shape[0], basin_mat.shape[1] basin_mat_delineated = np.zeros((basin_mat_x, basin_mat_y)) for r in range(basin_mat.shape[0]): for c in range(basin_mat.shape[1]): # Resolution of basin files is 0.25 and that of dem file # is 0.0083. Thus, one cell in basin is equivalent to # 30 cells of the DEM file. top, bottom = r * 30, (r + 1) * 30 left, right = c * 30, (c + 1) * 30 # Get the corresponding indexes in dem file cell_group = watershed[top:bottom, left:right] if cell_group.size: # Find the most common watershed in given cells values, counts = np.unique(cell_group, return_counts=True) ind = np.argmax(counts) # Assign the most common watershed in DEM to the corresponding cell in basin basin_mat_delineated[r, c] = values[ind] savemat(output_fname, {'basin_mat_delineated': basin_mat_delineated})
import richdem as rd fl = './data/NE/cedar2m/hdr.adf' outfl = './data/cedar2m_d8_accum.tiff' dem = rd.LoadGDAL(fl) rd.FillDepressions(dem, in_place=True) accum_d8 = rd.FlowAccumulation(dem, method='D8') rd.SaveGDAL(outfl, accum_d8)
def get_d8_without_depression(self, dem_img, pad=3): dem_rd = rd.rdarray(dem_img, no_data=-9999) dem_filled_rd = np.array(rd.FillDepressions(dem_rd, in_place=False)) d8_without_depression = self.get_d8(dem_filled_rd, pad=pad) return d8_without_depression
def _build_terrain_params(self, mode='pygsflow'): """This method computes flow accumulation/direction rasters for both RichDEM and PyGSFLOW. RichDEM seems to fill depressions more effectively and is fast.""" self.dem = rd.LoadGDAL(self.cfg.elevation, no_data=0.0) if np.any(self.dem == 0.0): for r in range(self.dem.shape[0]): d = self.dem[r, :].ravel() idx = np.arange(len(d)) self.dem[r, :] = np.interp(idx, idx[d > 0.0], d[d > 0.0]) if mode == 'richdem': # RichDEM flow accumulation and direction rd.FillDepressions(self.dem, epsilon=0.0001, in_place=True) self.dem = rd.rdarray(self.dem, no_data=0, dtype=float) rd_flow_accumulation = rd.FlowAccumulation(self.dem, method='D8') props = rd.FlowProportions(dem=self.dem, method='D8') # remap directions to pygsflow nomenclature dirs = np.ones_like(rd_flow_accumulation) for i in range(1, 9): dirs = np.where(props[:, :, i] == 1, np.ones_like(dirs) * i, dirs) rd_flow_directions = copy(dirs) for k, v in d8_map.items(): rd_flow_directions[dirs == k] = v # manually flow corners and edges inward rd_flow_directions[0, 0] = 2 rd_flow_directions[0, -1] = 8 rd_flow_directions[-1, 0] = 128 rd_flow_directions[-1, -1] = 32 rd_flow_directions[0, 1:-1] = 4 rd_flow_directions[1:-1, 0] = 1 rd_flow_directions[1:-1, -1] = 16 rd_flow_directions[-1, 1:-1] = 64 self.flow_direction = rd_flow_directions self.flow_accumulation = rd_flow_accumulation elif mode == 'pygsflow': # pygsflow flow accumulation and direction fa = FlowAccumulation(self.dem, self.modelgrid.xcellcenters, self.modelgrid.ycellcenters, verbose=False) self.flow_direction = fa.flow_directions(dijkstra=True, breach=0.001) self.flow_accumulation = fa.flow_accumulation() else: raise NotImplementedError( 'Must choose between "pygsflow" and "richdem" for ' 'flow calculations') fa = FlowAccumulation(self.dem, self.modelgrid.xcellcenters, self.modelgrid.ycellcenters, hru_type=self.hru_lakeless, flow_dir_array=self.flow_direction, verbose=False) self.watershed = fa.define_watershed(self.pour_pt, self.modelgrid, fmt='xy') self.streams = fa.make_streams(self.flow_direction, self.flow_accumulation, threshold=100, min_stream_len=10) self.cascades = fa.get_cascades(streams=self.streams, pour_point=self.pour_pt, fmt='xy', modelgrid=self.modelgrid) self.hru_aspect = bu.d8_to_hru_aspect(self.flow_direction) self.hru_slope = bu.d8_to_hru_slope(self.flow_direction, self.dem, self.modelgrid.xcellcenters, self.modelgrid.ycellcenters)
matplotlib.use("Agg") import numpy as np import richdem as rd from matplotlib import pyplot as plt ###Input the parameters #Gridded data e.g.raster file #Load the data and convert it to an array for RichDEM fname = 'L:/feather_river_mixing_paper/dem/pomd_out.tif' # Loading the raster with rasterio raster = rd.LoadGDAL(fname) #rasterfig = rd.rdShow(raster, ignore_colours=[0], axes=False, cmap='gist_earth', figsize=(8,5.5)) raster_filled = rd.FillDepressions(raster, epsilon=True, in_place=False) #rasterfig_filled = rd.rdShow(raster_filled, ignore_colours=[0], axes=False, cmap='gist_earth', vmin=rasterfig['vmin'], vmax=rasterfig['vmax'], figsize=(8,5.5)) accum_d8 = rd.FlowAccumulation(raster_filled, method='D8') #d8_fig = rd.rdShow(accum_d8, figsize=(8,5.5), axes=False, cmap='jet') slope = rd.TerrainAttribute(raster_filled, attrib='slope_riserun') #rd.rdShow(slope, axes=False, cmap='jet', figsize=(8,5.5)) profile_curvature = rd.TerrainAttribute(raster_filled, attrib='curvature') #rd.rdShow(profile_curvature, axes=False, cmap='jet', figsize=(8,5.5)) print(raster) temp = np.flip(raster, 0) raster = temp
import pandas as pd from osgeo import gdal import numpy as np import matplotlib.pyplot as plt import richdem as rd import os os.chdir('C:/temp/smr/trimmer_peak') dempath = 'dem/dem.tif' demds = gdal.Open(dempath) geot = demds.GetGeoTransform() demnp = demds.GetRasterBand(1).ReadAsArray() nrow = demds.RasterYSize ncol = demds.RasterXSize demds = None demfil = rd.FillDepressions(rd.LoadGDAL(dempath)) rdaccum = rd.FlowAccumulation(demfil, method='Dinf') slpds = gdal.Open('export/arcmap/gtiffs/FVSLOP.tif') slpnp = slpds.GetRasterBand(1).ReadAsArray() * 100.0 aspds = gdal.Open('export/arcmap/gtiffs/TASPEC.tif') aspnp = aspds.GetRasterBand(1).ReadAsArray() #clipath = 'climate/424856.cli' #temple fork clipath = 'climate/265191.cli' #trimmer peak clidat = np.genfromtxt(clipath, skip_header=15) lat = 41.82 #latitude lat2d = np.full((nrow, ncol), lat) pfc = 0.0 #percent forest cover #set simulation time frame