HighMap library (C++)
Loading...
Searching...
No Matches
hmap::Graph Class Reference

Graph class, to manipulate graphs in 2D. More...

#include <graph.hpp>

Inheritance diagram for hmap::Graph:
Collaboration diagram for hmap::Graph:

Public Member Functions

 Graph ()=default
 Construct a new Graph object.
 Graph (Cloud cloud)
 Construct a new Graph object based on a cloud of points.
 Graph (std::vector< Point > points)
 Construct a new Graph object based on a list of points.
 Graph (std::vector< float > x, std::vector< float > y)
 Construct a new Graph object based on x and y coordinates.
void add_edge (int u, int v, float weight)
 Add an edge connecting two node indices with explicit weight.
void add_edge (int u, int v)
 Add an edge connecting two node indices with default geometric distance weight.
void add_edge (glm::ivec2 edge, float weight)
 Add an edge with explicit weight.
void add_edge (glm::ivec2 edge)
 Add an edge with default geometric distance weight.
void clear_edges () noexcept
 Clear all edges from the graph.
std::vector< float > compute_distance_to_outlet () const
 Compute the distance to the downstream outlet for each node in the graph.
std::vector< float > compute_flow_accumulation () const
 Compute accumulated upstream flow length along directed stream edges.
std::vector< float > compute_relative_widths (float exponent=1.0f) const
 Compute relative channel width ratio in [0, 1] for each node in the graph.
std::vector< int > compute_strahler_order () const
 Compute the Strahler stream order for each node in the graph.
size_t degree (int u) const
 Get the degree (number of incident edges) of node u.
std::vector< int > dijkstra (int source_point_index, int target_point_index) const
 Return the shortest route between two points using Dijkstra's algorithm.
bool empty_edges () const noexcept
 Check whether the graph has no edges.
void enforce_downhill_elevation (float min_slope=0.001f)
 Enforce monotonic downhill elevations on all graph nodes.
Edge get_edge (size_t k) const
 Get an edge by index.
float get_edge_length (size_t k) const
 Get the Euclidean length of edge k.
std::vector< float > get_edge_x_pairs () const
 Return x coordinates of the edges (as pairs).
std::vector< float > get_edge_y_pairs () const
 Return y coordinates of the edges (as pairs).
const std::vector< Edge > & get_edges () const noexcept
 Get the edge list.
std::vector< float > get_lengths () const
 Get the Euclidean lengths of all the edges.
size_t get_nedges () const noexcept
 Get the number of edges in the graph.
Graph minimum_spanning_tree_prim () const
 Generate a Minimum Spanning Tree (MST) using Prim's algorithm.
const std::vector< Neighbor > & neighbors (int u) const
 Get the neighbors of node u.
size_t num_edges () const noexcept
 Get the number of edges in the graph.
void print () const
 Print the graph data to the standard output.
Graph remove_orphan_points () const
 Remove orphan points (points with no connected edges).
void set_edge_weight (size_t k, float weight)
 Set the weight of edge k.
void set_edge_weight (int u, int v, float weight)
 Set the weight of an edge between node u and node v.
void to_array (Array &array, const BBox2D &bbox, bool color_by_edge_weight=true) const
 Project the graph to an array and optionally color by edge weight.
void to_array_fractalize (Array &array, const BBox2D &bbox, int iterations, std::uint32_t seed, float sigma=0.3f, int orientation=0, float persistence=1.f) const
 Apply fractalization to graph edges and project to an array.
Array to_array_sdf (glm::ivec2 shape, const BBox2D &bbox, Array *p_noise_x=nullptr, Array *p_noise_y=nullptr, const BBox2D &bbox_array=BBox2D{}) const
 Generate an array filled with the Signed Distance Function (SDF) to the graph.
void to_csv (const std::string &fname_xy, const std::string &fname_edges) const
 Export graph data to CSV files.
