WigglyRivers.rivers package
Submodules
WigglyRivers.rivers.CompareMeanders module
Functions related to comparison of meander databases
- WigglyRivers.rivers.CompareMeanders.classify_meanders(manual_indices: list, auto_indices: list, threshold: float = 0.8) tuple[source]
Comparison between the manual and automatic detection of meanders and classifies the comparison into four categories
Zone I: The automatic detection is a good approximation of the manual detection.
Zone II: The automatic detection is only a part of the manual detection.
Zone III: The automatic detection is a superset of the manual detection.
Zone IV: The automatic detection did not detect the
- Parameters:
manual_indices (list) – List of indices of the manually selected meanders.
auto_indices (list) – List of indices of the automatically selected meanders.
threshold (float, optional) – Threshold for classification among zones. Defaults to 0.8.
- Returns:
- classification_value, f_oa, f_om
classification_value (int): Value of the classification. f_oa (float): Fraction of the automatic meander that is inside
the manual meander.
- f_om (float): Fraction of the manual meander that is inside
the automatic meander.
- Return type:
tuple
- WigglyRivers.rivers.CompareMeanders.extract_closet_meanders(database_1: DataFrame, database_2: DataFrame, link_x: str = 'x_o', link_y: str = 'y_o', threshold: float = 0.8) DataFrame[source]
Extracts the closest meander from both meander databases using the intersect of the linking x and y coordiantes.
In this function we will compare meanders in database_1 with all the meanders on database_2.
- Parameters:
database_1 (pd.Dataframe) – Dataframe with the meander information extracted from the Rivers class to compare with database 2.
database_2 (pd.Dataframe) – Dataframe with the meander information extracted from the River Class to compare with database 1.
link_x (str, optional) – linking variable for x coordiantes. Defaults to “x_o”.
link_y (str, optional) – linking variable for y coordiantes. Defaults to “y_o”.
threshold (float, optional) – Threshold for classification among zones. Defaults to 0.8.
- Returns:
Dataframe with classification done among the meanders.
- Return type:
pd.Dataframe
WigglyRivers.rivers.ReachExtraction module
This class extracts the complete reaches obtained with the model
- class WigglyRivers.rivers.ReachExtraction.CompleteReachExtraction(data, comid_id='nhdplusid', logger=None, **kwargs)[source]
Bases:
objectThis class obtained meander information from the NHD dataset. It works by loading the NHD geometry and using different methods to obtain meander information.
The following are the available attributes
Attribute
Description
data
Pandas dataframe with the NHD information.
comid_id
String with the name of the comid column.
logger
Logger object.
The following are the methods of the class.
Methods
Description
load_coords
Load coordinates from file.
map_complete_network
Map comid network from the headwaters to the terminal nodes.
map_complete_network_down_up
Map the entire database. It will do exploration from the terminal nodes to the headwaters. Saving the information in each reach.
map_complete_network
Map comid network from the headwaters to the terminal
map_complete_reach
Map individual comid network from starting comid to
map_coordinates
Extract coordinates from the comid list.
- load_coords(path_coords: str) None[source]
DESCRIPTION:
Load coordinates from a file.
Args:
- param path_coords:
str Path to the coordinates file.
- property logger
logger for debbuging
- map_complete_network(start_comids: list | ndarray | None = None, huc_number: int = 4, max_num_comids: int | None = None, cut_comid_number: int = 3, do_not_overlap: bool = True) None[source]
DESCRIPTION:
Map comid network from the headwaters to the terminal nodes.
Args:
- param start_comids:
list, np.ndarray, Default None List of comids to be extracted.
- param huc_number:
int, Default 4 HUC number to be extracted.
- param max_num_comids:
int, Default None Maximum number of comids to be extracted.
- param cut_comid_number:
int, Minimum number of comids contained in a reach to be extracted
- param do_not_overlap:
bool, Default False If True, the comids will not overlap.
- map_complete_network_down_up(huc_number: int = 4)[source]
DESCRIPTION:
Map comid network from the headwaters to the terminal nodes.
Args:
- param huc_number:
int, Default 4 HUC number to be extracted.
- map_complete_reach(start_comid: str, huc_number: int = 4, do_not_overlap: bool = True) Tuple[list | ndarray, list][source]
DESCRIPTION:
Separate complete reach comid from the ToNode and FromNode values
Args:
- param start_comid:
str, Start comid value.
- param huc_number:
int, Default 4 Path of the current reach.
- param do_not_overlap:
bool, Default True If True, the reach extracted will not overlap with existing reaches extracted previously.
- return reach:
list, List of comids for the values
- rtype reach:
Union[list, np.ndarray]
- return huc_n:
list, List of huc numbers for the values
- map_coordinates(comid_list, file_coords)[source]
DESCRIPTION:
Map Coordinates and additional data to the comid_list
Args:
- param comid_list:
list, List with comid values
- param file_coords:
str, File name where the coordiantes will be saved.
- property save_format
save format of the files
WigglyRivers.rivers.RiverFunctions module
Functions related to meander creation and fitting.
- WigglyRivers.rivers.RiverFunctions.calculate_amplitude(x: ndarray, y: ndarray) ndarray[source]
Calculate amplitude of the meanders. This funcion rotates the meanders and calculates the distance between the maximum and minimum y values.
Additionally, it calculates the dimensionless coordinate of the meanders $x^*$ that depends on the angle between the starting point of the meander and each point within the meander.
Equation:
\[A = \max(y) - \min(y)\]\[x^* = \frac{\beta}{\pi} - 0.5\]example:
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) y = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) amplitude = calculate_amplitude(x, y)
- Parameters:
x (np.ndarray) – x coordinates.
y (np.ndarray) – y coordinates.
- Returns:
Amplitude of the meanders.
- Return type:
np.ndarray
- WigglyRivers.rivers.RiverFunctions.calculate_asymetry(x: ndarray, y: ndarray, c: ndarray) Tuple[float, float, float][source]
Calculate the asymmetry of the meander using Eq. 24 in Howard and Hemberger (1991).
If the value is lower than zero the meander has an assymetry to the left, and if the value is higher than zero the meander has an assymetry to the right. For most NHDPlus information cases left is upstream and right is downstream.
Equation:
\[a = \frac{\lambda_u - \lambda_d}{\lambda}\]example:
x = np.linspace(0, 100, 100) y = np.sin(x) c = calculate_curvature(x, y) a = calculate_asymetry(x, y, c)
References:
Howard, A. D., & Hemberger, A. T. (1991). Multivariate characterization of meandering. Geomorphology, 4(3–4), 161–186. https://doi.org/10.1016/0169-555X(91)90002-R
- Parameters:
x (np.ndarray) – x coordinates.
y (np.ndarray) – y coordinates.
c (np.ndarray) – curvature of the meander.
- Returns:
- asymmetry of the meander, half-length of
the meander, length of the upper part of the meander, length of the lower part of the meander.
- Return type:
Tuple[float, float, float]
- WigglyRivers.rivers.RiverFunctions.calculate_channel_width(da: ndarray) ndarray[source]
Calculate the channel width from the drainage area.
This function uses equation (15) presented in Wilkerson et al. (2014).
example:
da = 100 w = calculate_channel_width(da)
References:
Wilkerson, G. V., Kandel, D. R., Perg, L. A., Dietrich, W. E., Wilcock, P. R., & Whiles, M. R. (2014). Continental-scale relationship between bankfull width and drainage area for single-thread alluvial channels. Water Resources Research, 50. https://doi.org/10.1002/2013WR013916
- Parameters:
da (np.ndarray) – Drainage area in km^2.
- Returns:
Channel width in m.
- Return type:
np.ndarray
- WigglyRivers.rivers.RiverFunctions.calculate_coordinates_from_curvature(s_curvature: ndarray, c: ndarray, x: ndarray, y: ndarray) Tuple[ndarray, ndarray][source]
Calculate the coordinates from the curvature of the river. The coordinates are calculated using a numerical integration method. Using the angle between the initial direction.
Equation:
\[x = x_0 + \int_0^{s_n} C ds\]\[y = y_0 + \int_0^{s_n} C ds\]example:
s_curvature = np.linspace(0, 100, 100) c = np.sin(s_curvature) x = np.cos(s_curvature) y = np.sin(s_curvature) x_r, y_r = calculate_coordinates_from_curvature(s_curvature, c, x, y)
- Parameters:
s_curvature (np.ndarray) – streamwise coordinates.
c (np.ndarray) – curvature.
x (np.ndarray) – x initial two coordinates.
y (np.ndarray) – y initial two coordinates.
- Returns:
x and y reconstructed coordinates.
- Return type:
Tuple[np.ndarray, np.ndarray]
- WigglyRivers.rivers.RiverFunctions.calculate_curvature(ss: ndarray, xs: ndarray, ys: ndarray, derivatives: dict | None = None) Tuple[ndarray, ndarray, ndarray][source]
Calculate curvature and the direction angle from the coordinates and the arc-length of the river transect.
The equation for curvature and direction angle are based on the equations presented in (Güneralp and Rhoads, 2008).
If the derivatives are not provided, the function will calculate them using the np.gradient function.
Equation:
\[C = \frac{x'y''-y'x''}{[(x')^2+(y')^2]^{3/2}}\]example:
ss = np.linspace(0, 100, 100) xs = np.sin(ss) ys = np.cos(ss) r, c, theta = calculate_curvature(ss, xs, ys)
References:
Güneralp, İ., & Rhoads, B. L. (2008). Continuous Characterization of the Planform Geometry and Curvature of Meandering Rivers. Geographical Analysis, 40(1), 1–25. https://doi.org/10.1111/j.0016-7363.2007.00711.x
- Parameters:
ss (np.ndarray) – streamwise coordinates.
xs (np.ndarray) – x coordinates.
ys (np.ndarray) – y coordinates.
derivatives (Union[dict, None], optional) – derivatives of the coordinates. If None the function will calculate them using np.gradient function. The dictionary must contain the following keys: - ‘dxds’: derivative of x with respect to s. - ‘dyds’: derivative of y with respect to s. - ‘d2xds2’: second derivative of x with respect to s. - ‘d2yds2’: second derivative of y with respect to s Defaults to None.
- Returns:
- curvature, radius of
curvature, and direction angle.
- Return type:
Tuple[np.ndarray, np.ndarray, np.ndarray]
- WigglyRivers.rivers.RiverFunctions.calculate_direction_angle(ss: ndarray, xs: ndarray, ys: ndarray, derivatives: dict | None = None) ndarray[source]
Calculate the direction angle from the coordinates and the arc-length. Keep in mind that this calculation would not work if the river direction is in the second and third cartesian quadrants from the start of the river.
To have a better estimate of the direction angle use the function
RiverFunctions.calculate_curvature().Equation:
\[\theta = \theta_0 + \int_{s=0}^{s=s_n}Cds\]# Calculate direction angle ss = np.linspace(0, 100, 100) xs = np.sin(ss) ys = np.cos(ss) theta = calculate_direction_angle(ss, xs, ys) print(theta)
- Parameters:
ss (np.ndarray) – streamwise coordinates.
xs (np.ndarray) – x coordinates.
ys (np.ndarray) – y coordinates.
derivatives (Union[dict, None], optional) – Dictionary with the derivatives of the coordinates with respect to the arc-length. Defaults to None.
- Returns:
Direction angle.
- Return type:
np.ndarray
- WigglyRivers.rivers.RiverFunctions.calculate_direction_azimuth(ss: ndarray, xs: ndarray, ys: ndarray, derivatives: dict | None = None) ndarray[source]
Calculate the direction azimuth from the coordinates and the arc-length. Keep in mind that this calculation would not work if the river direction is in the second and third cartesian plane quadrants from the start of the river.
To have a better estimate of the direction angle use the function
RiverFunctions.calculate_curvature().Equation:
\[\theta = \tan^{-1}\left(\frac{y'}{x'}\right)\]example:
ss = np.linspace(0, 100, 100) xs = np.sin(ss) ys = np.cos(ss) theta = calculate_direction_azimuth(ss, xs, ys)
- Parameters:
ss (np.ndarray) – arc-length
xs (np.ndarray) – x coordinates
ys (np.ndarray) – y coordinates
derivatives (Union[dict, None], optional) – Dictionary with the derivatives of the coordinates with respect to the arc-length. Defaults to None.
- Returns:
Direction azimuth.
- Return type:
np.ndarray
- WigglyRivers.rivers.RiverFunctions.calculate_funneling_factor(x: ndarray, y: ndarray, s: ndarray, idx_st: int, idx_end: int) dict[source]
Calculate the funneling factor of the meander. The funneling factor is calculated by dividing the distance around the lobe by the distance between the inflection points.
Equation:
\[FF = \frac{L_l}{L_n}\]example:
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) y = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) s = np.linspace(0, 100, 100) idx_st = 0 idx_end = -1 results = calculate_funneling_factor(x, y, s, idx_st, idx_end) print(results)
- Parameters:
x (np.ndarray) – x coordinates.
y (np.ndarray) – y coordinates.
s (np.ndarray) – s coordinates.
idx_st (int) – index of the start point.
idx_end (int) – index of the end point.
- Raises:
ValueError – Raises if meander wraps on itself.
ValueError – Raises if the funneling factor is too small
- Returns:
- Dictionary with the following keys:
FF: float, Funneling factor of the curvature.
L_l: float, Length of the lobe.
L_n: float, Length of the neck.
s_l: float, s-coordinate of the start point of the lobe.
s_n: float, s-coordinate of the end point of the neck.
- Return type:
dict
- WigglyRivers.rivers.RiverFunctions.calculate_l(x: ndarray, y: ndarray) float[source]
Calculate valley length.
Equation:
\[l = \sqrt{(x_{end}-x_{start})^2+(y_{end}-y_{start})^2}\]example:
x = np.linspace(0, 100, 100) y = np.sin(x) l = calculate_l(x, y)
- Parameters:
x (np.ndarray) – x coordinates.
y (np.ndarray) – y coordinates.
- Returns:
valley length.
- Return type:
float
- WigglyRivers.rivers.RiverFunctions.calculate_lambda(x: ndarray, y: ndarray) float[source]
calculate the lenth of the meander.
Equation:
\[\lambda = \sum_{i=j}^k\sqrt{(x_{i+1}-x_{i})^2+(y_{i+1}-y_{i})^2}\]example:
x = np.linspace(0, 100, 100) y = np.sin(x) l = calculate_lambda(x, y)
- Parameters:
x (np.ndarray) – x coordinates.
y (np.ndarray) – y coordinates.
- Returns:
length of the meander.
- Return type:
np.ndarray
- WigglyRivers.rivers.RiverFunctions.calculate_radius_of_curvature(x: ndarray, y: ndarray, wavelength: float) Tuple[float, float, float][source]
Calculate the radius of curvature of the meander by fitting a circle to the half-meander section and using the wavelength as the arc length.
Equation:
\[\frac{1}{R} = \frac{\lambda}{2 \pi w}\]example:
x = np.linspace(0, 100, 100) y = np.sin(x) wavelength = 100 x_c, y_c, radius = calculate_radius_of_curvature(x, y, wavelength)
- Parameters:
x (np.ndarray) – x coordinates.
y (np.ndarray) – y coordinates.
wavelength (float) – Wavelength of the meander.
- Returns:
- x and y coordinates of the center and radius
of curvature.
- Return type:
Tuple[float, float, float]
- WigglyRivers.rivers.RiverFunctions.calculate_sinuosity(l: float, lambda_value: float) float[source]
Calculate the sinuosity.
Equation:
\[sinuosity = \frac{\lambda}{l}\]example:
l = calculate_l(x, y) lambda_value = calculate_lambda(x, y) sinuosity = calculate_sinuosity(l, lambda_value)
- Parameters:
l (float) – valley length.
lambda_value (float) – meander length.
- Returns:
sinuosity.
- Return type:
float
- WigglyRivers.rivers.RiverFunctions.calculate_spectrum_cuts(s: ndarray, c: ndarray) Tuple[ndarray, ndarray][source]
Calculate the spectrum cuts of the curvature.
example:
s = np.linspace(0, 100, 100) c = np.sin(s) peaks_min, min_s = calculate_spectrum_cuts(s, c)
- Parameters:
s (np.ndarray) – Streamwise distance vector.
c (np.ndarray) – Curvature.
- Returns:
- Tuple of the indices of the minima of the
curvature and the streamwise distance of the minima of the curvature.
- Return type:
Tuple[np.ndarray, np.ndarray]
- WigglyRivers.rivers.RiverFunctions.convert_str_float_list_vector(x_val: str) ndarray[source]
Convert string to float vector
example:
x_val = '[1, 2, 3, 4]' x_val = convert_str_float_list_vector(x_val)
- Parameters:
x_val (str) – String with the values separated by commas.
- Returns:
Vector with the values.
- Return type:
np.ndarray
- WigglyRivers.rivers.RiverFunctions.extend_node_bound(node: Node, c: ndarray) Node[source]
Extend the bounds of a node in the meanders.
- Parameters:
node (Node) – Node of the meanders.
c (np.ndarray) – Curvature of the transect.
- Returns:
- Node with idx_planimetry_extended_start and
idx_planimetry_extended_end.
- Return type:
Node
- WigglyRivers.rivers.RiverFunctions.fit_splines(s: ndarray, x: ndarray, y: ndarray, method: str = 'geometric_mean', ds: float = 0, k: int = 3, smooth: int = 0, ext: int = 0, return_derivatives: bool = True) Tuple[ndarray, ndarray, ndarray, ndarray, ndarray][source]
This function fits a spline to the coordinates with the minimum distance of the river.
example:
s = np.linspace(0, 100, 100) x = np.sin(s) y = np.cos(s) s_poly, x_poly, y_poly = fit_splines(s, x, y)
- Parameters:
s (np.ndarray) – Streamwise distance
x (np.ndarray) – x coordinates.
y (np.ndarray) – y coordinates.
method (str, optional) – Method to use for fitting the spline. The method can be “min”, “geometric_mean”, or “mean”. Defaults to “geometric_mean”.
ds (float, optional) – Distance between points in the spline. This parameter overrides the method parameter. Defaults to 0.
k (int, optional) – Degree of the spline. Defaults to 3.
smooth (int, optional) – Smoothness of the spline. Defaults to 0.
ext (int, optional) – Number of points to extrapolate. Defaults to 0.
return_derivatives (bool, optional) – Whether to return derivatives. Defaults to True.
- Raises:
ValueError – If method is not recognized.
- Returns:
- Tuple
of the spline points, x coordinates, y coordinates, derivatives of the spline, and derivatives of the x coordinates.
- Return type:
Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]
- WigglyRivers.rivers.RiverFunctions.fit_splines_complete(data: dict, method: str = 'geometric_mean', ds: float = 0, k: int = 3, smooth: float = 0, ext: int = 0) dict[source]
function to fit splines to the data of the River class.
example:
data = { "comid": comid, "so": so, "s": s, "x": x, "y": y, "z": z, "da_sqkm": da, "w_m": w, } splines = fit_splines_complete(data)
- Parameters:
data (dict) – dictionary containing the data of the river
method (str, optional) – Method to use for fitting the spline. The method can be “min”, “geometric_mean”, or “mean”. Defaults to “geometric_mean”.
ds (float, optional) – Distance between points in the spline. This parameter overrides the method parameter. Defaults to 0.
k (int, optional) – Degree of the spline. Defaults to 3.
smooth (int, optional) – Smoothness of the spline. Defaults to 0.
ext (int, optional) – Number of points to extrapolate. Defaults to 0.
- Raises:
ValueError – if method is not implemented
- Returns:
dictionary containing the splines
- Return type:
dict
- WigglyRivers.rivers.RiverFunctions.get_inflection_points(s: ndarray, c: ndarray) Tuple[ndarray, ndarray, ndarray, ndarray][source]
Obtain the inflection points from the curvature.
example:
s = np.linspace(0, 100, 100)\ c = np.sin(s)\ s_inf, c_inf = get_inflection_points(s, c)\
- Parameters:
s (np.ndarray) – streamwise coordinates.
c (np.ndarray) – Curvature.
- Returns:
- streamwise coordinates, curvature,
left curvature inflection point, and right curvature inflection point.
- Return type:
Tuple[np.ndarray, np.ndarray]
- WigglyRivers.rivers.RiverFunctions.get_reach_distances(x_coord: ndarray) ndarray[source]
This function calculates the cummulative streamwise distance of the river transect using the coordinates.
example:
x_coord = np.array([[1, 1], [1, 2], [2, 2]]) s = get_reach_distances(x_coord) print(s)
- Parameters:
x_coord (np.ndarray) – [x, y] coordinates in (n_points, 2)
- Returns:
Distance from the start point to the end point.
- Return type:
np.ndarray
- WigglyRivers.rivers.RiverFunctions.kinoshita_curve_abad(theta_0: float, lambda_value: float, j_s: float, j_f: float, n: int, m_points: int = 1000, ds: None | float = None) Tuple[ndarray, ndarray, dict][source]
Generate a Kinoshita Curve with the information related to the reach generated. The Kinoshita curve is based on (Kinoshita, 1961). The equations presented in this function are based on the equations presented in (Abad and Garcia, 2009).
Equation:
\[\theta(s) = \theta_0 \sin(k s) + \theta_0^3 (j_s \cos(3 k s) - j_f \sin(3 k s))\]example:
x, y, data = kinoshita_curve_abad( theta_0=110*np.pi/180, lambda_value=100, j_s=0.020, j_f=0, n=3, m_points=1000, ds=None )
References
Abad, J. D., & Garcia, M. H. (2009). Experiments in a high-amplitude Kinoshita meandering channel: 1. Implications of bend orientation on mean and turbulent flow structure: KINOSHITA CHANNEL, 1. Water Resources Research, 45(2). https://doi.org/10.1029/2008WR007016
Kinoshita, R. (1961). Investigation of channel deformation in Ishikari River. Report of Bureau of Resources, 174. Retrieved from https://cir.nii.ac.jp/crid/1571417124444824064
- Parameters:
theta_0 (float) – Maximum angular amplitude in radians.
lambda_value (float) – Arc wavelength.
j_s (float) – Skewness.
j_f (float) – Flatness or “fatness”.
n (int) – Number of meander loops.
m_points (int, optional) – Number of points that describe the meander. This parameter would be overwritten if ds is provided. Defaults to 1000.
ds (Union[None, float], optional) – delta of distance. If this parameter is None the function will calculate the distance between points using the number of pints (m_points). Defaults to None.
- Returns:
- X and Y coordinates and a
dictionary with the curvature, theta, streamwise coordinates, maximum length, maximum y extent, and sinuosity. The dictionary contains the following keys - ‘curve’: curvature, - ‘theta’: values of theta in each iteration, - ‘s’: streamwise coordinates, - ‘lmax’: maximum length, - ‘ymax’: maximum y extent, - ‘sinuosity’: sinuosity (sigma = smax/lmax).
- Return type:
Tuple[np.ndarray, np.ndarray, dict]
- WigglyRivers.rivers.RiverFunctions.kinoshita_curve_zolezzi(theta_0: float, lambda_value: float, theta_s: float, theta_f: float, n: int, m_points: int = 1000, ds: None | float = None) Tuple[ndarray, ndarray, dict][source]
Generate a Kinoshita Curve with the information related to reach generated.
The Kinoshita curve is based on (Kinoshita, 1961). The equations presented in this function are based on the equations presented in (Zolezzi and Güneralp, 2016).
Equation:
\[\theta(s) = \theta_0 \cos(k s) + \theta_s \sin(3 k s) + \theta_f \cos(3 k s)\]example:
x, y, data = kinoshita_curve_zolezzi( theta_0=110*np.pi/180, lambda_value=100, theta_s=0.344, theta_f=0.031, n=3, m_points=1000, ds=None )
References:
Kinoshita, R. (1961). Investigation of channel deformation in Ishikari River. Report of Bureau of Resources, 174. Retrieved from https://cir.nii.ac.jp/crid/1571417124444824064
Zolezzi, G., & Güneralp, I. (2016). Continuous wavelet characterization of the wavelengths and regularity of meandering rivers. Geomorphology, 252, 98–111. https://doi.org/10.1016/j.geomorph.2015.07.029
- Parameters:
theta_0 (float) – Maximum angular amplitude in radians.
lambda_value (float) – Arc wavelength.
theta_s (float) – coefficient for Skewness in radians.
theta_f (float) – coefficient for Fatness in radians.
n (int) – Number of loops.
m_points (int, optional) – Number of points that describe the meander. This parameter would be overwritten if ds is provided. Defaults to 1000.
ds (Union[None, float], optional) – delta of distance. If this parameter is None the function will calculate the distance between points using the number of pints (m_points). Defaults to None.
- Returns:
- X and Y coordinates and a
dictionary with the curvature, theta, streamwise coordinates, maximum length, maximum y extent, and sinuosity. The dictionary contains the following keys - ‘curve’: curvature, - ‘theta’: values of theta in each iteration, - ‘s’: streamwise coordinates, - ‘lmax’: maximum length, - ‘ymax’: maximum y extent, - ‘sinuosity’: sinuosity (sigma = smax/lmax).
- Return type:
Tuple[np.ndarray, np.ndarray, dict]
- WigglyRivers.rivers.RiverFunctions.line_intersection(line1: ndarray, line2: ndarray) Tuple[float, float][source]
find the intersection of two lines.
example:
line1 = np.array([[0, 0], [1, 1]]) line2 = np.array([[1, 0], [0, 1]]) x, y = line_intersection(line1, line2)
- Parameters:
line1 (np.ndarray) – Vector with the coordinates of the first line.
line2 (np.ndarray) – Vector with the coordinates of the second line.
- Raises:
Exception – Handle the case when the lines do not intersect.
- Returns:
x and y coordinates of the intersection.
- Return type:
Tuple[float, float]
- WigglyRivers.rivers.RiverFunctions.rle(in_array: ndarray) Tuple[ndarray, ndarray, ndarray][source]
Run length encoding. Partial credit to R rle function. Multi datatype arrays catered for including non Numpy.
- Parameters:
in_array (np.ndarray) – Array with values
- Returns:
- return
z: np.ndarray, run lengths. p: np.ndarray, start positions. ia: np.ndarray, values.
- Return type:
Tuple[np.ndarray, np.ndarray, np.ndarray]
- WigglyRivers.rivers.RiverFunctions.rotate(p: ndarray, p1: ndarray | None = None, p2: ndarray | None = None, theta: float | None = None) Tuple[ndarray, float][source]
rotate points (p) an angle theta or rotate the points such that p1 and p2 are aligned with the x-axis. The angle theta is calculated from the points p1 and p2. The rotation is done with the following matrix:
\[\begin{split}\begin{bmatrix} \cos(\theta) & \sin(\theta) \\ -\sin(\theta) & \cos(\theta) \end{bmatrix}\end{split}\]example:
# Rotate points based on p1 and p2 p = np.array([[1, 1], [1, 2], [2, 2]]) p1 = np.array([1, 1]) p2 = np.array([2, 2]) p_rot, theta = rotate(p, p1, p2) print(p_rot) print(theta) # Rotate points based on theta p = np.array([[1, 1], [1, 2], [2, 2]]) p_rot, theta = rotate(p, theta=np.pi/2) print(p_rot)
- Parameters:
p (np.ndarray) – original coordinates as (n_points, n_variables)
p1 (Union[np.ndarray, None], option) – initial coordinates as (1, n_variables). Defaults to None.
p2 (Union[np.ndarray, None], option) – ending coordinates as (1, n_variables). Defaults to None.
theta (Union[float, None], optional) – Angle of rotation. If None the code will calculate the angle from p1 and p2 and rotate the points such that p1 and p2 are aligned with the x-axis. If theta is provided, the code will rotate the points with theta. Defaults to None.
- Returns:
rotated points and the angle theta.
- Return type:
Tuple[np.ndarray, float]
- WigglyRivers.rivers.RiverFunctions.smooth_data(x: ndarray, y: ndarray, s: ndarray, poly_order: int = 2, savgol_window: int = 2, gaussian_window: int = 1) Tuple[ndarray, ndarray, ndarray][source]
smooth the data using savgol and gaussian filters.
example:
x = np.linspace(0, 100, 100) y = np.sin(x) s = np.linspace(0, 100, 100) s_smooth, x_smooth, y_smooth = smooth_data(x, y, s)
- Parameters:
x (np.ndarray) – x coordinates
y (np.ndarray) – y coordinates
s (np.ndarray) – streamwise coordinates
poly_order (int, optional) – order of the polynomial. Defaults to 2.
savgol_window (int, optional) – window size for savgol filter. Defaults to 2.
gaussian_window (int, optional) – window size for gaussian filter. Defaults to 1.
- Raises:
ValueError – if savgol_window is not odd
- Returns:
smoothed streamwise coordinates x_smooth (np.ndarray): smoothed x coordinates y_smooth (np.ndarray): smoothed y coordinates
- Return type:
s_smooth (np.ndarray)
- WigglyRivers.rivers.RiverFunctions.translate(p: ndarray, p1: ndarray) ndarray[source]
translate points (p) with respect to p1.
example:
p = np.array([[1, 1], [1, 2], [2, 2]]) p1 = np.array([1, 1]) p_trans = translate(p, p1) print(p_trans)
- Parameters:
p (np.ndarray) – points to translate
p1 (np.ndarray) – point to translate with respect to
- Returns:
translated points
- Return type:
np.ndarray
- WigglyRivers.rivers.RiverFunctions.translate_rotate(points, index_initial, index_final, theta=None)[source]
Description:
Translate and rotate points.
Args:
- param points:
np.ndarray Original coordinates as (n_points, n_variables)
- type points:
np.ndarray
- param index_initial:
int, Index of initial coordinates
- type index_initial:
int,
- param index_final:
int, Index of final coordinates
- type index_final:
int
- param theta:
float, Rotating angle in radians. If None, the code will calculate the angle from p1 and p2
- type theta:
float
- return:
rotation_matrix: np.ndarray, Translated and rotated points. theta: float, Angle of rotation.
WigglyRivers.rivers.RiversNetwork module
- DESCRIPTION:
Scripts related to meander creation and fitting.
- class WigglyRivers.rivers.RiversNetwork.Meander(id_meander, s, x, y, z, ind_start, ind_end, w_m=None, w_m_gm=None, c=None, sk=nan, fl=nan, comid=nan, x_o=None, y_o=None, ind_start_o=None, ind_end_o=None, so=None, x_inf=None, y_inf=None, s_inf=None, wavelength=None, metrics=None, calculations=True, automatic_flag=0, inflection_flag=False, tree_id=-1, scale_by_width=False)[source]
Bases:
objectThis class is the basic form of a meander. From the coordinates and height it calculates the basic metrics to report them.
Attribute
Description
s
Vector of distances of each point.
x
x-dir coordiantes.
y
y-dir coordiantes.
z
Height of each point.
ind_start
Start index in River.
ind_end
End index in River.
w_m
Width of the River.
w_m_gm
Geometric mean width of the River.
c
Curvature of the meander.
sk
Skewness.
fl
Flatness.
comid
COMID of the meander.
x_o
x-dir coordinates of the original river.
y_o
y-dir coordinates of the original river.
ind_start_o
Start index in original river.
ind_end_o
End index in original river.
so
Stream order of each point.
x_inf
x-dir coordinates of the inflection points.
y_inf
y-dir coordinates of the inflection points.
s_inf
Distance of the inflection points.
wavelength
Wavelength of the meander.
metrics
Calculated metrics.
calculations
Boolean to perform calculations.
automatic_flag
Boolean to indicate if the meander was automatically detected.
inflection_flag
Boolean to indicate if the meander has inflection points.
tree_id
Tree ID of the meander.
scale_by_width
Boolean to scale the meander by the width of the river.
The following are the methods of the class.
- calculate_amplitude()[source]
Calculate the amplitude of the meander by rotating the meander from the inflection points and calculating the distance between the minimum and maximum y values. Additionally, it calculates the dimensionless coordinate of the meander proposed by Lin and Limaye (2022).
Equations:
\[A = \max(y) - \min(y)\]\[x^* = \frac{\beta}{\pi} - 0.5\]\[A^* = \frac{A}{w_m}\]example:
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) y = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) amplitude, x_star, center_point, coords_apex = RF.calculate_amplitude(x, y)
References:
Li, Y., & Limaye, A. B. (2022). Testing Predictions for Migration of Meandering Rivers: Fit for a Curvature-Based Model Depends on Streamwise Location and Timescale. Journal of Geophysical Research: Earth Surface, 127(12), e2022JF006776. https://doi.org/10.1029/2022JF006776
- calculate_wavelength()[source]
This is an estimate of the wavelength that from data turns out to be 2 times the arc-length of the meander (lambda).
- get_infection_points()[source]
Description:
Have an estimate of the inflection points of the meander. This function calculates the curvature of the meander and then smooths the planimetry until it obtains the two inflection.
This is an approximation. A better way to obtained these values is to use the wavelet analysis in the automated detection.
- class WigglyRivers.rivers.RiversNetwork.RiverDatasets(scale=1, translate=False, logger=None)[source]
Bases:
objectThis class generates rivers from NHD Information.
Attribute
Description
scale
Scaling the river variables.
translate
Translate river variables
rivers
dictionary with rivers
The following are the methods of the class.
Methods
Description
add_river
Add river network
add_files
Add path to NHD files and HUC 04 of the network. These files have to be created beforehand with the pyDatAPros package.
map_network
Map the complete network from a list of start comids.
load_linking_network
Load the linking network from a file.
load_extracted_in_comid_network
Load the comid extracted in order to map the complete network.
get_reaches_from_network
Get reach coordinates from the comid network dictionary.
get_reach
Extract coordinates of a complete reach from the NHD dataset.
get_metric_database
Extract the meander metrics.
save_databases_meanders
Save meander metric database.
save_rivers
Save river files.
load_rivers_network
Load rivers dataset.
plot_rivers
Plot river network.
- add_files(path_data: str, huc04: str, path_coords: str | None = None, comid_id: str = 'nhdplusid', load_coords: bool = False) None[source]
Description:
This method adds the path to the NHD files and links the coordinates of the river network for reach extraction. It also creates the reach_generator object.
Args:
- param path_data:
str Path to the NHD files.
- type path_data:
str
- param huc04:
str HUC04 of the river network.
- type huc04:
str
- param path_coords:
str, default=None Path to the coordinates of the river network.
- type path_coords:
str
- param comid_id:
str, default=’nhdplus_id’ Name of the column with the comid id.
- type comid_id:
str
- return:
None
- add_river(id_value, x, y, s=None, z=None, so=None, comid=None, da_sqkm=None, w_m=None, huc04=nan, huc_n=nan, start_comid=nan, resample_flag=True, within_waterbody=None, uid=None, kwargs_resample=None, scale_by_width=False)[source]
Description:
Add river into the class
Args:
- param id_value:
int, ID of the river.
- param x:
np.array, X coordinates of the river.
- param y:
np.array, Y coordinates of the river.
- param s:
np.array, Distance long the river.
- param z:
np.array, Elevation of the river
- param so:
np.array, optional, Stream order of each coordinate of the river
- param comid:
np.array, optional, Comid of each coordinate of the river
- param da:
np.array, optional, Drainage area of each coordinate of the river
- param w:
np.array, optional, Width of the river
- param huc04:
str, optional, HUC 04 of the river
- param huc_n:
str, optional, level of the HUC of the river
- param start_comid:
int, optional, Comid of the start of the river
- param resample_flag:
bool, optional, If the splines have been calculated
- param uid:
str, optional, Unique ID of the river
- param method_spline:
str, optional, default=’geometric_mean’ Method used to calculate the distance between points in the spline options are: ‘min’, ‘mean’, and ‘geometric_mean’
- extract_cwt_data(rivers_ids=[])[source]
Description:
Extract continuous wavelet transform information.
- get_reach(id_value, start_comid=None, comid_list=None, huc=8, kwargs_resample={'method': 'geometric_mean'}, scale_by_width=False, uid=None)[source]
Description:
Get complete reach.
Args:
- param id_value:
str, float, int id of the river.
- type id_value:
int
- param start_comid:
float, comid of the start of the reach.
- type start_comid:
float
- param comid_list:
list list of comids to get the reach.
- param huc:
int huc number to get reach, if 4 it will get to the subregion level.
- type huc:
int
- param kwargs_resample:
dict kwargs to resample the reach. by default the method is ‘geometric_mean’. For more information look at the River class.
- type kwargs_resample:
dict
- param scale_by_width:
bool, default=False If True, the reach will be scaled by the width of the river.
- type scale_by_width:
bool
- param uid:
str, optional, Unique ID of the river
- type uid:
str
- get_reaches_from_network(huc: str, headwaters_comid: list | ndarray = None, linking_network_file: str = None, comid_network_file: str = None, min_distance: float = 1000.0, path_out: str = None, joblib_n_jobs: int = 1, file_name: None | str = None) None[source]
Description:
Get reach coordinates from the comid network dictionary.
Args:
- param headwaters_comid:
list, np.ndarray, List of headwaters comids
- type headwaters_comid:
list, np.ndarray
- param linking_network_file:
str, None, Path to the linking network file
- type linking_network_file:
str, None
- param comid_network_file:
str, None, Path to the comid network file
- type comid_network_file:
str, None
- param min_distance:
float, Minimum distance of the reach from the headwaters in meters
- type min_distance:
float
- param path_out:
str, None, Path to save the reach coordinates
- type path_out:
str, None
- param joblib_n_jobs:
int, default=1, Number of jobs to run in parallel
- type joblib_n_jobs:
int
- param extract_all:
bool, default=True, If True, the comid_network will be loaded and the complete comid lists will be extracted. If False, only the headwaters comid will be loaded.
- return:
None
- load_extracted_in_comid_network(path_file: str, huc=None) list[source]
Description:
Load the comid extracted in order to map the complete network.
Args:
- param path_file:
str, Path to the comid_network file.
- type path_file:
str
- param extract_all:
bool, default=True, If True, the comid_network will be loaded and the complete comid lists will be extracted. If False, only the headwaters comid will be loaded.
- return extracted_comids:
list, List of extracted comids
- rtype:
list
- load_huc_list_in_comid_network(path_file: str) list[source]
Description:
Load the comid extracted in order to map the complete network.
Args:
- param path_file:
str, Path to the comid_network file.
- type path_file:
str
- param extract_all:
bool, default=True, If True, the comid_network will be loaded and the complete comid lists will be extracted. If False, only the headwaters comid will be loaded.
- return extracted_comids:
list, List of extracted comids
- rtype:
list
- load_linking_network(path_file: str) None[source]
Description:
Load the linking network from a file.
Args:
- param path_file:
str, Path to the file with the linking network
- type path_file:
str
- return:
None
- load_river_network(path_file: str, headwaters_comid: str | None = None, fn_tree_scales: str | None = None, fn_tree_scales_database: str | None = None, fn_meanders_database: str | None = None, kwargs_resample=None, scale_by_width=None, recalculate_inflection_points=False, **kwargs) None[source]
Description:
Load the river network from an hdf5 file.
Args:
- param path_file:
str, Path to the hdf5 file
- type path_file:
str
- param headwaters_comid:
str, None, Default is None Name of the headwaters to extract. If None all the headwaters will be extracted.
- type headwaters_comid:
str, Defualt is None
- param fn_tree_scales:
str, Default is None Name of the file with the tree scales.
- type fn_tree_scales:
str
- param fn_tree_scales_database:
str, Default is None Name of the file with the tree scales database.
- type fn_tree_scales_database:
str
- param fn_meanders_database:
str, Default is None Name of the file with the meanders database.
- type fn_meanders_database:
str
- param kwargs_resample:
dict, Default is None Dictionary with the kwargs to resample the reach. If None, the kwargs will be extracted from the file.
- type kwargs_resample:
dict
- param scale_by_width:
bool, Have the rivers to be scaled by the minimum width.
- type scale_by_width:
bool
- param kwargs:
dict, Additional kwargs to add to the river.
- type kwargs:
dict
- property logger
- map_network(method: str = 'upstream', start_comids: float | str | list | ndarray | None = None, huc: int = 4, cut_comid_number: int = 3, max_num_comids: int = None, path_out: str = None, extension: str = 'feather') None[source]
Description:
Map the complete network from a list of start comids. Two lists will be created within the reach_generator object. One with the complete network as a dictionary and the other with the linking between the comids as a pandas dataframe.
If a path_out is provided, the complete network will saved as an ‘hdf5’ file with the string headwaters COMIDS as keys. The dataframe will be saved as with the extension given. By default it will be saved as ‘feather’.
There are two methods to map the network. The first one is ‘upstream’ and the second one is ‘downstream’. The first one starts from the terminal nodes and goes upstream recursively mapping the network. The second one starts from the headwaters and goes downstream until it reaches the terminal nodes or nodes that have already been extracted. The default method is ‘upstream’ because it works faster and it is more efficient.
Args:
- param method:
str, default=’upstream’ Method to map the network. Options are ‘upstream’ and ‘downstream’
- type methods:
str
- params start_comids:
list, List of start comids
- type start_comids:
list, np.ndarray
- params huc:
int, HUC number to cut to in the network
- type huc:
int
- params cut_comid_number:
int, Minimum number of comids per complete reach extraction
- type cut_comid_number:
int
- param max_num_comids:
int, Maximum number of comids per complete reach extraction
- type max_num_comids:
int
- param path_out:
str, Path to save the complete network
- type path_out:
str
- param extension:
str, Extension of the file to save the complete network
- type extension:
str
- return:
None
- plot_rivers(comids: float | int | str | list | None = None, engine: str = 'matplotlib', data_source='resample', **kwargs)[source]
Description:
Plot rivers from the river network.
Args:
- param comid:
float, int, str, list Comid of the river to plot
- type comid:
float, int, str
- save_cwt_data(path_output, file_name, rivers_ids=[])[source]
Description:
Save continuous wavelet transform information.
- save_databases_meanders(path_output, file_name)[source]
Description:
Save meander database
Args:
- param path_output:
str, Path to save the database
- type path_output:
str
- param file_name:
str, Name of the file to save the database
- type file_name:
str
- save_rivers(path_output, file_name, save_cwt_info=False, rivers_ids=[], fn_tree_scales='tree_scales.p', fn_tree_scales_database='tree_scales_database.feather', fn_meander_database='meander_database.csv')[source]
Description:
Save river files.
Args:
- param path_output:
str, Path to save the database
- type path_output:
str
- param file_name:
str, Name of the file to save the database
- type file_name:
str
- param save_cwt_info:
bool, default=False, If True, the CWT information will be saved as a pickle file.
- type save_cwt_info:
bool
- param fn_tree_scales:
str, default=’tree_scales.p’, Name of the file to save the tree scales, this file must be saved as a pickle file.
- type fn_tree_scales:
str
- param fn_tree_scales_database:
str, default=’tree_scales_database.feather’, Name of the file to save the tree scales database, this file can be saved as a feather or csv file.
- type fn_tree_scales_database:
str
- param fn_meander_database:
str, default=’meander_database.csv’, Name of the file to save the meander database, this file can be saved as a feather or csv file.
- type fn_meander_database:
str
- save_tree_scales(path_output, fn_tree_scales='tree_scales.p', fn_tree_scales_database='tree_scales_database.feather', rivers_ids=[])[source]
Description:
Save meander database
Args:
- param path_output:
str, Path to save the database
- type path_output:
str
- param file_name:
str, Name of the file to save the Tree scales object
- type file_name:
str
- class WigglyRivers.rivers.RiversNetwork.RiverTransect(uid: str | int | float, id_value: str | int | float, x: list | ndarray, y: list | ndarray, s: list | ndarray, z: List | ndarray | None = None, so: None | list | ndarray = None, comid: None | list | ndarray = None, da_sqkm: None | list | ndarray = None, w_m: None | list | ndarray = None, huc04: None | list | ndarray = None, huc_n: None | list | ndarray = None, start_comid: None | str | float | int = None, within_waterbody: None | list | ndarray = None, resample_flag: None | bool = True, kwargs_resample: None | dict = None, scale_by_width: None | bool = False, logger: None | Logger = None)[source]
Bases:
objectThis class is the basic form of rivers. Each river is contains the following base attributes.
Attribute
Description
uid
Unique Identifier for the River.
id_value
id for river.
s_o
Original vector of distances of each point.
x_o
Original x-dir coordiantes.
y_o
Original y-dir coordiantes.
z_o
Original height of each point.
so_o
Original Stream order of each point.
comid_so
Original comid for rivers
s
Spline fitted vector of distances of each point.
x
Spline fitted x-dir coordiantes.
y
Spline fitted y-dir coordiantes.
z
Spline fitted Height of each point.
so
Spline fitted stream order of each point.
comid
comid for rivers
da_sqkm
Drainage area in square kilometers. Optional
w_m
Width of the river in meters. Optional
huc04
HUC 04 for the reach. Optional This value is used for future reconstruction of the river using the NHDPlus dataset.
huc_n
number of HUC where data was clipped. Optional This value is used for future reconstruction of the river using the NHDPlus dataset.
start_comid
comid of the start of the reach. Optional This value is used for future reconstruction of the river using the NHDPlus dataset.
within_waterbody
vector that provides the section where the river is within a water body. Optional
resample_flag
Flag to resample the river. Default is True.
kwargs_resample
Resample kwargs. Default is None. The values accepted are:
- ‘method’: str, method to calculate the distance
between points. Options include: ‘min’, ‘mean’, ‘geometric_mean’, ‘geometric_mean_width’, ‘min_width’. The shorter the distance the heavier the file will be. Default is ‘min_width’.
- ‘ds’: Set distance to perorm the resampling.
If this value is None the distance will be calculated using the method provided. This distance will overide the method provided. The shorter the distance the heavier the file will be. Default is None.
- ‘k’: int, polynomial order of the spline.
Default is 3.
- ‘smooth’: float, smoothing factor for the spline.
The smoothing factor depends on the amount of points in the data, then the given number will be multiplied by the length of the data. Please look at scipy.interpolate.UnivariateSpline for more information. We recommend testing values that vary over orders of magnitude with respect to the length of the data. Default is 0.0.
- ‘ext’: int, controls the extrapolation mode for
elements not in the interval defined by the knot sequence. Default is 0. 0: return extrapolated values. 1: return zero 2: return 0 raise ValueError 3: return the boundary value. Please look at scipy.interpolate.UnivariateSpline for more information.
logger
Logger object.
The following are the methods of the class.
Methods
Description
set_gamma_width
Set value of gamma threshold for width for the CWT.
set_data_source
Set data source to extract data from
extract_data_to_save
Extract data to save in a file.
set_planimetry_derivatives
Set planimetry derivatives.
set_splines
Set splines of the x and y coordinates of the river.
eval_splines
Evaluate splines of the x and y coordinates of the river.
scale_coordinates
Scale coordinates by a given value
translate_xy_start
Translate coordinates to xy start
calculate_spline
Calculate spline of the river
calculate_smooth
Smooth the planimetry of the river.
calculate_curvature
Calculate curvature of the river.
extract_cwt_tree
Extract CWT and tree of the river
extract_meanders
Extract meanders from the river with CWT process.
get_cwt_curvature
Get CWT of the curvature of the river.
get_cwt_angle
Get CWT of the angle of the river.
extract_tree
Extract tree from the cwt of the river.
find_peaks_in_poly
Find peaks in the polygons of the cwt.
detect_meander_from_cwt
Detect meander from the cwt.
get_tree_center_points_in_planimtry
Get center points of the tree.
update_tree_scales
Update tree scales object
get_meander_bounds_from_cwt
Get meander bounds from the cwt.
add_meanders_from_bounds
Add meanders from captured bounds comming from cwt.
plot_cwt
Plot cwt tree of the river.
add_meander
Add meander to the river.
report_meander_metrics
Report meander Metrics.
remove_meander
Remove meander from list.
- add_meander(id_meander, ind_start, ind_end, metrics=None, sk=nan, fl=nan, automatic_flag=0, inflection_flag=False, tree_id=-1, x_inf=None, y_inf=None, s_inf=None, wavelength=None)[source]
Description:
Add meander to the meander list
Args:
- param id_meander:
int or str, Id of the meander.
- param ind_start:
int, Start index.
- param ind_end:
int, End index.
- param curvature_side:
int, Side of the curvature. Default np.nan.
- param metrics:
dict, Dictionary of metrics. Default None.
- param c:
np.array, Curvature. Default None.
- param s_curvature:
np.array, Distance along the curvature. Default None.
- param sk:
np.array, Skewness. Default None.
- param fl:
np.array, Flatness. Default None.
- param automatic_flag:
int, flag to add if the meander comes from the automated detection.
- param inflection_flag:
bool, flag to add if the points given are the inflection points of the meander.
- param tree_id:
int, Id of the tree where the meander belongs. Default -1.
- return:
- add_meanders_from_tree_scales(bounds_array_str='inflection', overwrite=False, clip='no')[source]
Description:
Add meanders from the database
Args:
- param bounds_array_str:
str, Default ‘inflection’. This parameter serves as a flag to indicate if the user wants to save the full-meander extent (‘extended’) or only the extent of the inflection points (‘inflection’).
- param overwrite:
bool, Default False. If True, overwrite the current meanders. Default False.
- param clip:
str, Default ‘no’. Clip meander bounds to other meander bounds to have a train of meanders. Only works if bounds_array_str=’inflection’. The possible options are: ‘no’: will not clip the meanders bounds. ‘downstream’: will clip the downstream begining meander bound to the upstream ending
meander bound.
- ‘upstream’: will clip the upstream ending meander bound to the downstream begining
meander bound.
- return:
- calculate_curvature(data_source: str = 'resample')[source]
Description:
Calculate the curvature and the direction angle of the river.
Args:
- param data_source:
str, Data source to use. Either ‘original’ or ‘smooth’.
- calculate_smooth(poly_order: int = 2, savgol_window: int = 3, gaussian_window: int = 1)[source]
Description:
Smooth the planimetry of the river.
Args:
- param poly_order:
int, Order of the polynomial to use for smoothing.
- type poly_order:
int
- param savgol_window:
int, Window size for the Savitzky-Golay filter.
- type savgol_window:
int
- param gaussian_window:
int, Window size for the Gaussian filter.
- type gaussian_window:
int
- calculate_spline(function=<function fit_splines_complete>, *args, **kwargs)[source]
Description:
Calculate spline of the river
Args:
- param function:
function, Function to use for calculating the spline. Default is RiverFunctions.fit_splines_complete.
- type function:
function
- param args:
list, List of arguments to pass to the function.
- type args:
list
- param kwargs:
dict, Dictionary of arguments to pass to the function.
- type kwargs:
dict
- create_meander_geopandas_dataframe(database='meander', geometry_columns=['x_o', 'y_o'], shape_type='line', crs='esri:102003')[source]
Description:
Create a geopandas dataframe from the meander dataframe
Args:
- param database:
str, Database to extract the meander information. Default ‘tree_scales’.
- param geometry_columns:
list, List of columns to use as geometry. Default [‘x_o’, ‘y_o’].
- param shape_type:
str, Shape type. Default ‘line’.
- param crs:
str, Coordinate reference system. Default ‘esri:102003’.
- eval_splines(s_value)[source]
Description:
evaluate splines of the x and y coordinates of the planimetry.
Args:
- param s_value:
float or array-like, Value of s to evaluate the splines.
- type s_value:
float or array-like
- extract_cwt_tree(bound_to_poly: bool = False, cwt_kwargs: dict | None = None)[source]
Description:
Extracts meanders from the river network using CWT.
Args:
- param bounds_array_str:
str, Bounds array string to use for the CWT. Either ‘aggregated’ or ‘individual’.
- param bound_to_poly:
bool, If True, the CWT is bound to the polygon.
- type bounds_array_str:
- param cwt_kwargs:
dict, Dictionary of CWT parameters. Look at function River.get_cwt() for parameters.
- type cwt_kwargs:
dict
- find_peaks_in_poly(remove_inside_coi: bool = False)[source]
Description:
Find the peaks in the polygon.
Args:
- param remove_inside_coi:
bool, If True, remove peaks that are inside the cone of influence.
- return:
- get_cwt_angle(pad: float = 1, dj: float = 0.05, s0: float = -1, j1: float = -1, mother: str = 'MORLET', m: int = 2)[source]
Description:
Calculate the continuous wavelet transform (CWT) of the direction angle.
Args:
- param pad:
int, Add padding of zeros to the curvature.
- param dj:
float, Spacing between discrete scales.
- param s0:
float, Smallest scale of the wavelet. Default 2*ds.
- param j1:
float, Number of scales minus one. Default 1/dj.
- param mother:
str, Mother wavelet. Default ‘MORLET’.
- param m:
int, Parameter of the mother wavelet. Default 2.
- return:
- get_cwt_curvature(pad: float = 1, dj: float = 0.05, s0: float = -1, j1: float = -1, mother: str = 'DOG', m: int = 2, sigtest=0, lag1=0, siglvl=0.95, dof=None)[source]
Description:
Calculate the continuous wavelet transform (CWT) of the curvature.
Args:
- param pad:
int, Add padding of zeros to the curvature.
- param dj:
float, Spacing between discrete scales.
- param s0:
float, Smallest scale of the wavelet. Default 2*ds.
- param j1:
float, Number of scales minus one. Default 1/dj.
- param mother:
str, Mother wavelet. Default ‘DOG’.
- param m:
int, Parameter of the mother wavelet. Default 2.
- return:
- get_tree_center_points_in_planimetry()[source]
Description:
Get the center points of the meanders.
- interactive_meander_characterization_plot(inflection_flag=False, mapbox_token=None, **kwargs)[source]
Description:
Interactive meander characterization. This function will only work in a Jupyter Notebook.
In this function, the idea is to select full meanders that only has one lobe and one neck. The user can also pick to select the half-meanders based on the location of the inflection points by setting inflection_flag=True.
- property logger
- plot_tree_nodes(include_width=True, title=None, **kwargs)[source]
Description:
Plot tree nodes.
Args:
- param include_width:
bool, If True, include width in the plot. Default True.
- param kwargs:
Keyword arguments to pass to the plot function. Look in utilities.graphs.plot_tree_from_anytree for more information in these arguments.
- prune_tree_by_gamma_width(gamma)[source]
Description:
Prune meanders by gamma width. Meanders with gamma width smaller than w_m_factor * gamma width are removed.
This function will change the key ‘meander_in_level_root_leaf’ in tree_scales. The key ‘meander_in_level_root_leaf’ contains the level where the meander is located in each branch.
Args:
- param gamma:
float Factor to multiply gamma width. Meanders with gamma width smaller than w_m_factor * gamma width are removed.
- prune_tree_by_peak_power(factor=0.1)[source]
Description:
Prune the tree scales by comparing the peak power of the parent to the ones of the children
- prune_tree_by_sinuosity(sinuosity_threshold=1.1, sinuosity_var='sn')[source]
Description:
Prune the meander nodes that have a sinuosity lower than the sinuosity_threshold.
Args:
- param sinuosity_var:
str, Sinuosity variable to use. Default ‘sn’.
- param sinuosity_threshold:
float, Sinuosity threshold. Default 1.1.
- remove_meander(id_meander)[source]
Description:
Remove meander from the meander list
Args:
- param id_meander:
int or str, Id of the meander.
- save_meanders_database(path_output, file_name, database='meander', type_info='shapefile', geometry_columns=['x_o', 'y_o'], shape_type='line', crs='esri:102003', **kwargs)[source]
Description:
Save meander database.
Args:
- param path_output:
str, Path to save the file.
- param file_name:
str, File name.
- param database:
str, Database to extract the meander information. Default ‘meander’.
- param type_info:
str, Type of file to save. Default ‘shapefile’.
- param geometry_columns:
list, List of columns to use as geometry. Default [‘x_o’, ‘y_o’].
- param shape_type:
str, Shape type. Default ‘line’.
- param crs:
str, Coordinate reference system. Default ‘esri:102003’.
- save_river_coordinates(path_output, file_name, type_info='shapefile', geometry_columns=['x_o', 'y_o'], shape_type='line', crs='esri:102003', **kwargs)[source]
Description:
Save river object.
Args:
- param path_output:
str, Path to save the file.
- param file_name:
str, File name.
- scale_coordinates(value: float)[source]
Description:
Scale coordinates by a given value
Args:
- param value:
float, Value to scale the coordinates.
- type value:
float
- set_data_source(data_source: str)[source]
Description:
Set data source to extract data from.
Args:
- param data_source:
str Set data source to extract data from. Options are:
‘original’: Original data ‘resample’: Resampled data ‘smooth’: Smoothed data
- type data_source:
str
- set_gamma_width(gamma: None | float | int = None)[source]
Description:
Set value of gamma threshold for width
Args:
- param gamma:
float, int, None Value of gamma threshold for width
- type gamma:
float, int, None
- set_planimetry_derivatives(planimetry_derivatives)[source]
Description:
Set planimetry derivatives
Args:
- param planimetry_derivatives:
dict, Dictionary with the planimetry derivatives, the keys are:
‘dxds’: derivative of x with respect to s ‘dyds’: derivative of y with respect to s ‘d2xds2’: second derivative of x with respect to s ‘d2yds2’: second derivative of y with respect to s
- type planimetry_derivatives:
dict
- set_splines(splines)[source]
Description:
Set splines of the x and y coordinates of the planimetry
Args:
- param planimetry_derivatives:
dict, Dictionary with the planimetry derivatives, the keys are:
‘dxds’: derivative of x with respect to s ‘dyds’: derivative of y with respect to s ‘d2xds2’: second derivative of x with respect to s ‘d2yds2’: second derivative of y with respect to s
- type planimetry_derivatives:
dict