deltas
delta_directionality
Created on Sun Nov 18 19:26:01 2018
@author: Jon
- rivgraph.deltas.delta_directionality.set_link_directions(links, nodes, imshape, manual_set_csv=None)[source]
Set each link direction in a network.
This function sets the direction of each link within the network. It calls a number of helping functions and uses a somewhat-complicated logic to achieve this. The algorithms and logic is described in this open-access paper: https://esurf.copernicus.org/articles/8/87/2020/esurf-8-87-2020.pdf
Every time this is run, all directionality information is reset and recomputed. This includes checking for manually set links via the provided csv.
- Parameters:
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
imshape (tuple) – Shape of binary mask as (nrows, ncols).
manual_set_csv (str, optional) – Path to a user-provided csv file of known link directions. The default is None.
- Returns:
links (dict) – Network links and associated properties with all directions set.
nodes (dict) – Network nodes and associated properties with all directions set.
- rivgraph.deltas.delta_directionality.set_initial_directionality(links, nodes, imshape)[source]
Make initial attempt to set flow directions.
Makes an initial attempt to set all flow directions within the network. This represents the core of the “delta recipe” described in the following open access paper: https://esurf.copernicus.org/articles/8/87/2020/esurf-8-87-2020.pdf However, note that as RivGraph develops, this recipe may no longer match the one presented in that paper. The recipe chains together a number of exploitative algorithms to iteratively set flow directions for the most certain links first.
- Parameters:
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
imshape (tuple) – Shape of binary mask as (nrows, ncols).
- Returns:
links (dict) – Network links and associated properties with initial directions set.
nodes (dict) – Network nodes and associated properties with initial directions set.
- rivgraph.deltas.delta_directionality.fix_delta_cycles(links, nodes, imshape)[source]
Attempt to resolve cycles within the network.
Attempts to resolve all cycles within the delta network. This function is essentially a wrapper for
fix_delta_cycle(), which is where the heavy lifting is actually done. This function finds cycles, callsfix_delta_cycle()on each one, then aggregates the results.- Parameters:
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
imshape (tuple) – Shape of binary mask as (nrows, ncols).
- Returns:
links (dict) – Network links and associated properties with all possible cycles fixed.
nodes (dict) – Network nodes and associated properties with all possible cycles fixed.
allfixed (bool) – True if all cycles were resolved, else False.
- rivgraph.deltas.delta_directionality.fix_delta_cycle(links, nodes, cyc_links, imshape)[source]
Attempt to resolve a single cycle.
Attempts to resolve a single cycle within a delta network. The general logic is that all link directions of the cycle are un-set except for those set by highly-reliable algorithms, and a modified direction-setting recipe is implemented to re-set these algorithms. This was developed according to the most commonly-encountered cases for real deltas, but could certainly be improved.
- Parameters:
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
cyc_links (list) – Link ids comprising the cycle to fix.
imshape (tuple) – Shape of binary mask as (nrows, ncols).
- Returns:
links (dict) – Network links and associated properties with cycle fixed, if possible.
nodes (dict) – Network nodes and associated properties with cycle fixed, if possible.
fixed (bool) – True if the cycle was resolved, else False.
- rivgraph.deltas.delta_directionality.hull_coords(xy)[source]
Compute convex hull of a set of input points.
Computes the convex hull of a set of input points. Arranges the convex hull coordinates in a clockwise manner and removes the longest edge. This function is required by
dir_synthetic_dem().- Parameters:
xy (np.array) – Two element array. First element contains x coordinates, second contains y coordinates of points to compute a convex hull around.
- Returns:
hull_coords – Nx2 array of coordinates defining the convex hull of the input points.
- Return type:
np.array
- rivgraph.deltas.delta_directionality.dir_synthetic_DEM(links, nodes, imshape)[source]
Build a synthetic DEM using inlet/outlet locations.
Builds a synthetic DEM by considering inlets as “hills” and outlets as “depressions.” This synthetic is then used to compute the “slope” of each link, which is added to the links dictionary. Additionally, direction guesses for each link’s flow are computed.
- Parameters:
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
imshape (tuple) – Shape of binary mask as (nrows, ncols).
- Returns:
links (dict) – Network links and associated properties including a ‘slope’.
nodes (dict) – Network nodes and associated properties.
delta_metrics
Created on Mon May 21 09:00:01 2018
@author: Jon
- exception rivgraph.deltas.delta_metrics.ExperimentalDeltaMetricWarning[source]
Warning raised when computing legacy delta metrics.
- __weakref__
list of weak references to the object
- rivgraph.deltas.delta_metrics.list_metric_names()[source]
Return the stable output names produced by
compute_delta_metrics().
- rivgraph.deltas.delta_metrics.compute_delta_metrics(links, nodes, *, routing='width', inlet=None, inlet_weights=None, metrics=None, n_random=200, warn_experimental=True, return_intermediates=False)[source]
Compute delta metrics.
- Parameters:
links (dict) – RivGraph network dictionaries.
nodes (dict) – RivGraph network dictionaries.
routing ({"width", "uniform"}, optional) – Internal bifurcation routing policy used to build the weighted graph consumed by the legacy metric formulas.
inlet ({None, "width", "equal", "user"}, optional) – Boundary-condition policy for multiple-inlet networks. When multiple inlets are present, an explicit policy is required so inlet handling is never implicit. Explicit multi-inlet handling uses a virtual-source super-apex rather than pruning to a single real inlet.
inlet_weights (mapping, optional) – Required when
inlet='user'. Maps inlet node ids to nonnegative source weights.metrics (str or sequence[str], optional) – Restrict computation to a subset of metric outputs. Names must match those returned by
list_metric_names(). By default all metrics are computed.n_random (int, optional) – Number of random trials used when computing
nER_randomized.warn_experimental (bool, optional) – Emit a one-time warning that the delta metrics are experimental.
return_intermediates (bool, optional) – When True, also return the intermediate adjacency/steady-state context used by the metric functions.
- Returns:
Metric outputs, or
(metrics, deltavars)whenreturn_intermediates=True.- Return type:
dict or tuple[dict, dict]
- rivgraph.deltas.delta_metrics.add_super_apex_to_network(links, nodes, imshape)[source]
If multiple inlets are present, this adds a virtual-source “super apex” directly upstream of all inlet nodes. The synthetic links created have zero length and widths equal to the sum of the widths of the links connected to their respective inlet node.
- rivgraph.deltas.delta_metrics.remove_super_apex_from_network(links, nodes)[source]
If a virtual-source super-apex is present, this function deletes it and its connecting links.
- rivgraph.deltas.delta_metrics.graphiphy(links, nodes, weight=None, inletweights=None, *, split_parallel_links=False, return_parallel_metadata=False)[source]
Converts RivGraph links and nodes into a NetworkX graph object.
- Parameters:
links (dict) – RivGraph links and their attributes
nodes (dict) – RivGraph nodes and their attributes
weight (str, optional) – Link attribute to use to weight the NetworkX graph. If not provided or None, the graph will be unweighted (links of 1 and 0)
inletweights (list, optional) – Optional manual weights for the inlet links when using the virtual-source super-apex functionality. Overrides the weight set by the inlet link attribute in favor of values from the provided list. List must be in the same order and have the same length as
nodes['inlets'].split_parallel_links (bool, optional) – When True, surviving directed parallel links are preserved by inserting synthetic intermediate nodes into all but one link per parallel set so the resulting DiGraph does not collapse them.
return_parallel_metadata (bool, optional) – When True, also return a small metadata dictionary describing whether internal parallel-link splitting was used.
- Returns:
G (networkx.DiGraph) – Returns a NetworkX DiGraph object weighted by the link attribute specified in the optional parameter
weight.metadata (dict, optional) – Returned only when
return_parallel_metadata=True.
- rivgraph.deltas.delta_metrics.normalize_adj_matrix(G)[source]
Normalize adjacency matrix.
Normalizes a graph’s adjacency matrix so the sum of weights of each row equals one. G is a networkx Graph with weights assigned.
- rivgraph.deltas.delta_metrics.intermediate_vars(G, epsilon=1e-10)[source]
Compute intermediate variables and matrices.
Computes the intermediate variables and matrices required to compute delta metrics. This function prevents the re-computation of many matrices required in the metric functions.
Notes
Historically this function built several adjacency variants and repeatedly called the legacy eigen-based steady-state solver. The returned dictionary shape is preserved, but the shared plumbing is now handled by the propagation-based core in
_delta_metrics_core.
- rivgraph.deltas.delta_metrics.find_inlet_outlet_nodes(A)[source]
Find inlet and outlet nodes.
Given an input adjacency matrix (A), returns the inlet and outlet nodes. The graph should contain a single apex.
- rivgraph.deltas.delta_metrics.get_dag_diagnostics(links, nodes)[source]
Summarize whether a RivGraph network is a directed acyclic graph.
- Parameters:
links (dict) – RivGraph network dictionaries.
nodes (dict) – RivGraph network dictionaries.
- Returns:
Diagnostic summary with boolean
is_dagand, when cyclic, acyclic_regionslist describing strongly connected components that contain one or more directed cycles.- Return type:
dict
- rivgraph.deltas.delta_metrics.assert_dag_for_steady_state(links, nodes)[source]
Raise an informative error if the supplied network is not a DAG.
- rivgraph.deltas.delta_metrics.compute_steady_state_link_fluxes(G, links, nodes, weight_name='flux_ss', routing='width', inlet=None, inlet_weights=None, validate=True)[source]
Compute steady-state link fluxes.
- Parameters:
G (networkx graph) – Kept for backward compatibility but ignored by the new implementation.
links (dict)
nodes (dict)
weight_name (str, optional)
routing (str, optional) – Routing policy. Currently supports ‘width’ and ‘uniform’.
inlet (str, optional) – Inlet partition policy. Currently supports ‘width’, ‘equal’, and ‘user’. If None, width-based inlet partitioning is used.
inlet_weights (dict, optional) – Required when inlet=’user’. Mapping of inlet node id to nonnegative weight.
validate (bool, optional) – When True, require the directed network to be a DAG before propagating steady-state fluxes.
- rivgraph.deltas.delta_metrics.delta_subN_F(A, epsilon=1e-10)[source]
Compute steady state flux distribution.
Computes the steady state flux distribution in the delta nodes when the system is fed with a constant unity influx from the Apex. Also defines the subnetworks apex-to-outlet. The SubN is an NxM matrix, where N is number of nodes and M is number of outlets. For each mth outlet, its contributing subnetwork is given by the nonzero entries in SubN. The values in SubN are the degree of “belongingness” of each node to its subnetwork. If SubN(m,n) = 0, the m’th node does not belong to the n’th subnetwork; but if SubN(m,n) = 1, the m’th node belongs only to the n’th subnetwork. The values in SubN may be interpreted as the percentage of tracers that pass through node m that eventually make their way to the outlet of subnetwork n.
Notes
Historically this function used an eigenvalue/nullspace formulation and an epsilon cutoff to recover the steady-state solution. For DAGs, the same quantities can be computed directly by topological propagation, which is more stable and avoids brittle eigenvalue thresholding. The
epsilonargument is retained for backward compatibility and is now used only as a validation/zero-detection tolerance.
- rivgraph.deltas.delta_metrics.nl_entropy_rate(A)[source]
Compute nonlocal entropy rate.
Computes the nonlocal entropy rate (nER) corresponding to the delta (inlcuding flux partition) represented by matrix A
- rivgraph.deltas.delta_metrics.delta_nER(deltavars, N=500)[source]
Compute nonlocal entropy rate.
Compute the nonlocal entrop rate (nER) corresponding to the delta (including flux partition) represented by adjacency matrix A, and compares its value with the nER resulting from randomizing the flux partition.
- Returns:
pExc – the probability that the value of nER for a randomization of the fluxes on the topology dictated by A exceeds the actual value of nER. If the value of pExc is lower than 0.10, we considered that the actual partition of fluxes is an extreme value of nER
nER_Delta – the nonlinear entropy rate for the provided adjacency matrix
nER_randA – the nonlinear entropy rates for the N randomized deltas
- rivgraph.deltas.delta_metrics.top_entropy_based_topo(deltavars, epsilon=1e-10)[source]
Compute topologic mutual information and conditional entropies.
Computes the Topologic Mutual Information (TMI) and the Topologic Conditional Entropy for each subnetwork.
- rivgraph.deltas.delta_metrics.top_link_sharing_index(deltavars, epsilon=1e-10)[source]
Compute the link sharing index.
Computes the Link Sharing Index (LSI) which quantifies the overlapping (in terms of links) of each subnetwork with other subnetworks in the delta.
- rivgraph.deltas.delta_metrics.top_number_alternative_paths(deltavars, epsilon=1e-15)[source]
Compute number of alternative paths.
Computes the number of alternative paths (Nap) in the combinatorics sense from the Apex to each of the shoreline outlets.
- rivgraph.deltas.delta_metrics.top_resistance_distance(deltavars, epsilon=1e-15)[source]
Compute the topologic resistance distance.
The resistance distance between the apex and each outlet is computed on the undirected, unweighted graph induced by that outlet’s topologic subnetwork. The result is normalized by the unweighted shortest-path distance so values remain comparable across subnetworks of different size.
- rivgraph.deltas.delta_metrics.graphshortestpath(A, start, finish)[source]
Find the shortest path.
Uses networkx functions to find the shortest path along a graph defined by A; path is simply defined as the number of links. Actual length not considered. Number of links in the shortest path is returned.
- rivgraph.deltas.delta_metrics.top_s2s_topo_pairwise_dep(deltavars, epsilon=1e-10)[source]
Compute subnetwork topologic pairwise dependence.
This function computes the Subnetwork to Subnetwork Topologic Pairwise Dependence (TPD) which quantifies the overlapping for all pairs of subnetworks in terms of links.
- rivgraph.deltas.delta_metrics.dyn_flux_sharing_index(deltavars, epsilon=1e-10)[source]
Compute the flux sharing index.
Computes the Flux Sharing Index (LSI) which quantifies the overlapping (in terms of flux) of each subnetwork with other subnetworks in the delta.
- rivgraph.deltas.delta_metrics.dyn_leakage_index(deltavars, epsilon=1e-10)[source]
Compute the leakage index.
Computes the LI which accounts for the fraction of flux in subnetwork i leaked to other subnetworks.
- rivgraph.deltas.delta_metrics.dyn_pairwise_dep(deltavars, epsilon=1e-10)[source]
Compute subnetwork dynamic pairwise dependence.
Computes the subnetwork to subnetwork dynamic pairwise dependence (DPD) which quantifies the overlapping for all pairs of subnetworks in terms of flux.
- rivgraph.deltas.delta_metrics.dyn_entropy_based_dyn(deltavars, epsilon=1e-10)[source]
Compute dynamic mutual information and dynamic conditional entropy.
Computes the Dynamic Mutual Information (DMI) and the Dynamic Conditional Entropy for each subnetwork.
- rivgraph.deltas.delta_metrics.dist_from_apex(nodes, imshape)[source]
Calculate normalized distance from apex.
Does this for nodes. Calculates a normalized distances from apex, ignores pixel resolution.
- Parameters:
nodes (dict) – RivGraph dictionary of nodes
imshape (tuple) – Tuple of the shape of the domain (e.g., Imask.shape)
- Returns:
norm_dist – List of normalized straight line distances between each node and the inlet in the same order as the nodes come in the input nodes dictionary.
- Return type:
list
- rivgraph.deltas.delta_metrics.calc_QR(links, nodes, wt='wid_adj', new_at='graphQR')[source]
Clunky solution (target for optimization) to get QR at bifurcations.
QR is defined as the larger branch Q / smaller branch Q per Edmonds & Slingerland 2008 [2]. This measure of flux partitioning at a bifurcation does not scale beyond bifurcations to trifurcations etc. The graph-based flux partitioning scheme also assumes flow is routed in a steady-state manner based on the width (or some other attribute) of the links in the network. Therefore the actual flux value doesn’t matter, we can calculate QR as larger width / smaller width from the two branches as that will be the same as if we’d calculated the steady-state fluxes and taken their ratio. The function is written flexibly to allow one to assuming flux weighting by an attribute other than the link width if desired.
Warning
QR values calculated at nodes located at confluences, polyfurcations, or any other non-bifurcating location will be incorrect!
- Parameters:
links (dict) – RivGraph links dictionary
nodes (dict) – RivGraph nodes dictionary
wt (str, optional) – String pointing to the link attribute to use when calculating ratios, optional, default is ‘wid_adj’ which is the adjusted link widths
new_at (str, optional) – Name of the new attribute to add to the nodes dictionary, optional, default is ‘graphQR’ to indicate the graph calculated QR value
- Returns:
nodes – RivGraph dictionary with new_at attribute added
- Return type:
dict
delta_utils
A collection of functions for pruning a delta channel network.
- rivgraph.deltas.delta_utils.prune_delta(links, nodes, shoreline_shp, inlets_shp, imshape, gt, wkt, prune_less)[source]
Prune a delta network.
Clips a delta channel network given an inlet and shoreline shapefile and removes spurious links.
- Parameters:
links (dict) – stores the network’s links and their properties
nodes (dict) – stores the network’s nodes and their properties
shoreline_shp (str) – path to the shoreline shapefile (polyline)
inlets_shp (str) – path to the shapefile of inlet locations (point shapefile)
imshape (tuple) – Shape of the source mask raster.
gt (tuple) – Geotransform tuple of the source mask raster.
wkt (str) – WKT representation of the source mask CRS.
prune_less (bool) – Boolean to prune the network less… the first spur removal can create problems, especially for very small/simple networks.
- Returns:
links (dict) – updated links dictionary
nodes (dict) – updated nodes dictionary
- rivgraph.deltas.delta_utils.find_inlet_nodes(nodes, inlets_shp, imshape, gt, wkt)[source]
Load inlets from a shapefile.
Loads the user-defined inlet nodes point shapefile and uses it to identify the inlet nodes within the network.
- Parameters:
links (dict) – stores the network’s links and their properties
inlets_shp (str) – path to the shapefile of inlet locations (point shapefile)
imshape (tuple) – Shape of the source mask raster.
gt (tuple) – Geotransform tuple of the source mask raster.
wkt (str) – WKT representation of the source mask CRS.
- Returns:
nodes – nodes dictionary with ‘inlets’ key containing list of inlet node ids
- Return type:
dict
- rivgraph.deltas.delta_utils.clip_by_shoreline(links, nodes, shoreline_shp, imshape, gt, wkt)[source]
Clips links by a provided shoreline shapefile. The largest network is presumed to be the delta network and is thus retained. The network should have been de-spurred before running this function.
- Parameters:
links (dict) – stores the network’s links and their properties
nodes (dict) – stores the network’s nodes and their properties
shoreline_shp (str) – path to the shapefile of shoreline polyline
imshape (tuple) – Shape of the source mask raster.
gt (tuple) – Geotransform tuple of the source mask raster.
wkt (str) – WKT representation of the source mask CRS.
- Returns:
links (dict) – links dictionary representing network clipped by the shoreline
nodes (dict) – nodes dictionary representing network clipped by the shoreline. ‘outlets’ has been added to the dictionary to store a list of outlet node ids