void to_png (const std::string &fname, glm::ivec2 shape={512, 512}) const
 Export the graph as a PNG image file.
Public Member Functions inherited from hmap::Cloud
 Cloud ()
 Default constructor for the Cloud class.
virtual ~Cloud ()=default
 Cloud (int npoints, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Constructs a new Cloud object with random positions and values.
 Cloud (const std::vector< Point > &points)
 Constructs a new Cloud object based on a list of existing points.
 Cloud (std::vector< Point > &&points) noexcept
 Move-constructs a new Cloud object from an existing points vector.
 Cloud (const std::vector< float > &x, const std::vector< float > &y, float default_value=0.f)
 Constructs a new Cloud object from lists of x and y coordinates.
 Cloud (const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &v)
 Constructs a new Cloud object from lists of x and y coordinates with assigned values.
 Cloud (const std::vector< glm::ivec2 > &indices, const glm::ivec2 &shape, const BBox2D &bbox=BBox2D{})
 Construct a point cloud from grid indices mapped to a bounding box.
 Cloud (const std::vector< glm::vec3 > &xyv)
 Constructs a new Cloud object from lists of xyz data as glm::vec3.
BBox2D get_bbox () const
 Get the bounding box of the cloud.
Point get_center () const
 Calculates the centroid of a set of points.
std::vector< int > get_convex_hull () const
 Computes the indices of the points that form the convex hull of a set of points.
std::vector< float > get_values () const
 Get the values assigned to the points in the cloud.
float get_values_max () const
 Get the maximum value among the points in the cloud.
float get_values_min () const
 Get the minimum value among the points in the cloud.
std::vector< float > get_x () const
 Get the x coordinates of the points in the cloud.
std::vector< float > get_xy () const
 Get the concatenated x and y coordinates of the points in the cloud.
std::vector< float > get_y () const
 Get the y coordinates of the points in the cloud.
size_t nearest_point (const glm::vec2 &xy) const
 Find the index of the nearest point in the cloud.
void set_points (const std::vector< float > &x, const std::vector< float > &y)
 Set points of the using x, y coordinates.
void set_values (const std::vector< float > &new_values)
 Set new values for the cloud points.
void set_values (float new_value)
 Set a single value for all cloud points.
void set_values_from_array (const Array &array, const BBox2D &bbox=BBox2D{})
 Set the values of the cloud points using values from an underlying array.
void set_values_from_array (const Array &array, ArraySampling sampling, float radius=0.f, const BBox2D &bbox=BBox2D{})
 Set the values of the cloud points from an array, using a given sampling strategy.
void set_values_from_border_distance (const BBox2D &bbox=BBox2D{})
 Sets point values based on their distance to the bounding box border.
void set_values_from_chull_distance ()
 Set the values of the cloud points based on the distance to the convex hull of the cloud.
void set_values_from_min_distance ()
 Sets point values based on the distance to their nearest neighbor.
Point & operator[] (size_t index)
 Access point by index.
const Point & operator[] (size_t index) const
 Access point by index (const).
Point & at (size_t index)
 Access point with bounds checking.
const Point & at (size_t index) const
 Access point with bounds checking (const).
Point & back ()
 Access the last point.
const Point & back () const
 Access the last point (const).
std::vector< Point >::iterator begin () noexcept
 Returns an iterator to the first point.
std::vector< Point >::const_iterator begin () const noexcept
 Returns a const iterator to the first point.
size_t capacity () const noexcept
 Returns the number of points that can be held in currently allocated storage.
std::vector< Point >::const_iterator cbegin () const noexcept
 Returns a const iterator to the first point.
std::vector< Point >::const_iterator cend () const noexcept
 Returns a const iterator to the end.
void clear ()
 Clear all data from the cloud.
Point * data () noexcept
 Direct pointer to the underlying point array.
const Point * data () const noexcept
 Direct pointer to the underlying point array (const).
void emplace_back (float x, float y, float v=0.f)
 Appends a new point in-place.
bool empty () const
 Check whether the cloud has no points.
std::vector< Point >::iterator end () noexcept
 Returns an iterator to the end.
std::vector< Point >::const_iterator end () const noexcept
 Returns a const iterator to the end.
std::vector< Point >::iterator erase (std::vector< Point >::const_iterator pos)
 Erases the point at the specified position.
std::vector< Point >::iterator erase (std::vector< Point >::const_iterator first, std::vector< Point >::const_iterator last)
 Erases the range of points [first, last).
Point & front ()
 Access the first point.
const Point & front () const
 Access the first point (const).
std::vector< Point >::iterator insert (std::vector< Point >::const_iterator pos, const Point &value)
 Inserts a point before pos.
std::vector< Point >::iterator insert (std::vector< Point >::const_iterator pos, Point &&value)
 Inserts a point before pos (move).
template<typename InputIt>
std::vector< Point >::iterator insert (std::vector< Point >::const_iterator pos, InputIt first, InputIt last)
 Inserts elements from range [first, last) before pos.
void pop_back ()
 Removes the last point.
void push_back (const Point &p)
 Appends a point.
void push_back (Point &&p)
 Appends a point (move).
void reserve (size_t new_cap)
 Reserves storage for at least the specified number of points.
size_t size () const
 Get the number of points in the cloud.
void print () const
 Print information about the cloud's points.
void randomize (std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Randomize the positions and values of the cloud points.
void remap_values (float vmin, float vmax)
 Remap the values of the cloud points to a target range.
void shuffle (float dx, float dy, std::uint32_t seed, float dv=0.f)
 Randomly perturbs the positions and values of all points in the cloud.
void snap_points_to_bounding_box (const BBox2D &bbox=BBox2D{}, float tolerance_ratio=1.f)
 Snap points to the bounding box edges and corners.
bool from_csv (const std::string &fname)
 Loads point data from a CSV file into the Cloud object.
void to_array (Array &array, const BBox2D &bbox=BBox2D{}) const
 Project the cloud points onto an array.
Array to_array (glm::ivec2 shape, const BBox2D &bbox) const
 See hmap::to_array.
void to_array_interp (Array &array, const BBox2D &bbox=BBox2D{}, InterpolationMethod2D interpolation_method=InterpolationMethod2D::ITP2D_DELAUNAY, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const BBox2D &bbox_array=BBox2D{}) const
 Interpolate the values of an array using the cloud points.
void to_csv (const std::string &fname) const
 Export the cloud data to a CSV file.
Graph to_graph_delaunay () const
 Convert the cloud to a graph using Delaunay triangulation.
void to_png (const std::string &fname, int cmap, const BBox2D &bbox=BBox2D{}, int depth=0, glm::ivec2 shape={512, 512}) const
 Saves the current data as a PNG image file.
std::vector< glm::vec3 > to_vec3 () const
 Convert path points to a vector of 3D positions.

Additional Inherited Members

Protected Attributes inherited from hmap::Cloud
std::vector< Point > points = {}
 Points of the cloud.

Detailed Description

Graph class, to manipulate graphs in 2D.

This class represents a 2D graph, allowing the creation, manipulation, and analysis of graphs derived from point clouds. It supports operations such as graph construction, traversal, and various geometric analyses. This class inherits from the Cloud class, leveraging the functionalities of point clouds while adding graph-specific methods.

Example

#include "highmap.hpp"
int main(void)
{
int seed = 1;
hmap::BBox2D bbox = {-1.f, 2.f, 0.f, 5.f};
// create a cloud of points and convert it to a graph using Delaunay
// triangulation
int npoints = 10;
hmap::Cloud cloud = hmap::Cloud(npoints, seed, bbox);
hmap::Graph graph = cloud.to_graph_delaunay();
graph.print();
graph.to_png("ex_graph0.png");
graph.to_csv("ex_graph_nodes.csv", "ex_graph_edges.csv");
}
Represents a collection of unordered points in 2D space.
Definition cloud.hpp:61
Graph to_graph_delaunay() const
Convert the cloud to a graph using Delaunay triangulation.
Definition cloud.cpp:822
Graph class, to manipulate graphs in 2D.
Definition graph.hpp:70
void to_png(const std::string &fname, glm::ivec2 shape={512, 512}) const
Export the graph as a PNG image file.
Definition graph.cpp:997
void print() const
Print the graph data to the standard output.
Definition graph.cpp:813
void to_csv(const std::string &fname_xy, const std::string &fname_edges) const
Export graph data to CSV files.
Definition graph.cpp:983
int main(int argc, char **argv)
Definition main.cpp:12
Axis-aligned 2D bounding box in world coordinates.
Definition bbox2d.hpp:25

Result

Constructor & Destructor Documentation

◆ Graph() [1/4]

hmap::Graph::Graph ( )
default

Construct a new Graph object.

◆ Graph() [2/4]

hmap::Graph::Graph ( Cloud cloud)

Construct a new Graph object based on a cloud of points.

Parameters
cloudThe cloud of points used to initialize the graph.

◆ Graph() [3/4]

hmap::Graph::Graph ( std::vector< Point > points)

Construct a new Graph object based on a list of points.

Parameters
pointsThe list of points used to initialize the graph.

◆ Graph() [4/4]

hmap::Graph::Graph ( std::vector< float > x,
std::vector< float > y )

Construct a new Graph object based on x and y coordinates.

Parameters
xVector of x coordinates for the points.
yVector of y coordinates for the points.

Member Function Documentation

◆ add_edge() [1/4]

void hmap::Graph::add_edge ( int u,
int v,
float weight )

Add an edge connecting two node indices with explicit weight.

Parameters
uNode 1 index.
vNode 2 index.
weightEdge weight.

◆ add_edge() [2/4]

void hmap::Graph::add_edge ( int u,
int v )

Add an edge connecting two node indices with default geometric distance weight.

Parameters
uNode 1 index.
vNode 2 index.

◆ add_edge() [3/4]

void hmap::Graph::add_edge ( glm::ivec2 edge,
float weight )

Add an edge with explicit weight.

Parameters
edgePair of node indices.
weightEdge weight.

◆ add_edge() [4/4]

void hmap::Graph::add_edge ( glm::ivec2 edge)

Add an edge with default geometric distance weight.

Parameters
edgePair of node indices.

◆ clear_edges()

void hmap::Graph::clear_edges ( )
noexcept

Clear all edges from the graph.

◆ compute_distance_to_outlet()

std::vector< float > hmap::Graph::compute_distance_to_outlet ( ) const

Compute the distance to the downstream outlet for each node in the graph.

Flow direction is inferred from node elevation values (stored in v), directing flow from higher to lower elevation. Outlets (sinks / terminal nodes) have distance 0.

Returns
Vector containing the downstream distance to outlet for each node.

◆ compute_flow_accumulation()

std::vector< float > hmap::Graph::compute_flow_accumulation ( ) const

Compute accumulated upstream flow length along directed stream edges.

Traverses nodes in topological order from upstream headwaters to downstream outlets, accumulating incoming edge lengths:

accum[v] = sum_{u in upstream(v)} (accum[u] + dist(u, v))

Headwater nodes with no incoming upstream flow start with 0.

Returns
Vector containing accumulated upstream length per node.

◆ compute_relative_widths()

std::vector< float > hmap::Graph::compute_relative_widths ( float exponent = 1.0f) const

Compute relative channel width ratio in [0, 1] for each node in the graph.

Scaling smoothly from 0 at the upstream headwater roots up to 1 at the downstream outlets:

r = (1 - d_outlet / max_d_outlet)^exponent

Parameters
exponentScaling exponent applied to normalized distance to outlet.
Returns
Vector containing relative width ratio in [0, 1] per node.

◆ compute_strahler_order()

std::vector< int > hmap::Graph::compute_strahler_order ( ) const

Compute the Strahler stream order for each node in the graph.

Flow direction is inferred from node elevation values (stored in v), directing flow from higher to lower elevation. Headwater leaves start with order 1 and orders increase at confluent junctions.

Returns
Vector containing the Strahler order for each node index.

◆ degree()

size_t hmap::Graph::degree ( int u) const

Get the degree (number of incident edges) of node u.

Parameters
uNode index.
Returns
Degree of node u.

◆ dijkstra()

std::vector< int > hmap::Graph::dijkstra ( int source_point_index,
int target_point_index ) const

Return the shortest route between two points using Dijkstra's algorithm.

Parameters
source_point_indexStarting point index.
target_point_indexEnding point index.
Returns
std::vector<int> Path of node indices from source to target.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
int seed = 1;
hmap::BBox2D bbox = {-1.f, 2.f, 0.f, 5.f};
// create a cloud of points and convert it to a graph using Delaunay
// triangulation
int npoints = 15;
hmap::Cloud cloud = hmap::Cloud(npoints, seed, bbox);
hmap::Graph graph = cloud.to_graph_delaunay();
graph.print();
int i_point_start = 0;
int i_point_end = 4;
std::vector<int> route = graph.dijkstra(i_point_start, i_point_end);
std::cout << "Route (point indices):\n";
for (auto &p : route)
std::cout << p << "\n";
}
std::vector< int > dijkstra(int source_point_index, int target_point_index) const
Return the shortest route between two points using Dijkstra's algorithm.
Definition graph.cpp:615

◆ empty_edges()

bool hmap::Graph::empty_edges ( ) const
noexcept

Check whether the graph has no edges.

Returns
True if no edges, false otherwise.

◆ enforce_downhill_elevation()

void hmap::Graph::enforce_downhill_elevation ( float min_slope = 0.001f)

Enforce monotonic downhill elevations on all graph nodes.

Traverses nodes from upstream headwaters to downstream outlets in topological order, ensuring each downstream node satisfies:

v_downstream <= v_upstream - min_slope * edge_length

Parameters
min_slopeMinimum downhill slope along each directed edge.

◆ get_edge()

Edge hmap::Graph::get_edge ( size_t k) const

Get an edge by index.

Parameters
kEdge index.
Returns
Edge structure.

◆ get_edge_length()

float hmap::Graph::get_edge_length ( size_t k) const

Get the Euclidean length of edge k.

Parameters
kEdge index.
Returns
float Euclidean length of the edge.

◆ get_edge_x_pairs()

std::vector< float > hmap::Graph::get_edge_x_pairs ( ) const

Return x coordinates of the edges (as pairs).

Returns
std::vector<float> The x coordinates of the edges.

◆ get_edge_y_pairs()

std::vector< float > hmap::Graph::get_edge_y_pairs ( ) const

Return y coordinates of the edges (as pairs).

Returns
std::vector<float> The y coordinates of the edges.

◆ get_edges()

const std::vector< Edge > & hmap::Graph::get_edges ( ) const
noexcept

Get the edge list.

Returns
Const reference to the edge vector.

◆ get_lengths()

std::vector< float > hmap::Graph::get_lengths ( ) const

Get the Euclidean lengths of all the edges.

Returns
std::vector<float> The lengths of all the edges.

◆ get_nedges()

size_t hmap::Graph::get_nedges ( ) const
noexcept

Get the number of edges in the graph.

Returns
size_t Number of edges.

◆ minimum_spanning_tree_prim()

Graph hmap::Graph::minimum_spanning_tree_prim ( ) const

Generate a Minimum Spanning Tree (MST) using Prim's algorithm.

Returns
Graph The Minimum Spanning Tree (MST) of the graph.

Example

#include "highmap.hpp"
int main(void)
{
int seed = 1;
hmap::BBox2D bbox = {-1.f, 2.f, 0.f, 5.f};
// create a cloud of points and convert it to a graph using Delaunay
// triangulation
int npoints = 10;
hmap::Cloud cloud = hmap::Cloud(npoints, seed, bbox);
hmap::Graph graph_delaunay = cloud.to_graph_delaunay();
hmap::Graph graph_mst = graph_delaunay.minimum_spanning_tree_prim();
graph_delaunay.to_png("ex_graph_minimum_spanning_tree_prim0.png");
graph_mst.to_png("ex_graph_minimum_spanning_tree_prim1.png");
}
Graph minimum_spanning_tree_prim() const
Generate a Minimum Spanning Tree (MST) using Prim's algorithm.
Definition graph.cpp:751

◆ neighbors()

const std::vector< Neighbor > & hmap::Graph::neighbors ( int u) const

Get the neighbors of node u.

Parameters
uNode index.
Returns
List of Neighbor objects.

◆ num_edges()

size_t hmap::Graph::num_edges ( ) const
noexcept

Get the number of edges in the graph.

Returns
size_t Total number of edges.

◆ print()

void hmap::Graph::print ( ) const

Print the graph data to the standard output.

◆ remove_orphan_points()

Graph hmap::Graph::remove_orphan_points ( ) const

Remove orphan points (points with no connected edges).

Returns
Graph A new graph object with orphan points removed.

◆ set_edge_weight() [1/2]

void hmap::Graph::set_edge_weight ( size_t k,
float weight )

Set the weight of edge k.

Parameters
kEdge index.
weightNew weight.

◆ set_edge_weight() [2/2]

void hmap::Graph::set_edge_weight ( int u,
int v,
float weight )

Set the weight of an edge between node u and node v.

Parameters
uNode 1 index.
vNode 2 index.
weightNew weight.

◆ to_array()

void hmap::Graph::to_array ( Array & array,
const BBox2D & bbox,
bool color_by_edge_weight = true ) const

Project the graph to an array and optionally color by edge weight.

Parameters
arrayThe input array to project onto.
bboxBounding box for projection.
color_by_edge_weightColor lines by edge weight if true.

◆ to_array_fractalize()

void hmap::Graph::to_array_fractalize ( Array & array,
const BBox2D & bbox,
int iterations,
std::uint32_t seed,
float sigma = 0.3f,
int orientation = 0,
float persistence = 1.f ) const

Apply fractalization to graph edges and project to an array.

Parameters
arrayDestination array.
bboxBounding box.
iterationsNumber of fractal iterations.
seedRandom seed.
sigmaDisplacement magnitude.
orientationDisplacement orientation.
persistenceOctave persistence.

◆ to_array_sdf()

Array hmap::Graph::to_array_sdf ( glm::ivec2 shape,
const BBox2D & bbox,
Array * p_noise_x = nullptr,
Array * p_noise_y = nullptr,
const BBox2D & bbox_array = BBox2D{} ) const

Generate an array filled with the Signed Distance Function (SDF) to the graph.

Parameters
shapeOutput array dimensions.
bboxBounding box.
p_noise_xOptional X noise array for domain warping.
p_noise_yOptional Y noise array for domain warping.
bbox_arrayOutput array bounding box.
Returns
Array SDF array.

◆ to_csv()

void hmap::Graph::to_csv ( const std::string & fname_xy,
const std::string & fname_edges ) const

Export graph data to CSV files.

Parameters
fname_xyOutput CSV for node (x, y, v).
fname_edgesOutput CSV for edges (u, v, weight).

◆ to_png()

void hmap::Graph::to_png ( const std::string & fname,
glm::ivec2 shape = {512, 512} ) const

Export the graph as a PNG image file.

Parameters
fnameOutput image path.
shapeImage dimensions in pixels.

The documentation for this class was generated from the following files: