Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
io_graph.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
140#ifndef IO_GRAPH_H
141#define IO_GRAPH_H
142
143#include <algorithm>
144#include <fstream>
145#include <iostream>
146#include <memory>
147#include <type_traits>
148#include <tpl_graph.H>
149#include <ah-graph-concepts.H>
150#include <ah-errors.H>
151
152namespace Aleph
153{
154
163template <class GT>
165{
171 void operator()(std::ofstream & output, GT & g, typename GT::Node * p)
172 {
173 (void)g;
174 static_assert(std::is_trivially_copyable_v<typename GT::Node_Type>,
175 "Dft_Store_Node writes the bytes of the info: for an info that is "
176 "not trivially copyable, as std::string, give IO_Graph a functor of your own");
177 output.write(reinterpret_cast<const char*>(&p->get_info()),
178 sizeof(typename GT::Node_Type));
179 }
180
186 void operator()(std::ostream & output, GT & g, typename GT::Node * p)
187 {
188 (void)g;
189 output << p->get_info() << std::endl;
190 }
191};
192
201template <class GT>
203{
209 void operator()(std::ofstream & output, GT & g, typename GT::Arc * a)
210 {
211 (void)g;
212 static_assert(std::is_trivially_copyable_v<typename GT::Arc_Type>,
213 "Dft_Store_Arc writes the bytes of the info: for an info that is "
214 "not trivially copyable, as std::string, give IO_Graph a functor of your own");
215 output.write(reinterpret_cast<const char*>(&a->get_info()),
216 sizeof(typename GT::Arc_Type));
217 }
218
224 void operator()(std::ostream & output, GT & g, typename GT::Arc * a)
225 {
226 (void)g;
227 output << a->get_info() << std::endl;
228 }
229};
230
239template <class GT>
241{
247 void operator()(std::ifstream & input, GT & g, typename GT::Node * p)
248 {
249 (void)g;
250 static_assert(std::is_trivially_copyable_v<typename GT::Node_Type>,
251 "Dft_Load_Node reads the bytes of the info: for an info that is "
252 "not trivially copyable, as std::string, give IO_Graph a functor of your own");
253 input.read(reinterpret_cast<char*>(&p->get_info()),
254 sizeof(typename GT::Node_Type));
255 }
256
262 void operator()(std::istream & input, GT & g, typename GT::Node * p)
263 {
264 (void)g;
265 input >> p->get_info();
266 }
267};
268
277template <class GT>
279{
285 void operator()(std::ifstream & input, GT & g, typename GT::Arc * a)
286 {
287 (void)g;
288 static_assert(std::is_trivially_copyable_v<typename GT::Arc_Type>,
289 "Dft_Load_Arc reads the bytes of the info: for an info that is "
290 "not trivially copyable, as std::string, give IO_Graph a functor of your own");
291 input.read(reinterpret_cast<char*>(&a->get_info()),
292 sizeof(typename GT::Arc_Type));
293 }
294
300 void operator()(std::istream & input, GT & g, typename GT::Arc * a)
301 {
302 (void)g;
303 input >> a->get_info();
304 }
305};
306
336template <AlephGraph GT,
337 class Load_Node = Dft_Load_Node<GT>,
338 class Store_Node = Dft_Store_Node<GT>,
339 class Load_Arc = Dft_Load_Arc<GT>,
340 class Store_Arc = Dft_Store_Arc<GT>,
341 NodeFilter<GT> NF = Aleph::Dft_Show_Node<GT>,
342 ArcFilter<GT> AF = Aleph::Dft_Show_Arc<GT>>
344{
345 GT & g;
346
347 Load_Node load_node = Load_Node();
348 Store_Node store_node = Store_Node();
349 Load_Arc load_arc = Load_Arc();
350 Store_Arc store_arc = Store_Arc();
351
352 NF node_filter = NF();
353 AF arc_filter = AF();
354
355 bool verbose_mode = false;
356
357public:
358
366 void set_verbose(bool v) noexcept { verbose_mode = v; }
367
371 [[nodiscard]] bool is_verbose() const noexcept { return verbose_mode; }
372
376 void set_load_node(const Load_Node & ln) { load_node = ln; }
377
381 void set_store_node(const Store_Node & sn) { store_node = sn; }
382
386 void set_load_arc(const Load_Arc & la) { load_arc = la; }
387
391 void set_store_arc(const Store_Arc & sa) { store_arc = sa; }
392
396 void set_node_filter(const NF & nf) { node_filter = nf; }
397
405 void set_arc_filter(const AF & af) requires std::is_copy_assignable_v<AF>
406 {
407 arc_filter = af;
408 }
409
417 explicit IO_Graph(GT & __g) noexcept requires std::is_default_constructible_v<AF>
418 : g(__g) {}
419
426 explicit IO_Graph(GT * gptr) noexcept requires std::is_default_constructible_v<AF>
427 : g(*gptr) {}
428
433 IO_Graph(GT & __g, AF af) : g(__g), arc_filter(std::move(af)) {}
434
439 IO_Graph(GT * gptr, AF af) : g(*gptr), arc_filter(std::move(af)) {}
440
441private:
442
446 {
447 int i = 0;
448 for (Node_Iterator<GT, NF> it(g, node_filter); it.has_curr(); it.next_ne(), ++i)
449 nodes_table.insert(it.get_curr(), i);
450 return size_t(i);
451 }
452
455 {
456 size_t n = 0;
457 for (Arc_Iterator<GT, AF> it(g, arc_filter); it.has_curr(); it.next_ne())
458 {
459 auto a = it.get_curr();
460 if (nodes_table.search(g.get_src_node(a)) != nullptr and
461 nodes_table.search(g.get_tgt_node(a)) != nullptr)
462 ++n;
463 }
464 return n;
465 }
466
467public:
468
482 void save(std::ofstream & output)
483 {
484 // The counts go before what they count: the nodes and arcs that the
485 // filters show, counted first, an arc only with both of its ends
487 const size_t num_nodes = number_shown_nodes(nodes_table);
488 const size_t num_arcs = count_shown_arcs(nodes_table);
489
490 if (verbose_mode)
491 std::cout << "Storing " << num_nodes << " nodes ... ";
492
493 output.write(reinterpret_cast<const char*>(&num_nodes), sizeof(num_nodes));
494
495 int i = 0;
496 for (Node_Iterator<GT, NF> it(g, node_filter); it.has_curr();
497 it.next_ne(), ++i)
498 {
499 if (verbose_mode)
500 std::cout << i << " ";
501
502 store_node(output, g, it.get_curr());
503 }
504
505 if (verbose_mode)
506 std::cout << " done " << std::endl
507 << "Storing " << num_arcs << " arcs ... " << std::endl;
508
509 output.write(reinterpret_cast<const char*>(&num_arcs), sizeof(num_arcs));
510
511 for (Arc_Iterator<GT, AF> it(g, arc_filter); it.has_curr(); it.next_ne())
512 {
513 auto a = it.get_curr();
514
515 auto src = g.get_src_node(a);
516 auto tgt = g.get_tgt_node(a);
517 if (nodes_table.search(src) == nullptr or nodes_table.search(tgt) == nullptr)
518 continue; // an end that the node filter hides
519
520 const int src_idx = nodes_table.find(src);
521 const int tgt_idx = nodes_table.find(tgt);
522
523 output.write(reinterpret_cast<const char*>(&src_idx), sizeof(int));
524 output.write(reinterpret_cast<const char*>(&tgt_idx), sizeof(int));
525
526 if (verbose_mode)
527 std::cout << " " << src_idx << "--" << tgt_idx << " ";
528
529 store_arc(output, g, a);
530
531 if (verbose_mode)
532 std::cout << std::endl;
533 }
534
535 if (verbose_mode)
536 std::cout << " done " << std::endl << std::endl;
537 }
538
552 void load(std::ifstream & input)
553 {
554 size_t num_nodes;
555 input.read(reinterpret_cast<char*>(&num_nodes), sizeof(num_nodes));
556 ah_runtime_error_if(not input.good())
557 << "Failed to read node count from binary stream";
558
559 if (verbose_mode)
560 std::cout << "Loading " << num_nodes << " nodes ...";
561
562 Loaded_Nodes nodes_table(num_nodes);
563 try
564 {
565 for (size_t i = 0; i < num_nodes; ++i)
566 {
567 std::unique_ptr<typename GT::Node> p(new typename GT::Node);
568
569 if (verbose_mode)
570 std::cout << " " << i;
571
572 load_node(input, g, p.get());
573 ah_runtime_error_if(not input.good())
574 << "Failed to load node " << i << " from binary stream";
575
576 nodes_table.add(g, std::move(p));
577 }
578
579 size_t num_arcs;
580 input.read(reinterpret_cast<char*>(&num_arcs), sizeof(num_arcs));
581 ah_runtime_error_if(not input.good())
582 << "Failed to read arc count from binary stream";
583
584 if (verbose_mode)
585 std::cout << " done " << std::endl
586 << "Loading " << num_arcs << " arcs ... " << std::endl;
587
588 for (size_t i = 0; i < num_arcs; ++i)
589 {
590 int src_idx;
591 input.read(reinterpret_cast<char*>(&src_idx), sizeof(int));
592 ah_runtime_error_if(not input.good())
593 << "Failed to read source index for arc " << i;
594
595 int tgt_idx;
596 input.read(reinterpret_cast<char*>(&tgt_idx), sizeof(int));
597 ah_runtime_error_if(not input.good())
598 << "Failed to read target index for arc " << i;
599
600 auto src = nodes_table.node(src_idx, i, "source");
601 auto tgt = nodes_table.node(tgt_idx, i, "target");
602 auto a = g.insert_arc(src, tgt);
603
604 if (verbose_mode)
605 std::cout << " " << src_idx << "--" << tgt_idx << " ";
606
607 load_arc(input, g, a);
608 ah_runtime_error_if(not input.good())
609 << "Failed to load arc " << i << " data";
610
611 if (verbose_mode)
612 std::cout << std::endl;
613 }
614 }
615 catch (...)
616 {
617 nodes_table.remove_from(g);
618 throw;
619 }
620
621 if (verbose_mode)
622 std::cout << " done " << std::endl << std::endl;
623 }
624
644 void save_in_text_mode(std::ostream & output)
645 {
646 // The counts go first: the nodes and arcs that the filters show, an
647 // arc only with both of its ends
649 const size_t num_nodes = number_shown_nodes(nodes_table);
650 const size_t num_arcs = count_shown_arcs(nodes_table);
651
652 output << num_nodes << std::endl
653 << num_arcs << std::endl;
654
655 if (verbose_mode)
656 std::cout << "Storing " << num_nodes << " nodes ... ";
657
658 int i = 0;
659 for (Node_Iterator<GT, NF> it(g, node_filter); it.has_curr();
660 it.next_ne(), ++i)
661 {
662 if (verbose_mode)
663 std::cout << i << " ";
664
665 store_node(output, g, it.get_curr());
666 }
667
668 if (verbose_mode)
669 std::cout << " done " << std::endl
670 << "Storing " << num_arcs << " arcs ... " << std::endl;
671
672 for (Arc_Iterator<GT, AF> it(g, arc_filter); it.has_curr(); it.next_ne())
673 {
674 auto a = it.get_curr();
675
676 auto src = g.get_src_node(a);
677 auto tgt = g.get_tgt_node(a);
678 if (nodes_table.search(src) == nullptr or nodes_table.search(tgt) == nullptr)
679 continue; // an end that the node filter hides
680
681 const int src_idx = nodes_table.find(src);
682 const int tgt_idx = nodes_table.find(tgt);
683
684 output << src_idx << " " << tgt_idx << " ";
685
686 if (verbose_mode)
687 std::cout << " " << src_idx << "--" << tgt_idx << " ";
688
689 store_arc(output, g, a);
690
691 if (verbose_mode)
692 std::cout << std::endl;
693 }
694
695 if (verbose_mode)
696 std::cout << " done " << std::endl << std::endl;
697 }
698
712 void load_in_text_mode(std::istream & input)
713 {
714 size_t num_nodes;
715 size_t num_arcs;
716
717 input >> num_nodes >> num_arcs;
718 ah_runtime_error_if(not input.good())
719 << "Failed to read node/arc count from text stream";
720
721 input.ignore();
722
723 if (verbose_mode)
724 std::cout << "Loading " << num_nodes << " nodes ...";
725
726 Loaded_Nodes nodes_table(num_nodes);
727 try
728 {
729 for (size_t i = 0; i < num_nodes; ++i)
730 {
731 std::unique_ptr<typename GT::Node> p(new typename GT::Node);
732
733 if (verbose_mode)
734 std::cout << " " << i;
735
736 load_node(input, g, p.get());
737 ah_runtime_error_if(not input.good())
738 << "Failed to load node " << i << " from text stream";
739
740 nodes_table.add(g, std::move(p));
741 }
742
743 if (verbose_mode)
744 std::cout << " done " << std::endl
745 << "Loading " << num_arcs << " arcs ... " << std::endl;
746
747 for (size_t i = 0; i < num_arcs; ++i)
748 {
749 int src_idx;
750 int tgt_idx;
751
752 input >> src_idx >> tgt_idx;
753 ah_runtime_error_if(not input.good())
754 << "Failed to read arc " << i << " indices from text stream";
755
756 auto src = nodes_table.node(src_idx, i, "source");
757 auto tgt = nodes_table.node(tgt_idx, i, "target");
758 auto a = g.insert_arc(src, tgt);
759
760 if (verbose_mode)
761 std::cout << " " << src_idx << "--" << tgt_idx << " ";
762
763 load_arc(input, g, a);
764 ah_runtime_error_if(not input.good())
765 << "Failed to load arc " << i << " data from text stream";
766
767 if (verbose_mode)
768 std::cout << std::endl;
769 }
770 }
771 catch (...)
772 {
773 nodes_table.remove_from(g);
774 throw;
775 }
776
777 if (verbose_mode)
778 std::cout << " done " << std::endl << std::endl;
779 }
780
781private:
782
790 {
791 static constexpr size_t Max_Reserved = size_t(1) << 20;
792
794 size_t reserved = 0;
795 size_t num_loaded = 0;
796
797 public:
798
801 explicit Loaded_Nodes(const size_t num_nodes)
803 {
804 if (reserved > 0)
805 table.reserve(0, reserved - 1);
806 }
807
809 void add(GT & g, std::unique_ptr<typename GT::Node> p)
810 {
811 // The entry first: a node of the graph is always in the table
812 typename GT::Node * & slot =
814 slot = g.insert_node(p.release());
815 ++num_loaded;
816 }
817
820 typename GT::Node * node(const int idx, const size_t i, const char * end) const
821 {
822 // A negative idx is a size_t beyond num_loaded too
823 if (static_cast<size_t>(idx) >= num_loaded) [[unlikely]]
824 throw_invalid_index(idx, i, end);
825 return table(idx);
826 }
827
828 private:
829
830 // Apart, so that node() stays small enough to be inlined in the loads
831 [[noreturn, gnu::noinline, gnu::cold]]
832 void throw_invalid_index(const int idx, const size_t i, const char * end) const
833 {
834 ah_runtime_error() << "Invalid " << end << " index " << idx << " of arc "
835 << i << ": the stream has " << num_loaded << " nodes";
836 }
837
838 public:
839
842 {
843 for (size_t i = 0; i < num_loaded; ++i)
844 g.remove_node(table(i));
845 }
846 };
847
848public:
849};
850
851} // namespace Aleph
852
853// Global namespace compatibility
854using Aleph::IO_Graph;
859
860#endif // IO_GRAPH_H
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error()
Throws std::runtime_error unconditionally.
Definition ah-errors.H:431
#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
int num_nodes
Definition btreepic.C:410
T & touch(const size_t i)
Touch the entry i.
T & access(const size_t i) noexcept
Fast access without checking allocation and bound_min_clock checking.
void reserve(const size_t l, const size_t r)
Allocate a range of entries.
Dynamic map implemented with a treap.
Pair * search(const Key &key) noexcept(nothrow_search)
Collect all keys.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Data & find(const Key &key)
Find the value associated with key.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
The nodes that a load has read, by their index in the stream.
Definition io_graph.H:790
static constexpr size_t Max_Reserved
Definition io_graph.H:791
void add(GT &g, std::unique_ptr< typename GT::Node > p)
Insert the node p, loaded, into g, as the node of the next index.
Definition io_graph.H:809
void throw_invalid_index(const int idx, const size_t i, const char *end) const
Definition io_graph.H:832
DynArray< typename GT::Node * > table
Definition io_graph.H:793
void remove_from(GT &g)
Remove from g the nodes read, with their arcs: a load failed.
Definition io_graph.H:841
Loaded_Nodes(const size_t num_nodes)
Reserve for num_nodes nodes, the count of the stream, or Max_Reserved if it is greater.
Definition io_graph.H:801
GT::Node * node(const int idx, const size_t i, const char *end) const
The node of index idx of the stream, an end of the arc i.
Definition io_graph.H:820
Graph serialization and deserialization class.
Definition io_graph.H:344
void save(std::ofstream &output)
Save graph to binary stream.
Definition io_graph.H:482
size_t number_shown_nodes(DynMapTreap< typename GT::Node *, int > &nodes_table)
Gives each node that the node filter shows its number in the file, in the order of the saves,...
Definition io_graph.H:445
Store_Arc store_arc
Definition io_graph.H:350
void set_store_arc(const Store_Arc &sa)
Set the arc storage functor.
Definition io_graph.H:391
void save_in_text_mode(std::ostream &output)
Save graph to text stream.
Definition io_graph.H:644
void load_in_text_mode(std::istream &input)
Load graph from text stream.
Definition io_graph.H:712
void load(std::ifstream &input)
Load graph from binary stream.
Definition io_graph.H:552
bool is_verbose() const noexcept
Check if verbose mode is enabled.
Definition io_graph.H:371
size_t count_shown_arcs(const DynMapTreap< typename GT::Node *, int > &nodes_table)
The arcs that the arc filter shows whose two ends are numbered.
Definition io_graph.H:454
void set_store_node(const Store_Node &sn)
Set the node storage functor.
Definition io_graph.H:381
void set_load_arc(const Load_Arc &la)
Set the arc loading functor.
Definition io_graph.H:386
Load_Node load_node
Definition io_graph.H:347
Store_Node store_node
Definition io_graph.H:348
void set_verbose(bool v) noexcept
Enable or disable verbose mode.
Definition io_graph.H:366
void set_arc_filter(const AF &af)
Set the arc filter for save operations.
Definition io_graph.H:405
void set_node_filter(const NF &nf)
Set the node filter for save operations.
Definition io_graph.H:396
void set_load_node(const Load_Node &ln)
Set the node loading functor.
Definition io_graph.H:376
IO_Graph(GT &__g, AF af)
Construct from graph reference, with the arc filter.
Definition io_graph.H:433
IO_Graph(GT &__g) noexcept
Construct from graph reference.
Definition io_graph.H:417
IO_Graph(GT *gptr, AF af)
Construct from graph pointer, with the arc filter.
Definition io_graph.H:439
IO_Graph(GT *gptr) noexcept
Construct from graph pointer.
Definition io_graph.H:426
Load_Arc load_arc
Definition io_graph.H:349
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
typename Node::Node_Type Node_Type
The arc class type.
Definition tpl_graph.H:447
virtual void remove_node(Node *node)
Remove a node from the graph and free its memory.
Definition tpl_graph.H:557
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
typename Arc::Arc_Type Arc_Type
The type of data stored in the arc.
Definition tpl_graph.H:450
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
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
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
STL namespace.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Default arc loading functor for binary and text modes.
Definition io_graph.H:279
void operator()(std::ifstream &input, GT &g, typename GT::Arc *a)
Load arc from binary stream.
Definition io_graph.H:285
void operator()(std::istream &input, GT &g, typename GT::Arc *a)
Load arc from text stream.
Definition io_graph.H:300
Default node loading functor for binary and text modes.
Definition io_graph.H:241
void operator()(std::istream &input, GT &g, typename GT::Node *p)
Load node from text stream.
Definition io_graph.H:262
void operator()(std::ifstream &input, GT &g, typename GT::Node *p)
Load node from binary stream.
Definition io_graph.H:247
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Default filter for the graph nodes.
Definition tpl_graph.H:1228
Default arc storage functor for binary and text modes.
Definition io_graph.H:203
void operator()(std::ostream &output, GT &g, typename GT::Arc *a)
Store arc to text stream.
Definition io_graph.H:224
void operator()(std::ofstream &output, GT &g, typename GT::Arc *a)
Store arc to binary stream.
Definition io_graph.H:209
Default node storage functor for binary and text modes.
Definition io_graph.H:165
void operator()(std::ofstream &output, GT &g, typename GT::Node *p)
Store node to binary stream.
Definition io_graph.H:171
void operator()(std::ostream &output, GT &g, typename GT::Node *p)
Store node to text stream.
Definition io_graph.H:186
Generic graph and digraph implementations.
ofstream output
Definition writeHeap.C:215