rivgraph¶
RivGraph (classes.py)¶
Classes for running rivgraph commands on your channel network or centerline.
-
class
rivgraph.classes.
delta
(name, path_to_mask, results_folder=None, verbose=False)[source]¶ A class to manage and organize data and methods for analyzing a delta channel network. This class inherets all the attributes and methods of the rivnetwork class, but also includes delta-specific attributes and methods.
-
Iskel
¶ image of the skeletonized binary mask
- Type
np.ndarray
-
topo_metrics
¶ Contains a number of connectivity and network metrics.
- Type
dict
-
__init__
(name, path_to_mask, results_folder=None, verbose=False)[source]¶ - Parameters
name (str) – The name of the delta channel network; also defines the folder name for storing results.
path_to_mask (str) – Points to the channel network mask file path
results_folder (str, optional) – Specifies a directory where results should be stored
verbose (str, optional) – RivGraph will output processing progress if ‘True’. Default is ‘False’.
-
assign_flow_directions
()[source]¶ Computes flow directions for each link in the delta channel network.
-
compute_topologic_metrics
()[source]¶ Computes a suite of connectivity and network metrics for a delta channel network.
-
prune_network
(path_shoreline=None, path_inletnodes=None)[source]¶ Prunes the delta by removing spurs and links beyond the provided shoreline. Paths may be provided to shoreline and inlet nodes shapefiles, otherwise their location is specified by paths dictionary.
- Parameters
path_shoreline (str, optional) – Path to shoreline shapefile/geosjon. The default is None but will check for the file at paths[‘shoreline’].
path_inletnodes (str, optional) – Path to inlet nodes shapefile/geojson. The default is None but will check for the file at paths[‘inlet_nodes’].
- Returns
None, but saves pruned links and nodes dictionaries to class object.
-
-
class
rivgraph.classes.
river
(name, path_to_mask, results_folder=None, exit_sides=None, verbose=False)[source]¶ A class to manage and organize data and methods for analyzing a braided river channel network. This class inherets all the attributes and methods of the rivnewtwork class, but also includes delta-specific attributes and methods.
-
Iskel
¶ Image of the skeletonized binary mask
- Type
np.ndarray
-
topo_metrics
¶ Contains a number of connectivity and network metrics.
- Type
dict
-
centerline
¶ Centerline of the holes-filled river channel network mask. First element in tuple are x-coordinates; second are y-coordinates.
- Type
tuple of two numpy.ndarrays
-
centerline_smooth
¶ A smooth version of centerline
- Type
shapely.geometry.LineString
-
max_valley_width_pixels
¶ The maximum valley width in pixels, defined by widths along the centerline
- Type
np.int
-
width_chans
¶ Average channel width
- Type
float
-
width_extent
¶ Average width of the holes-filled channel mask
- Type
float
-
meshlines
¶ The lines of the mesh that are perpendicular to the local river direction
- Type
list of shapely.geometry.LineString
-
meshpolys
¶ Polygons comprising the along-channel mesh
- Type
list of shapely.geometry.Polygon
-
compute_centerline
()[source]¶ Computes the centerline of the holes-filled river channel network mask.
-
compute_mesh
(grid_spacing=None, smoothing=0.1, bufferdist=None)[source]¶ Computes a mesh that follows the channel centerline; grid_spacing sets the length of each grid cell; bufferdist sets the width of each grid cell.
-
assign_flow_direcions
()¶ Computes flow directions for each link in the delta channel network.
-
set_flow_dirs_manually
()¶ Reads a user-created .csv file found at paths[‘fixlinks_csv’] to set flow directions of specified links.
-
__init__
(name, path_to_mask, results_folder=None, exit_sides=None, verbose=False)[source]¶ Initializes a channelnetwork class.
- Parameters
name (str) – The name of the channel network; also defines the folder name for storing results.
path_to_mask (str) – Points to the channel network mask file path
results_folder (str, optional) – Specifies a directory where results should be stored
exit_sides (str, optional) – Only required for river channel netowrks. A two-character string (from N, E, S, or W) that denotes which sides of the image the river intersects (upstream first) – e.g. ‘NS’, ‘EW’, ‘NW’, etc.
verbose (bool, optional) – If True, print run information and warnings to the console, default is False.
-
name
¶ the name of the channel network, usually the river or delta’s name
- Type
str
-
verbose
¶ [True] or False to specify if processing updates should be printed.
- Type
str
-
d
¶ object created by gdal.Open() that provides access to geotiff metadata
- Type
osgeo.gdal.Dataset
-
mask_path
¶ filepath to the input binary channel network mask
- Type
str
-
imshape
¶ dimensions of the image (rows, cols)
- Type
tuple
-
gt
¶ gdal-type Geotransform of the input mask geotiff
- Type
tuple
-
wkt
¶ well known text representation of coordinate reference system of input mask geotiff
- Type
str
-
epsg
¶ epsg code of the coordinate reference system of input mask geotiff
- Type
int
-
unit
¶ units of the coordinate reference system; typically ‘degree’ or ‘meter’
- Type
str
-
pixarea
¶ area of each pixel, in units of ‘unit’
- Type
int or float
-
pixlen
¶ length of each pixel, assumes sides are equal-length
- Type
int or float
-
paths
¶ dictionary of strings for managing where files should be read/written
- Type
dict
-
exit_sides
¶ two-character string denoting which sides of the image the channel network intersects (N,E,S, and/or W). Upstream side should be given first.
- Type
str
-
Imask
¶ binary mask found at mask_path loaded into a numpy array via gdal.Open().ReadAsArray(), dtype=np.bool
- Type
numpy.ndarray
-
links
¶ Stores the links of the network and associated properties
- Type
dict
-
nodes
¶ Stores the nodes of the network and associated properties
- Type
dict
-
Idist
¶ image of the distance transform of the binary mask, dtype=np.float
- Type
numpy.ndarray
-
assign_flow_directions
()[source]¶ Automatically sets flow directions for each link in a braided river channel network.
-
compute_centerline
()[source] Computes the centerline of the holes-filled river binary image.
-
compute_mesh
(grid_spacing=None, smoothing=0.1, buf_halfwidth=None)[source] Generates an along-centerline mesh that indicates a valley-direction of sorts. The mesh is useful for computing spatial statistics as a function of downstream distance. The resulting mesh captures the low-frequency characteristic of the river corridor.
This tool is tricky to fully automate, and the user may need to play with the smoothing and bufferdist parameters if errors are thrown or the result is not satisfying.
- Parameters
grid_spacing (float) – Defines the distance between perpendicular-to-centerline transects. Units are defined by input mask CRS.
smoothing (float) – Defines the smoothing window of the left- and right-valleylines as a fraction of the total centerline length. Range is [0, 1].
buf_halfwidth (float) – Defines the offset distance of the left- and right-valleylines from from the centerline. Units correspond to those of the CRS of the input mask.
-
prune_network
()[source] Prunes the computed river network.
-
skeletonize
()[source] Skeletonizes the river binary mask.
-
-
class
rivgraph.classes.
rivnetwork
(name, path_to_mask, results_folder=None, exit_sides=None, verbose=False)[source]¶ Base rivnetwork class.
The rivnetwork class organizes data and methods for channel networks. This is a parent class to the delta and river classes which inherit rivnetwork methods and attributes. This class thus represents the common elements of river and delta channel networks.
-
__init__
(name, path_to_mask, results_folder=None, exit_sides=None, verbose=False)[source]¶ Initializes a channelnetwork class.
- Parameters
name (str) – The name of the channel network; also defines the folder name for storing results.
path_to_mask (str) – Points to the channel network mask file path
results_folder (str, optional) – Specifies a directory where results should be stored
exit_sides (str, optional) – Only required for river channel netowrks. A two-character string (from N, E, S, or W) that denotes which sides of the image the river intersects (upstream first) – e.g. ‘NS’, ‘EW’, ‘NW’, etc.
verbose (bool, optional) – If True, print run information and warnings to the console, default is False.
-
name
¶ the name of the channel network, usually the river or delta’s name
- Type
str
-
verbose
¶ [True] or False to specify if processing updates should be printed.
- Type
str
-
d
¶ object created by gdal.Open() that provides access to geotiff metadata
- Type
osgeo.gdal.Dataset
-
mask_path
¶ filepath to the input binary channel network mask
- Type
str
-
imshape
¶ dimensions of the image (rows, cols)
- Type
tuple
-
gt
¶ gdal-type Geotransform of the input mask geotiff
- Type
tuple
-
wkt
¶ well known text representation of coordinate reference system of input mask geotiff
- Type
str
-
epsg
¶ epsg code of the coordinate reference system of input mask geotiff
- Type
int
-
unit
¶ units of the coordinate reference system; typically ‘degree’ or ‘meter’
- Type
str
-
pixarea
¶ area of each pixel, in units of ‘unit’
- Type
int or float
-
pixlen
¶ length of each pixel, assumes sides are equal-length
- Type
int or float
-
paths
¶ dictionary of strings for managing where files should be read/written
- Type
dict
-
exit_sides
¶ two-character string denoting which sides of the image the channel network intersects (N,E,S, and/or W). Upstream side should be given first.
- Type
str
-
Imask
¶ binary mask found at mask_path loaded into a numpy array via gdal.Open().ReadAsArray(), dtype=np.bool
- Type
numpy.ndarray
-
links
¶ Stores the links of the network and associated properties
- Type
dict
-
nodes
¶ Stores the nodes of the network and associated properties
- Type
dict
-
Idist
¶ image of the distance transform of the binary mask, dtype=np.float
- Type
numpy.ndarray
-
__weakref__
¶ list of weak references to the object (if defined)
-
adjacency_matrix
(weight=None, normalized=False)[source]¶ Returns the adjacency matrix for a graph defined by links and nodes dictionaries.
- Parameters
weight (str, optional) – [None] or the attribute in the links dictionary to use for weighting links. Typically ‘wid_adj’ or ‘len’.
normalized (bool, optional) – If True, each row in the adjacency matrix will sum to one. [False] by default.
- Returns
A – an NxN matrix representing the connectivity of the graph, where N is the number of nodes in the network. See adjacency matrix for more details.
- Return type
numpy.ndarray
-
compute_junction_angles
(weight=None)[source]¶ Computes the angle at nodes where only three links are connected. Directions must be assigned before angles can be computed. Also defines each 3-link node as ‘confluence’ or ‘bifurcation’ and appends this designation to the nodes dictionary.
- Parameters
weight (str) – [None], ‘exp’ (exponential), or ‘lin’ (linear) to determine the decay of the weights the contributions of pixels as we move away from the junction node.
-
compute_link_width_and_length
()[source]¶ Computes widths and lengths of each link in the links dictionary and appends them as dictionary attributes.
-
compute_network
()[source]¶ Computes the links and nodes of the channel network mask. First skeletonizes the mask if not already done, then resolves the skeleton’s graph.
-
get_islands
(props=['area', 'maxwidth', 'major_axis_length', 'minor_axis_length', 'surrounding_links'])[source]¶ Finds all the islands in the binary mask and computes their morphological properties. Can be used to help “clean” masks of small islands.
- Parameters
props (list, optional) – Properties to compute for each island. Properties can be any of those provided by rivgraph.im_utils.regionprops. The default is [‘area’, ‘maxwidth’, ‘major_axis_length’, ‘minor_axis_length’].
- Returns
islands – Contains the polygons of each island with the requested property attributes as columns. An additional ‘remove’ attribute is initialized to make thresholding easier.
- Return type
geopandas GeoDataFrame
-
load_network
(path=None)[source]¶ Loads the link and nodes dictionaries from a .pkl file.
- Parameters
path (str) – path–including extension–to network .pkl file. If [None], file is loaded from path found in paths[‘network_pickle’]
-
plot
(*kwargs, axis=None)[source]¶ Generates matplotlib plots of the network.
- Parameters
*kwargs (str) – If [None], both of the following plots will be generated: ‘network’: links and nodes are plotted, labeled with their ids ‘directions’: links are plotted with their directionality indicated
-
save_network
(path=None)[source]¶ Writes the link and nodes dictionaries to a .pkl file.
- Parameters
path (str) – path–including extension–to network .pkl file. If [None], file written to path found in paths[‘network_pickle’]
-
to_geotiff
(export)[source]¶ Writes geotiffs to disk.
- Parameters
export (str) –
- Select a raster to write to geotiff. Choose from:
’directions’ - network burned into a raster with link directions from 0 (upstream) to 1 (downstream)) ‘skeleton’ - skeletonized mask ‘distance’ - distance-transformed mask
-
to_geovectors
(export='network', ftype='json')[source]¶ Writes the links and nodes of the network to geovectors.
- Parameters
export (str) –
Determines which features to export. Choose from:
all (exports all available vector data)
network (links and nodes)
links
nodes
centerline (river classes only)
mesh (centerline mesh, river classes only)
centerline_smooth (river classes only)
ftype (str) –
Sets the output file format. Choose from:
json (GeoJSON)
shp (ESRI Shapefile)
-
Directionality Utilities (directionality.py)¶
Created on Wed Nov 7 11:38:16 2018 @author: Jon
-
rivgraph.directionality.
add_directionality_trackers
(links, nodes, ntype)[source]¶ Adds fields to the links and nodes dictionaries that are required for setting and diagnosing directionality. Nodes are not altered in this function, but passed for consistency and generalizability.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
ntype (str) – Network type. Choose either ‘delta’ or ‘river’.
- Returns
links (dict) – Network links with added directionality properties.
nodes (dict) – Network nodes and associated properties.
-
rivgraph.directionality.
algmap
(key)[source]¶ Returns a numeric key corresponding to each algorithm used by RivGraph to set link directionality. These numbers are found in links[‘guess_alg’] and links[‘certain_alg’] and are useful for diagnosing issues in setting directionality.
- Parameters
key (str) – See the mapper below for the possible keywords.
- Returns
algno – Numeric representation of direction-setting algorithm.
- Return type
float or int
-
rivgraph.directionality.
check_continuity
(links, nodes)[source]¶ Finds all sinks or sources within the network, excluding inlets and outlets. Returns any nodes where continuity is violated. Only checks nodes for whom all attached links are certain.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
problem_nodes – Node ids corresponding to nodes[‘id’] where continuity is violated.
- Return type
list
-
rivgraph.directionality.
cycle_get_original_orientation
(links, lids)[source]¶ Saves the orientation of a set of links. Used before attempting to fix cycles. Properties besides ‘conn’ must also be reversed, so their original orientations are also stored.
- Parameters
links (dict) – Network links and associated properties.
lids (list) – Link ids whose orientations should be saved.
- Returns
orig – A subset of the links dictionary containing the orientations of each link in lids.
- Return type
dict
-
rivgraph.directionality.
cycle_return_to_original_orientation
(links, orig)[source]¶ Returns a set of links to its original orientation.
- Parameters
links (dict) – Network links and associated properties.
orig (dict) – Network links and associated properties to return to original orientations.
- Returns
links – Network links and associated properties in their original orientations.
- Return type
dict
-
rivgraph.directionality.
dir_bridges
(links, nodes)[source]¶ Guesses directionality of bridge links. Bridge links are those which flow must pass through to reach the outlet; in other words, if a bridge link is removed from the network, there will no longer be just one connected network. Directionality is inferred by consideration of which subnetwork (after removing the bridge link) contains inlet and outlet nodes.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
dir_known_link_angles
(links, nodes, dims, checklinks='all')[source]¶ Guesses directionality for unknown links whose immediately adjacent links’ directionalities are known. Computes the angle of “flow” between outlet and inlet end nodes for each neighboring link, then sets the unknown link such that its orientation minimizes the error between its neighbors and itself.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
dims (tuple) – Shape of the input mask as (nrows, ncols).
checklinks (list OR str, optional) – A list of link ids can be provided to check only specific links. Otherwise, the default is ‘all’ which checks all links.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
dir_main_channel
(links, nodes)[source]¶ Guesses directionality of links based on shortest paths from widest inlet link to all the outlet links. Links are also weighted by width, such that deviations from the “main channel” width cost more to traverse.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
dir_set_manually
(links, nodes, manual_set_csv)[source]¶ Sets link directions based on a user-provided csv-file. The csv file has exactly two columns; one called ‘link_id’, and one called ‘usnode’. This file can be created automatically by the function io_utils.create_manual_dir_csv().
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
manual_set_csv (str) – Path to csv defining which links have which upstream nodes.
- Returns
links (dict) – Network links and associated properties with specified links set manually.
nodes (dict) – Network nodes and associated properties with specified links set manually.
-
rivgraph.directionality.
dir_shortest_paths_links
(links, nodes, difthresh=0)[source]¶ Guesses a link’s directionality by which of its endpoint nodes is closer to the nearest outlet (or preoutlet). “difthresh” refers to the difference in distances between endpoint nodes; higher means directionality is less likely to be ascertained.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
difthresh (int, optional) – Threshold for the length (in number of nodes) that must be surpassed between an unknown link’s endpoints for directionality to be set. Lengths are measured from the link’s endpoints to the nearest outlet (or preoutlet). The default is 0.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
dir_shortest_paths_nodes
(links, nodes)[source]¶ Guesses link directionality based on the shortest path from its end nodes to the nearest outlet (or pre-outlet). For each unknown link, if the path flows through the link attached to the node (as opposed to immediately away from the link), its directionality is set; otherwise nothing is done. Note that this will not set all links’ directionalities.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
find_a_cycle
(links, nodes)[source]¶ Finds a single cycle in the network. Multiple cycles may exist; this function returns only the first one encountered.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
cycle_nodes (list) – Node ids comprising the cycle. Arranged in order of cycle.
cycle_links (list) – Link ids comprising the cycle. Arranged in order of cycle.
-
rivgraph.directionality.
fix_cycles
(links, nodes)[source]¶ Attempts to remove all cycles in the directed graph. A number of approaches are tried, and if any of them result in a source/sink node or a cycle, another approach is attempted until the cycle is resolved or we run out of approaches.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links and associated properties with all possible cycles resolved.
nodes (dict) – Network nodes and associated properties with all possible cycles resolved
n_cycles_remaining (int) – Number of cycles that were unresolvable.
-
rivgraph.directionality.
fix_sources_and_sinks
(links, nodes)[source]¶ Fixes sources and sinks within the network by flipping link directionality near the problem node(s). The links to flip are chosen by ensuring they do not create a cycle; if multiple links can be flipped, the shortest one is chosen. If no solution is found, links are returned to their original orientation.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links and associated properties with sources/sinks fixed if possible.
nodes (dict) – Network links and associated properties with sources/sinks fixed if possible.
-
rivgraph.directionality.
flip_links_in_G
(G, links2flip)[source]¶ Flips the directionality of links in a networkx graph object.
- Parameters
G (networkx.Graph or similar) – Graph object representing the network.
links2flip (tuple or) – An Nx2 tuple containing the US and DS node ids of the edge (link) to flip.
- Returns
G – Graph object representing the network with the requested links flipped.
- Return type
networkx.Graph or similar
-
rivgraph.directionality.
get_cycles
(links, nodes, checknode='all')[source]¶ Finds either all cycles in the network or cycles containing the checknode’th node. Cycles are returned as both nodes and links.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
checknode (int OR str, optional) – ID of node to check for its inclusion in any cycles. If the default value ‘all’ is selected, all cycles will be returned.
- Returns
cycle_nodes (list of lists) – List containing lists of all cycles found in the network; cycles are returned in cyclic order and in terms of node ids.
cycles_links (TYPE) – List containing lists of all cycles found in the network; cycles are returned in cyclic order and in terms of link ids.
-
rivgraph.directionality.
get_link_vector
(links, nodes, linkid, imshape, pixlen=1, normalized=True, trim=False)[source]¶ Computes the normalized vector of a link that indicates the direction of flow through a link based on its connectivity. This function will first trim the link by its endpoint (half)width values to mitigate cases where where wide channels are connected to narrow channels.
Requires a link contain at least min_len_for_trim pixels post-trimming.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
linkid (int) – ID of the link correspoinding to those found in links[‘id’].
imshape (tuple) – Shape of the binary mask as (nrows, ncols).
pixlen (float, optional) – Length resolution of each pixel. The default is 1.
normalized (bool, optional) – If True, will return a vector on [-1, 1]. The default is True.
trim (bool, optional) – If True, links will be trimmed to remove possibly direction-biasing end segments. If False, the untrimmed link endpoints will define the vector direction. The default is False.
- Returns
link_vec – Two-element array describing the x and y components of the direction vector describing the link.
- Return type
np.array
-
rivgraph.directionality.
merge_list_of_lists
(inlist)[source]¶ Merges a list of lists into a single list, but removes duplicates. Uses networkx and itertools for a fun solution.
- Parameters
inlist (list of lists) – List of lists to merge without dulplicates.
- Returns
merged – List of length equal to number of unique entries across all lists of inlist.
- Return type
list
-
rivgraph.directionality.
nodepath_to_links
(path, links, nodes)[source]¶ Converts a path defined by node ids to a path defined by link ids.
- Parameters
path (list) – Node ids comprising a path within the network.
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
linkpath – Link ids comprising the path defined by the given node ids.
- Return type
list
-
rivgraph.directionality.
set_artificial_nodes
(links, nodes, checknodes='all')[source]¶ This function is deprecated as of v0.3 and is no longer called.
Set the directionality of links where aritificial nodes were added. For such loops, flow will travel the same way through both sides of the loop (to avoid cycles). Therefore, if one side is known, we can set the other side. Method 1 sets a broken link if its counterpart is known. Method 2 sets a side of the loop if the other side is known. Method 3 sets both sides if the input to one of the end nodes is known.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
checknodes (int or str, optional) – Node ids to check for presence of settable artificial links. If ‘all’, all nodes in the network are checked.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
set_by_known_flow_directions
(links, nodes, imshape, angthresh=2, lenthresh=0, nknown_thresh=1, alg=6)[source]¶ Sets unknown link directions by determining which flow direction through the link minimizes the overall change in flow direction at the connecting nodes. For a set of links connected to a node, at least one of the links’ directions must be known for this algorithm to be effective. Links are set from longest to shortest, as longer links generally have less uncertainty associated with their directions.
A number of thresholds are provided as options to control the power of the algorithm. This function should generally be applied iteratively, beginning with the most restrictive thresholds and gradually relaxing them.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
imshape (tuple) – Shape of the binary mask as (nrows, ncols).
angthresh (float, optional) – Angle in radians to determine if an unknown link is parallel enough to its connected known links to set its direction. The default is 2.
lenthresh (int, optional) – Length in pixels of the minimum link length required to use this algorithm to set its directionality. The default is 0.
nknown_thresh (int, optional) – Number of known connected links required to use this algorithm to set the unknown link’s directionality. The default is 1.
alg (float, optional) – Algorithm ID to assign to the set link. The default is 6.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
set_by_nearest_main_channel
(links, nodes, imshape, nodethresh=0)[source]¶ Sets all possible links’ directions using the nearest main channel. The main channels are found as the widest, shortest paths from each inlet to each outlet. For each unknown link, the distance is computed from its endpoints to the nearest nodes of the nearest main channel. If the nearest nodes of the main channel include more than 2 + nodethresh nodes, the direction of the main channel is used to set the unknown link.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
imshape (tuple) – Shape of binary mask as (nrows, ncols).
nodethresh (int, optional) – Threshold for the number of nodes along the nearest main channel that must be encompassed by the unknown link’s endnodes to confidently set the unknown link’s direction. The default is 0.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
set_continuity
(links, nodes, checknodes='all')[source]¶ Sets link directions by enforce continuity at each node such that there are no sources or sinks within the network. Iterates until no more links directions can be set.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
checknodes (list OR str, optional) – Each link connected to each node id in this list will be checked for continuity. All nodes will be checked if using the default value ‘all’.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
set_inletoutlet
(links, nodes)[source]¶ Sets directions of links that are connected to inlets and outlets.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
set_link
(links, nodes, linkidx, usnode, alg=9999, checkcontinuity=True)[source]¶ Sets a link directionality. Option to check for continuity (including parallel links) after setting.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
linkidx (int) – Index of link within links[‘id’] to set. This index can be found from the link id via links[‘id’].index(linkid).
usnode (int) – Node id of the upstream node.
alg (int, optional) – The algorithm id used to set the link. Used for diagnostic purposes and fixing cycles. The default is 9999.
checkcontinuity (bool, optional) – If True, checks nearby links for continuity and parallel links after setting the link’s direction. The default is True.
- Returns
links (dict) – Network links and associated properties with updated link direction.
nodes (dict) – Network nodes and associated properties with updated link direction.
-
rivgraph.directionality.
set_parallel_links
(links, nodes, knownlink)[source]¶ Sets directionality of parallel links. If two links are parallel, they share the same end nodes. If the direction of one of the links is known, the other must be set in a direction to avoide creating a cycle within the graph. This function thus prevents cycles from being created and in general should be run after any link direction is set.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
knownlink (int) – Link id of link whose direction has been set to check for parallel links.
- Returns
links (dict) – Network links and associated properties updated to set directionality according to this algorithm.
nodes (dict) – Network nodes and associated properties updated to set directionality according to this algorithm.
-
rivgraph.directionality.
widest_inlet_index
(links, nodes)[source]¶ Finds the index of the inlet occurring at the widest link. Index is with respect to the nodes[‘id’] list.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
inlet_idx – Index of the inlet node of the widest link.
- Return type
int
Georeferencing Utilities (geo_utils.py)¶
Utilities for reading, writing, managing, processing, manipulating, etc. geographic data including tiffs, vrts, shapefiles, etc.
6/2/2020 - Consider merging this into io_utils and im_utils. Not much actual functionality here, and some of these functions are simply unused.
-
rivgraph.geo_utils.
coords_to_xy
(xs, ys, gt)[source]¶ Transforms a set of xs, ys in projected coordinates to rows, columns within a geotiff.
- Parameters
xs (list or np.array()) – Specifies the E-W coordinates (longitude).
ys (list or np.array()) – Specifies the N-S coordinates (latitude).
gt (tuple) – 6-element tuple gdal GeoTransform. (uL_x, x_res, rotation, ul_y, rotation, y_res). Automatically created by gdal’s GetGeoTransform() method.
- Returns
rowcols – Nx2 array of (row, col) indices corresponding to the inpute coordinates. N = len(xs).
- Return type
np.array()
-
rivgraph.geo_utils.
crop_geotif
(tif, cropto='first_nonzero', npad=0, outpath=None)[source]¶ Crops a geotiff to the minimum bounding box as defined by the first nonzero pixels along each direction. The cropped image is written to disk.
- Parameters
tif (str) – Path to geotiff to crop.
cropto (str) – [first_nonzero] is currently the only choice.
npad (int) – Number of pixels to add to each direction of the cropped image.
outpath (str) – Defines the path where the cropped image will be written to disk. If [None], the file will be written to the same directory as the input geotiff.
- Returns
output_file – Path to the saved, cropped geotiff.
- Return type
str
-
rivgraph.geo_utils.
geotiff_vals_from_coords
(coords, gd_obj)[source]¶ Returns pixel values at specific coordinates from a geotiff object.
- Parameters
coords (np.array()) – An Nx2 numpy array, where each row is a (lat, lon) pair.
gd_obj (osgeo.gdal.Dataset) – Geotiff object created with gdal.Open().
- Returns
vals – The value of the pixels of the geotiff for each coordinate.
- Return type
list
-
rivgraph.geo_utils.
get_unit
(crs)[source]¶ Returns the units for a projection defined by an EPSG code. See https://en.wikibooks.org/wiki/PROJ.4#Units for a list of unit string maps.
- Parameters
crs (pyproj CRS object) – Defines the coordinate reference system.
- Returns
unit – The unit of the provided epsg code.
- Return type
str
-
rivgraph.geo_utils.
idx_to_coords
(idx, gd_obj)[source]¶ Transforms a set of indices from a geotiff image to their corresponding coordinates.
- Parameters
idx (np.array()) – Specifies the indices to transform. See np.ravel_index for more info.
gd_obj (osego.gdal.Dataset) – gdal object of the geotiff from which indices were computed.
- Returns
cx, cy – x and y coordinates of the provided indices.
- Return type
tuple
-
rivgraph.geo_utils.
transform_coords
(xs, ys, inputEPSG, outputEPSG)[source]¶ Transforms a set of coordinates from one epsg to another. This implementation differs from above by using pyproj.
- Parameters
xs (np.array) – Specifies the x-coordinates to transform.
ys (np.array) – Specifies the y-coordinates to transform.
inputEPSG (int) – epsg code corresponding to xs, ys
outputEPSG (int) – epsg code corresponding to desired CRS.
- Returns
xy – Two element array of transformed (x, y) coordinates. xy[0] are transformed x coordinates, xy[1] are transformed y coordinates.
- Return type
np.array()
-
rivgraph.geo_utils.
xy_to_coords
(xs, ys, gt)[source]¶ Transforms a set of x and y coordinates to their corresponding coordinates within a geotiff image.
- Parameters
xs (np.array) – Specifies the x-coordinates to transform.
ys (np.array) – Specifies the y-coordinates to transform.
gt (tuple) – 6-element tuple gdal GeoTransform. (uL_x, x_res, rotation, ul_y, rotation, y_res). Automatically created by gdal’s GetGeoTransform() method.
- Returns
cx, cy – Column and row indices of the provided coordinates.
- Return type
tuple
Image Utilities (im_utils.py)¶
Note
Almost all the functions that manipulate images within this file require that the images be binary.
Many of these functions are wrappers around functionality found in skimage or opencv that either add additonal functionality or provide convenience.
-
rivgraph.im_utils.
blob_idcs
(I, connectivity=2)[source]¶ Finds all the indices for each blob within I.
- Parameters
I (np.array) – Binary image containing blobs.
connectivity (int, optional) – If 1, 4-connectivity will be used to determine connected blobs. If 2, 8-connectivity will be used. The default is 2.
- Returns
idcs – An n-element list of sets, where n is the number of blobs in I, and each set contains the pixel indices within I of a blob.
- Return type
list
-
rivgraph.im_utils.
bp_kernels
(caseno)[source]¶ Provides kernels for convolving with branchpoints image to remove special cases (where three branchpoints make an “L” shape). There are 8 possible orientations (caseno’s).
- Parameters
caseno (int) – Identifier for specific kernel cases. Can be 1-8.
- Returns
kernel – 3x3 kernel corresponding to the caseno.
- Return type
np.array
-
rivgraph.im_utils.
crop_binary_coords
(coords)[source]¶ Crops an array of (row, col) coordinates (e.g. blob indices) to the smallest possible array.
- Parameters
coords (np.array) – N x 2 array. First column are rows, second are columns of pixel coordinates.
- Returns
I (np.array) – Image of the cropped coordinates, plus padding if desired.
clipped (list) – Number of pixels in [left, top, right, bottom] direction that were clipped. Clipped returns the indices within the original coords image that define where I should be positioned within the original image.
-
rivgraph.im_utils.
crop_binary_im
(I)[source]¶ Crops a binary image to the smallest bounding box containing all the “on” pixels in the image.
- Parameters
I (np.array) – Binary image to crop.
- Returns
Icrop (np.array) – The cropped binary image.
pads (list) – Four element list containing the number of pixels that were cropped from the [left, top, right, bottom] of I.
-
rivgraph.im_utils.
dilate
(I, n=1, strel='square')[source]¶ Dilates a binary image using a specified kernel shape.
- Parameters
I (np.array) – Binary image to dilate.
n (int, optional) – Number of times to apply the dilating kernel. The default is 1.
strel (str, optional) – Kernel shape. Follows skimage’s options, but only ‘square’, ‘plus’, and ‘disk’ are supported. The default is ‘square’.
- Returns
Id – Dilated binary image. Same shape as I.
- Return type
np.array
-
rivgraph.im_utils.
downsample_binary_image
(I, newsize, thresh=0.05)[source]¶ Given an input binary image and a new size, this downsamples (i.e. reduces resolution) the input image to the new size. A pixel is considered “on” in the new image if ‘thresh’ fraction of its area is covered by the higher-res image. E.g. set ‘thresh’ to zero if you want the output image to be “on” everywhere at least a single pixel is “on” in the original image.
- Parameters
I (np.array) – Binary image to downsample.
newsize (tuple) – Two entry tuple (nrows, ncols) specifying the desired shape of the image.
thresh (float, optional) – The fraction of filled area that downsampled pixels must have to consider them on. Setting to 0 is the equialent of “all touched”. The default is 0.05.
- Returns
Iout – The downsampled image.
- Return type
np.array
-
rivgraph.im_utils.
edge_coords
(sizeI, dtype='flat')[source]¶ Given an image size, returns the coordinates of all the edge pixels (4 edges). Can return as indices (dtype=flat) or x,y coordinates (dtype=’xy’).
- Parameters
sizeI (tuple) – Shape of the image.
dtype (str, optional) – If ‘flat’, returns output as indices within I. If ‘xy’, returns (col, row) of edge pixels.
- Returns
edgepts – Coordinates of the edge pixels. If dtype==’flat’, returns a set. If dtype==’xy’, returns a list of [columns, rows].
- Return type
set or list
-
rivgraph.im_utils.
erode
(I, n=1, strel='square')[source]¶ Erodes a binary image using a specified kernel shape.
- Parameters
I (np.array) – Binary image to erode.
n (int, optional) – Number of times to apply the eroding kernel. The default is 1.
strel (str, optional) – Kernel shape. Follows skimage’s options, but only ‘square’, ‘plus’, and ‘disk’ are supported. The default is ‘square’.
- Returns
Ie – Eroded binary image. Same shape as I.
- Return type
np.array
-
rivgraph.im_utils.
fill_holes
(I, maxholesize=0)[source]¶ Fills holes up to a specified size in a binary image. The boundary pixels of the image are turned off before identifying holes so that holes created by the edge of the image are not considered holes.
- Parameters
I (np.array) – Binary image.
maxholesize (int, optional) – The maximum allowed hole size in pixels. The default is 0.
- Returns
I – The holes-filled image.
- Return type
np.array
-
rivgraph.im_utils.
four_conn
(idcs, I)[source]¶ Returns the number of 4-connected neighbors for a given flat index in I. idcs must be a list, even if a single value.
- Parameters
idcs (list) – Indices within I to find 4-connected neighbors.
I (np.array) – Binary image.
- Returns
fourconn – Number of four-connected neighbors for each index in idcs.
- Return type
list
-
rivgraph.im_utils.
get_array
(idx, I, size)[source]¶ Returns a sub-image of an input image, centered at a specified index within the input image and a specified size.
- Parameters
idx (int) – Index within I on which to center the returned array. Can also be a [row, col] list.
I (np.array) – Image to pull from.
size (list) – Two-entry list specifying the number of [rows, cols] to return from I centered at idx.
- Returns
subimage (np.array) – The sub-image of I, centered at idx with shape specified by size.
row (int) – The first row within I that the sub-image is drawn from.
col (int) – The first column within I that the sub-image is drawn from.
-
rivgraph.im_utils.
hand_clean
(I, action='erase')[source]¶ Allows user to hand-draw regions of interest on a binary mask that can either be filled (set to True) or erased (set to False). Only one polygon can be drawn per call.
- Interact with plot via the following:
left-click: save a vertex of the polygon right-click: remove the last point (useful when zooming/panning) enter key: stop recording points
Possible actions are ‘erase’ (default) and ‘fill’.
Requires matplotlib and Python Image Library (PIL), but they are imported here so that this function can be imported independently of the script.
- Parameters
I (np.array) – Binary image to fill or erase with hand-drawn polygons.
action (str, optional) – If ==’fill’, will fill the drawn region. If ==’erase’, will erase the drawn region. The default is ‘erase’.
- Returns
I – The image with the hand-drawn polygon either filled or erased.
- Return type
np.array
-
rivgraph.im_utils.
im_connectivity
(I)[source]¶ Returns an image of 8-connectivity for an input image of all pixels in a binary image.
- Parameters
I (np.array) – Binary image.
- Returns
Iret – Image of 8-connectivity count for each pixel in the input image.
- Return type
np.array
-
rivgraph.im_utils.
imshowpair
(I1, I2)[source]¶ Overlays two binary images with a color scheme that shows their differences and overlaps. Provides similar functionality to matlab’s imshowpair. Useful for quick diagnostic of differences between two binary images.
This function will plot on current figure if it exists, else it will create a new one.
- Parameters
I1 (np.array) – The first binary image.
I2 (np.array) – The second binary image.
- Returns
- Return type
None.
-
rivgraph.im_utils.
largest_blobs
(I, nlargest=1, action='remove', connectivity=2)[source]¶ Provides filtering for the largest blobs in a binary image. Can choose to either keep or remove them.
- Parameters
I (np.array) – Binary image to filter.
nlargest (int, optional) – Number of blobs to filter. The default is 1.
action (str, optional) – If ‘keep’, will keep the nlargest blobs. If ‘remove’, will remove the nlargest blobs. The default is ‘remove’.
connectivity (int, optional) – If 1, 4-connectivity will be used to determine connected blobs. If 2, 8-connectivity will be used. The default is 2.
- Returns
Ic – The filtered image. Same shape as I.
- Return type
np.array
-
rivgraph.im_utils.
neighbor_idcs
(c, r)[source]¶ Returns the column, row coordinats of all eight neighbors of a given column and row.
Returns are ordered as
- [0 1 2
3 4 5 6 7]
- Parameters
c (int) – Column.
r (int) – Row.
- Returns
cidcs (list) – Columns of the eight neighbors.
ridcs (TYPE) – Rows of the eight neighbors.
-
rivgraph.im_utils.
neighbor_vals
(I, c, r)[source]¶ Returns the neighbor values in I of a specified pixel coordinate. Handles edge cases.
- Parameters
I (np.array) – Image to draw values from.
c (int) – Column defining pixel to find neighbor values.
r (int) – Row defining pixel to find neighbor values.
- Returns
vals – A flattened array of all the neighboring pixel values.
- Return type
np.array
-
rivgraph.im_utils.
neighbor_xy
(c, r, idx)[source]¶ Returns the coordinates of a neighbor of a pixel given the index of the desired neighbor. Indices should be provided according to
- [0 1 2
3 4 5 6 7].
- Parameters
c (int) – Column of the pixel to find the neighbor.
r (int) – Row of the pixel to find the neighbor.
idx (int) – Index of the neighbor position.
- Returns
c (int) – Column of the neighbor pixel.
r (int) – Row of the neighbor pixel.
-
rivgraph.im_utils.
neighbors_flat
(idx, imflat, ncols, filt='nonzero')[source]¶ Returns all 8-neighbor pixel indices and values from an index of a flattened image. Can filter out zero values with the filt keyword.
- Parameters
idx (int) – Index within imflat to return neighbors.
imflat (np.array) – Flattened image (using np.ravel).
ncols (int) – Number of columns in the un-flattened image.
filt (str, optional) – If ‘nonzero’, only nonzero indices and values are returned. Else all neighbors are returned.
- Returns
idcs (np.array) – Indices within the flattened image of neighboring pixels.
vals (np.array) – Values within the flattened image of neighboring pixels; matches idcs.
-
rivgraph.im_utils.
nfour_connectivity
(I)[source]¶ Returns an image of four-connectivity for each pixel, where the pixel value is the number of 4-connected neighbors.
- Parameters
I (np.array) – Binary image.
- Returns
Infc – Image of 4-connectivity for each pixel. Same shape as I.
- Return type
np.array
-
rivgraph.im_utils.
regionprops
(I, props, connectivity=2)[source]¶ Finds blobs within a binary image and returns requested properties of each blob.
This function was modeled after matlab’s regionprops and is essentially a wrapper for skimage’s regionprops. Not all of skimage’s available blob properties are available here, but they can easily be added.
- Parameters
I (np.array) – Binary image containing blobs.
props (list) – Properties to compute for each blob. Can include ‘area’, ‘coords’, ‘perimeter’, ‘centroid’, ‘mean’, ‘perimeter’, ‘perim_len’, ‘convex_area’, ‘eccentricity’, ‘convex_area’, ‘major_axis_length’, ‘minor_axis_length’, ‘label’.
connectivity (int, optional) – If 1, 4-connectivity will be used to determine connected blobs. If 2, 8-connectivity will be used. The default is 2.
- Returns
out (dict) – Keys of the dictionary correspond to the requested properties. Values for each key are lists of that property, in order such that, e.g., the first entry of each property’s list corresponds to the same blob.
Ilabeled (np.array) – Image where each pixel’s value corresponds to its blob label. Labels can be returned by specifying ‘label’ as a property.
-
rivgraph.im_utils.
reglobalize_flat_idx
(idxlist, idxlistdims, row_offset, col_offset, globaldims)[source]¶ Takes a list of indices from a subimage and returns their indices within their parent image.
If idxlist is (x,y), then idxlistdims should be (dim_x, dim_y), etc.
- Parameters
idxlist (np.array or list or set) – List-like array of indices within the subimage.
idxlistdims (tuple) – (nrows, ncols) of the subimage.
row_offset (int) – The row in the parent image corresponding to the lowest row in the subimage.
col_offset (int) – The column in the parent image corresponding to the left-most column in the subimage.
globaldims (tuple) – (nrows, ncols) of the parent image.
- Returns
idcsflat – The indices in indexlist in terms of the parent image.
- Return type
list
-
rivgraph.im_utils.
remove_blobs
(I, blobthresh, connectivity=2)[source]¶ Remove blobs of a binary image that are smaller than blobthresh. A blob is simply a set of connected “on” pixels.
- Parameters
I (np.array) – Binary image to remove blobs from.
blobthresh (int) – Minimum number of pixels a blob must contain for it to be kept.
connectivity (int, optional) – If 1, 4-connectivity will be used to determine connected blobs. If 2, 8-connectivity will be used. The default is 2.
- Returns
Ic – Binary image with blobs filetered. Same shape as I.
- Return type
np.array
-
rivgraph.im_utils.
skel_branchpoints
(Iskel)[source]¶ Finds the branchpoints in a skeletonized image. Branchpoints are not simply those with more than two neighbors; they are identified in a way that minimizes the number of branchpoints required to resolve the skeleton fully with the fewest number of branchpoints.
- Parameters
Iskel (np.array) – Skeletonized image.
- Returns
Ibps – Binary image of shape Iskel where only branchpoints are on.
- Return type
np.array.
-
rivgraph.im_utils.
skel_endpoints
(Iskel)[source]¶ Finds all the endpoints of a skeleton.
- Parameters
Iskel (np.array) – Binary skeleton image.
- Returns
eps – Skeleton endpoint positions in (row, col) format.
- Return type
np.array
-
rivgraph.im_utils.
skel_kernels
(caseno)[source]¶ Provides kernels for convolving with skeleton image to remove the following case:
0 0 0 1 1 1 0 1 0
and its rotations. The center pixel would be removed as doing so does not break connectivity of the skeleton.
- Parameters
caseno (int) – Identifier for specific kernel cases. Can be 1-4.
- Returns
kernel – 3x3 kernel corresponding to the caseno.
- Return type
np.array
-
rivgraph.im_utils.
skel_pixel_curvature
(Iskel, nwalk=4)[source]¶ Provides an estimate of the curvature at most pixels within a skeleton image. Not all pixels are considered; some boundary pixels (i.e. those near the end of the skeleton) will not be computed. The more pruned and thinned the input skeleton, the less likely that any strange values will be returned. This code was written so that strange cases are merely skipped.
Given an input skeleton image, the code looks at each pixel and fits a trendline through npix pixels “upstream” and “downstream” of the pixel in question. Scale is therefore set by npixels; larger will reduce variability in the curvature estimates.
- Parameters
Iskel (np.array) – Binary skeleton image to compute curvatures.
nwalk (int, optional) – Number of pixels to walk away, in each direction, to define the curve to compute a pixel’s curvature. Higher results in smoother curvature values. The default is 4.
- Returns
I – Image wherein pixel values represent the curvature of the skeleton.
- Return type
np.array
-
rivgraph.im_utils.
trim_idcs
(imshape, idcs)[source]¶ Trims a list of indices by removing the indices that cannot fit within a raster of imshape.
- Parameters
imshape (tuple) – Shape of image to filter idcs against.
idcs (np.array) – Indices to ensure fit within an image of shape imshape.
- Returns
idcs – Indices that can fit within imshape.
- Return type
np.array
Input/Output Utilities (io_utils.py)¶
Functions for input/output.
Created on Sun Sep 16 15:15:18 2018
@author: Jon
-
rivgraph.io_utils.
centerline_to_geovector
(cl, crs, path_export)[source]¶ Exports centerline coordinates as a georeferenced linestring. Can be used with any set of coordinates.
- Parameters
cl (np.array) – ((xs), (ys)) array of coordinates to write. The coordinates should already be in terms of the provided crs.
crs (pyproj.CRS) – CRS object specifying the coordinate reference system of the provided coordinates
path_export (str) – Path, including extension, specifying where to save the coordinates export.
- Returns
- Return type
None.
-
rivgraph.io_utils.
colortable
(ctype)[source]¶ Generates a gdal-ingestible color table for a set of pre-defined options. Can add your own colortable options. See https://gdal.org/doxygen/structGDALColorEntry.html and https://gis.stackexchange.com/questions/158195/python-gdal-create-geotiff-from-array-with-colormapping for guidance.
- Parameters
ctype (str) – Specifies the type of colortable to return. Choose from {‘binary’, ‘skel’, ‘mask’, ‘tile’, or ‘GSW’}.
- Returns
color_table – Color table that can be supplied to gdal when creating a raster.
- Return type
gdal.ColorTable()
-
rivgraph.io_utils.
coords_from_geovector
(path_geovector)[source]¶ Retreives coordinates from a shapefile containing a LineString or Points.
- Parameters
path_geovector (str) – Path, including .shp extension, of the file containing coordinates.
- Returns
coords – Coordinates (x, y) of the vertices in the provided geovector.
- Return type
list of tuples
-
rivgraph.io_utils.
coords_to_geovector
(coords, epsg, path_export)[source]¶ Exports coordinates to a Point shapefile.
- Parameters
coords (list-like of list-likes) – List or tuple of (x, y) coordinates to export.
epsg (int) – EPSG code of the coordinate reference system of the coordinates.
path_export (str) – Path with .shp extension where the shapefile should be saved.
- Returns
- Return type
None.
-
rivgraph.io_utils.
create_manual_dir_csv
(path_csv)[source]¶ Creates a .csv file for fixing links manually.
- Parameters
path_csv (str) – Path, including .csv extension, where the .csv is written.
- Returns
- Return type
None.
-
rivgraph.io_utils.
get_driver
(path_file)[source]¶ Finds the proper geopandas driver for saving a geodataframe. Keys off the extension in the filename, and supports either shapefiles or geojsons.
- Parameters
path_file (str) – Where the file will be saved.
- Returns
driver – Driver string specifying file format when using geopandas’ to_file().
- Return type
str
-
rivgraph.io_utils.
links_to_geofile
(links, dims, gt, crs, path_export)[source]¶ Saves the links of the network to a georeferencedshapefile or geojson. Computed link properties are saved as attributes when available. Note that the ‘wid_pix’ property, which stores the width at each pixel along the link, may be truncated depending on its length and the filetype. The filetype is specified by the export path.
- Parameters
links (dict) – Network links and associated properties.
dims (tuple) – (nrows, ncols) of the original mask from which links were derived.
gt (tuple) – GDAL geotransform of the original mask from which links were derived.
crs (pyrpoj.CRS) – CRS object specifying the coordinate reference system of the original mask from which links were derived.
path_export (str) – Path, including extension, specifying where to save the links export.
- Returns
- Return type
None.
-
rivgraph.io_utils.
nodes_to_geofile
(nodes, dims, gt, crs, path_export)[source]¶ Saves the nodes of the network to a georeferencedshapefile or geojson. Computed node properties are appended as attributes when available. The filetype is specified by the export path.
- Parameters
nodes (dict) – Network nodes and associated properties.
dims (tuple) – (nrows, ncols) of the original mask from which nodes were derived.
gt (tuple) – GDAL geotransform of the original mask from which nodes were derived.
crs (pyrpoj.CRS) – CRS object specifying the coordinate reference system of the original mask from which nodes were derived.
path_export (str) – Path, including extension, where to save the nodes export.
- Returns
- Return type
None.
-
rivgraph.io_utils.
pickle_links_and_nodes
(links, nodes, path_out)[source]¶ Saves the links and nodes dictionaries to a pickle file for easy loading.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
path_out (str) – Where to save the pickle.
- Returns
- Return type
None.
-
rivgraph.io_utils.
prepare_paths
(path_results, name, path_mask)[source]¶ Creates a dictionary of paths for most of the RivGraph-exportable files.
- Parameters
path_results (str) – The directory of the path where results are exported. Will be created if it does not exist.
name (str) – Name of the analysis that is prepended to exported results.
path_mask (str) – Path to the mask geotiff, including extension.
- Returns
paths – Contains all the export paths. Not all will be necessarily used, but all possible exports’ paths are contained.
- Return type
dict
-
rivgraph.io_utils.
shapely_list_to_geovectors
(shplist, crs, path_export)[source]¶ Exports a list of shapely geometries to a GIS-ingestible format.
- Parameters
shplist (list) – A list of shapely.geometry objects defining components of the mesh.
crs (pyproj.CRS) – CRS object specifying the coordinate reference system of the geometries to export.
path_export (str) – Path, including extension, where the geovector data should be written. Extensions can be either ‘.shp’ or ‘.geojson’.
- Returns
- Return type
None.
-
rivgraph.io_utils.
unpickle_links_and_nodes
(path_pickle)[source]¶ Unpickles a previously pickled network. Note that ordered_set is reloaded within this function so that pickle can interpret OrderedSet object fields.
- Parameters
path_pickle (str) – Path to the pickled network.
- Returns
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
-
rivgraph.io_utils.
write_geotiff
(raster, gt, wkt, path_export, dtype='GDT_UInt16', options=['COMPRESS=LZW'], nbands=1, nodata=None, color_table=None)[source]¶ Writes a georeferenced raster to disk.
- Parameters
raster (np.array) – Image to be written. Shape is (nrows, ncols, nbands), although if only one band is present the shape can be just (nrows, ncols).
gt (tuple) – GDAL geotransform for the raster. Often this can simply be copied from another geotiff via gdal.Open(path_to_geotiff).GetGeoTransform(). Can also be constructed following the gdal convention of (leftmost coordinate, pixel width, xskew, uppermost coordinate, pixel height, yskew). For non-rotated images, the skews will be zero.
wkt (str) – Well-known text describing the coordinate reference system of the raster. Can be copied from another geotiff with gdal.Open(path_to_geotiff).GetProjection().
path_export (str) – Path with extension of the geotiff to export.
dtype (gdal.GDT_XXX, optional) – Gdal data type. Options for XXX include Byte, UInt16, UInt32, Int32, Float32, Float64 and complex types CInt16, Cint32, CFloat32 and CFloat64. If storing decimal data, use a Float type, binary data use Byte type. The default is gdal.GDT_UInt16 (non-float).
options (list of strings, optional) – Options that can be fed to gdal dataset creator. See YYY for what can be specified by options. The default is [‘COMPRESS=LZW’].
nbands (int, optional) – Number of bands of the raster. The default is 1.
nodata (numeric, optional) – Pixels with this value will be written as nodata. If None, no nodata value will be considered. The default is None.
color_table (gdal.ColorTable, optional) – Color table to append to the geotiff. Can use colortable() function to create, or create a custom type with gdal.ColorTable(). Note that color_tables can only be specified for Byte and UInt16 datatypes. The default is None.
- Returns
- Return type
None.
-
rivgraph.io_utils.
write_linkdirs_geotiff
(links, gdobj, path_export)[source]¶ Creates a geotiff where links are colored according to their directionality. Pixels in each link are interpolated between 0 and 1 such that the upstream pixel is 0 and the downstream-most pixel is 1. In a GIS, color can then be set to visualize flow directionality.
- Parameters
links (dict) – Network links and associated properties.
gdobj (osgeo.gdal.Dataset) – GDAL object correspondng to the original mask from which links were derived.
path_export (str) – Path, including .tif extension, where the directions geotiff is written.
- Returns
- Return type
None.
Network Utilities (ln_utils.py)¶
Created on Mon Sep 10 09:59:52 2018
@author: Jon
-
rivgraph.ln_utils.
add_artificial_nodes
(links, nodes, gd_obj)[source]¶ Add artificial nodes.
Some topologic metrics fail for graphs that contain parallel links, or links that share the same end nodes. This function alleviates that issue by inserting artificial nodes into all but one of the parallel links. The shortest link of the parallel set will not receive an artificial node. For simplicity of coding, when a node is added, the old link is deleted and two new links are put in its place.
A new attribute is appended to the nodes dictionary called ‘arts’ that contains the node IDs of artifical nodes.
If flow directions are needed, this function should be run after setting them. If flow directions have been set for links, the properties of the link that is broken into two are appended to the two parts. This may result in some properties that are no longer correct, e.g. slope.
Additionally, the ‘guess’ attribute of the links where artificial nodes are added will be incorrect as it doesn’t account for the artificial node, but references the original end nodes.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
gdobj (osgeo.gdal.Dataset) – GDAL dataset of the original mask, created via gdal.Open().
- Returns
links (dict) – Network links with aritifical nodes added.
nodes (dict) – Network nodes with artificial nodes added as a new ‘arts’ attribute.
-
rivgraph.ln_utils.
add_link
(links, nodes, idcs)[source]¶ Add a new link to the network.
Adds a new link to the network. Connectivity is updated in nodes to account for the added link. Attributes such as link width, length are not recomputed here; must be recomputed for the entire network.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
idcs (list) – Pixel indices comprising the link.
- Raises
RuntimeError – Raised if the added link isn’t connected to existing nodes at both ends.
- Returns
links (dict) – Network links with the link added.
nodes (dict) – Network nodes with the link added.
-
rivgraph.ln_utils.
add_node
(nodes, idx, linkconn)[source]¶ Add a new node to the network.
Adds a new node to the network. Connectivity is updated in links to account for the added node. No node properties (e.g. juncation angle) are updated.
- Parameters
nodes (dict) – Network nodes and associated properties.
idx (int) – Pixel index within the original mask of the node to add.
linkconn (list or int) – ID(s) of the link that the node is connected to.
- Returns
nodes – Network nodes with the node added.
- Return type
dict
-
rivgraph.ln_utils.
adjust_for_padding
(links, nodes, npad, dims, initial_dims)[source]¶ Adjust mask for any padding.
In some cases, a mask is padded before extracting the network. In order to ensure the extracted network maps to the original mask, the padding must be stripped away from all the coordinates of the network. The function achieves this by adjusting the [‘idx’] attributes of the links and nodes.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
npad (int) – Pad width to remove. Assumes padding was performed on all four edges of image.
dims (tuple) – (nrows, ncols) of the padded image.
initial_dims (tuple) – (nrows, ncols) of the original (unpadded) image.
- Returns
links (dict) – Network links adjusted to remove padding.
nodes (dict) – Network nodes adjusted to remove padding.
-
rivgraph.ln_utils.
append_link_lengths
(links, gdobj)[source]¶ Append link lengths to each link.
Appends link lengths to each link. Lengths are computed in the units of the coordinate reference system of the original mask.
This function provides a subset of the functionality of
link_widths_and_lengths()
. It is used when only link lengths are needed for, e.g. finding shortest paths.- Parameters
links (dict) – Network links and associated properties.
gdobj (osgeo.gdal.Dataset) – GDAL dataset of the original mask, created via gdal.Open().
- Returns
links – Network links with length attribute appended.
- Return type
dict
-
rivgraph.ln_utils.
conn_links
(nodes, links, node_idx)[source]¶ Find first and last pixels of all links connected to a node.
Finds the first and last pixels of all links connected to the node specified by node_idx.
- Parameters
nodes (dict) – Network nodes and associated properties.
links (dict) – Network links and associated properties.
node_idx (int) – Index of the node (not its id) to query.
- Returns
link_pix – A list of [first pixel, last pixel] for each link connected to the node specified by node_idx.
- Return type
list of lists
-
rivgraph.ln_utils.
delete_link
(links, nodes, linkid)[source]¶ Delete a link from the network.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
linkid (int) – ID of link (as found in links[‘id’]) to delete.
- Returns
links (dict) – Network links with link updated.
nodes (dict) – Network nodes with node updated.
-
rivgraph.ln_utils.
delete_node
(nodes, nodeid, warn=True)[source]¶ Delete a node from the network.
Deletes a node from the network. Assumes that the node’s connected links have already been deleted, and hence does not update the links dictionary.
- Parameters
nodes (dict) – Network nodes and associated properties.
nodeid (int) – ID of the node (as found in nodes[‘id’]) to delete.
warn (bool, optional) – If True, will print a warning if a node is being deleted that is still connected to links in the network. The default is True.
- Returns
nodes – Network nodes with the node deleted.
- Return type
dict
-
rivgraph.ln_utils.
find_art_links
(links, nodes)[source]¶ Find artificial links.
Finds the triad links corresponding to each artificial node. The triad links are the two links connected to the artifical node, and the link parallel to these two links.
Adds a new ‘arts’ property to the links dictionary that contains the triad set for each artificial node in nodes[‘arts’].
This function has little use after changing how RivGraph considers parallel links.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links – Network link with ‘arts’ attribute.
- Return type
dict
-
rivgraph.ln_utils.
find_parallel_links
(links, nodes)[source]¶ Find parallel links within the graph.
Finds all parallel links within the graph. A set of parallel links all have the same start and end node. A new attribute called ‘parallels’ is added to the links dictionary.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links with parallel attribute appended.
nodes (dict) – Network nodes and associated properties.
-
rivgraph.ln_utils.
flip_link
(links, linkid)[source]¶ Reverse a link’s direction.
Reverses a link’s direction by flipping the ordering of its comprising pixels, as well as any ordered attributes.
- Parameters
links (dict) – Network links and associated properties.
linkid (int) – ID of the link to flip (within links[‘id’]).
- Returns
links – Network links with the link flipped.
- Return type
dict
-
rivgraph.ln_utils.
junction_angles
(links, nodes, imshape, pixlen, weight=None)[source]¶ Compute junction angles.
Computes junction angles between links in a network with directions set. Only nodes of degree three are considered for simplicity. Angles are only computed between the two links that share a common flow directions. The acute-most angle between these two links is returned.
The direction of an individual link is poorly constrained. The number of pixels along the link to consider for computing its direction can result in vastly different directions depending on the link’s morphology. The weight argument above allows a degree of control over how to weight the contribution of pixels to a link’s direction vector.
Also computes the ratio of link widths (max/min) at junctions, and determines whether the junction is a confluence (joining) or a bifurcation (diverging).
The following attributes are appended to the nodes dictionary:
int_ang : the interior angle between the two links in the
width_ratio : the ratio of the maximum/minimum link widths for the two links whose directions agree
jtype : the junction type, either ‘b’ifurcation or ‘c’onfluence
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
imshape (tuple) – (nrows, ncols) of the original mask.
pixlen (numeric) – Resolution of the image; assumes same resolution in the horizontal and vertical.
weight (str, optional) –
How to weight pixel contributions to a link’s direction vector as we move away from the joining node. Choose from
None : all pixels are weighted equally
lin : the contribution of pixels decreases linearly as we move away from the joining node.
exp : the contribution of pixels decreases exponentially as we move away from the joining node.
The default is None.
- Raises
KeyError – Ensures that flow directions have been computed before running this function.
RuntimeError – Catches any strange cases where a junction is neither a bifurcation nor junction. Have not encountered this yet, please report if triggered.
- Returns
nodes – Network nodes and associated properties.
- Return type
dict
-
rivgraph.ln_utils.
link_updater
(links, linkid, idx=-1, conn=-1)[source]¶ Update the link dictionary.
Updates link dictionary by appending a new link or adding connectivity to an existing link. This function cannot add a new link.
- Parameters
links (dict) – Network links and associated properties. Should contain ‘id’, ‘idx’, and ‘conn’ at a minimum.
linkid (int) – ID of the link to update.
idx (list or int, optional) – Pixel indices of the link to update. The default is -1, which effectively skips updating the idx field.
conn (int, optional) – Node id (as found in nodes[‘id’]) connected to the link. The default is -1, which effectively skips updating the ‘id’ field.
- Returns
links – Network links with link updated.
- Return type
dict
-
rivgraph.ln_utils.
link_widths_and_lengths
(links, Idt, pixlen=1)[source]¶ Compute all link widths and lengths.
Computes link widths and lengths for all links in the network. A distance transform approach is used where the width of a pixel is its distance to the nearest non-max pixel times two.
There is a slight twist. When a skeleton is computed for a very wide channel with a narrow tributary, there is a very straight section of the skeleton as it leaves the wide channel to go into the tributary; this straight section (so-called “false” pixels) should not be used to compute average link width, as it’s technically part of the wide channel. The twist here accounts for that by elminating the ends of the each link from computing widths and lengths, where the distance along each end is equal to the half-width of the endmost pixels. Adjusted link widths and lengths are also computed that account for this effect.
The following new attributes are added to the links dictionary:
‘len’ : the length of the full link
‘wid_pix’ : the width of each pixel in the link
‘wid’ : the average width of all pixels of the link
‘wid_adj’ : the “adjusted” average width of all link pixels excluding “false” pixels
‘len_adj’ : the “adjusted” length of the link after excluding “false” pixels
- Parameters
links (dict) – Network links and associated properties.
Idt (np.array) – Distance transform of the original mask.
pixlen (float or int, optional) – Length (or resolution) of the pixel. If provided, assumes that the pixel resolution is the same in the horizontal and vertical directions. The default is 1, which corresponds to computing widths and lengths in units of pixels.
- Returns
links – Network links with width and length properties appended.
- Return type
dict
-
rivgraph.ln_utils.
links_to_gpd
(links, gdobj)[source]¶ Convert the links dictionary to a GeoPandas GeoDataFrame.
- Parameters
links (dict) – Network links and associated properties.
gdobj (osgeo.gdal.Dataset) – DESCRIPTION.
- Returns
links_gpd – GDAL dataset of the original mask, created via gdal.Open().
- Return type
TYPE
-
rivgraph.ln_utils.
node_updater
(nodes, idx, conn)[source]¶ Update the node dictionary.
Updates node dictionary by adding connectivity and idx information to an existing node. The function cannot add a node to the network.
- Parameters
nodes (dict) – Network nodes and associated properties Should contain ‘id’, ‘idx’, and ‘conn’ keys at a minimum.
idx (int) – The index of the node, as found in nodes[‘idx’].
conn (int) – Link id (as found in links[‘id’]) connected to the node.
- Returns
nodes – Network nodes with node updated.
- Return type
dict
-
rivgraph.ln_utils.
plot_dirlinks
(links, dims)[source]¶ Plots the network links with flow direction denoted.
- Parameters
links (dict) – Network links with flow directions set.
dims (tuple) – (nrows, ncols) of original mask that links were derived from.
- Returns
- Return type
None.
-
rivgraph.ln_utils.
plot_network
(links, nodes, Imask, name, axis=None)[source]¶ Plots the network with labeled link and node IDs.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
Imask (np.array) – The original binary mask.
name (str) – Name of the channel network for labeling the plot.
axis (matplotlib.axex._subplots.AxesSubplot, optional) – If provided, plotting will occur within the provided axis. Can be created with matplotlib.pyplot.subplots(). The default is None.
- Returns
- Return type
None.
-
rivgraph.ln_utils.
remove_all_spurs
(links, nodes, dontremove=[])[source]¶ Remove spurs.
Removes all links who have a node of degree one. This is performed iteratively until all spurs are removed. Also removes redundant nodes (i.e. nodes with degree two.)
- Parameters
links (dict) – Network link and associated properties.
nodes (dict) – Network nodes and associated properties.
dontremove (list, optional) – Node IDs not to remove (e.g. inlet and/or outlet nodes). The default is [].
- Returns
links (dict) – Network links with spurs removed.
nodes (dict) – Network nodes with spurs removed.
-
rivgraph.ln_utils.
remove_disconnected_bridge_links
(links, nodes)[source]¶ Remove disconnected bridge links.
When simplifying a channel network, there are often tributaries joining the network further downstream. These tributaries may have loops, which prevents their automatic removal by simple pruning.
This function helps prune these cases by removing bridge links that are not integral to the network. A bridge link is one whose removal results in an increase in the number of connected components in the network. Each bridge link is temporarily removed from the network. This leaves two end nodes which were connected by the bridge link. A bridge link is integral if a path can be found from the end nodes to inlets and outlets (if one end node is connected to an inlet(s), the other must be connected to an outlet(s)).
After all non-integral bridge links are removed, the connected component network that contains the inlet and outlets is returned; all other subnetworks are removed.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Pruned network links.
nodes (dict) – Pruned network nodes.
-
rivgraph.ln_utils.
remove_duplicate_links
(links, nodes)[source]¶ Eliminates any duplicate links in the network.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links with duplicate links removed.
nodes (dict) – Network nodes with duplicate nodes removed.
-
rivgraph.ln_utils.
remove_single_pixel_links
(links, nodes)[source]¶ Remove single pixel links.
RivGraph’s resolving of the network can result in single-pixel links that can be removed without altering connectivity. This function removes those.
- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links with single pixel links removed.
nodes (dict) – Network nodes with single pixel links removed.
-
rivgraph.ln_utils.
remove_two_link_nodes
(links, nodes, dontremove)[source]¶ Remove superfluous nodes.
Removes superfluous nodes from the network; i.e. nodes with degree two. Is called by
remove_all_spurs()
.- Parameters
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
dontremove (list) – Node IDs that should not be removed (e.g. inlets or outlets).
- Returns
links (dict) – Network links with superfluous nodes removed.
nodes (dict) – Network nodes with superfluous nodes removed.
Mask to Graph Utilities (mask_to_graph.py)¶
Functions for converting a binary channel mask to a graphical representation.
-
rivgraph.mask_to_graph.
pad_river_im
(I, es, pm=2)[source]¶ Pads the edges of a binary river image by extending the ends of the river. Different than mirrored padding in that the “mirror” here is just a rectangle. This simplifies skeletonization and interpretation in cases where the channel is complex near the boundaries.
- Parameters
I (np.array) – Binary image to pad; typically a river channel network.
es (str) – A two-character string (from N, E, S, or W) that denotes which sides of the image the river intersects (upstream first) – e.g. ‘NS’, ‘EW’, ‘NW’, etc.
pm (int, optional) – Pad multiplier that sets the size of the padding. Multplies the blob size along the axis of the image that the blob intersect to determine the padding distance. The default is 2.
- Returns
Ip (np.array) – The padded image..
pads (list) – 4 entry list containing the number of pixels padded on the [n, s, e, w] edges of the image.
-
rivgraph.mask_to_graph.
simplify_skel
(Iskel)[source]¶ This function iterates through all skeleton pixels pixels that have connectivity > 2. It removes the pixel and checks if the number of blobs has changed after removal. If so, the pixel is necessary to maintain connectivity. Otherwise the pixel is not retained. It also adds pixels to the centers of “+” cases, as this reduces the number of branchpoints from 4 to 1.
- Parameters
Iskel (np.array) – Image of the skeleton to simplify.
- Returns
Iskel – The simplified skeleton.
- Return type
np.array
-
rivgraph.mask_to_graph.
skel_to_graph
(Iskel)[source]¶ Resolves a skeleton into its consitutent links and nodes. This function finds a starting point to walk along a skeleton, then begins the walk. Rules are in place to ensure the network is fully resolved. One of the key algorithms called by this function involves the identfication of branchpoints in a way that eliminates unnecessary ones to create a parsimonious network. Rules are baked in for how to walk along the skeleton in cases where multiple branchpoints are clustered or there are multiple possible links to walk along.
Note that some minor adjustments to the skeleton may be made in order to reduce the complexity of the network. For example, in the case of a “+” with a missing center pixel in the skeleton, this function will add the pixel to the center to enable the use of a single branchpoint as opposed to four.
The takeaway is that there is no guarantee that the input skeleton will be perfectly preserved when network-ifying. One possible workaround, if perfect preservation is required, is to resample the skeleton to double the resolution.
- Parameters
Iskel (np.ndarray) – Binary image of a skeleton.
- Returns
links (dict) – Links of the network with four properties:
’id’ - a list of unique ids for each link in the network
’idx’ - a list containing the pixel indices within Iskel that defines the link. These are ordered.
’conn’ - a list of 2-element lists containing the node ids that the link is connected to.
’n_networks’ - the number of disconnected networks found in the skeleton
nodes (dict) – Nodes of the network with four properties:
’id’ - a list of unique ids for each node in the network
’idx’ - the index within Iskel of the node location
’conn’ - a list of lists containing the link ids connected to this node
-
rivgraph.mask_to_graph.
skeletonize_mask
(Imask)[source]¶ Skeletonizes an input binary image, typically a mask. Also performs some skeleton simplification by (1) removing pixels that don’t alter connectivity, and (2) filling small skeleton holes and reskeletonizing.
- Parameters
Imask (np.array) – Binary image to be skeletonized.
- Returns
Iskel – The skeletonization of Imask.
- Return type
np.array
-
rivgraph.mask_to_graph.
skeletonize_river_mask
(I, es, padscale=2)[source]¶ Skeletonizes a binary mask of a river channel network. Differs from skeletonize mask above by using knowledge of the exit sides of the river with respect to the mask (I) to avoid edge effects of skeletonization by mirroring the mask at its ends, then trimming it after processing. As with skeletonize_mask, skeleton simplification is performed.
- Parameters
I (np.array) – Binary river mask to skeletonize.
es (str) – A two-character string (from N, E, S, or W) that denotes which sides of the image the river intersects (upstream first) – e.g. ‘NS’, ‘EW’, ‘NW’, etc.
padscale (int, optional) – Pad multiplier that sets the size of the padding. Multplies the blob size along the axis of the image that the blob intersect to determine the padding distance. The default is 2.
- Returns
Iskel – The skeletonization of I.
- Return type
np.array
Mask Filtering Utils (mask_utils.py)¶
Functions for filtering islands from channel masks. Currently in beta.
Also see im_utils
for morphologic operations that could be useful.
Created on Mon Jul 6 18:29:23 2020
@author: Jon
-
rivgraph.mask_utils.
get_island_properties
(Imask, pixlen, pixarea, crs, gt, props)[source]¶ Get island properties.
Skeleton Walking Utils (walk.py)¶
Functions for walking along skeletons and finding branchpoints.
Created on Mon Sep 10 09:39:19 2018
-
rivgraph.walk.
bp_cluster
(bp, Iskel)[source]¶ Find clusters of branchpoints.
Finds clusters of branchpoints; i.e. branchpoints that are immediately adjacent to each other in an 8-connected sense. This function is self- referential in order to find all neighboring branchpoints.
- Parameters
bp (list) – Contains the branchpoint cluster as indices (np.ravel_multi_index) within Iskel. In the initial call, this list contains only a single branchpoint.
Iskel (np.ndarray) – Image of the skeletonized mask.
- Returns
bp – Contains the branchpoint cluster as indices (np.ravel_multi_index) within Iskel.
- Return type
list
-
rivgraph.walk.
cant_walk
(links, linkidx, nodes, Iskel)[source]¶ Find pixels that cannot be walked to.
Given an input link defined by linkidx, return all the pixels that cannot be walked to. These include:
originating node (and any nodes adjacent to this one)
emanating links (i.e. first pixel away from each node)
links that have been resolved walking AWAY from the node (toward node not included)
- Parameters
links (dict) – Network links and associated properties.
linkidx (int) – Index of the link id within links[‘id’] of the link to analyze.
nodes (dict) – Network nodes and associated properties.
Iskel (np.ndarray) – Image of the skeletonized mask.
- Returns
walked – Indices of pixels within Iskel that have already been walked to.
- Return type
set
-
rivgraph.walk.
check_dup_links
(linkid, links, nodes, links2do)[source]¶ Check for duplicate links.
Checks that the link represented by linkid has no dubplicates in the network. If so, the link is removed.
- Parameters
linkid (int) – Id of the link to check for duplication.
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
links2do (OrderedSet) – This set keeps track of all the links that still need to be resolved in the full skeleton. It is generated and populated in
mask_to_graph
.
- Returns
links (dict) – Network links and associated properties with duplicate link removed, if it existed.
nodes (dict) – Network nodes and associated properties with duplicate ilnk removed, if it existed.
links2do (OrderedSet) – This set keeps track of all the links that still need to be resolved in the full skeleton. It is generated and populated in
mask_to_graph
. The duplicate link, if found, is removed from this set.
-
rivgraph.walk.
delete_link
(linkid, links, nodes)[source]¶ Delete a link from the links dictionary and update the nodes dictionary.
Deletes a link from the links dictionary and updates the nodes dictionary to account for the deleted link. This is a special case of the delete_link found in ln_utils.py, as no properties have been added yet. It is possible that this function could be replaced by that one.
- Parameters
linkid (int) – Id of the link to delete.
links (dict) – Network links and associated properties.
nodes (dict) – Network nodes and associated properties.
- Returns
links (dict) – Network links and associated properties with the link deleted.
nodes (dict) – Network nodes and associated properties with the link deleted.
-
rivgraph.walk.
find_emanators
(bpnode, Iskel)[source]¶ Find possible next steps along the skeleton.
Returns all possible next steps along the skeleton from a given pixel. Emanators are the second nodes in each link, or the first nodes away from the link endpoint.
- Parameters
bpnode (np.int) – Index within Iskel to look for emanators.
Iskel (np.ndarray) – Image of the skeletonized mask.
- Returns
all_emanators – Indices within Iskel representing emanating nodes from bpnode.
- Return type
set
-
rivgraph.walk.
get_neighbors
(idx, Iskel)[source]¶ Get a flattened array of neighboring pixel indices.
Returns a flattened array of the neighboring pixel indices within Iskel that are True. Only looks at 8-connected neighbors (i.e. a 3x3 kernel with centered on idx).
- Parameters
idx (np.int) – Index within Iskel to get neighbors.
Iskel (np.ndarray) – Image of the skeletonized mask, but can be any image array.
- Returns
neighbor_idcs_gloal – Indices within Iskel of True pixels bordering idx.
- Return type
list
-
rivgraph.walk.
handle_bp
(linkid, bpnode, nodes, links, links2do, Iskel)[source]¶ Handle branchpoints.
When walking along a skeleton and encountering a branchpoint, we want to initialize all un-done links emanating from the branchpoint. Each new link contains the branchpoint as the first index, and this function also takes the first step of the link.
- Parameters
linkid (int) – Link id of the link walking from.
bpnode (np.int) – Node id of the branchpoint to be resolved.
nodes (dict) – Network nodes and associated properties.
links (dict) – Network links and associated properties.
links2do (OrderedSet) – This set keeps track of all the links that still need to be resolved in the full skeleton. It is generated and populated in mask_to_graph.
Iskel (np.ndarray) – Image of the local skeletonized mask.
- Returns
links (TYPE) – Network links and associated properties with the branchpoint links added.
nodes (TYPE) – Network nodes and associated properties with the branchpoint-related nodes added.
links2do (OrderedSet) – Same as input, but with new link emanators added and linkid removed.
-
rivgraph.walk.
idcs_no_turnaround
(idcs, Iskel)[source]¶ Find possible indices to walk to given two input indices.
Returns list of possible indices to walk toward given two input indices (idcs).
Possible indices are defined as those which require no turning around; e.g. if moving down, only indices further below idcs[1] will be returned. Based on directionality, only three possible indices should be returned for all cases.
- Parameters
idcs (list) – Resolved indices within Iskel of the link, in order, for which the next step needs to be taken.
Iskel (np.ndarray) – Image of the skeletonized mask.
- Returns
poss_walk_idcs – Indices within Iskel of possible next steps that ensure the walk will not move “backwards.”
- Return type
list
-
rivgraph.walk.
is_bp
(idx, Iskel)[source]¶ Determine if an index is a branchpoint.
Determines if the index given by idx is a branchpoint. Branchpoints are not simply pixels in the skeleton with more than two neighbors; they are pruned through a somewhat complicated procedure that minimizes the number of required branchpoints to preserve the skeleton topology.
- Parameters
idx (np.int) – Index within Iskel to determine if it is a branchpoint.
Iskel (np.ndarray) – Image of the skeletonized mask, but can be any image array.
- Returns
isbp – 1 if idx is a branchpoint, else 0.
- Return type
int
-
rivgraph.walk.
isbp_parsimonious
(Ic, Icr, Inar, Infr)[source]¶ Computes parsimonious set of branchpoints.
- Parameters
Ic (np.ndarray) – Image of possible branchpoints; values correspond to number of neighbors.
Icr (np.ndarray) – Raveled (np.ravel) version of Ic.
Inar (np.ndarray) – Raveled version of image returned by naxes_connectivity.
Infr (np.ndarray) – Raveled version of image returned by nfour_connectivity.
- Returns
bps – All branchpoint indices within Ic.
- Return type
list
-
rivgraph.walk.
isbp_walk_for_bps
(I, bpi)[source]¶ Find branchpoints by walking from a pixel.
Finds branchpoints by ensuring that all pixels in the sub-skeleton can be walked to from the set of already-found branchpoints, without visiting the same pixel more than once.
- Parameters
I (np.ndarray) – Binary image of a skeleton. In RivGraph, the skeleton is a reduced and padded version of Iskel.
bpi (list) – Indices within I of the branchpoint to begin walk.
- Returns
bpi – Branchpoint indices in I.
- Return type
list
-
rivgraph.walk.
naxes_connectivity
(I)[source]¶ Compute number of axes of connectivity.
Computes the number of axes of connectivity for each pixel in an input skeleton. The maximum is four; horizontal, vertical, and two diagonals.
The number of axes of pixel connectivity is used to determine where to place branchpoints.
- Parameters
I (np.ndarray) – Binary image of a skeleton. In RivGraph, the skeleton is a reduced and padded version of Iskel.
- Returns
Inax – Same shape as I; values correspond to the number of axes represented by each pixel’s connectivity.
- Return type
np.ndarray
-
rivgraph.walk.
walkable_neighbors
(link, Iskel)[source]¶ Find all walkable neighbors from the end pixel of an input link.
Returns all the walkable neighbors from the end pixel of an input link. Walkable neighbors are simply pixels that are “on” within Iskel. The pixels in the link are excluded as possibilities.
- Parameters
link (list) – Contains all the pixel indices within Iskel of the link to find walkable neighbors.
Iskel (np.ndarray) – Image of the skeletonized mask.
- Returns
neighs – Indices within Iskel of neighboring pixels to walk to.
- Return type
set


