def FlowAccumulation(): parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description="""RichDEM Flow Accumulation A variety of methods are available. Method Note Reference Tarboton Alias for Dinf. Dinf Alias for Tarboton. Quinn Holmgren with exponent=1. Holmgren(E) Generalization of Quinn. Freeman(E) TODO FairfieldLeymarie Alias for Rho8. Rho8 Alias for FairfieldLeymarie. OCallaghan Alias for D8. 10.1016/S0734-189X(84)80011-0 D8 Alias for OCallaghan. 10.1016/S0734-189X(84)80011-0 Methods marked (E) require the exponent argument. """) parser.add_argument('dem', type=str, help='Elevation model') parser.add_argument('outname', type=str, help='Name of output file') parser.add_argument('-m', '--method', type=str, required=True, help='Flow accumulation method to use') parser.add_argument('-e', '--exponent', type=float, help='Some methods require an exponent') 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)) accum = rd.FlowAccumulation(dem, method=args.method, exponent=args.exponent) rd.SaveGDAL(args.outname, accum)
def main(): """ RichDEM flat resolution: give a gentle slope """ # 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"] _method = options["method"] _exponent = options["exponent"] _weights = options["weights"] if (_method == "Holmgren") or (_method == "Freeman"): if _exponent == "": g.message( flags="w", message=("Exponent must be defined for " + "Holmgren or Freeman methods. " + "Exiting."), ) return else: _exponent = float(_exponent) else: _exponent = None if _weights == "": rd_weights = None else: g_weights = garray.array(_weights, null=np.nan) rd_weights = rd.rdarray(g_weights, no_data=np.nan) dem = garray.array(_input, null=np.nan) mask = dem * 0 + 1 rd_input = rd.rdarray(dem, no_data=np.nan) del dem rd_output = rd.FlowAccumulation( dem=rd_input, method=_method, exponent=_exponent, weights=rd_weights, in_place=False, ) rd_output *= mask accum = garray.array() accum[:] = rd_output[:] accum.write(_output, overwrite=gscript.overwrite())
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 main(): """ RichDEM flat resolution: give a gentle slope """ # 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".')) options, flags = gscript.parser() _input = options['input'] _output = options['output'] _method = options['method'] _exponent = options['exponent'] _weights = options['weights'] if (_method == 'Holmgren') or (_method == 'Freeman'): if _exponent == '': g.message(flags='w', message=('Exponent must be defined for ' + 'Holmgren or Freeman methods. ' + 'Exiting.')) return else: _exponent = float(_exponent) else: _exponent = None if _weights == '': rd_weights = None else: g_weights = garray.array() g_weights.read(_weights, null=np.nan) rd_weights = rd.rdarray(g_weights, no_data=np.nan) dem = garray.array() dem.read(_input, null=np.nan) mask = dem * 0 + 1 rd_input = rd.rdarray(dem, no_data=np.nan) del dem rd_output = rd.FlowAccumulation(dem=rd_input, method=_method, exponent=_exponent, weights=rd_weights, in_place=False) rd_output *= mask accum = garray.array() accum[:] = rd_output[:] accum.write(_output, overwrite=gscript.overwrite())
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 weighted_accum(in_dir, weight, out_directory, out_raster, boundary_geom): # uses the pysheds library to calculate flow accumulation, however its weighted with by a given array. with rasterio.open(os.path.join(out_directory, weight)) as src: weights = src.read(1) weights = np.where(weights == -9999, 0, 1) norm = np.linalg.norm(weights) weights = weights / norm # # g.accumulation(data='dir', weights=weights, out_name='weights_accum') # grid.to_raster('weights_accum', os.path.join(out_directory, out_raster),dtype=np.int32) accum = rd.FlowAccumulation(dem, method='D8', weights=weights.astype('float64')) rd.SaveGDAL(os.path.join(out_directory, "temp.tif"), accum) clip_to_boundary(out_directory, out_dir, boundary_geom, f"temp.tif", out_raster)
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)
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 np_curvature(x, y, z): d = y[1, 0] - y[0, 0] dy, dx = np.gradient(z, d) dz = np.sqrt(dx * dx + dy * dy) dy, dx = np.gradient(dz, d) return np.sqrt(dx * dx + dy * dy) # Gaussian hill n = 234 x, y, z = gaussian_hill_elevation(n) d = y[1, 0] - y[0, 0] sca = rd.FlowAccumulation(rd.rdarray(z, no_data=-9999), method='Freeman', exponent=1.1) sca *= d fg, ax = pl.subplots(1, 3) im = ax[0].imshow(z, cmap=pl.cm.cividis_r) cb = fg.colorbar(im, ax=ax[0], orientation='horizontal') cb.set_label('Elevation') im = ax[1].imshow(sca, cmap=pl.cm.viridis_r) cb = fg.colorbar(im, ax=ax[1], orientation='horizontal') cb.set_label('SCA (Freeman 1991 flow accumulation, MFD)') v = gaussian_hill_sca(n) - sca vmin = v.min() im = ax[2].imshow(v, cmap=pl.cm.seismic, vmin=vmin, vmax=-vmin)
###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 print(raster) y = np.size(raster, 1) x = np.size(raster, 0) print(np.shape(raster))
neigh_contri = RT.flow_from_neighcells(pitremovedDEM) ####### Simulate water balance for i in range(1,Pin_2d .shape[0]): s[i, :, :] = s[i - 1, :, :] + Pin_2d[i,:,:] hwt[i, :, :] = watht.ht_wattab(np.divide(s[i, :, :], soildepth), fc_p, por_p, soildepth) qlat_out[i, :, :] = qlat_2d(ksat, slope, hwt[i, :, :], geot_info[1], geot_info[1]) qlat_in[i, :, :] = RT.routeflow(neigh_contri, qlat_out[i, :, :]) s[i, :, :] = s[i, :, :] + qlat_in[i,:,:] - qlat_out[i,:,:] actET[i, :, :] = ET.simET_2d(PotET_2d[i, :, :], fc, wp, s[i - 1, :, :]) s[i,:,:] = s[i,:,:] - actET[i,:,:] percol[i, :, :] = perc_2d(kv, watht.ht_wattab(por, fc, np.divide(s[i, :, :], 1.0), soildepth)) s[i, :, :] = s[i, :, :] - percol[i,:,:] q[i, :, :] = np.where(s[i, :, :] > (soildepth*por), (s[i, :, :] - (soildepth*por)), 0.0) qa[i, :, :] = rd.FlowAccumulation(rd.LoadGDAL(dem_path), method='Dinf', weights=q[i,:,:]) s[i, :, :] = np.where(s[i, :, :] > (soildepth * por), (soildepth * por), s[i, :, :]) ###########################TBD################################################# ##### Some plots outrow = nrow-1 outcol = ncol-1 plt.plot(doy, qlat_in[:, outrow, outcol], 'g', doy, qa[:, outrow, outcol], 'c', doy, (qa[:, outrow, outcol]+qlat_in[:, outrow, outcol]), 'b') #plt.show() #plt.plot(doy, hwt[:, outrow, outcol], 'b') #plt.show() #plt.plot(doy, s[:, outrow, outcol], 'b') #plt.show()
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 daystart = 50
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)
import richdem import matplotlib.pyplot as plt infile = '/Users/mistral/Documents/CUBoulder/Science/Sulzer/data/Hydrology/ifsar_merged.tif' rd = richdem.LoadGDAL(infile, no_data=-9999) #filled = richdem.FillDepressions(rd, in_place=False) flow_acc = richdem.FlowAccumulation(rd, method='Rho8') fig, (ax1, ax2) = plt.subplots(1, 2) ax1.imshow(flow_acc, interpolation='none', vmin=40, vmax=100) ax2.imshow(rd, interpolation='none', vmin=2000, vmax=3000) ax1.set_xlim([2100, 3000]) ax1.set_ylim([3300, 2800]) ax2.set_xlim([2100, 3000]) ax2.set_ylim([3300, 2800]) #ax1.colorbar() #ax2.colorbar() plt.show() richdem.SaveGDAL( "/Users/mistral/Documents/CUBoulder/Science/Sulzer/data/Hydrology/Rho8_filled.tif", flow_acc)