Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_visualization_test.cc
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
43#include <gtest/gtest.h>
44#include <sstream>
45#include <stdexcept>
46#include <string>
47
48#include <tpl_graph.H>
49#include <tpl_graph_utils.H>
50#include <generate_graph.H>
51#include <graph_to_tree.H>
53#include <generate_tree.H>
54#include <tpl_tree_node.H>
55
56using namespace std;
57using namespace testing;
58using namespace Aleph;
59
60// ============================================================================
61// Test Fixtures
62// ============================================================================
63
65class SimpleGraphTest : public Test
66{
67protected:
70 using Arc = Graph::Arc;
71
76
77 void SetUp() override
78 {
79 n1 = g.insert_node(1);
80 n2 = g.insert_node(2);
81 n3 = g.insert_node(3);
82 g.insert_arc(n1, n2, 10);
83 g.insert_arc(n2, n3, 20);
84 g.insert_arc(n1, n3, 30);
85 }
86};
87
89class SimpleDigraphTest : public Test
90{
91protected:
95
100
101 void SetUp() override
102 {
103 n1 = g.insert_node(1);
104 n2 = g.insert_node(2);
105 n3 = g.insert_node(3);
106 g.insert_arc(n1, n2, 10);
107 g.insert_arc(n2, n3, 20);
108 g.insert_arc(n1, n3, 30);
109 }
110};
111
113class TreeGraphTest : public Test
114{
115protected:
119
125
126 void SetUp() override
127 {
128 // Create a simple tree:
129 // root(1)
130 // / |
131 // child1(2) child2(3)
132 // |
133 // grandchild(4)
134 root = tree.insert_node(1);
138
142 }
143};
144
145// ============================================================================
146// generate_graph.H Tests - Graphviz DOT generation
147// ============================================================================
148
149TEST_F(SimpleGraphTest, GenerateGraphvizContainsGraphKeyword)
150{
151 ostringstream out;
153 string result = out.str();
154
155 // Should contain "graph {" for undirected graphs
156 EXPECT_NE(result.find("graph {"), string::npos);
157 // Should NOT contain "digraph"
158 EXPECT_EQ(result.find("digraph {"), string::npos);
159}
160
161TEST_F(SimpleDigraphTest, GenerateGraphvizContainsDigraphKeyword)
162{
163 ostringstream out;
165 string result = out.str();
166
167 // Should contain "digraph {" for directed graphs
168 EXPECT_NE(result.find("digraph {"), string::npos);
169}
170
171TEST_F(SimpleGraphTest, GenerateGraphvizContainsAllNodes)
172{
173 ostringstream out;
175 string result = out.str();
176
177 // Should contain labels for all nodes
178 EXPECT_NE(result.find("label = \"1\""), string::npos);
179 EXPECT_NE(result.find("label = \"2\""), string::npos);
180 EXPECT_NE(result.find("label = \"3\""), string::npos);
181}
182
183TEST_F(SimpleGraphTest, GenerateGraphvizContainsArcs)
184{
185 ostringstream out;
187 string result = out.str();
188
189 // Should contain "--" for undirected graph arcs
190 EXPECT_NE(result.find("--"), string::npos);
191}
192
193TEST_F(SimpleDigraphTest, GenerateGraphvizContainsDirectedArcs)
194{
195 ostringstream out;
197 string result = out.str();
198
199 // Should contain "->" for directed graph arcs
200 EXPECT_NE(result.find("->"), string::npos);
201}
202
203TEST_F(SimpleGraphTest, GenerateGraphvizRespectRankdir)
204{
205 ostringstream out;
207 string result = out.str();
208
209 EXPECT_NE(result.find("rankdir = TB"), string::npos);
210}
211
212TEST_F(SimpleGraphTest, GenerateGraphvizClosesWithBrace)
213{
214 ostringstream out;
216 string result = out.str();
217
218 // Should end with closing brace
219 size_t lastBrace = result.rfind('}');
220 EXPECT_NE(lastBrace, string::npos);
221}
222
223// Test default attribute functors
224TEST_F(SimpleGraphTest, DftNodeAttrOutputsLabel)
225{
226 ostringstream out;
227 Dft_Node_Attr<Graph>()(g, n1, out);
228 string result = out.str();
229
230 EXPECT_NE(result.find("label"), string::npos);
231 EXPECT_NE(result.find("1"), string::npos);
232}
233
234TEST_F(SimpleGraphTest, DftArcAttrOutputsLabel)
235{
236 auto arc = g.get_first_arc();
237 ostringstream out;
238 Dft_Arc_Attr<Graph>()(g, arc, out);
239 string result = out.str();
240
241 EXPECT_NE(result.find("label"), string::npos);
242}
243
244// Test Dummy_Attr always returns false
245TEST_F(SimpleGraphTest, DummyAttrReturnsFalse)
246{
247 Dummy_Attr<Graph> dummy;
248 EXPECT_FALSE(dummy(n1));
249 EXPECT_FALSE(dummy(g.get_first_arc()));
250}
251
252// ============================================================================
253// generate_spanning_tree_picture.H Tests
254// ============================================================================
255
256TEST_F(SimpleGraphTest, ShadeSpanNodeReturnsEmptyForNullCookie)
257{
258 NODE_COOKIE(n1) = nullptr;
260 EXPECT_EQ(shader(n1), "");
261}
262
263TEST_F(SimpleGraphTest, ShadeSpanNodeReturnsShadowForNonNullCookie)
264{
265 NODE_COOKIE(n1) = n2; // non-null cookie
267 EXPECT_EQ(shader(n1), "SHADOW-NODE");
268}
269
270TEST_F(SimpleGraphTest, ShadeSpanArcReturnsArcForNullCookie)
271{
272 auto arc = g.get_first_arc();
273 ARC_COOKIE(arc) = nullptr;
275 EXPECT_EQ(shader(arc), "ARC");
276}
277
278TEST_F(SimpleGraphTest, ShadeSpanArcReturnsShadowForNonNullCookie)
279{
280 auto arc = g.get_first_arc();
281 ARC_COOKIE(arc) = n1; // non-null cookie
283 EXPECT_EQ(shader(arc), "SHADOW-ARC");
284}
285
286// ============================================================================
287// graph_to_tree.H Tests
288// ============================================================================
289
292{
295 {
296 tnode->get_key() = gnode->get_info();
297 }
298};
299
300TEST_F(TreeGraphTest, GraphToTreeNodeCreatesRoot)
301{
302 Tree_Node<int>* treeRoot =
304
305 ASSERT_NE(treeRoot, nullptr);
306 EXPECT_EQ(treeRoot->get_key(), 1);
307
308 destroy_tree(treeRoot);
309}
310
311TEST_F(TreeGraphTest, GraphToTreeNodeCreatesChildren)
312{
313 Tree_Node<int>* treeRoot =
315
316 // Root should have children
317 auto* firstChild = treeRoot->get_left_child();
318 ASSERT_NE(firstChild, nullptr);
319
320 // Count children
321 int childCount = 0;
322 for (auto* child = firstChild; child != nullptr;
323 child = child->get_right_sibling())
324 childCount++;
325
326 EXPECT_EQ(childCount, 2); // child1 and child2
327
328 destroy_tree(treeRoot);
329}
330
331TEST_F(TreeGraphTest, GraphToTreeNodePreservesStructure)
332{
333 Tree_Node<int>* treeRoot =
335
336 // Find all node values
337 set<int> values;
338 function<void(Tree_Node<int>*)> collectValues = [&](Tree_Node<int>* node) {
339 if (node == nullptr) return;
340 values.insert(node->get_key());
341 for (auto* child = node->get_left_child(); child != nullptr;
342 child = child->get_right_sibling())
343 collectValues(child);
344 };
345
346 collectValues(treeRoot);
347
348 // Should contain all original values
349 EXPECT_TRUE(values.count(1) > 0);
350 EXPECT_TRUE(values.count(2) > 0);
351 EXPECT_TRUE(values.count(3) > 0);
352 EXPECT_TRUE(values.count(4) > 0);
353 EXPECT_EQ(values.size(), 4u);
354
355 destroy_tree(treeRoot);
356}
357
358TEST_F(TreeGraphTest, GraphToTreeNodeThrowsOnCyclicGraph)
359{
360 // Add an arc to create a cycle
361 tree.insert_arc(grandchild, root, 0);
362
364 EXPECT_THROW(Converter()(tree, root), std::domain_error);
365}
366
367// A conversion marked the arcs, so that the next one on the same graph
368// stopped at the root
369TEST_F(TreeGraphTest, GraphToTreeNodeConvertsTheSameGraphAgain)
370{
371 for (int i = 0; i < 4; ++i)
372 {
373 SCOPED_TRACE(i);
374 Tree_Node<int> * t = i < 2
376 : graph_to_tree_node<Graph, int, IntConvert>(tree, root);
377 size_t nodes = 0;
378 t->traverse([&nodes](auto) { ++nodes; return true; });
379 EXPECT_EQ(nodes, 4u);
380 destroy_tree(t);
381 }
382}
383
384namespace
385{
386 // A key that counts the keys that live
387 struct Counted_Key
388 {
389 static inline long live = 0;
390 int value = 0;
391
392 Counted_Key() { ++live; }
393 Counted_Key(const Counted_Key & k) : value(k.value) { ++live; }
394 Counted_Key & operator = (const Counted_Key &) = default;
395 ~Counted_Key() { --live; }
396 };
397
398 // Converts the first two nodes, and throws on the third
399 struct Failing_Convert
400 {
401 static inline int calls = 0;
402
403 void operator()(List_Graph<Graph_Node<int>, Graph_Arc<int>>::Node * gnode,
404 Tree_Node<Counted_Key> * tnode) const
405 {
406 if (++calls == 3)
407 throw std::runtime_error("conversion");
408 tnode->get_key().value = gnode->get_info();
409 }
410 };
411}
412
413// If the conversion threw, the tree built so far was lost
414TEST_F(TreeGraphTest, GraphToTreeNodeFreesTheTreeIfTheConversionThrows)
415{
416 Failing_Convert::calls = 0;
418 std::runtime_error);
419 EXPECT_EQ(Counted_Key::live, 0);
420
421 Failing_Convert::calls = 0;
422 EXPECT_THROW((graph_to_tree_node<Graph, Counted_Key, Failing_Convert>(tree, root)),
423 std::runtime_error);
424 EXPECT_EQ(Counted_Key::live, 0);
425}
426
427// ============================================================================
428// generate_tree.H Tests (additional to existing tests)
429// ============================================================================
430
431TEST_F(TreeGraphTest, GenerateTreeOutputsRoot)
432{
433 Tree_Node<int>* treeRoot =
435
436 ostringstream out;
437 generate_tree(treeRoot, out);
438 string result = out.str();
439
440 // Should start with Root
441 EXPECT_EQ(result.find("Root"), 0u);
442
443 destroy_tree(treeRoot);
444}
445
446TEST_F(TreeGraphTest, GenerateTreeOutputsDeweyNotation)
447{
448 Tree_Node<int>* treeRoot =
450
451 ostringstream out;
452 generate_tree(treeRoot, out);
453 string result = out.str();
454
455 // Should contain Node entries with Dewey notation
456 EXPECT_NE(result.find("Node "), string::npos);
457
458 destroy_tree(treeRoot);
459}
460
461TEST(GenerateTreeGraphvizTest, EscapesSpecialCharactersInLabels)
462{
463 struct RawWriter
464 {
465 string operator()(Tree_Node<string> * p) { return p->get_key(); }
466 };
467
468 auto * root = new Tree_Node<string>;
469 root->get_key() = "say \"hi\"\npath\\leaf";
470
471 ostringstream out;
472 generate_tree_graphviz<Tree_Node<string>, RawWriter>(root, out);
473 const string result = out.str();
474
475 EXPECT_NE(result.find("label=\"say \\\"hi\\\"\\npath\\\\leaf\""), string::npos);
476 EXPECT_EQ(result.find("label=\"say \"hi\""), string::npos);
477
478 delete root;
479}
480
481// ============================================================================
482// Integration Tests
483// ============================================================================
484
485TEST_F(TreeGraphTest, FullPipelineGraphToTreeToOutput)
486{
487 // Convert graph to tree
488 Tree_Node<int>* treeRoot =
490
491 // Generate tree output
492 ostringstream out;
493 generate_tree(treeRoot, out);
494 string result = out.str();
495
496 // Verify output is non-empty and has expected structure
497 EXPECT_FALSE(result.empty());
498 EXPECT_NE(result.find("Root"), string::npos);
499 EXPECT_NE(result.find("\"1\""), string::npos); // Root value
500
501 destroy_tree(treeRoot);
502}
503
504// ============================================================================
505// Edge Cases
506// ============================================================================
507
508TEST(EmptyGraphTest, GenerateGraphvizHandlesEmptyGraph)
509{
511
512 ostringstream out;
514 string result = out.str();
515
516 // Should still produce valid DOT structure
517 EXPECT_NE(result.find("graph {"), string::npos);
518 EXPECT_NE(result.find("}"), string::npos);
519}
520
521TEST(SingleNodeGraphTest, GenerateGraphvizHandlesSingleNode)
522{
524 g.insert_node(42);
525
526 ostringstream out;
528 string result = out.str();
529
530 EXPECT_NE(result.find("42"), string::npos);
531}
532
533TEST(SingleNodeTreeTest, GraphToTreeNodeHandlesSingleNode)
534{
536 auto* node = g.insert_node(42);
537
538 struct Conv {
539 void operator()(decltype(node) gn, Tree_Node<int>* tn) {
540 tn->get_key() = gn->get_info();
541 }
542 };
543
544 Tree_Node<int>* treeRoot =
546
547 ASSERT_NE(treeRoot, nullptr);
548 EXPECT_EQ(treeRoot->get_key(), 42);
549 EXPECT_EQ(treeRoot->get_left_child(), nullptr);
550
551 destroy_tree(treeRoot);
552}
553
554// ============================================================================
555// Type Traits Tests
556// ============================================================================
557
558TEST(TypeTraitsTest, DftWriteConvertsToString)
559{
560 Tree_Node<int> node;
561 node.get_key() = 123;
562
564 string result = writer(&node);
565
566 EXPECT_EQ(result, "123");
567}
568
569// ============================================================================
570// Additional generate_graph.H Tests
571// ============================================================================
572
573// Test digraph_graphviz() - always outputs digraph format
574TEST_F(SimpleGraphTest, DigraphGraphvizForcesDigraphFormat)
575{
576 // Custom functors for digraph_graphviz
577 struct NodeAttr {
578 void operator()(const Graph&, Node* n, ostream& out) {
579 out << "label=\"" << n->get_info() << "\"";
580 }
581 };
582 struct ArcAttr {
583 void operator()(const Graph&, Arc* a, ostream& out) {
584 out << "label=\"" << a->get_info() << "\"";
585 }
586 };
587
588 ostringstream out;
589 digraph_graphviz<Graph, NodeAttr, ArcAttr, Dft_Show_Node<Graph>, Dft_Show_Arc<Graph>>
590 (g, out);
591 string result = out.str();
592
593 // Should contain "digraph {" even for undirected graph
594 EXPECT_NE(result.find("digraph {"), string::npos);
595 EXPECT_NE(result.find("->"), string::npos);
596}
597
598// Test Generate_Graphviz struct
599TEST_F(SimpleGraphTest, GenerateGraphvizStructWorks)
600{
601 struct WriteNode {
602 string operator()(Node* n) const { return to_string(n->get_info()); }
603 };
604 struct WriteArc {
605 string operator()(Arc* a) const { return to_string(a->get_info()); }
606 };
607
608 ostringstream out;
610 string result = out.str();
611
612 EXPECT_NE(result.find("graph {"), string::npos);
613 EXPECT_NE(result.find("rankdir = TB"), string::npos);
614}
615
616// Test custom rankdir values
617TEST_F(SimpleGraphTest, GenerateGraphvizDifferentRankdirs)
618{
619 const vector<string> rankdirs = {"TB", "BT", "LR", "RL"};
620
621 for (const auto& dir : rankdirs) {
622 ostringstream out;
624 string result = out.str();
625 EXPECT_NE(result.find("rankdir = " + dir), string::npos)
626 << "Failed for rankdir: " << dir;
627 }
628}
629
630// Test with string node info
631TEST(StringNodeGraphTest, GenerateGraphvizWithStringNodes)
632{
634 SGraph g;
635 auto* a = g.insert_node("Alpha");
636 auto* b = g.insert_node("Beta");
637 g.insert_arc(a, b, 1);
638
639 ostringstream out;
641 string result = out.str();
642
643 EXPECT_NE(result.find("Alpha"), string::npos);
644 EXPECT_NE(result.find("Beta"), string::npos);
645}
646
647// Test with double arc weights
648TEST(DoubleArcGraphTest, GenerateGraphvizWithDoubleArcs)
649{
651 DGraph g;
652 auto* a = g.insert_node(1);
653 auto* b = g.insert_node(2);
654 g.insert_arc(a, b, 3.14159);
655
656 ostringstream out;
658 string result = out.str();
659
660 EXPECT_NE(result.find("3.14"), string::npos);
661}
662
663// Test DAG with rank_graphviz
664TEST(DAGTest, RankGraphvizCreatesSubgraphs)
665{
667 DAG g;
668
669 // Create a simple DAG: 1 -> 2 -> 3
670 auto* n1 = g.insert_node(1);
671 auto* n2 = g.insert_node(2);
672 auto* n3 = g.insert_node(3);
673 g.insert_arc(n1, n2, 0);
674 g.insert_arc(n2, n3, 0);
675
676 struct NodeAttr {
677 void operator()(const DAG&, DAG::Node* n, ostream& out) {
678 out << "label=\"" << n->get_info() << "\"";
679 }
680 };
681 struct ArcAttr {
682 void operator()(const DAG&, DAG::Arc*, ostream& out) {
683 out << "";
684 }
685 };
686
687 ostringstream out;
688 size_t numRanks = rank_graphviz<DAG, NodeAttr, ArcAttr,
690
691 string result = out.str();
692
693 // Should have multiple ranks
694 EXPECT_GE(numRanks, 1u);
695 // Should contain subgraph declarations
696 EXPECT_NE(result.find("subgraph"), string::npos);
697 EXPECT_NE(result.find("rank"), string::npos);
698}
699
700// ============================================================================
701// Additional generate_tree.H Tests
702// ============================================================================
703
704// Test generate_forest with multiple trees
705TEST(ForestTest, GenerateForestOutputsMultipleTrees)
706{
707 // Create a forest of 3 single-node trees as siblings
708 Tree_Node<int>* tree1 = new Tree_Node<int>;
709 Tree_Node<int>* tree2 = new Tree_Node<int>;
710 Tree_Node<int>* tree3 = new Tree_Node<int>;
711
712 tree1->get_key() = 100;
713 tree2->get_key() = 200;
714 tree3->get_key() = 300;
715
716 // Link as siblings
717 tree1->insert_right_sibling(tree2);
718 tree2->insert_right_sibling(tree3);
719
720 ostringstream out;
721 generate_forest(tree1, out);
722 string result = out.str();
723
724 // Should contain all three roots
725 EXPECT_NE(result.find("100"), string::npos);
726 EXPECT_NE(result.find("200"), string::npos);
727 EXPECT_NE(result.find("300"), string::npos);
728
729 // Should have multiple "Root" entries
730 size_t firstRoot = result.find("Root");
731 size_t secondRoot = result.find("Root", firstRoot + 1);
732 size_t thirdRoot = result.find("Root", secondRoot + 1);
733
734 EXPECT_NE(firstRoot, string::npos);
735 EXPECT_NE(secondRoot, string::npos);
736 EXPECT_NE(thirdRoot, string::npos);
737
738 // Clean up - siblings are not automatically deleted
739 delete tree1;
740 delete tree2;
741 delete tree3;
742}
743
744// Test custom Write functor
745TEST(CustomWriteTest, GenerateTreeWithCustomWriter)
746{
747 struct HexWriter {
748 string operator()(Tree_Node<int>* p) {
749 ostringstream ss;
750 ss << "0x" << hex << p->get_key();
751 return ss.str();
752 }
753 };
754
756 root->get_key() = 255;
757
758 ostringstream out;
759 generate_tree<Tree_Node<int>, HexWriter>(root, out);
760 string result = out.str();
761
762 EXPECT_NE(result.find("0xff"), string::npos);
763
764 delete root;
765}
766
767// Test deep tree (many levels)
768TEST(DeepTreeTest, GenerateTreeHandlesDeepTree)
769{
770 const int DEPTH = 10;
772 root->get_key() = 0;
773
774 Tree_Node<int>* current = root;
775 for (int i = 1; i < DEPTH; ++i) {
776 Tree_Node<int>* child = new Tree_Node<int>;
777 child->get_key() = i;
778 current->insert_leftmost_child(child);
779 current = child;
780 }
781
782 ostringstream out;
784 string result = out.str();
785
786 // Should contain all nodes
787 for (int i = 0; i < DEPTH; ++i) {
788 EXPECT_NE(result.find("\"" + to_string(i) + "\""), string::npos)
789 << "Missing node " << i;
790 }
791
792 // Should have deep Dewey notation like "0.0.0.0..."
793 // The deepest node would have 9 dots in its Dewey number
794 EXPECT_NE(result.find("Node 0.0.0.0"), string::npos);
795
797}
798
799// Test wide tree (many siblings)
800TEST(WideTreeTest, GenerateTreeHandlesWideTree)
801{
802 const int WIDTH = 10;
804 root->get_key() = 0;
805
806 for (int i = 1; i <= WIDTH; ++i) {
807 Tree_Node<int>* child = new Tree_Node<int>;
808 child->get_key() = i;
809 root->insert_rightmost_child(child);
810 }
811
812 ostringstream out;
814 string result = out.str();
815
816 // Should contain all children
817 for (int i = 1; i <= WIDTH; ++i) {
818 EXPECT_NE(result.find("\"" + to_string(i) + "\""), string::npos)
819 << "Missing child " << i;
820 }
821
823}
824
825// ============================================================================
826// graph_to_tree.H Additional Tests
827// ============================================================================
828
829// Test free function graph_to_tree_node (not just the class)
830TEST_F(TreeGraphTest, FreeFunctionGraphToTreeNodeWorks)
831{
832 Tree_Node<int>* treeRoot =
833 graph_to_tree_node<Graph, int, IntConvert, Dft_Show_Arc<Graph>>(tree, root);
834
835 ASSERT_NE(treeRoot, nullptr);
836 EXPECT_EQ(treeRoot->get_key(), 1);
837
838 destroy_tree(treeRoot);
839}
840
841// Test with different starting nodes
842TEST_F(TreeGraphTest, GraphToTreeNodeFromDifferentRoot)
843{
844 // Start from child1 instead of root
845 Tree_Node<int>* treeRoot =
847
848 ASSERT_NE(treeRoot, nullptr);
849 EXPECT_EQ(treeRoot->get_key(), 2); // child1's value
850
851 // Should have grandchild as child (and root as parent via traversal)
852 auto* firstChild = treeRoot->get_left_child();
853 ASSERT_NE(firstChild, nullptr);
854
855 destroy_tree(treeRoot);
856}
857
858// Test converter that transforms data
859TEST_F(TreeGraphTest, GraphToTreeNodeWithTransformingConverter)
860{
861 struct DoubleConvert {
863 void operator()(GNode* gnode, Tree_Node<int>* tnode) {
864 tnode->get_key() = gnode->get_info() * 2; // Double the value
865 }
866 };
867
868 Tree_Node<int>* treeRoot =
870
871 EXPECT_EQ(treeRoot->get_key(), 2); // 1 * 2 = 2
872
873 destroy_tree(treeRoot);
874}
875
876// Test with string keys in tree
877TEST_F(TreeGraphTest, GraphToTreeNodeWithStringKeys)
878{
879 struct StringConvert {
881 void operator()(GNode* gnode, Tree_Node<string>* tnode) {
882 tnode->get_key() = "Node_" + to_string(gnode->get_info());
883 }
884 };
885
886 Tree_Node<string>* treeRoot =
888
889 EXPECT_EQ(treeRoot->get_key(), "Node_1");
890
891 destroy_tree(treeRoot);
892}
893
894// ============================================================================
895// Custom Filter Tests
896// ============================================================================
897
898// Custom arc filter that only shows arcs with weight > threshold
899template <typename GT>
901{
902 int threshold = 15;
903
904 bool operator()(typename GT::Arc* a) const {
905 return a->get_info() > threshold;
906 }
907};
908
909TEST_F(SimpleGraphTest, GenerateGraphvizWithArcFilter)
910{
911 // Our graph has arcs with weights 10, 20, 30
912 // Filter should only show arcs > 15 (so 20 and 30)
913
914 struct NodeAttr {
915 void operator()(const Graph&, Node* n, ostream& out) {
916 out << "label=\"" << n->get_info() << "\"";
917 }
918 };
919 struct ArcAttr {
920 void operator()(const Graph&, Arc* a, ostream& out) {
921 out << "label=\"" << a->get_info() << "\"";
922 }
923 };
924
925 ostringstream out;
926 generate_graphviz<Graph, NodeAttr, ArcAttr, Dft_Show_Node<Graph>, WeightFilter<Graph>>
927 (g, out, NodeAttr(), ArcAttr(), "LR");
928 string result = out.str();
929
930 // Should contain arcs with weight 20 and 30
931 EXPECT_NE(result.find("20"), string::npos);
932 EXPECT_NE(result.find("30"), string::npos);
933 // Should NOT contain arc with weight 10
934 EXPECT_EQ(result.find("\"10\""), string::npos);
935}
936
937// ============================================================================
938// Stress Tests
939// ============================================================================
940
941TEST(LargeGraphTest, GenerateGraphvizHandlesLargeGraph)
942{
944 LGraph g;
945
946 const int NUM_NODES = 100;
947 vector<LGraph::Node*> nodes;
948
949 // Create nodes
950 for (int i = 0; i < NUM_NODES; ++i) {
951 nodes.push_back(g.insert_node(i));
952 }
953
954 // Create a path
955 for (int i = 0; i < NUM_NODES - 1; ++i) {
956 g.insert_arc(nodes[i], nodes[i + 1], i);
957 }
958
959 ostringstream out;
961 string result = out.str();
962
963 // Should produce valid output
964 EXPECT_NE(result.find("graph {"), string::npos);
965 EXPECT_NE(result.find("}"), string::npos);
966
967 // Should contain first and last nodes
968 EXPECT_NE(result.find("\"0\""), string::npos);
969 EXPECT_NE(result.find("\"99\""), string::npos);
970}
971
972TEST(LargeTreeTest, GraphToTreeNodeHandlesLargeTree)
973{
975 LGraph tree;
976
977 const int NUM_NODES = 100;
978 vector<LGraph::Node*> nodes;
979
980 // Create nodes
981 for (int i = 0; i < NUM_NODES; ++i) {
982 nodes.push_back(tree.insert_node(i));
983 }
984
985 // Create a binary-ish tree structure
986 for (int i = 1; i < NUM_NODES; ++i) {
987 int parent = (i - 1) / 2;
988 tree.insert_arc(nodes[parent], nodes[i], 0);
989 }
990
991 struct Conv {
992 void operator()(LGraph::Node* gn, Tree_Node<int>* tn) {
993 tn->get_key() = gn->get_info();
994 }
995 };
996
997 Tree_Node<int>* treeRoot =
999
1000 ASSERT_NE(treeRoot, nullptr);
1001 EXPECT_EQ(treeRoot->get_key(), 0);
1002
1003 // Count all nodes
1004 int count = 0;
1005 function<void(Tree_Node<int>*)> countNodes = [&](Tree_Node<int>* node) {
1006 if (node == nullptr) return;
1007 count++;
1008 for (auto* child = node->get_left_child(); child != nullptr;
1009 child = child->get_right_sibling())
1010 countNodes(child);
1011 };
1012 countNodes(treeRoot);
1013
1014 EXPECT_EQ(count, NUM_NODES);
1015
1016 destroy_tree(treeRoot);
1017}
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
typename BaseGraph::Arc Arc
Definition graph-dry.H:4381
typename BaseGraph::Node Node
Definition graph-dry.H:4380
Functor class to convert a tree graph to Tree_Node structure.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Graph_Arc< int > Arc
The node class type.
Definition tpl_graph.H:444
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Graph class implemented with singly-linked adjacency lists.
Definition tpl_sgraph.H:274
Arc * insert_arc(Node *src, Node *tgt, void *a)
Definition tpl_sgraph.H:552
virtual Node * insert_node(Node *p)
Insertion of a node whose memory has already been allocated.
Definition tpl_sgraph.H:532
Forward declaration used by CRTP helpers before the full node definition.
bool traverse(Operation op)
Preorder traversal over all nodes executing op.
Tree_Node * get_left_child() const noexcept
Returns the leftmost child of this.
void insert_right_sibling(Tree_Node *p) noexcept
Inserts p to the right of this node.
T & get_key() noexcept
Returns a modifiable reference to the node contents.
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
Simple digraph for testing.
Simple graph for testing.
Tree graph for graph_to_tree conversion testing.
#define TEST(name)
Grafo::Node GNode
Definition floyd.cc:58
Graph visualization and output generation utilities.
Spanning tree visualization with highlighted tree/non-tree edges.
Tree visualization and output generation.
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
Convert spanning tree graphs to Tree_Node structures.
TEST_F(SimpleGraphTest, GenerateGraphvizContainsGraphKeyword)
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
#define ARC_COOKIE(p)
Return the arc cookie
#define NODE_COOKIE(p)
Return the node cookie
size_t rank_graphviz(const GT &g, std::ostream &out, Node_Attr node_attr=Node_Attr(), Arc_Attr arc_attr=Arc_Attr(), const std::string &rankdir="LR", SA sa=SA())
Generate Graphviz DOT output with topological ranking.
void generate_forest(Node *root, std::ostream &out)
Generate a forest specification for the ntreepic drawing tool.
void generate_tree(Node *root, std::ostream &out, const int &tree_number=0)
Generate a tree specification for the ntreepic drawing tool.
void destroy_tree(Node *root)
Destroys (frees memory) the tree whose root is root.
Main namespace for Aleph-w library functions.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
STL namespace.
#define WIDTH(p)
Definition ntreepic.C:362
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Default filter for the graph nodes.
Definition tpl_graph.H:1228
Functor for generating Graphviz specifications.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Functor class for generating Graphviz DOT specifications.
Converter from Graph::Node to int for Tree_Node.
List_Graph< Graph_Node< int >, Graph_Arc< int > >::Node GraphNode
void operator()(GraphNode *gnode, Tree_Node< int > *tnode)
Shading functor for spanning tree arcs.
Shading functor for spanning tree nodes.
bool operator()(typename GT::Arc *a) const
Functor to convert tree node to string for output.
string operator()(Tree_Node< int > *p)
Dnode< int > Test
Definition testDnode.C:42
static int * k
Generic graph and digraph implementations.
Utility algorithms and operations for graphs.
General tree (n-ary tree) node.