---
layout: page
current: professor
title: Professor
navigation: true
logo: False
class: page-template
subclass: 'post page'
---
Prof. Dong-Geol choi
Assistant Professor
Dept. of Information and Communication Engineering
Hanbat National University, Republic of Korea
Tel. : +82-42-821-1213
Email: dgchoi [at] hanbat.ac.kr
biography
Dong-Geol Choi received the B.S and M.S degrees in Electric Engineering and Computer Science from Hanyang University in 2005 and 2007, respectively, and the Ph.D degree in the Robotics Program from Korea Advanced Institute of Science and Technology (KAIST) in 2016.
After working at the KAIST as a postdoctoral researcher and research assistant professor until Aug 2018. He is currently an Assistant Professor with the Department of Information and Communication Engineering, in Hanbat National University. His research interests include sensor fusion, autonomous robotics, and artificial intelligence issues. Dr. Choi received a fellowship award from Qualcomm Korea R&D Center in 2013. He was a member of ‘Team KAIST,’ which won the first place in DARPA Robotics Challenge Finals 2015. He is a member of the IEEE.
Research Interests
Robot Vision
Sensor Fusion
Autonomous Robot System
Artificial Intelligence
Honors & Awards
1st place in DARPA Robotics Challenge Finals, “Team KAIST,” June, 7, 2015.
[project page]
Gradient-based Camera Exposure Control for Outdoor Mobile Platform
Inwook Shim and Tae-Hyun Oh and Joon-Young Lee and Jinwook Choi and Dong-Geol Choi* and In So Kweon
IEEE Transactions on Circuits and Systems for Video Technology, 2018
Real-Time head pose estimation using multi-task deep neural network
Byungtae Ahn, Dong-Geol Choi*, Jaesik Park and In So Kweon Robotics and Autonomous Systems , 2018.
Structure-From-Motion in 3D Space Using 2D Lidars
Dong-Geol Choi*, Yunsu Bok, Jun-Sik Kim, Inwook Shim, In So Kweon Sensors, 2017
Extrinsic Calibration of a camera and a 2D laser without overlab
Yunsu Bok, Dong-Geol Choi*, and In So Kweon Robotics and Autonomous Systems , Feb 2016.
Extrinsic Calibration of 2D Lidars using Two Orthogonal Planes
Dong-Geol Choi*, Yunsu Bok, Jun-sik Kimand In So Kweon IEEE Transactions on Robotics (T-RO), Feb 2016
An Autonomous Driving System for Unknown Environments using a Unified Map
Inwook Shim, Jongwon Choi, Seunghak Shin, Tae-Hyun Oh, Unghui Lee, Byungtae Ahn, Dong-Geol Choi, David Hyunchul Shim, and In So Kweon IEEE Transactions on Intelligent Transportation Systems (T-ITS), Feb 2015
Sensor Fusion of Cameras and a Laser for City-Scale 3D Reconstruction
Yunsu Bok, Dong-Geol Choi, and In So Kweon Sensors, Dec 2014.
Capturing Village-level Heritages with a Hand-held Camera-Laser Fusion Sensor
Yunsu Bok, Yekeun Jeong, Dong-Geol Choi, and In So Kweon International Journal of Computer Vision (IJCV), Aug 2011
Development of a 5-DOF Hybrid Micro-Manipulator and Implementation to Needle Manipulation Process in Medical Applications
Goo Bong Chung, Jae Heon Chung, Dong Geol Choi, Byung-Ju Yi, Seok Young Han, and Seon Jung Kim The Journal, Key Engineering Materials, Dec 2006
International Conference
Extrinsic Calibration of Non-overlapping Camera-Laser System using Structured Environment
Yunsu Bok, Dong-Geol Choi, Pascal Vasseur, and In So Kweon In Proc. of IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), Sep 2014.
[pdf]
Extrinsic Calibration of 2D Laser Sensors
Dong-Geol Choi, Yunsu Bok, Jun-sik Kim, and In So Kweon In Proc. of IEEE International Conference on Robotics & Automation (ICRA), May 2014.
[pdf]
Robust Computer Vision Techniques for High-quality 3D Modeling
Joon-Young Lee, Jiyoung Jung, Yunsu Bok, Jaesik Park, Dong-Geol Choi, Yudeog Han, and In So Kweon In Proc. of IAPR Asian Conference on Pattern Recognition (ACPR), Nov 2013.
[pdf]
Generalized Laser Three-Point Algorithm for Motion Estimation of Camera-Laser Fusion System
Yunsu Bok, Dong-Geol Choi, and In So Kweon In Proc. of IEEE International Conference on Robotics & Automation (ICRA), May 2013.
[pdf]
Multi Lidar System for fast obstacle detection
Inwook Shim, Dong-Geol Choi, Seunghak Shin, and In So Kweon In Proc. of International Conference on Ubiquitous Robots and Ambient Intelligence (URAI), Nov 2012.
[pdf]
Autonomous Homing based on Laser-Camera Fusion System
Dong-Geol Choi, Inwook Shim, Yunsu Bok, Tae-Hyun Oh, and In So Kweon
In Proc. of IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), Sep 2012.
[pdf]
Capturing City-level Scenes with a Synchronized Camera-Laser Fusion Sensor
Yunsu Bok, Dong-Geol Choi, Yekeun Jeong, and In So Kweon
In Proc. of IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), Sep 2011.
[pdf]
Robust Road Detection Based On Optimal Fusion Ratio of Classifier Dong-Geol Choi, Youngbae Hwang, and In So Kweon
nternational Conference on Mechatronics and Information Technology (ICMIT), Nov 2009.
[pdf]
Capturing Village-level Heritages with a Hand-held Camera-Laser Fusion Sensor
Yunsu Bok, Dong-Geol Choi, Yekeun Jeong, and In So Kweon In Proc. of IEEE International Conference on Computer Vision (ICCV), Oct 2009.
[pdf]
Intelligent Grasping by Learning from Observation
Seong-Young Ko, Hanbyul Joo, Dong-Geol Choi, Hyeongwoo Kim, and In So Kweon In Proc. of International Conference on Ubiquitous Robots and Ambient Intelligence (URAI), Nov 2008.
[pdf]
Design of an endoscopic robot using a spring backbone
Dong-Geol Choi, Byung-Ju Yi and Young Su Kim In Proc. of IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), Sep 2007.
[pdf]
Optimal Motion Planning of Auto Illumination Robot System
Dong-Geol Choi, Byung-Ju Yi and Whee Kuk Kim IEEE conference on mechatronics and Automation (ICMA), Sep 2007.
[pdf]
Development of a 5-DOF Hybrid Micro-Manipulator for Needle Manipulation in Brain Surgery
Goo Bong Chung, Jae Heon Chung, Dong-Geol Choi, Byung-Ju Yi, Whee Kuk Kim, and Young Soo Kim World Congress on Medical Physics and Biomedical Engineering (IUPESM), 2006
An Image-Guided Robot System for Spinal Fusion
Jae Heon Chung, Goo Bong Chung, Dong-Geol Choi, Sung Min Kim, Se Min Oh, Byung-Ju Yi, and Whee Kuk Kim, Young Soo Kim, and Jong Il Park World Congress on Medical Physics and Biomedical Engineering (IUPESM), 2006
Implementation of Auto Surgical Illumination Robotic System Using Ultrasonic Sensor-based Tracking Algorithm
Dong-Geol Choi, Byung-Ju Yi , Whee Kuk Kim and Young Su Kim World Congress on Medical Physics and Biomedical Engineering (IUPESM), 2006
Thesis
PH. D. Thesis, KAIST, 2016, Robust SLAM and sensor calibration frameworks for robots using 2D LiDARs and cameras
M.Sc. Thesis, Hanyang Univ., 2007, Auto surgical illumination robot system using ultrasonic sensor based tracking algorithm and spring backbone micro endoscope