Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_components.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
51# ifndef TPL_COMPONENTS_H
52# define TPL_COMPONENTS_H
53
54# include <ah-graph-concepts.H>
55
56# include <tpl_agraph.H>
57# include <tpl_dfs_stack.H>
58# include <ah-errors.H>
59
60namespace Aleph {
61
112template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
114{
115 SA sa;
116 const GT * gptr = nullptr;
117 size_t count = 0;
118
119public:
120
126 Build_Subgraph(SA arc_filter = SA())
127 : sa(arc_filter) { /* empty */ }
128
129 private:
130
131 // A node that waits for the one that it visits, its image in the
132 // subgraph, and the next arc of it to look at
134 {
135 typename GT::Node * sg_src;
137
138 [[gnu::always_inline]] ALEPH_FLATTEN
139 Map_Frame(typename GT::Node * g_src, typename GT::Node * image, SA & sa)
140 : sg_src(image), it(g_src, sa) {}
141
142 [[gnu::always_inline]] ALEPH_FLATTEN
143 void next_arc() noexcept(noexcept(it.next_ne())) { it.next_ne(); }
144 };
145
146 // Marks p and counts it, and gives its image, which it inserts in sg.
147 // A node gets its image when it is visited, so that a cookie that it
148 // had before, as those that Tarjan leaves, is not taken for its image;
149 // and it maps to its image alone, not through such a cookie.
150 [[gnu::always_inline]] typename GT::Node * visit(GT & sg, typename GT::Node * p)
151 {
152 NODE_BITS(p).set_bit(Build_Subtree, true);
153 ++count;
154
155 auto sg_p = sg.insert_node(p->get_info());
156 NODE_COOKIE(p) = nullptr; // else map_nodes() would compose with it
157 GT::map_nodes(p, sg_p);
158 return sg_p;
159 }
160
161 // Inserts in sg the copy of arc, from sg_src to sg_tgt, and maps them
162 [[gnu::always_inline]]
163 static void copy_arc(GT & sg, typename GT::Arc * arc,
164 typename GT::Node * sg_src, typename GT::Node * sg_tgt)
165 {
166 auto sg_arc = sg.insert_arc(sg_src, sg_tgt, arc->get_info());
167 ARC_COOKIE(arc) = nullptr; // else map_arcs() would compose with it
168 GT::map_arcs(arc, sg_arc);
169 }
170
171 // Copies into sg the arcs of f that were not, toward the nodes visited,
172 // up to one whose target was not visited, which it gives, with the
173 // iterator on that arc, whose copy waits for the image of that target;
174 // nullptr when the arcs are done
175 [[gnu::always_inline]]
176 typename GT::Node * next_to_visit(GT & sg, Map_Frame & f)
177 {
178 for (; f.it.has_curr(); f.next_arc())
179 {
180 auto arc = f.it.get_current_arc_ne();
182 continue;
183
184 // Get the target before the mark, which the compiler takes for a
185 // store that could change the iterator
186 auto g_tgt = f.it.get_tgt_node_ne();
187
188 // Mark arc as visited
189 ARC_BITS(arc).set_bit(Build_Subtree, true);
190
191 if (not IS_NODE_VISITED(g_tgt, Build_Subtree))
192 return g_tgt;
193
194 copy_arc(sg, arc, f.sg_src, mapped_node<GT>(g_tgt));
195 }
196 return nullptr;
197 }
198
199 // Visits g_tgt, the target of the arc on which f stays, and copies that
200 // arc; gives the image of g_tgt
201 [[gnu::always_inline]]
202 typename GT::Node * visit_through(GT & sg, Map_Frame & f, typename GT::Node * g_tgt)
203 {
204 auto sg_tgt = visit(sg, g_tgt);
205 copy_arc(sg, f.it.get_current_arc_ne(), f.sg_src, sg_tgt);
206 return sg_tgt;
207 }
208
209 // DFS that builds a mapped subgraph. A path can have as many nodes as
210 // the graph, too many for recursion, so that the search keeps its own
211 // stack; the order of the visits is that of a recursion.
212 void build_subgraph(GT & sg, typename GT::Node * g_src)
213 {
214 if (IS_NODE_VISITED(g_src, Build_Subtree))
215 return;
216
217 // The node being visited keeps its iterator in here until it visits a
218 // node; then it waits in frames, where it goes on when it comes back.
219 // here is optional, so that the frame of each node is built in its
220 // place: a frame keeps the filter, which may not be assignable
222 std::optional<Map_Frame> here(std::in_place, g_src, visit(sg, g_src), sa);
223 while (true)
224 {
225 if (auto g_tgt = next_to_visit(sg, *here))
226 { // the iterator stays on the arc to g_tgt, as in a recursion
227 auto sg_tgt = visit_through(sg, *here, g_tgt);
228 frames.push(std::move(*here));
229 here.emplace(g_tgt, sg_tgt, sa);
230 continue;
231 }
232
233 while (true) // back to the nodes that wait
234 {
235 if (frames.is_empty())
236 return;
237
238 Map_Frame & f = frames.top();
239 f.next_arc(); // past the arc to the node that was visited
240 if (auto g_tgt = next_to_visit(sg, f))
241 {
242 here.emplace(g_tgt, visit_through(sg, f, g_tgt), sa);
243 break;
244 }
245 frames.pop();
246 }
247 }
248 }
249
250 // The next arc of a node to look at
252 {
254
255 [[gnu::always_inline]] ALEPH_FLATTEN
256 Arc_Frame(typename GT::Node * p, SA & sa) : it(p, sa) {}
257
258 [[gnu::always_inline]] ALEPH_FLATTEN
259 void next_arc() noexcept(noexcept(it.next_ne())) { it.next_ne(); }
260
261 // Moves the iterator, while count < n, to the next arc not visited
262 // whose target was not visited either, and gives that target; it marks
263 // the arcs not visited that it passes. nullptr when the arcs are done
264 // or count == n.
265 [[gnu::always_inline]] ALEPH_FLATTEN
266 typename GT::Node * next_target(const size_t & count, const size_t n)
267 noexcept(noexcept(it.next_ne()))
268 {
269 for (; count < n and it.has_curr(); it.next_ne())
270 {
271 auto arc = it.get_current_arc_ne();
273 continue;
274
275 // Mark arc as visited, after taking its target: the compiler
276 // takes the mark for a store that could change the iterator
277 auto tgt = it.get_tgt_node_ne();
278 ARC_BITS(arc).set_bit(Build_Subtree, true);
279 if (not IS_NODE_VISITED(tgt, Build_Subtree))
280 return tgt;
281 }
282 return nullptr;
283 }
284 };
285
286 // DFS that builds the list of the nodes reachable from p. A path can
287 // have as many nodes as the graph, too many for recursion, so that the
288 // search keeps its own stack; the order of the visits is that of a
289 // recursion.
290 template <template <class> class List>
292 {
294 return;
295
296 const size_t n = gptr->get_num_nodes();
297
298 // Marks q and appends it to l, and gives it
299 auto visit = [this, &l](typename GT::Node * q)
300 {
301 NODE_BITS(q).set_bit(Build_Subtree, true);
302 ++count;
303 l.append(q);
304 return q;
305 };
306
307 // The node being visited keeps its iterator in here until it visits a
308 // node; then it waits in frames, where it goes on when it comes back.
309 // here is optional, as in the search above
311 std::optional<Arc_Frame> here(std::in_place, visit(p), sa);
312 while (true)
313 {
314 if (auto tgt = here->next_target(count, n))
315 { // the iterator stays on the arc to tgt, as in a recursion
316 frames.push(std::move(*here));
317 here.emplace(visit(tgt), sa);
318 continue;
319 }
320
321 while (true) // back to the nodes that wait
322 {
323 if (frames.is_empty())
324 return;
325
326 Arc_Frame & f = frames.top();
327 f.next_arc(); // past the arc to the node that was visited
328 if (auto tgt = f.next_target(count, n))
329 {
330 here.emplace(visit(tgt), sa);
331 break;
332 }
333 frames.pop();
334 }
335 }
336 }
337
338public:
339
355 void operator () (const GT & g, GT & sg, typename GT::Node * g_src)
356 {
357 ah_invalid_argument_if(g_src == nullptr)
358 << "Build_Subgraph: source node cannot be null";
359
360 gptr = &g;
361 count = 0;
362 build_subgraph(sg, g_src);
363 }
364
375 GT operator () (const GT & g, typename GT::Node * src)
376 {
377 ah_invalid_argument_if(src == nullptr)
378 << "Build_Subgraph: source node cannot be null";
379
380 GT sg;
381 gptr = &g;
382 count = 0;
383 build_subgraph(sg, src);
384 return sg;
385 }
386
401 typename GT::Node * src)
402 {
403 ah_invalid_argument_if(src == nullptr)
404 << "Build_Subgraph: source node cannot be null";
405
406 gptr = &g;
407 count = 0;
408 build_subgraph<DynList>(list, src);
409 }
410};
411
412
466template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
468{
469 SA sa;
470
471public:
472
478 Unconnected_Components(SA arc_filter = SA())
479 : sa(arc_filter) { /* empty */ }
480
490 template <template <class> class List>
491 void compute_blocks(const GT & g, List<GT> & list)
492 {
494 << "Unconnected_Components does not work on digraphs";
495 g.reset_nodes();
496 g.reset_arcs();
497 size_t count = 0; // Count of visited nodes
498
499 for (typename GT::Node_Iterator it(g);
500 count < g.get_num_nodes() and it.has_curr(); it.next_ne())
501 {
502 auto curr = it.get_current_node_ne();
504 continue;
505
506 // Create new subgraph for this component
507 GT & subgraph = list.append(GT());
508
510 build(g, subgraph, curr);
511
512 count += subgraph.get_num_nodes();
513 }
514 }
515
525 template <template <class> class List>
527 {
529 << "Unconnected_Components does not work on digraphs";
530 g.reset_nodes();
531 g.reset_arcs();
532 size_t count = 0; // Count of visited nodes
533
534 for (typename GT::Node_Iterator i(g);
535 count < g.get_num_nodes() and i.has_curr(); i.next_ne())
536 {
537 auto curr = i.get_current_node_ne();
539 continue;
540
541 // Create new node list for this component
542 auto & l = list.append(List<typename GT::Node*>());
543
545 build(g, l, curr);
546
547 count += l.size();
548 }
549 }
550
565 void operator () (const GT & g, DynList<GT> & list)
566 {
567 compute_blocks<DynList>(g, list);
568 }
569
584 {
585 compute_lists<DynList>(g, list);
586 }
587
595 size_t count_components(const GT & g)
596 {
598 compute_lists<DynList>(g, components);
599 return components.size();
600 }
601
610 bool is_connected(const GT & g)
611 {
613 << "Unconnected_Components does not work on digraphs";
614 if (g.get_num_nodes() <= 1)
615 return true;
616 return count_components(g) == 1;
617 }
618};
619
620
621} // end namespace Aleph
622
623# endif // TPL_COMPONENTS_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
C++20 concepts for the protocol shared by graph algorithms.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
Build a mapped subgraph from a graph starting at a given node.
static void copy_arc(GT &sg, typename GT::Arc *arc, typename GT::Node *sg_src, typename GT::Node *sg_tgt)
void operator()(const GT &g, GT &sg, typename GT::Node *g_src)
Build a mapped subgraph starting from a specific node.
GT::Node * visit_through(GT &sg, Map_Frame &f, typename GT::Node *g_tgt)
void build_subgraph(List< typename GT::Node * > &l, typename GT::Node *p)
GT::Node * next_to_visit(GT &sg, Map_Frame &f)
void build_subgraph(GT &sg, typename GT::Node *g_src)
GT::Node * visit(GT &sg, typename GT::Node *p)
Build_Subgraph(SA arc_filter=SA())
Construct a subgraph builder with optional arc filter.
Stack of the frames of a depth-first search that does not recurse.
T & push(Args &&...args)
Builds a frame on top of the stack.
bool is_empty() const noexcept
Whether the stack has no frames.
T & top() noexcept
The top frame; the stack must not be empty.
void pop() noexcept
Destroys the top frame; the stack must not be empty.
Node belonging to a double circular linked list with header node.
Definition tpl_dnode.H:106
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Compute the connected components of a graph.
void compute_blocks(const GT &g, List< GT > &list)
Compute connected components as mapped subgraphs.
Unconnected_Components(SA arc_filter=SA())
Construct a component finder with optional arc filter.
void compute_lists(const GT &g, List< List< typename GT::Node * > > &list)
Compute connected components as lists of node pointers.
void operator()(const GT &g, DynList< GT > &list)
Compute connected components as mapped subgraphs.
size_t count_components(const GT &g)
Count the number of connected components in a graph.
bool is_connected(const GT &g)
Check if a graph is connected.
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
NodeInfo & get_info() noexcept
Return a modifiable reference to the data contained in the node.
Definition graph-dry.H:753
void reset_arcs() const
Reset all the arcs of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1213
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
static void map_arcs(A1 *p, A2 *q) noexcept
Map the arcs through their cookies.
Definition graph-dry.H:1312
void reset_nodes() const
Reset all the nodes of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1206
static void map_nodes(N1 *p, N2 *q) noexcept
Map the nodes through their cookies.
Definition graph-dry.H:1281
#define ARC_COOKIE(p)
Return the arc cookie
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
#define ARC_BITS(p)
Return the control bits of arc p.
#define NODE_COOKIE(p)
Return the node cookie
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
#define NODE_BITS(p)
Get the control bits of a node.
#define ALEPH_FLATTEN
[[gnu::flatten]], or nothing where it would only make the compilation slower.
@ Build_Subtree
Definition aleph-graph.H:80
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
void next_ne() noexcept(noexcept(std::declval< Aleph::const_iterator_t< HeadC > & >().next_ne()) and noexcept(std::declval< ZipIterator< TailC... > & >().next_ne()))
Advance all underlying iterators (unchecked variant).
Definition ah-zip.H:252
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
void next_arc() noexcept(noexcept(it.next_ne()))
GT::Node * next_target(const size_t &count, const size_t n) noexcept(noexcept(it.next_ne()))
Arc_Frame(typename GT::Node *p, SA &sa)
Node_Arc_Iterator< GT, SA > it
Map_Frame(typename GT::Node *g_src, typename GT::Node *image, SA &sa)
Node_Arc_Iterator< GT, SA > it
void next_arc() noexcept(noexcept(it.next_ne()))
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Array-based graph implementation.
Stack of the frames of a depth-first search that does not recurse.
DynList< int > l