Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Dial.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
82# ifndef DIAL_H
83# define DIAL_H
84
85# include <ah-graph-concepts.H>
86
87# include <limits>
88# include <type_traits>
89# include <tpl_array.H>
90# include <tpl_graph_utils.H>
91# include <ah-errors.H>
92
93namespace Aleph
94{
123 template <AlephGraph GT,
124 ArcDistance<GT> Distance = Dft_Dist<GT>,
125 template <typename, class> class Itor = Node_Arc_Iterator,
126 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
128 {
129 public:
131 using Node = typename GT::Node;
132 using Arc = typename GT::Arc;
133
134 static_assert(std::is_integral_v<Distance_Type>,
135 "Dial's algorithm requires integral distance type");
136
137 private:
138 SA sa;
140 bool painted = false;
141 GT *ptr_g = nullptr;
142 Node *s = nullptr;
143 static constexpr size_t Max_Sane_Buckets = 16u * 1024u * 1024u;
144
145 static constexpr Distance_Type Inf =
146 std::numeric_limits<Distance_Type>::max();
147
149 {
153
154 Node_Info() noexcept : dist(Inf), parent(nullptr), parent_arc(nullptr) {}
155 };
156
157#define DIAL_INFO(p) (static_cast<Node_Info *>(NODE_COOKIE(p)))
158#define DIAL_DIST(p) (DIAL_INFO(p)->dist)
159#define DIAL_PARENT(p) (DIAL_INFO(p)->parent)
160#define DIAL_PARC(p) (DIAL_INFO(p)->parent_arc)
161
163 {
164 painted = false;
165 ptr_g = nullptr;
166 s = nullptr;
167 }
168
171 {
173 const GT * g = nullptr;
174 bool committed = false;
175
176 public:
181 Dial_Init_Guard(Dial_Min_Paths & __owner, const GT & __g) noexcept
182 : owner(&__owner), g(&__g)
183 {
184 // empty
185 }
186
195
197 void commit() noexcept { committed = true; }
198
201 {
202 if (not committed)
203 {
206 }
207 }
208 };
209
210 void init(const GT & g)
211 {
212 ptr_g = &const_cast<GT &>(g);
213 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next())
214 {
215 auto p = it.get_curr();
217 NODE_COOKIE(p) = nullptr;
218 }
219 for (typename GT::Arc_Iterator it(g); it.has_curr(); it.next())
220 g.reset_bit(it.get_curr(), Aleph::Spanning_Tree);
221
222 try
223 {
224 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next())
225 NODE_COOKIE(it.get_curr()) = new Node_Info;
226 }
227 catch (...)
228 {
231 throw;
232 }
233 }
234
236 {
237 for (typename GT::Node_Iterator it(*ptr_g); it.has_curr(); it.next())
238 {
239 auto p = it.get_curr();
240 auto info = DIAL_INFO(p);
241 auto parent = info->parent;
242 delete info;
243 NODE_COOKIE(p) = parent;
244 }
245 }
246
248 {
249 if (ptr_g == nullptr)
250 return;
251
252 for (typename GT::Node_Iterator it(*ptr_g); it.has_curr(); it.next())
253 {
254 auto p = it.get_curr();
255 auto info = DIAL_INFO(p);
256 if (info != nullptr)
257 delete info;
258 NODE_COOKIE(p) = nullptr;
260 }
261
262 for (typename GT::Arc_Iterator it(*ptr_g); it.has_curr(); it.next())
263 ptr_g->reset_bit(it.get_curr(), Aleph::Spanning_Tree);
264 }
265
266 // The largest weight of an arc that the filter shows: a hidden arc
267 // does not count, whatever its weight
269 {
270 Distance_Type max_w = 0;
271 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next())
272 {
273 auto w = distance(it.get_curr());
274 ah_domain_error_if(w < 0) << "Dial: negative weight " << w << " not allowed";
275 if (w > max_w)
276 max_w = w;
277 }
278 return max_w;
279 }
280
281 void run_dial(const GT & g, Node *start, Node *end = nullptr)
282 {
283 auto max_w = find_max_weight(g);
284
285 if (max_w == 0)
286 {
287 // All edges have weight 0: simple BFS
288 DIAL_DIST(start) = 0;
289 NODE_BITS(start).set_bit(Aleph::Spanning_Tree, true);
290
291 DynList<Node *> queue;
292 queue.append(start);
293
294 while (not queue.is_empty())
295 {
296 auto curr = queue.remove_first();
297
298 if (end != nullptr and curr == end)
299 break;
300
301 for (Itor<GT, SA> it(curr, sa); it.has_curr(); it.next())
302 {
303 auto arc = it.get_current_arc();
304 auto tgt = g.get_connected_node(arc, curr);
305
306 if (DIAL_DIST(tgt) > 0)
307 {
308 DIAL_DIST(tgt) = 0;
309 DIAL_PARENT(tgt) = curr;
310 DIAL_PARC(tgt) = arc;
311 NODE_BITS(tgt).set_bit(Aleph::Spanning_Tree, true);
312 ARC_BITS(arc).set_bit(Aleph::Spanning_Tree, true);
313 queue.append(tgt);
314 }
315 }
316 }
317 return;
318 }
319
320 auto num_nodes = g.get_num_nodes();
321 const size_t path_edge_bound = num_nodes > 0 ? num_nodes - 1 : 0;
322 const size_t max_w_size = static_cast<size_t>(max_w);
323
324 // Maximum possible shortest-path distance in this graph:
325 // (|V|-1) * max_w. Compute it with checked size_t arithmetic.
326 ah_overflow_error_if(max_w_size != 0 and
327 path_edge_bound > std::numeric_limits<size_t>::max() / max_w_size)
328 << "Dial: overflow computing max_dist = (|V|-1) * max_w with |V|="
329 << num_nodes << " and max_w=" << max_w;
330
331 const size_t max_dist_size = path_edge_bound * max_w_size;
332 ah_overflow_error_if(max_dist_size > static_cast<size_t>(std::numeric_limits<Distance_Type>::max()))
333 << "Dial: max_dist " << max_dist_size
334 << " exceeds Distance_Type range; use a wider type or Dijkstra";
335 ah_overflow_error_if(max_dist_size == std::numeric_limits<size_t>::max())
336 << "Dial: overflow computing number of buckets";
337
338 const Distance_Type max_dist = static_cast<Distance_Type>(max_dist_size);
339 const size_t num_buckets = max_dist_size + 1;
341 << "Dial: bucket count " << num_buckets
342 << " exceeds safety limit " << Max_Sane_Buckets
343 << "; use Dijkstra_Min_Paths for large weight ranges";
344
345 Array<DynList<Node *>> buckets(num_buckets, DynList<Node *>());
346
347 DIAL_DIST(start) = 0;
348 NODE_BITS(start).set_bit(Aleph::Spanning_Tree, true);
349 buckets[0].append(start);
350
351 size_t processed = 0;
352
353 for (size_t idx = 0; idx < num_buckets and processed < num_nodes; ++idx)
354 {
355 while (not buckets[idx].is_empty())
356 {
357 auto curr = buckets[idx].remove_first();
358 auto curr_dist = DIAL_DIST(curr);
359
360 // Skip if this entry is stale (node was already relaxed to
361 // a shorter distance)
362 if (static_cast<size_t>(curr_dist) != idx)
363 continue;
364
365 ++processed;
366
367 if (end != nullptr and curr == end)
368 return;
369
370 for (Itor<GT, SA> it(curr, sa); it.has_curr(); it.next())
371 {
372 auto arc = it.get_current_arc();
373 auto tgt = g.get_connected_node(arc, curr);
374 auto w = distance(arc);
375 ah_domain_error_if(w < 0) << "Dial: negative weight " << w
376 << " not allowed";
377 ah_overflow_error_if(curr_dist > std::numeric_limits<Distance_Type>::max() - w)
378 << "Dial: overflow computing new_dist = curr_dist + w";
379 auto new_dist = curr_dist + w;
380
381 // Distances above the computed bound are not representable in buckets.
382 if (new_dist > max_dist)
383 continue;
384
385 if (new_dist < DIAL_DIST(tgt))
386 {
387 // Clear previous Spanning_Tree mark for tgt's parent arc
388 // to correctly handle multi-edges and avoid stale marks.
389 if (DIAL_PARC(tgt) != nullptr)
390 ARC_BITS(DIAL_PARC(tgt)).set_bit(Aleph::Spanning_Tree, false);
391
392 DIAL_DIST(tgt) = new_dist;
393 DIAL_PARENT(tgt) = curr;
394 DIAL_PARC(tgt) = arc;
395 NODE_BITS(tgt).set_bit(Aleph::Spanning_Tree, true);
396 ARC_BITS(arc).set_bit(Aleph::Spanning_Tree, true);
397 buckets[static_cast<size_t>(new_dist)].append(tgt);
398 }
399 }
400 }
401 }
402 }
403
404 public:
410 Dial_Min_Paths(Distance dist = Distance(), SA __sa = SA())
411 : sa(__sa), distance(dist)
412 {
413 // empty
414 }
415
419 [[nodiscard]] bool is_painted() const noexcept { return painted; }
420
424 [[nodiscard]] Node * get_start_node() const noexcept { return s; }
425
429 [[nodiscard]] GT * get_graph() const noexcept { return ptr_g; }
430
448 void paint_min_paths_tree(const GT & g, Node *start)
449 {
450 ah_domain_error_if(start == nullptr) << "start node cannot be null";
451 ah_domain_error_if(g.get_num_nodes() == 0) << "graph is empty";
452
453 painted = false;
454 s = nullptr;
455
456 init(g);
457 Dial_Init_Guard guard(*this, g);
458 s = start;
459 run_dial(g, start);
460 uninit_paint();
461 guard.commit();
462 painted = true;
463 }
464
475 [[nodiscard]] Distance_Type get_distance(Node *node)
476 {
477 ah_domain_error_if(not painted) << "Graph has not been painted";
478 ah_domain_error_if(node == nullptr) << "node cannot be null";
479
480 if (node == s)
481 return Distance_Type(0);
482
484 << "node is not reachable from start";
485
486 Distance_Type total = 0;
487 for (auto curr = node; curr != s;)
488 {
489 auto parent = static_cast<Node *>(NODE_COOKIE(curr));
490 ah_domain_error_if(parent == nullptr)
491 << "Dial: path reconstruction failed (null parent)";
492
493 bool found = false;
494 for (Itor<GT, SA> it(parent, sa); it.has_curr(); it.next())
495 {
496 auto arc = it.get_current_arc();
497 auto tgt = ptr_g->get_connected_node(arc, parent);
498 if (tgt == curr and IS_ARC_VISITED(arc, Aleph::Spanning_Tree))
499 {
500 total += distance(arc);
501 found = true;
502 break;
503 }
504 }
505 ah_domain_error_if(not found)
506 << "Dial: path reconstruction failed (arc not found)";
507
508 curr = parent;
509 }
510
511 return total;
512 }
513
525 {
526 ah_domain_error_if(not painted) << "Graph has not been painted";
527 ah_domain_error_if(ptr_g == nullptr) << "No computation has been done";
528
529 return Aleph::get_min_path<GT, Distance>(s, end, path, distance);
530 }
531
551 Distance_Type find_min_path(const GT & g, Node *start, Node *end,
552 Path<GT> & path)
553 {
554 ah_domain_error_if(start == nullptr) << "start node cannot be null";
555 ah_domain_error_if(end == nullptr) << "end node cannot be null";
556 ah_domain_error_if(g.get_num_nodes() == 0) << "graph is empty";
557
558 path.empty();
559
560 painted = false;
561 s = nullptr;
562
563 init(g);
564 Dial_Init_Guard guard(*this, g);
565 s = start;
566 run_dial(g, start, end);
567 uninit_paint();
568 guard.commit();
569 painted = true;
570
572 return Inf;
573
574 return get_min_path(end, path);
575 }
576
591 Distance_Type operator()(const GT & g, Node *start, Node *end,
592 Path<GT> & path)
593 {
594 return find_min_path(g, start, end, path);
595 }
596
597#undef DIAL_INFO
598#undef DIAL_DIST
599#undef DIAL_PARENT
600#undef DIAL_PARC
601 };
602} // end namespace Aleph
603
604# endif // DIAL_H
#define DIAL_PARC(p)
Definition Dial.H:160
#define DIAL_PARENT(p)
Definition Dial.H:159
#define DIAL_DIST(p)
Definition Dial.H:158
#define DIAL_INFO(p)
Definition Dial.H:157
Exception handling system with formatted messages for Aleph-w.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
Definition ah-errors.H:415
C++20 concepts for the protocol shared by graph algorithms.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
long double w
Definition btreepic.C:153
int num_nodes
Definition btreepic.C:410
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Default distance accessor for arc weights.
RAII guard for Dial initialization and cleanup.
Definition Dial.H:171
Dial_Init_Guard & operator=(const Dial_Init_Guard &)=delete
Deleted copy assignment.
~Dial_Init_Guard() noexcept
Destructor.
Definition Dial.H:200
void commit() noexcept
Commits the operation, preventing cleanup on destruction.
Definition Dial.H:197
Dial_Init_Guard(Dial_Init_Guard &&)=delete
Deleted move constructor.
Dial_Init_Guard(Dial_Min_Paths &__owner, const GT &__g) noexcept
Constructor.
Definition Dial.H:181
Dial_Init_Guard(const Dial_Init_Guard &)=delete
Deleted copy constructor.
Dial's algorithm for shortest paths with integer weights.
Definition Dial.H:128
Distance_Type get_distance(Node *node)
Gets the accumulated distance to a node after painting.
Definition Dial.H:475
Distance_Type get_min_path(Node *end, Path< GT > &path)
Extracts a shortest path from a previously painted graph.
Definition Dial.H:524
GT * get_graph() const noexcept
Get the graph of the last computation.
Definition Dial.H:429
void run_dial(const GT &g, Node *start, Node *end=nullptr)
Definition Dial.H:281
void paint_min_paths_tree(const GT &g, Node *start)
Paints the shortest paths tree on the graph from start.
Definition Dial.H:448
void init(const GT &g)
Definition Dial.H:210
Node * get_start_node() const noexcept
Get the start node of the last computation.
Definition Dial.H:424
bool is_painted() const noexcept
Check if the graph has been painted.
Definition Dial.H:419
static constexpr Distance_Type Inf
Definition Dial.H:145
typename GT::Node Node
Definition Dial.H:131
Distance distance
Definition Dial.H:139
static constexpr size_t Max_Sane_Buckets
Definition Dial.H:143
Distance_Type operator()(const GT &g, Node *start, Node *end, Path< GT > &path)
Computes shortest path (operator interface).
Definition Dial.H:591
Distance_Type find_min_path(const GT &g, Node *start, Node *end, Path< GT > &path)
Computes the shortest path from start to end.
Definition Dial.H:551
typename Distance::Distance_Type Distance_Type
Definition Dial.H:130
Distance_Type find_max_weight(const GT &g)
Definition Dial.H:268
typename GT::Arc Arc
Definition Dial.H:132
Dial_Min_Paths(Distance dist=Distance(), SA __sa=SA())
Constructor.
Definition Dial.H:410
void uninit_paint()
Definition Dial.H:235
void uninit_discard()
Definition Dial.H:247
void reset_state_after_failure() noexcept
Definition Dial.H:162
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
T remove_first()
See remove().
Definition htlist.H:1473
void next()
Advances the iterator to the next filtered element.
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Path on a graph.
Definition tpl_graph.H:3832
void empty()
Clean the path: all the nodes and arc are removed.
Definition tpl_graph.H:3999
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
Definition graph-dry.H:1058
void reset_bit(Node *node, int bit) const noexcept
Reset the bit of node (to zero)
Definition graph-dry.H:1087
#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.
@ Spanning_Tree
Definition aleph-graph.H:79
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
static std::atomic< bool > init
Definition hash-fct.C:54
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Distance accessor.
Dynamic array container with automatic resizing.
Utility algorithms and operations for graphs.