Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Planarity_Test.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
92#ifndef PLANARITY_TEST_H
93#define PLANARITY_TEST_H
94
95# include <ah-graph-concepts.H>
96
97#include <algorithm>
98#include <cmath>
99#include <cstddef>
100#include <limits>
101#include <sstream>
102#include <string>
103#include <utility>
104
105#include <ah-errors.H>
106#include <tpl_array.H>
107#include <tpl_dfs_stack.H>
108#include <tpl_dynMapTree.H>
109#include <tpl_dynSetTree.H>
110#include <tpl_graph.H>
111#include <tpl_sort_utils.H>
112#include <ah-iterator.H>
113
114namespace Aleph {
126
131inline const char *to_string(const Planarity_Certificate_Type type) noexcept
132{
133 switch (type)
134 {
136 return "None";
138 return "K5_Subdivision";
140 return "K33_Subdivision";
142 return "Minimal_NonPlanar_Obstruction";
143 }
144
145 return "Unknown";
146}
147
157{
164 bool compute_embedding = false;
165
171
178
183
189
194
199
204
208 size_t certificate_max_reduction_passes = std::numeric_limits<size_t>::max();
209};
210
221template <AlephGraph GT>
281
286template <AlephGraph GT>
288{
289 using Node = typename GT::Node;
290
291 size_t face_a = 0;
292 size_t face_b = 0;
293 Node *primal_src = nullptr;
294 Node *primal_tgt = nullptr;
295};
296
304template <AlephGraph GT>
331
337{
341 size_t preferred_outer_face = std::numeric_limits<size_t>::max();
342
345
348
350 double relaxation_tolerance = 1e-10;
351
353 double outer_face_radius = 1.0;
354
356 double component_spacing = 3.0;
357
360};
361
366template <AlephGraph GT>
368{
369 using Node = typename GT::Node;
370
372 {
373 Node *node = nullptr;
374 double x = 0;
375 double y = 0;
376 };
377
378 bool has_embedding = false;
379 bool drawing_available = false;
382
383 size_t chosen_outer_face = std::numeric_limits<size_t>::max();
385 size_t crossing_count = 0;
386 size_t num_components = 0;
387
389};
390
396{
398 bool pretty_json = true;
399
402
405
408};
409
414template <AlephGraph GT>
435
442template <class GT>
444{
445 std::string operator()(typename GT::Node *node) const
446 {
447 std::ostringstream out;
448 out << node;
449 return out.str();
450 }
451};
452
453template <class GT>
456
457namespace planarity_detail {
458
459static constexpr size_t Null_Edge = std::numeric_limits<size_t>::max();
460
462{
463 size_t u = 0;
464 size_t v = 0;
465
466 bool operator<(const Edge_Key &other) const noexcept
467 {
468 if (u < other.u)
469 return true;
470 if (other.u < u)
471 return false;
472 return v < other.v;
473 }
474};
475
477{
478 size_t u = 0;
479 size_t v = 0;
480};
481
483{
484 size_t low = Null_Edge;
485 size_t high = Null_Edge;
486
487 bool operator==(const Interval &other) const noexcept = default;
488};
489
491{
494
495 bool operator == (const Conflict_Pair &other) const noexcept = default;
496};
497
498inline bool interval_empty(const Interval &i) noexcept
499{
500 return i.low == Null_Edge;
501}
502
503inline bool pair_empty(const Conflict_Pair &p) noexcept
504{
505 return interval_empty(p.left) and interval_empty(p.right);
506}
507
509{
510 size_t u = 0;
511 size_t v = 0;
512
513 bool operator<(const Dart_Key &other) const noexcept
514 {
515 if (u < other.u)
516 return true;
517 if (other.u < u)
518 return false;
519 return v < other.v;
520 }
521};
522
524{
525 size_t u = Null_Edge;
526 size_t v = Null_Edge;
528};
529
530inline std::string json_escape_string(const std::string &s)
531{
532 std::ostringstream out;
533 for (const char i : s)
534 switch (const auto c = static_cast<unsigned char>(i))
535 {
536 case '\"':
537 out << "\\\"";
538 break;
539 case '\\':
540 out << "\\\\";
541 break;
542 case '\b':
543 out << "\\b";
544 break;
545 case '\f':
546 out << "\\f";
547 break;
548 case '\n':
549 out << "\\n";
550 break;
551 case '\r':
552 out << "\\r";
553 break;
554 case '\t':
555 out << "\\t";
556 break;
557 default:
558 if (c < 0x20)
559 {
560 out << "\\u00";
561 const char *hex = "0123456789abcdef";
562 out << hex[(c >> 4) & 0xF] << hex[c & 0xF];
563 }
564 else
565 out << static_cast<char>(c);
566 break;
567 }
568
569 return out.str();
570}
571
572inline std::string dot_escape_string(const std::string &s)
573{
574 std::ostringstream out;
575 for (const char c : s)
576 if (c == '\"' or c == '\\')
577 out << '\\' << c;
578 else if (c == '\n')
579 out << "\\n";
580 else
581 out << c;
582 return out.str();
583}
584
585inline std::string xml_escape_string(const std::string &s)
586{
587 std::ostringstream out;
588 for (const char i : s)
589 switch (const auto c = static_cast<unsigned char>(i))
590 {
591 case '&':
592 out << "&amp;";
593 break;
594 case '<':
595 out << "&lt;";
596 break;
597 case '>':
598 out << "&gt;";
599 break;
600 case '\"':
601 out << "&quot;";
602 break;
603 case '\'':
604 out << "&apos;";
605 break;
606 default:
607 if (c < 0x20 and c != '\n' and c != '\r' and c != '\t')
608 {
609 const char *hex = "0123456789ABCDEF";
610 out << "&#x";
611 out << hex[(c >> 4) & 0xF] << hex[c & 0xF] << ";";
612 }
613 else
614 out << static_cast<char>(c);
615 break;
616 }
617 return out.str();
618}
619
620template <class PtrT>
621std::string pointer_to_string(const PtrT ptr)
622{
623 std::ostringstream out;
624 out << ptr;
625 return out.str();
626}
627
628template <AlephGraph GT>
632{
633 using Node = typename GT::Node;
634
635 nodes.empty();
636 node_to_id.empty();
637
638 auto add_node = [&](Node *node)
639 {
640 if (node == nullptr or node_to_id.contains(node))
641 return;
642 const size_t id = nodes.size();
643 node_to_id.insert(node, id);
644 nodes.append(node);
645 };
646
647 for (auto it = result.certificate_branch_nodes.get_it(); it.has_curr(); it.next_ne())
648 add_node(it.get_curr_ne());
649
650 for (auto it = result.certificate_obstruction_edges.get_it(); it.has_curr(); it.next_ne())
651 {
652 add_node(it.get_curr_ne().src);
653 add_node(it.get_curr_ne().tgt);
654 }
655
656 for (auto pit = result.certificate_paths.get_it(); pit.has_curr(); pit.next_ne())
657 {
658 const auto &path = pit.get_curr_ne();
659 for (auto nit = path.nodes.get_it(); nit.has_curr(); nit.next_ne())
660 add_node(nit.get_curr_ne());
661
662 for (auto eit = path.edges.get_it(); eit.has_curr(); eit.next_ne())
663 {
664 add_node(eit.get_curr_ne().src);
665 add_node(eit.get_curr_ne().tgt);
666 }
667 }
668}
669
670inline double orient2d(const double ax,
671 const double ay,
672 const double bx,
673 const double by,
674 const double cx,
675 const double cy) noexcept
676{
677 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
678}
679
680inline bool bounding_boxes_intersect(const double ax,
681 const double ay,
682 const double bx,
683 const double by,
684 const double cx,
685 const double cy,
686 const double dx,
687 const double dy) noexcept
688{
689 const double min_ab_x = std::min(ax, bx);
690 const double max_ab_x = std::max(ax, bx);
691 const double min_ab_y = std::min(ay, by);
692 const double max_ab_y = std::max(ay, by);
693
694 const double min_cd_x = std::min(cx, dx);
695 const double max_cd_x = std::max(cx, dx);
696 const double min_cd_y = std::min(cy, dy);
697 const double max_cd_y = std::max(cy, dy);
698
699 return min_ab_x <= max_cd_x and min_cd_x <= max_ab_x and min_ab_y <= max_cd_y and
700 min_cd_y <= max_ab_y;
701}
702
703inline bool segments_properly_intersect(const double ax,
704 const double ay,
705 const double bx,
706 const double by,
707 const double cx,
708 const double cy,
709 const double dx,
710 const double dy) noexcept
711{
712 if (not bounding_boxes_intersect(ax, ay, bx, by, cx, cy, dx, dy))
713 return false;
714
715 constexpr double eps = 1e-12;
716 const double o1 = orient2d(ax, ay, bx, by, cx, cy);
717 const double o2 = orient2d(ax, ay, bx, by, dx, dy);
718 const double o3 = orient2d(cx, cy, dx, dy, ax, ay);
719 const double o4 = orient2d(cx, cy, dx, dy, bx, by);
720
721 // Strict intersection only (shared endpoints handled outside).
722 return (o1 * o2 < -eps) and (o3 * o4 < -eps);
723}
724
725template <AlephGraph GT, ArcFilter<GT> SA>
727{
728 using Node = typename GT::Node;
729 using Arc = typename GT::Arc;
730
731 const GT &g_;
732 SA sa_;
734
736
739
743
747
750
761
763
764 bool planar_ = true;
765
766 size_t add_oriented_edge(const size_t src, const size_t tgt)
767 {
768 const size_t id = oriented_src_.size();
771
772 side_.append(1);
773 lowpt_.append(0);
774 lowpt2_.append(0);
779
780 return id;
781 }
782
783 size_t other_endpoint(const size_t edge_id, const size_t x) const
784 {
785 const Simple_Edge &e = edges_[edge_id];
786 return e.u == x ? e.v : e.u;
787 }
788
790 {
791 for (size_t i = 1; i < a.size(); ++i)
792 {
793 const size_t key = a[i];
794 size_t j = i;
795 while (j > 0 and key < a[j - 1])
796 {
797 a[j] = a[j - 1];
798 --j;
799 }
800 a[j] = key;
801 }
802 }
803
804 static size_t factorial_bounded(const size_t n, const size_t cap)
805 {
806 if (n <= 1)
807 return 1;
808
809 if (cap == 0)
810 return 1;
811
812 size_t ret = 1;
813 for (size_t i = 2; i <= n; ++i)
814 {
815 if (ret > cap / i)
816 return cap + 1;
817 ret *= i;
818 }
819
820 return ret;
821 }
822
823 size_t count_components() const
824 {
825 if (result_.simplified_num_nodes == 0)
826 return 0;
827
828 Array<char> vis(result_.simplified_num_nodes, 0);
829 size_t comps = 0;
830
831 for (size_t s = 0; s < result_.simplified_num_nodes; ++s)
832 {
833 if (vis[s])
834 continue;
835
836 ++comps;
837 vis[s] = 1;
838
839 Array<size_t> stack;
840 stack.append(s);
841
842 while (not stack.is_empty())
843 {
844 const size_t v = stack.remove_last();
845
846 for (auto it = incident_edges_[v].get_it(); it.has_curr(); it.next_ne())
847 {
848 const size_t eid = it.get_curr_ne();
849 const size_t w = other_endpoint(eid, v);
850 if (vis[w])
851 continue;
852
853 vis[w] = 1;
854 stack.append(w);
855 }
856 }
857 }
858
859 return comps;
860 }
861
862 static size_t find_in_array(const Array<size_t> &a, const size_t value)
863 {
864 for (size_t i = 0; i < a.size(); ++i)
865 if (a[i] == value)
866 return i;
867
868 return Null_Edge;
869 }
870
872 const size_t pos,
873 const size_t first,
875 {
876 if (pos >= tail.size())
877 {
878 Array<size_t> order;
879 order.reserve(tail.size() + 1);
880 order.append(first);
881 for (unsigned long i : tail)
882 order.append(i);
883 out.append(std::move(order));
884 return;
885 }
886
887 for (size_t i = pos; i < tail.size(); ++i)
888 {
889 std::swap(tail[pos], tail[i]);
890 generate_permutations(tail, pos + 1, first, out);
891 std::swap(tail[pos], tail[i]);
892 }
893 }
894
896 const size_t isolated_vertices,
897 const size_t num_components,
898 Array<Array<size_t>> &face_idx,
899 size_t &global_faces,
900 const bool enforce_euler = true) const
901 {
902 Array<size_t> dart_src;
903 Array<size_t> alpha;
904 dart_src.reserve(2 * result_.simplified_num_edges);
905 alpha.reserve(2 * result_.simplified_num_edges);
906
908
909 for (auto it = edges_.get_it(); it.has_curr(); it.next_ne())
910 {
911 const Simple_Edge &e = it.get_curr_ne();
912 const size_t d1 = dart_src.size();
913
914 dart_src.append(e.u);
915 alpha.append(d1 + 1);
916 dart_id.insert(Dart_Key{e.u, e.v}, d1);
917
918 dart_src.append(e.v);
919 alpha.append(d1);
920 dart_id.insert(Dart_Key{e.v, e.u}, d1 + 1);
921 }
922
923 Array<size_t> sigma(dart_src.size(), Null_Edge);
924 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
925 {
926 const auto &ord = order[v];
927 if (ord.is_empty())
928 continue;
929
930 for (size_t i = 0; i < ord.size(); ++i)
931 {
932 const size_t to = ord[i];
933 const size_t next = ord[(i + 1) % ord.size()];
934
935 const size_t a = dart_id.find(Dart_Key{v, to});
936 const size_t b = dart_id.find(Dart_Key{v, next});
937 sigma[a] = b;
938 }
939 }
940
941 for (const unsigned long d : sigma)
942 if (d == Null_Edge)
943 return false;
944
945 face_idx.empty();
946
947 Array<char> vis(dart_src.size(), 0);
948 size_t local_faces = 0;
949 for (size_t d = 0; d < dart_src.size(); ++d)
950 {
951 if (vis[d])
952 continue;
953
954 ++local_faces;
956
957 size_t x = d;
958 while (not vis[x])
959 {
960 vis[x] = 1;
961 f.append(dart_src[x]);
962 x = sigma[alpha[x]];
963 }
964
965 face_idx.append(std::move(f));
966 }
967
968 global_faces = local_faces + isolated_vertices - (num_components == 0 ? 0 : (num_components - 1));
969
970 if (not enforce_euler or not options_.embedding_validate_with_euler)
971 return true;
972
973 const long long lhs = static_cast<long long>(result_.simplified_num_nodes) -
974 static_cast<long long>(result_.simplified_num_edges) + static_cast<long long>(global_faces);
975
976 const long long rhs = static_cast<long long>(num_components) + 1;
977
978 return lhs == rhs;
979 }
980
982 const Array<Array<size_t>> &face_idx,
983 const size_t global_faces,
984 const bool is_lr_linear)
985 {
986 result_.has_combinatorial_embedding = true;
987 result_.embedding_is_lr_linear = is_lr_linear;
988 result_.embedding_num_faces = global_faces;
989
990 result_.embedding_rotation.empty();
991 result_.embedding_rotation.reserve(result_.simplified_num_nodes);
992 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
993 {
995 re.node = nodes_[v];
996
997 const auto &ord = order[v];
998 re.cw_neighbors.reserve(ord.size());
999 for (auto it = ord.get_it(); it.has_curr(); it.next_ne())
1000 re.cw_neighbors.append(nodes_[it.get_curr_ne()]);
1001
1002 result_.embedding_rotation.append(std::move(re));
1003 }
1004
1005 result_.embedding_faces.empty();
1006 result_.embedding_faces.reserve(face_idx.size());
1007 for (auto fit = face_idx.get_it(); fit.has_curr(); fit.next_ne())
1008 {
1009 const auto &f = fit.get_curr_ne();
1010 Array<Node *> mapped;
1011 mapped.reserve(f.size());
1012 for (auto it = f.get_it(); it.has_curr(); it.next_ne())
1013 mapped.append(nodes_[it.get_curr_ne()]);
1014 result_.embedding_faces.append(std::move(mapped));
1015 }
1016
1017 while (result_.embedding_faces.size() < result_.embedding_num_faces)
1018 result_.embedding_faces.append(Array<Node *>());
1019 }
1020
1021 bool conflicting(const Interval &i, const size_t edge_id) const
1022 {
1023 if (interval_empty(i) or i.high == Null_Edge)
1024 return false;
1025 return lowpt_[i.high] > lowpt_[edge_id];
1026 }
1027
1028 long lowest(const Conflict_Pair &p) const
1029 {
1030 const bool left_empty = interval_empty(p.left);
1031 const bool right_empty = interval_empty(p.right);
1032
1033 if (left_empty and right_empty)
1034 return std::numeric_limits<long>::max();
1035 if (left_empty)
1036 return lowpt_[p.right.low];
1037 if (right_empty)
1038 return lowpt_[p.left.low];
1039
1040 return std::min(lowpt_[p.left.low], lowpt_[p.right.low]);
1041 }
1042
1043 // The work on the oriented edge e, from v, once the search of its target
1044 // is done, if it is a tree edge: its nesting depth, and the low points
1045 // of the edge from which v was reached
1046 [[gnu::always_inline]]
1047 void finish_oriented_edge(const size_t v, const size_t e)
1048 {
1049 nesting_depth_[e] = 2 * lowpt_[e] + (lowpt2_[e] < height_[v] ? 1 : 0);
1050
1051 if (parent_edge_[v] == Null_Edge)
1052 return;
1053
1054 const size_t pe = parent_edge_[v];
1055 if (lowpt_[e] < lowpt_[pe])
1056 {
1057 lowpt2_[pe] = std::min(lowpt_[pe], lowpt2_[e]);
1058 lowpt_[pe] = lowpt_[e];
1059 }
1060 else if (lowpt_[e] > lowpt_[pe])
1061 lowpt2_[pe] = std::min(lowpt2_[pe], lowpt_[e]);
1062 else
1063 lowpt2_[pe] = std::min(lowpt2_[pe], lowpt2_[e]);
1064 }
1065
1066 // The items of a, from the first to one past the last; a does not grow
1067 // while they are used
1068 static std::pair<const size_t *, const size_t *>
1069 range_of(const Array<size_t> &a) noexcept
1070 {
1071 if (a.is_empty())
1072 return {nullptr, nullptr};
1073
1074 const size_t *first = &a.base();
1075 return {first, first + a.size()};
1076 }
1077
1078 // A node whose incident edges the orientation goes through: the node,
1079 // the next of its edges to look at, one past the last, and the tree edge
1080 // whose target is being searched, or Null_Edge
1082 {
1083 size_t v;
1084 const size_t *next;
1085 const size_t *end;
1086 size_t waiting;
1087 };
1088
1089 Orient_Frame orient_frame_of(const size_t v) const noexcept
1090 {
1091 const auto [first, end] = range_of(incident_edges_[v]);
1092 return Orient_Frame{v, first, end, Null_Edge};
1093 }
1094
1095 // Orients the edges that root reaches, depth-first. A path can have as
1096 // many nodes as the graph, too many for recursion, so that the search
1097 // keeps its own stack; the order of the visits is that of a recursion.
1098 void orient_dfs(const size_t root)
1099 {
1100 if (not planar_)
1101 return;
1102
1104 frames.push(orient_frame_of(root));
1105 while (not frames.is_empty())
1106 {
1107 Orient_Frame &f = frames.top();
1108 const size_t v = f.v;
1109 if (f.waiting != Null_Edge) // its target was searched
1110 {
1112 f.waiting = Null_Edge;
1113 }
1114
1115 bool descends = false;
1116 while (f.next != f.end)
1117 {
1118 const size_t uedge = *f.next++;
1119 if (undirected_edge_seen_[uedge])
1120 continue;
1121
1122 undirected_edge_seen_[uedge] = 1;
1123 const size_t w = other_endpoint(uedge, v);
1124
1125 const size_t e = add_oriented_edge(v, w);
1126 undirected_to_oriented_[uedge] = e;
1127 child_edges_[v].append(e);
1128
1129 lowpt_[e] = height_[v];
1130 lowpt2_[e] = height_[v];
1131
1132 if (height_[w] == -1)
1133 {
1134 parent_edge_[w] = e;
1135 height_[w] = height_[v] + 1;
1136 f.waiting = e;
1137 frames.push(orient_frame_of(w)); // f may move
1138 descends = true;
1139 break;
1140 }
1141
1142 lowpt_[e] = height_[w];
1144 }
1145
1146 if (not descends)
1147 frames.pop();
1148 }
1149 }
1150
1151 // Sorts E stably by key. Timsort takes linear time on a sorted E, and
1152 // sorts the short ones by binary insertion
1153 template <class Key>
1154 static void sort_by(Array<size_t> &E, const Key &key)
1155 {
1156 timsort(E, [&key](const size_t x, const size_t y) { return key(x) < key(y); });
1157 }
1158
1159 // Sorts the child edges of v by their nesting depth, as the test of v
1160 // takes them
1161 void sort_child_edges(const size_t v)
1162 {
1164 }
1165
1166 // The work on the child edge ei of v, whose first child edge is first,
1167 // once the test of its target is done, if it is a tree edge, or once its
1168 // conflict pair is pushed, if it is a back edge; false if it finds that
1169 // the graph is not planar
1170 [[gnu::always_inline]]
1171 bool finish_child_edge(const size_t v, const size_t first, const size_t ei)
1172 {
1173 if (not planar_)
1174 return false;
1175
1176 if (lowpt_[ei] < height_[v])
1177 return merge_child_edge(v, first, ei);
1178
1179 return true;
1180 }
1181
1182 // The part of finish_child_edge() for a child edge ei of v that returns
1183 // above v: its conflicts with those of the former child edges
1184 [[gnu::noinline]]
1185 bool merge_child_edge(const size_t v, const size_t first, const size_t ei)
1186 {
1187 const size_t e = parent_edge_[v];
1188 if (ei == first)
1189 {
1190 if (e != Null_Edge)
1191 lowpt_edge_[e] = lowpt_edge_[first];
1192 }
1193 else
1194 {
1195 Conflict_Pair p;
1196 do
1197 {
1198 Conflict_Pair q = stack_.get_last();
1199 (void) stack_.remove_last();
1200
1201 if (not interval_empty(q.left))
1202 std::swap(q.left, q.right);
1203
1204 if (not interval_empty(q.left))
1205 {
1206 planar_ = false;
1207 return false;
1208 }
1209
1210 if (lowpt_[q.right.low] > lowpt_[e])
1211 {
1212 if (interval_empty(p.right))
1213 p.right.high = q.right.high;
1214 else
1215 ref_[p.right.low] = q.right.high;
1216
1217 p.right.low = q.right.low;
1218 }
1219 else
1220 {
1221 ref_[q.right.low] = lowpt_edge_[e];
1222 }
1223 } while (not(stack_.get_last() == stack_bottom_[ei]));
1224
1225 while (conflicting(stack_.get_last().left, ei) or
1226 conflicting(stack_.get_last().right, ei))
1227 {
1228 Conflict_Pair q = stack_.get_last();
1229 (void) stack_.remove_last();
1230
1231 if (conflicting(q.right, ei))
1232 std::swap(q.left, q.right);
1233
1234 if (conflicting(q.right, ei))
1235 {
1236 planar_ = false;
1237 return false;
1238 }
1239
1240 if (p.right.low != Null_Edge)
1241 ref_[p.right.low] = q.right.high;
1242
1243 if (not interval_empty(q.right))
1244 p.right.low = q.right.low;
1245
1246 if (interval_empty(p.left))
1247 p.left.high = q.left.high;
1248 else
1249 ref_[p.left.low] = q.left.high;
1250
1251 p.left.low = q.left.low;
1252 }
1253
1254 if (not pair_empty(p))
1255 stack_.append(p);
1256 }
1257
1258 return true;
1259 }
1260
1261 // The work on v once its child edges are done: the back edges that
1262 // return to the parent of v leave the stack
1263 void finish_test(const size_t v)
1264 {
1265 const size_t e = parent_edge_[v];
1266 if (e == Null_Edge)
1267 return;
1268
1269 const size_t u = oriented_src_[e];
1270 while (stack_.size() > 1 and lowest(stack_.get_last()) == height_[u])
1271 {
1272 Conflict_Pair p = stack_.remove_last();
1273 if (not interval_empty(p.left))
1274 side_[p.left.low] = -1;
1275 }
1276
1277 if (stack_.size() > 1)
1278 {
1279 Conflict_Pair p = stack_.remove_last();
1280
1281 while (p.left.high != Null_Edge and oriented_tgt_[p.left.high] == u)
1282 p.left.high = ref_[p.left.high];
1283
1284 if (p.left.high == Null_Edge and p.left.low != Null_Edge)
1285 {
1286 ref_[p.left.low] = p.right.low;
1287 side_[p.left.low] = -1;
1288 p.left.low = Null_Edge;
1289 }
1290
1291 while (p.right.high != Null_Edge and oriented_tgt_[p.right.high] == u)
1292 p.right.high = ref_[p.right.high];
1293
1294 if (p.right.high == Null_Edge and p.right.low != Null_Edge)
1295 {
1296 ref_[p.right.low] = p.left.low;
1297 side_[p.right.low] = -1;
1298 p.right.low = Null_Edge;
1299 }
1300
1301 stack_.append(p);
1302 }
1303
1304 if (lowpt_[e] < height_[u])
1305 {
1306 const Conflict_Pair &top = stack_.get_last();
1307 const size_t h_left = top.left.high;
1308 const size_t h_right = top.right.high;
1309
1310 if (h_left != Null_Edge and (h_right == Null_Edge or lowpt_[h_left] > lowpt_[h_right]))
1311 ref_[e] = h_left;
1312 else
1313 ref_[e] = h_right;
1314 }
1315 }
1316
1317 // A node whose child edges the test goes through, sorted: the node, the
1318 // first of them, the next one and one past the last
1320 {
1321 size_t v;
1322 const size_t *first;
1323 const size_t *next;
1324 const size_t *end;
1325 };
1326
1327 // The frame of v, whose child edges it sorts first
1329 {
1331 const auto [first, end] = range_of(child_edges_[v]);
1332 return Test_Frame{v, first, first, end};
1333 }
1334
1335 // The LR test of the edges that root reaches. A path can have as many
1336 // nodes as the graph, too many for recursion, so that the test keeps
1337 // its own stack; the order of its steps is that of a recursion.
1338 void test_dfs(const size_t root)
1339 {
1340 if (not planar_)
1341 return;
1342
1343 Dfs_Stack<Test_Frame> frames;
1344 frames.push(test_frame_of(root));
1345 while (true)
1346 {
1347 Test_Frame &f = frames.top();
1348 const size_t v = f.v;
1349 if (f.next != f.end)
1350 {
1351 const size_t ei = *f.next;
1352 stack_bottom_[ei] = stack_.get_last();
1353
1354 const size_t w = oriented_tgt_[ei];
1355 if (ei == parent_edge_[w])
1356 { // the test of w goes first; then that of ei
1357 frames.push(test_frame_of(w)); // f may move
1358 continue;
1359 }
1360
1361 lowpt_edge_[ei] = ei;
1362 Conflict_Pair cp;
1363 cp.right.low = ei;
1364 cp.right.high = ei;
1365 stack_.append(cp);
1366
1367 if (not finish_child_edge(v, *f.first, ei))
1368 return;
1369 ++f.next;
1370 continue;
1371 }
1372
1373 finish_test(v);
1374 frames.pop();
1375 if (frames.is_empty())
1376 return;
1377
1378 Test_Frame &p = frames.top(); // the test of the edge to v goes on
1379 if (not finish_child_edge(p.v, *p.first, *p.next))
1380 return;
1381 ++p.next;
1382 }
1383 }
1384
1386 {
1387 if (result_.simplified_num_edges == 0)
1388 return false;
1389
1390 Array<long> comp_id(result_.simplified_num_nodes, -1);
1391 size_t next_comp = 0;
1392
1393 for (size_t s = 0; s < result_.simplified_num_nodes; ++s)
1394 {
1395 if (comp_id[s] != -1)
1396 continue;
1397
1398 Array<size_t> stack;
1399 stack.append(s);
1400 comp_id[s] = static_cast<long>(next_comp);
1401
1402 size_t num_vertices = 0;
1403 size_t degree_sum = 0;
1404
1405 while (not stack.is_empty())
1406 {
1407 const size_t v = stack.remove_last();
1408 ++num_vertices;
1409 degree_sum += incident_edges_[v].size();
1410
1411 for (auto it = incident_edges_[v].get_it(); it.has_curr(); it.next_ne())
1412 {
1413 const size_t uedge = it.get_curr_ne();
1414 const size_t w = other_endpoint(uedge, v);
1415 if (comp_id[w] != -1)
1416 continue;
1417
1418 comp_id[w] = static_cast<long>(next_comp);
1419 stack.append(w);
1420 }
1421 }
1422
1423 const size_t num_edges = degree_sum / 2;
1424 if (num_vertices >= 3 and num_edges > 3 * num_vertices - 6)
1425 return true;
1426
1427 ++next_comp;
1428 }
1429
1430 return false;
1431 }
1432
1434 {
1435 result_.num_nodes = g_.get_num_nodes();
1436 result_.input_is_digraph = g_.is_digraph();
1437
1438 nodes_.reserve(result_.num_nodes);
1439 for (Node_Iterator<GT> it(g_); it.has_curr(); it.next_ne())
1440 {
1441 Node *node = it.get_curr_ne();
1442 node_to_idx_.insert(node, nodes_.size());
1443 nodes_.append(node);
1444 }
1445
1446 incident_edges_.reserve(result_.num_nodes);
1447 child_edges_.reserve(result_.num_nodes);
1448 for (size_t i = 0; i < result_.num_nodes; ++i)
1449 {
1451 child_edges_.append(Array<size_t>());
1452 }
1453
1454 DynSetTree<Edge_Key> seen_edges;
1455 DynMapTree<Edge_Key, size_t> edge_to_idx;
1456
1457 for (Arc_Iterator<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
1458 {
1459 ++result_.num_input_arcs;
1460 Arc *arc = it.get_curr_ne();
1461 const size_t src = node_to_idx_.find(g_.get_src_node(arc));
1462 const size_t tgt = node_to_idx_.find(g_.get_tgt_node(arc));
1463
1464 if (src == tgt)
1465 {
1466 ++result_.ignored_loops;
1467 continue;
1468 }
1469
1470 const size_t u = std::min(src, tgt);
1471 const size_t v = std::max(src, tgt);
1472 const Edge_Key key{u, v};
1473
1474 if (seen_edges.contains(key))
1475 {
1476 ++result_.ignored_parallel_arcs;
1477 const size_t eid = edge_to_idx.find(key);
1478 simplified_edge_input_arcs_[eid].append(arc);
1479 continue;
1480 }
1481
1482 seen_edges.insert(key);
1483 const size_t eid = edges_.size();
1484 edge_to_idx.insert(key, eid);
1485
1486 edges_.append(Simple_Edge{u, v});
1487 incident_edges_[u].append(eid);
1488 incident_edges_[v].append(eid);
1490 simplified_edge_input_arcs_[eid].append(arc);
1491 }
1492
1493 result_.simplified_num_nodes = result_.num_nodes;
1494 result_.simplified_num_edges = edges_.size();
1495 }
1496
1498 {
1499 if (result_.simplified_num_edges == 0)
1500 return true;
1501
1502 height_ = Array<long>(result_.simplified_num_nodes, -1);
1503 parent_edge_ = Array<size_t>(result_.simplified_num_nodes, Null_Edge);
1504 undirected_edge_seen_ = Array<char>(result_.simplified_num_edges, 0);
1505 undirected_to_oriented_ = Array<size_t>(result_.simplified_num_edges, Null_Edge);
1506
1507 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
1508 {
1509 if (height_[v] != -1)
1510 continue;
1511
1512 roots_.append(v);
1513 height_[v] = 0;
1514 orient_dfs(v);
1515 }
1516
1517 for (auto it = roots_.get_it(); it.has_curr(); it.next_ne())
1518 {
1519 const size_t root = it.get_curr_ne();
1520 stack_.empty();
1521 stack_.append(Conflict_Pair());
1522 test_dfs(root);
1523 if (not planar_)
1524 return false;
1525 }
1526
1527 return true;
1528 }
1529
1530 bool simple_edges_are_planar(const Array<Simple_Edge> &simple_edges) const
1531 {
1533
1534 Tmp_Graph tg;
1535 Array<typename Tmp_Graph::Node *> tmp_nodes(result_.simplified_num_nodes,
1536 static_cast<typename Tmp_Graph::Node *>(nullptr));
1537
1538 for (size_t i = 0; i < result_.simplified_num_nodes; ++i)
1539 tmp_nodes[i] = tg.insert_node(i);
1540
1541 for (auto it = simple_edges.get_it(); it.has_curr(); it.next_ne())
1542 {
1543 const Simple_Edge &e = it.get_curr_ne();
1544 tg.insert_arc(tmp_nodes[e.u], tmp_nodes[e.v], 1);
1545 }
1546
1547 Planarity_Test_Options fast_options;
1548 fast_options.compute_embedding = false;
1549 fast_options.compute_nonplanar_certificate = false;
1550 fast_options.embedding_max_combinations = 0;
1551 fast_options.certificate_max_edges = 0;
1552 fast_options.certificate_max_reduction_passes = 0;
1553
1555 fast_options);
1556
1557 return checker.run().is_planar;
1558 }
1559
1560 static bool classify_k5(const Array<size_t> &branches, const Array<Compressed_Path> &paths)
1561 {
1562 if (branches.size() != 5 or paths.size() != 10)
1563 return false;
1564
1565 Array<Array<char>> mat;
1566 mat.reserve(5);
1567 for (size_t i = 0; i < 5; ++i)
1568 mat.append(Array<char>(static_cast<size_t>(5), static_cast<char>(0)));
1569
1570 Array<size_t> deg(static_cast<size_t>(5), static_cast<size_t>(0));
1571
1572 for (auto it = paths.get_it(); it.has_curr(); it.next_ne())
1573 {
1574 const Compressed_Path &p = it.get_curr_ne();
1575 const size_t iu = find_in_array(branches, p.u);
1576 const size_t iv = find_in_array(branches, p.v);
1577 if (iu == Null_Edge or iv == Null_Edge or iu == iv)
1578 return false;
1579
1580 if (mat[iu][iv])
1581 return false;
1582
1583 mat[iu][iv] = 1;
1584 mat[iv][iu] = 1;
1585 ++deg[iu];
1586 ++deg[iv];
1587 }
1588
1589 for (size_t i = 0; i < 5; ++i)
1590 {
1591 if (deg[i] != 4)
1592 return false;
1593
1594 for (size_t j = i + 1; j < 5; ++j)
1595 if (not mat[i][j])
1596 return false;
1597 }
1598
1599 return true;
1600 }
1601
1602 static bool classify_k33(const Array<size_t> &branches, const Array<Compressed_Path> &paths)
1603 {
1604 if (branches.size() != 6 or paths.size() != 9)
1605 return false;
1606
1607 Array<Array<char>> mat;
1608 mat.reserve(6);
1609 for (size_t i = 0; i < 6; ++i)
1610 mat.append(Array<char>(static_cast<size_t>(6), static_cast<char>(0)));
1611
1613 adj.reserve(6);
1614 for (size_t i = 0; i < 6; ++i)
1615 adj.append(Array<size_t>());
1616
1617 Array<size_t> deg(static_cast<size_t>(6), static_cast<size_t>(0));
1618
1619 for (auto it = paths.get_it(); it.has_curr(); it.next_ne())
1620 {
1621 const Compressed_Path &p = it.get_curr_ne();
1622 const size_t iu = find_in_array(branches, p.u);
1623 const size_t iv = find_in_array(branches, p.v);
1624 if (iu == Null_Edge or iv == Null_Edge or iu == iv)
1625 return false;
1626
1627 if (mat[iu][iv])
1628 return false;
1629
1630 mat[iu][iv] = 1;
1631 mat[iv][iu] = 1;
1632 adj[iu].append(iv);
1633 adj[iv].append(iu);
1634 ++deg[iu];
1635 ++deg[iv];
1636 }
1637
1638 for (size_t i = 0; i < 6; ++i)
1639 if (deg[i] != 3)
1640 return false;
1641
1642 Array<long> color(static_cast<size_t>(6), static_cast<long>(-1));
1643 for (size_t s = 0; s < 6; ++s)
1644 {
1645 if (color[s] != -1)
1646 continue;
1647
1648 color[s] = 0;
1649 Array<size_t> stack;
1650 stack.append(s);
1651
1652 while (not stack.is_empty())
1653 {
1654 const size_t u = stack.remove_last();
1655 for (auto it = adj[u].get_it(); it.has_curr(); it.next_ne())
1656 {
1657 const size_t v = it.get_curr_ne();
1658 if (color[v] == -1)
1659 {
1660 color[v] = 1 - color[u];
1661 stack.append(v);
1662 }
1663 else if (color[v] == color[u])
1664 return false;
1665 }
1666 }
1667 }
1668
1669 size_t left_count = 0;
1670 size_t right_count = 0;
1671 for (size_t i = 0; i < 6; ++i)
1672 if (color[i] == 0)
1673 ++left_count;
1674 else
1675 ++right_count;
1676
1677 if (left_count != 3 or right_count != 3)
1678 return false;
1679
1680 for (size_t i = 0; i < 6; ++i)
1681 for (size_t j = i + 1; j < 6; ++j)
1682 {
1683 if (color[i] == color[j] and mat[i][j])
1684 return false;
1685
1686 if (color[i] != color[j] and not mat[i][j])
1687 return false;
1688 }
1689
1690 return true;
1691 }
1692
1693 size_t find_simplified_edge_id(const size_t u, const size_t v) const
1694 {
1695 const size_t a = std::min(u, v);
1696 const size_t b = std::max(u, v);
1697
1698 for (size_t i = 0; i < edges_.size(); ++i)
1699 if (edges_[i].u == a and edges_[i].v == b)
1700 return i;
1701
1702 return Null_Edge;
1703 }
1704
1706 const size_t v) const
1707 {
1709 if (u < nodes_.size())
1710 w.src = nodes_[u];
1711 if (v < nodes_.size())
1712 w.tgt = nodes_[v];
1713
1714 const size_t eid = find_simplified_edge_id(u, v);
1715 if (eid == Null_Edge or eid >= simplified_edge_input_arcs_.size())
1716 return w;
1717
1718 const auto &arcs = simplified_edge_input_arcs_[eid];
1719 if (not arcs.is_empty())
1720 w.representative_input_arc = arcs[0];
1721
1722 w.input_arcs.reserve(arcs.size());
1723 for (auto it = arcs.get_it(); it.has_curr(); it.next_ne())
1724 w.input_arcs.append(it.get_curr_ne());
1725
1726 return w;
1727 }
1728
1730 {
1731 result_.certificate_branch_nodes.empty();
1732 result_.certificate_paths.empty();
1733
1734 result_.certificate_branch_nodes.reserve(branches.size());
1735 for (auto it = branches.get_it(); it.has_curr(); it.next_ne())
1736 result_.certificate_branch_nodes.append(nodes_[it.get_curr_ne()]);
1737
1738 result_.certificate_paths.reserve(paths.size());
1739 for (auto it = paths.get_it(); it.has_curr(); it.next_ne())
1740 {
1741 const Compressed_Path &p = it.get_curr_ne();
1743 witness.nodes.reserve(p.nodes.size());
1744 for (auto pit = p.nodes.get_it(); pit.has_curr(); pit.next_ne())
1745 witness.nodes.append(nodes_[pit.get_curr_ne()]);
1746
1747 if (p.nodes.size() >= 2)
1748 {
1749 witness.edges.reserve(p.nodes.size() - 1);
1750 for (size_t i = 1; i < p.nodes.size(); ++i)
1751 witness.edges.append(make_edge_witness(p.nodes[i - 1], p.nodes[i]));
1752 }
1753
1754 result_.certificate_paths.append(std::move(witness));
1755 }
1756 }
1757
1759 {
1760 if (result_.is_planar)
1761 return;
1762
1763 if (edges_.is_empty())
1764 return;
1765
1767 {
1768 result_.certificate_search_truncated = true;
1769 return;
1770 }
1771
1772 Array<Simple_Edge> witness = edges_;
1773
1775 result_.certificate_search_truncated = true;
1776 else
1777 {
1778 size_t pass_count = 0;
1779
1780 while (true)
1781 {
1782 bool changed = false;
1783 size_t i = 0;
1784
1785 while (i < witness.size())
1786 {
1787 Array<Simple_Edge> trial;
1788 trial.reserve(witness.size() - 1);
1789 for (size_t j = 0; j < witness.size(); ++j)
1790 if (j != i)
1791 trial.append(witness[j]);
1792
1793 if (simple_edges_are_planar(trial))
1794 ++i;
1795 else
1796 {
1797 witness = std::move(trial);
1798 changed = true;
1799 }
1800 }
1801
1802 Array<size_t> degree(result_.simplified_num_nodes, static_cast<size_t>(0));
1803 for (auto it = witness.get_it(); it.has_curr(); it.next_ne())
1804 {
1805 const auto &e = it.get_curr_ne();
1806 ++degree[e.u];
1807 ++degree[e.v];
1808 }
1809
1810 size_t v = 0;
1811 while (v < result_.simplified_num_nodes)
1812 {
1813 if (degree[v] == 0)
1814 {
1815 ++v;
1816 continue;
1817 }
1818
1819 Array<Simple_Edge> trial;
1820 trial.reserve(witness.size());
1821 for (auto it = witness.get_it(); it.has_curr(); it.next_ne())
1822 {
1823 const auto &e = it.get_curr_ne();
1824 if (e.u == v or e.v == v)
1825 continue;
1826 trial.append(e);
1827 }
1828
1829 if (trial.size() == witness.size())
1830 {
1831 ++v;
1832 continue;
1833 }
1834
1835 if (simple_edges_are_planar(trial))
1836 ++v;
1837 else
1838 {
1839 witness = std::move(trial);
1840 changed = true;
1841
1842 degree = Array<size_t>(result_.simplified_num_nodes, static_cast<size_t>(0));
1843 for (auto wit = witness.get_it(); wit.has_curr(); wit.next_ne())
1844 {
1845 const auto &e = wit.get_curr_ne();
1846 ++degree[e.u];
1847 ++degree[e.v];
1848 }
1849 v = 0;
1850 }
1851 }
1852
1853 if (not changed)
1854 break;
1855
1856 ++pass_count;
1858 {
1859 result_.certificate_search_truncated = true;
1860 break;
1861 }
1862 }
1863 }
1864
1865 result_.has_nonplanar_certificate = true;
1867
1868 result_.certificate_obstruction_edges.empty();
1869 result_.certificate_obstruction_edges.reserve(witness.size());
1870 for (auto it = witness.get_it(); it.has_curr(); it.next_ne())
1871 {
1872 const Simple_Edge &e = it.get_curr_ne();
1873 result_.certificate_obstruction_edges.append(make_edge_witness(e.u, e.v));
1874 }
1875
1876 Array<size_t> degree(result_.simplified_num_nodes, static_cast<size_t>(0));
1878 inc.reserve(result_.simplified_num_nodes);
1879 for (size_t i = 0; i < result_.simplified_num_nodes; ++i)
1880 inc.append(Array<size_t>());
1881
1882 for (size_t i = 0; i < witness.size(); ++i)
1883 {
1884 const auto &e = witness[i];
1885 ++degree[e.u];
1886 ++degree[e.v];
1887 inc[e.u].append(i);
1888 inc[e.v].append(i);
1889 }
1890
1891 Array<size_t> branches;
1892 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
1893 if (degree[v] > 0 and degree[v] != 2)
1894 branches.append(v);
1895
1896 if (branches.size() < 5)
1897 return;
1898
1900 {
1901 result_.certificate_search_truncated = true;
1902 return;
1903 }
1904
1905 Array<char> is_branch(result_.simplified_num_nodes, static_cast<char>(0));
1906 for (auto it = branches.get_it(); it.has_curr(); it.next_ne())
1907 is_branch[it.get_curr_ne()] = 1;
1908
1909 Array<char> used(witness.size(), static_cast<char>(0));
1911
1912 for (auto bit = branches.get_it(); bit.has_curr(); bit.next_ne())
1913 {
1914 const size_t b = bit.get_curr_ne();
1915
1916 for (auto eit = inc[b].get_it(); eit.has_curr(); eit.next_ne())
1917 {
1918 const size_t first_edge = eit.get_curr_ne();
1919 if (used[first_edge])
1920 continue;
1921
1922 used[first_edge] = 1;
1923
1925 p.u = b;
1926 p.nodes.append(b);
1927
1928 size_t curr = witness[first_edge].u == b ? witness[first_edge].v : witness[first_edge].u;
1929 size_t prev_edge = first_edge;
1930 size_t guard = 0;
1931
1932 while (curr < result_.simplified_num_nodes and not is_branch[curr])
1933 {
1934 p.nodes.append(curr);
1935
1936 if (inc[curr].size() != 2)
1937 break;
1938
1939 const size_t e0 = inc[curr][0];
1940 const size_t e1 = inc[curr][1];
1941 const size_t next_edge = e0 == prev_edge ? e1 : e0;
1942
1943 if (used[next_edge])
1944 break;
1945
1946 used[next_edge] = 1;
1947 prev_edge = next_edge;
1948
1949 const auto &ne = witness[next_edge];
1950 curr = ne.u == curr ? ne.v : ne.u;
1951
1952 ++guard;
1953 if (guard > witness.size())
1954 break;
1955 }
1956
1957 p.v = curr;
1958 if (p.nodes.is_empty() or p.nodes.get_last() != curr)
1959 p.nodes.append(curr);
1960
1961 if (p.u != p.v and p.v < result_.simplified_num_nodes and is_branch[p.v] and
1962 p.nodes.size() >= 2)
1963 paths.append(std::move(p));
1964 }
1965 }
1966
1967 if (paths.is_empty())
1968 return;
1969
1970 const size_t bcount = branches.size();
1971 Array<Array<long>> first_path;
1972 first_path.reserve(bcount);
1973 for (size_t i = 0; i < bcount; ++i)
1974 first_path.append(Array<long>(bcount, static_cast<long>(-1)));
1975
1976 for (size_t i = 0; i < paths.size(); ++i)
1977 {
1978 const Compressed_Path &p = paths[i];
1979 const size_t iu = find_in_array(branches, p.u);
1980 const size_t iv = find_in_array(branches, p.v);
1981 if (iu == Null_Edge or iv == Null_Edge or iu == iv)
1982 continue;
1983
1984 if (first_path[iu][iv] == -1)
1985 {
1986 first_path[iu][iv] = static_cast<long>(i);
1987 first_path[iv][iu] = static_cast<long>(i);
1988 }
1989 }
1990
1991 auto has_pair = [&](const size_t a, const size_t b) -> bool
1992 {
1993 return first_path[a][b] != -1;
1994 };
1995
1996 if (bcount >= 5)
1997 {
1998 for (size_t a = 0; a < bcount; ++a)
1999 for (size_t b = a + 1; b < bcount; ++b)
2000 for (size_t c = b + 1; c < bcount; ++c)
2001 for (size_t d = c + 1; d < bcount; ++d)
2002 for (size_t e = d + 1; e < bcount; ++e)
2003 {
2004 const size_t idx[5] = {a, b, c, d, e};
2005 bool ok = true;
2006 for (size_t i = 0; i < 5 and ok; ++i)
2007 for (size_t j = i + 1; j < 5; ++j)
2008 if (not has_pair(idx[i], idx[j]))
2009 ok = false;
2010
2011 if (not ok)
2012 continue;
2013
2014 Array<size_t> chosen_branches;
2015 chosen_branches.reserve(5);
2016 for (unsigned long i : idx)
2017 chosen_branches.append(branches[i]);
2018
2019 Array<Compressed_Path> chosen_paths;
2020 chosen_paths.reserve(10);
2021 for (size_t i = 0; i < 5; ++i)
2022 for (size_t j = i + 1; j < 5; ++j)
2023 chosen_paths.append(paths[static_cast<size_t>(first_path[idx[i]][idx[j]])]);
2024
2025 if (not classify_k5(chosen_branches, chosen_paths))
2026 continue;
2027
2029 fill_certificate_paths(chosen_branches, chosen_paths);
2030 return;
2031 }
2032 }
2033
2034 if (bcount >= 6)
2035 {
2036 for (size_t a = 0; a < bcount; ++a)
2037 for (size_t b = a + 1; b < bcount; ++b)
2038 for (size_t c = b + 1; c < bcount; ++c)
2039 for (size_t d = c + 1; d < bcount; ++d)
2040 for (size_t e = d + 1; e < bcount; ++e)
2041 for (size_t f = e + 1; f < bcount; ++f)
2042 {
2043 const size_t six[6] = {a, b, c, d, e, f};
2044
2045 const int partitions[10][3] = {{0, 1, 2}, {0, 1, 3}, {0, 1, 4}, {0, 1, 5},
2046 {0, 2, 3}, {0, 2, 4}, {0, 2, 5}, {0, 3, 4},
2047 {0, 3, 5}, {0, 4, 5}};
2048
2049 for (const auto &part : partitions)
2050 {
2051 Array<char> in_left(6, static_cast<char>(0));
2052 in_left[static_cast<size_t>(part[0])] = 1;
2053 in_left[static_cast<size_t>(part[1])] = 1;
2054 in_left[static_cast<size_t>(part[2])] = 1;
2055
2056 size_t left[3];
2057 size_t right[3];
2058 size_t li = 0;
2059 size_t ri = 0;
2060 for (size_t i = 0; i < 6; ++i)
2061 if (in_left[i])
2062 left[li++] = six[i];
2063 else
2064 right[ri++] = six[i];
2065
2066 bool ok = true;
2067 for (size_t i = 0; i < 3 and ok; ++i)
2068 for (size_t j : right)
2069 if (not has_pair(left[i], j))
2070 ok = false;
2071
2072 if (not ok)
2073 continue;
2074
2075 Array<size_t> chosen_branches;
2076 chosen_branches.reserve(6);
2077 for (unsigned long i : left)
2078 chosen_branches.append(branches[i]);
2079 for (unsigned long i : right)
2080 chosen_branches.append(branches[i]);
2081
2082 Array<Compressed_Path> chosen_paths;
2083 chosen_paths.reserve(9);
2084 for (unsigned long i : left)
2085 for (unsigned long j : right)
2086 chosen_paths.append(paths[static_cast<size_t>(first_path[i][j])]);
2087
2088 if (not classify_k33(chosen_branches, chosen_paths))
2089 continue;
2090
2092 fill_certificate_paths(chosen_branches, chosen_paths);
2093 return;
2094 }
2095 }
2096 }
2097 }
2098
2100 {
2101 if (result_.simplified_num_nodes == 0)
2102 {
2103 result_.has_combinatorial_embedding = true;
2104 result_.embedding_is_lr_linear = true;
2105 result_.embedding_num_faces = 0;
2106 return true;
2107 }
2108
2109 Array<Array<size_t>> order;
2110 order.reserve(result_.simplified_num_nodes);
2111 for (size_t i = 0; i < result_.simplified_num_nodes; ++i)
2112 order.append(Array<size_t>());
2113
2114 if (result_.simplified_num_edges == 0)
2115 {
2116 Array<Array<size_t>> faces;
2117 size_t global_faces = 0;
2118 if (not compute_faces_from_rotation(order, result_.simplified_num_nodes,
2119 result_.simplified_num_nodes, faces, global_faces))
2120 return false;
2121
2122 fill_embedding_result(order, faces, global_faces, true);
2123 return true;
2124 }
2125
2126 if (undirected_to_oriented_.size() != result_.simplified_num_edges)
2127 return false;
2128
2129 for (unsigned long ue : undirected_to_oriented_)
2130 if (ue == Null_Edge)
2131 return false;
2132
2133 Array<long> final_side = side_;
2134 Array<char> vis(oriented_src_.size(), static_cast<char>(0));
2135
2136 // The sign of e is its side times the sign of the edge that it refers
2137 // to. A chain of references can be as long as the edges, too long for
2138 // recursion: it is followed first, and then the signs are taken back
2139 // along it, in the order of a recursion
2141 auto sign_of = [&](const size_t e) -> long
2142 {
2143 for (size_t x = e; vis[x] == 0; x = ref_[x])
2144 {
2145 vis[x] = 1;
2146 chain.append(x);
2147 if (ref_[x] == Null_Edge)
2148 break;
2149 }
2150
2151 while (not chain.is_empty())
2152 {
2153 const size_t y = chain.remove_last();
2154 if (ref_[y] != Null_Edge)
2155 final_side[y] *= final_side[ref_[y]];
2156 vis[y] = 2;
2157 }
2158
2159 return final_side[e];
2160 };
2161
2162 Array<long> signed_depth(oriented_src_.size(), 0);
2163 for (size_t e = 0; e < oriented_src_.size(); ++e)
2164 {
2165 const long s = sign_of(e);
2166 signed_depth[e] = s < 0 ? -nesting_depth_[e] : nesting_depth_[e];
2167 }
2168
2169 // The embedding phase of the LR algorithm (Brandes, "The Left-Right
2170 // Planarity Test", 2009). The edges that leave a node in the
2171 // orientation go around it in the order of their signed nesting
2172 // depths; then a third depth-first search puts each edge that comes
2173 // into a node next to the reference of its side there. The rotation
2174 // of a node is a circular list of half edges: 2 e at the source of the
2175 // oriented edge e, and 2 e + 1 at its target.
2176 const size_t num_nodes = result_.simplified_num_nodes;
2177 const size_t num_halves = 2 * oriented_src_.size();
2178 Array<size_t> cw(num_halves, Null_Edge); // the next half edge around
2179 Array<size_t> ccw(num_halves, Null_Edge); // the former one
2182 Array<size_t> right_ref(num_nodes, Null_Edge);
2183
2184 // Puts h after ref around v, or alone if ref is Null_Edge
2185 auto put_after = [&](const size_t v, const size_t h, const size_t ref)
2186 {
2187 if (ref == Null_Edge)
2188 {
2189 cw[h] = ccw[h] = h;
2190 first[v] = h;
2191 return;
2192 }
2193
2194 const size_t next = cw[ref];
2195 cw[ref] = h;
2196 ccw[h] = ref;
2197 cw[h] = next;
2198 ccw[next] = h;
2199 };
2200
2201 // Puts h before ref around v; h is the first if ref was
2202 auto put_before = [&](const size_t v, const size_t h, const size_t ref)
2203 {
2204 if (ref == Null_Edge)
2205 {
2206 put_after(v, h, ref);
2207 return;
2208 }
2209
2210 put_after(v, h, ccw[ref]);
2211 if (ref == first[v])
2212 first[v] = h;
2213 };
2214
2215 // the test is done: the edges that leave each node can be sorted again
2216 for (size_t v = 0; v < num_nodes; ++v)
2217 {
2218 auto &E = child_edges_[v];
2219 sort_by(E, signed_depth);
2220
2221 size_t prev = Null_Edge;
2222 for (size_t i = 0; i < E.size(); ++i)
2223 {
2224 put_after(v, 2 * E[i], prev);
2225 prev = 2 * E[i];
2226 }
2227 }
2228
2229 // A node whose edges the third search goes through: the node, the next
2230 // of the edges that leave it, and one past the last
2231 struct Embed_Frame
2232 {
2233 size_t v;
2234 const size_t *next;
2235 const size_t *end;
2236 };
2237
2238 // A path can have as many nodes as the graph, too many for recursion,
2239 // so that the search keeps its own stack; the order of its steps is
2240 // that of a recursion
2242 for (auto rit = roots_.get_it(); rit.has_curr(); rit.next_ne())
2243 {
2244 const size_t root = rit.get_curr_ne();
2245 const auto [root_first, root_end] = range_of(child_edges_[root]);
2246 frames.push(Embed_Frame{root, root_first, root_end});
2247 while (not frames.is_empty())
2248 {
2249 Embed_Frame &f = frames.top();
2250 if (f.next == f.end)
2251 {
2252 frames.pop();
2253 continue;
2254 }
2255
2256 const size_t v = f.v;
2257 const size_t e = *f.next++;
2258 const size_t w = oriented_tgt_[e];
2259 if (e == parent_edge_[w]) // a tree edge: v goes first around w
2260 {
2261 put_before(w, 2 * e + 1, first[w]);
2262 left_ref[v] = right_ref[v] = 2 * e;
2263 const auto [w_first, w_end] = range_of(child_edges_[w]);
2264 frames.push(Embed_Frame{w, w_first, w_end}); // f may move
2265 }
2266 else if (final_side[e] > 0) // a back edge, on the right
2267 put_after(w, 2 * e + 1, right_ref[w]);
2268 else // on the left
2269 {
2270 put_before(w, 2 * e + 1, left_ref[w]);
2271 left_ref[w] = 2 * e + 1;
2272 }
2273 }
2274 }
2275
2276 size_t isolated_vertices = 0;
2277 for (size_t v = 0; v < num_nodes; ++v)
2278 {
2279 if (first[v] == Null_Edge)
2280 {
2281 ++isolated_vertices;
2282 continue;
2283 }
2284
2285 auto &ord = order[v];
2286 ord.reserve(incident_edges_[v].size());
2287 size_t h = first[v];
2288 do
2289 {
2290 const size_t e = h / 2;
2291 ord.append(h % 2 == 0 ? oriented_tgt_[e] : oriented_src_[e]);
2292 h = cw[h];
2293 }
2294 while (h != first[v]);
2295 }
2296
2297 const size_t num_components = count_components();
2298 {
2299 Array<Array<size_t>> faces;
2300 size_t global_faces = 0;
2301 if (compute_faces_from_rotation(order, isolated_vertices, num_components, faces, global_faces))
2302 {
2303 fill_embedding_result(order, faces, global_faces, true);
2304 return true;
2305 }
2306 }
2307
2309 {
2310 result_.embedding_search_truncated = true;
2311 return false;
2312 }
2313
2314 auto reverse_order = [](Array<size_t> &ord)
2315 {
2316 if (ord.size() <= 1)
2317 return;
2318
2319 size_t i = 0;
2320 size_t j = ord.size() - 1;
2321 while (i < j)
2322 {
2323 std::swap(ord[i], ord[j]);
2324 ++i;
2325 --j;
2326 }
2327 };
2328
2329 auto same_order = [](const Array<size_t> &a, const Array<size_t> &b) -> bool
2330 {
2331 if (a.size() != b.size())
2332 return false;
2333
2334 for (size_t i = 0; i < a.size(); ++i)
2335 if (a[i] != b[i])
2336 return false;
2337
2338 return true;
2339 };
2340
2341 auto append_unique_order = [&](Array<Array<size_t>> &opts, const Array<size_t> &cand)
2342 {
2343 for (auto it = opts.get_it(); it.has_curr(); it.next_ne())
2344 if (same_order(it.get_curr_ne(), cand))
2345 return;
2346
2347 opts.append(cand);
2348 };
2349
2350 auto add_adjacent_swaps = [&](Array<Array<size_t>> &opts, const Array<size_t> &src)
2351 {
2352 if (src.size() < 2)
2353 return;
2354
2355 for (size_t i = 0; i + 1 < src.size(); ++i)
2356 {
2357 Array<size_t> cand = src;
2358 std::swap(cand[i], cand[i + 1]);
2359 append_unique_order(opts, cand);
2360 }
2361 };
2362
2363 auto add_pair_swaps = [&](Array<Array<size_t>> &opts, const Array<size_t> &src)
2364 {
2365 if (src.size() < 2)
2366 return;
2367
2368 for (size_t i = 0; i + 1 < src.size(); ++i)
2369 for (size_t j = i + 1; j < src.size(); ++j)
2370 {
2371 Array<size_t> cand = src;
2372 std::swap(cand[i], cand[j]);
2373 append_unique_order(opts, cand);
2374 }
2375 };
2376
2377 Array<Array<Array<size_t>>> repair_options;
2378 repair_options.reserve(result_.simplified_num_nodes);
2379
2380 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
2381 {
2382 Array<Array<size_t>> opts;
2383 opts.append(order[v]);
2384
2385 if (order[v].size() >= 2)
2386 {
2387 Array<size_t> rev = order[v];
2388 reverse_order(rev);
2389 append_unique_order(opts, rev);
2390
2391 add_adjacent_swaps(opts, order[v]);
2392 add_adjacent_swaps(opts, rev);
2393
2394 // Dense planar subgraphs often need more than a flip.
2395 // For small local degree, include full pair swaps.
2396 if (order[v].size() <= 5)
2397 {
2398 add_pair_swaps(opts, order[v]);
2399 add_pair_swaps(opts, rev);
2400 }
2401 }
2402
2403 repair_options.append(std::move(opts));
2404 }
2405
2406 Array<size_t> vars;
2407 vars.reserve(result_.simplified_num_nodes);
2408 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
2409 if (repair_options[v].size() > 1)
2410 vars.append(v);
2411
2412 if (vars.is_empty())
2413 return false;
2414
2415 for (size_t i = 1; i < vars.size(); ++i)
2416 {
2417 const size_t key = vars[i];
2418 size_t j = i;
2419 while (j > 0 and repair_options[key].size() > repair_options[vars[j - 1]].size())
2420 {
2421 vars[j] = vars[j - 1];
2422 --j;
2423 }
2424 vars[j] = key;
2425 }
2426
2427 struct Repair_Quality
2428 {
2429 bool available = false;
2430 bool valid_embedding = false;
2431 long long abs_euler_delta = std::numeric_limits<long long>::max();
2432 size_t global_faces = 0;
2433 };
2434
2435 Array<size_t> selected(result_.simplified_num_nodes, static_cast<size_t>(0));
2436 size_t evaluated = 0;
2437 bool truncated = false;
2438
2439 auto build_candidate_order = [&](const Array<size_t> &sel, Array<Array<size_t>> &candidate)
2440 {
2441 candidate.empty();
2442 candidate.reserve(result_.simplified_num_nodes);
2443 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
2444 candidate.append(repair_options[v][sel[v]]);
2445 };
2446
2447 auto materialize_embedding = [&](const Array<size_t> &sel) -> bool
2448 {
2449 Array<Array<size_t>> candidate;
2450 build_candidate_order(sel, candidate);
2451
2452 Array<Array<size_t>> faces;
2453 size_t global_faces = 0;
2454 if (not compute_faces_from_rotation(candidate, isolated_vertices, num_components, faces,
2455 global_faces))
2456 return false;
2457
2458 fill_embedding_result(candidate, faces, global_faces, true);
2459 return true;
2460 };
2461
2462 auto evaluate_quality = [&](const Array<size_t> &sel, Repair_Quality &out) -> bool
2463 {
2464 if (evaluated >= options_.embedding_max_combinations)
2465 {
2466 truncated = true;
2467 return false;
2468 }
2469
2470 ++evaluated;
2471
2472 Array<Array<size_t>> candidate;
2473 build_candidate_order(sel, candidate);
2474
2475 Array<Array<size_t>> faces;
2476 size_t global_faces = 0;
2477 if (not compute_faces_from_rotation(candidate, isolated_vertices, num_components, faces,
2478 global_faces, false))
2479 {
2480 out.available = false;
2481 out.valid_embedding = false;
2482 out.abs_euler_delta = std::numeric_limits<long long>::max();
2483 out.global_faces = 0;
2484 return true;
2485 }
2486
2487 const long long lhs = static_cast<long long>(result_.simplified_num_nodes) -
2488 static_cast<long long>(result_.simplified_num_edges) + static_cast<long long>(global_faces);
2489 const long long rhs = static_cast<long long>(num_components) + 1;
2490
2491 long long delta = lhs - rhs;
2492 if (delta < 0)
2493 delta = -delta;
2494
2495 out.available = true;
2496 out.valid_embedding = (not options_.embedding_validate_with_euler) or delta == 0;
2497 out.abs_euler_delta = delta;
2498 out.global_faces = global_faces;
2499 return true;
2500 };
2501
2502 auto run_coordinate_descent = [&](const Array<size_t> &seed_selected) -> bool
2503 {
2504 selected = seed_selected;
2505
2506 Repair_Quality current_quality;
2507 if (not evaluate_quality(selected, current_quality))
2508 return false;
2509
2510 if (current_quality.valid_embedding and materialize_embedding(selected))
2511 return true;
2512
2513 const size_t max_passes = vars.size() == 0 ? 0 : 2 * vars.size();
2514 bool budget_hit = false;
2515
2516 for (size_t pass = 0; pass < max_passes; ++pass)
2517 {
2518 bool improved = false;
2519
2520 for (auto vit = vars.get_it(); vit.has_curr(); vit.next_ne())
2521 {
2522 const size_t v = vit.get_curr_ne();
2523 const size_t prev_opt = selected[v];
2524 size_t best_opt = prev_opt;
2525 Repair_Quality best_quality = current_quality;
2526
2527 for (size_t i = 0; i < repair_options[v].size(); ++i)
2528 {
2529 if (i == prev_opt)
2530 continue;
2531
2532 selected[v] = i;
2533 Repair_Quality cand_quality;
2534 if (not evaluate_quality(selected, cand_quality))
2535 {
2536 budget_hit = true;
2537 break;
2538 }
2539
2540 if (not cand_quality.available)
2541 continue;
2542
2543 if (cand_quality.valid_embedding and materialize_embedding(selected))
2544 return true;
2545
2546 if (cand_quality.abs_euler_delta < best_quality.abs_euler_delta or
2547 (cand_quality.abs_euler_delta == best_quality.abs_euler_delta and
2548 cand_quality.global_faces > best_quality.global_faces))
2549 {
2550 best_opt = i;
2551 best_quality = cand_quality;
2552 }
2553 }
2554
2555 if (budget_hit)
2556 break;
2557
2558 selected[v] = best_opt;
2559 if (best_opt != prev_opt)
2560 {
2561 current_quality = best_quality;
2562 improved = true;
2563 }
2564 }
2565
2566 if (budget_hit or not improved)
2567 break;
2568 }
2569
2570 return false;
2571 };
2572
2573 Array<size_t> base_seed(result_.simplified_num_nodes, static_cast<size_t>(0));
2574 if (run_coordinate_descent(base_seed))
2575 return true;
2576
2577 if (truncated)
2578 {
2579 result_.embedding_search_truncated = true;
2580 return false;
2581 }
2582
2583 Array<size_t> reverse_seed = base_seed;
2584 bool has_reverse_seed = false;
2585 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
2586 if (repair_options[v].size() > 1)
2587 {
2588 reverse_seed[v] = 1;
2589 has_reverse_seed = true;
2590 }
2591
2592 if (has_reverse_seed and run_coordinate_descent(reverse_seed))
2593 return true;
2594
2595 if (truncated)
2596 {
2597 result_.embedding_search_truncated = true;
2598 return false;
2599 }
2600
2601 for (auto vit = vars.get_it(); vit.has_curr(); vit.next_ne())
2602 {
2603 const size_t v = vit.get_curr_ne();
2604 for (size_t i = 1; i < repair_options[v].size(); ++i)
2605 {
2606 Array<size_t> seed = base_seed;
2607 seed[v] = i;
2608 if (run_coordinate_descent(seed))
2609 return true;
2610
2611 if (truncated)
2612 {
2613 result_.embedding_search_truncated = true;
2614 return false;
2615 }
2616 }
2617 }
2618
2619 const size_t max_pair_seed_vars = std::min(static_cast<size_t>(4), vars.size());
2620 for (size_t ia = 0; ia < max_pair_seed_vars; ++ia)
2621 for (size_t ib = ia + 1; ib < max_pair_seed_vars; ++ib)
2622 {
2623 const size_t va = vars[ia];
2624 const size_t vb = vars[ib];
2625 for (size_t oa = 1; oa < repair_options[va].size(); ++oa)
2626 for (size_t ob = 1; ob < repair_options[vb].size(); ++ob)
2627 {
2628 Array<size_t> seed = base_seed;
2629 seed[va] = oa;
2630 seed[vb] = ob;
2631 if (run_coordinate_descent(seed))
2632 return true;
2633
2634 if (truncated)
2635 {
2636 result_.embedding_search_truncated = true;
2637 return false;
2638 }
2639 }
2640 }
2641
2642 if (truncated)
2643 result_.embedding_search_truncated = true;
2644
2645 return false;
2646 }
2647
2649 {
2650 if (result_.simplified_num_nodes == 0)
2651 {
2652 result_.has_combinatorial_embedding = true;
2653 result_.embedding_is_lr_linear = false;
2654 result_.embedding_num_faces = 0;
2655 return true;
2656 }
2657
2658 Array<Array<size_t>> neighbors;
2659 neighbors.reserve(result_.simplified_num_nodes);
2660
2661 size_t isolated_vertices = 0;
2662 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
2663 {
2664 Array<size_t> ng;
2665 ng.reserve(incident_edges_[v].size());
2666 for (auto it = incident_edges_[v].get_it(); it.has_curr(); it.next_ne())
2667 ng.append(other_endpoint(it.get_curr_ne(), v));
2668
2670 if (ng.is_empty())
2671 ++isolated_vertices;
2672
2673 neighbors.append(std::move(ng));
2674 }
2675
2676 if (result_.simplified_num_edges == 0)
2677 {
2678 Array<Array<size_t>> order;
2679 order.reserve(result_.simplified_num_nodes);
2680 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
2681 order.append(Array<size_t>());
2682
2683 const size_t num_components = result_.simplified_num_nodes;
2684 Array<Array<size_t>> faces;
2685 size_t global_faces = 0;
2686
2687 if (not compute_faces_from_rotation(order, isolated_vertices, num_components, faces,
2688 global_faces))
2689 return false;
2690
2691 fill_embedding_result(order, faces, global_faces, false);
2692 return true;
2693 }
2694
2696 {
2697 result_.embedding_search_truncated = true;
2698 return false;
2699 }
2700
2701 Array<Array<Array<size_t>>> order_options;
2702 order_options.reserve(result_.simplified_num_nodes);
2703
2704 size_t combinations = 1;
2705 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
2706 {
2707 const auto &neigh = neighbors[v];
2708 const size_t d = neigh.size();
2709
2710 Array<Array<size_t>> opts;
2711 if (d <= 2)
2712 opts.append(neigh);
2713 else
2714 {
2715 const size_t cnt = factorial_bounded(d - 1, options_.embedding_max_combinations);
2717 combinations > options_.embedding_max_combinations / cnt)
2718 {
2719 result_.embedding_search_truncated = true;
2720 return false;
2721 }
2722
2723 combinations *= cnt;
2724
2725 const size_t first = neigh[0];
2726 Array<size_t> tail;
2727 tail.reserve(d - 1);
2728 for (size_t i = 1; i < d; ++i)
2729 tail.append(neigh[i]);
2730
2731 generate_permutations(tail, 0, first, opts);
2732 }
2733
2734 order_options.append(std::move(opts));
2735 }
2736
2737 Array<size_t> vars;
2738 vars.reserve(result_.simplified_num_nodes);
2739 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
2740 if (order_options[v].size() > 1)
2741 vars.append(v);
2742
2743 for (size_t i = 1; i < vars.size(); ++i)
2744 {
2745 const size_t key = vars[i];
2746 size_t j = i;
2747 while (j > 0 and order_options[key].size() > order_options[vars[j - 1]].size())
2748 {
2749 vars[j] = vars[j - 1];
2750 --j;
2751 }
2752 vars[j] = key;
2753 }
2754
2755 const size_t num_components = count_components();
2756 Array<size_t> selected(result_.simplified_num_nodes, 0);
2757
2758 auto evaluate = [&]() -> bool
2759 {
2760 Array<Array<size_t>> order;
2761 order.reserve(result_.simplified_num_nodes);
2762 for (size_t v = 0; v < result_.simplified_num_nodes; ++v)
2763 order.append(order_options[v][selected[v]]);
2764
2765 Array<Array<size_t>> faces;
2766 size_t global_faces = 0;
2767 if (not compute_faces_from_rotation(order, isolated_vertices, num_components, faces,
2768 global_faces))
2769 return false;
2770
2771 fill_embedding_result(order, faces, global_faces, false);
2772 return true;
2773 };
2774
2775 auto search = [&](auto &&self, const size_t pos) -> bool
2776 {
2777 if (pos == vars.size())
2778 return evaluate();
2779
2780 const size_t v = vars[pos];
2781 for (size_t i = 0; i < order_options[v].size(); ++i)
2782 {
2783 selected[v] = i;
2784 if (self(self, pos + 1))
2785 return true;
2786 }
2787
2788 return false;
2789 };
2790
2791 return search(search, 0);
2792 }
2793
2795 {
2797 return true;
2798
2800 {
2801 result_.embedding_search_truncated = true;
2802 return false;
2803 }
2804
2806 }
2807
2808public:
2810 : g_(g), sa_(std::move(sa)), options_(std::move(options))
2811 {
2812 // empty
2813 }
2814
2816 {
2818
2820 {
2821 result_.is_planar = false;
2822 result_.failed_euler_bound = true;
2823
2826
2827 return result_;
2828 }
2829
2830 result_.is_planar = run_lr_planarity_test();
2831
2832 if (result_.is_planar)
2833 {
2835 {
2836 result_.embedding_search_truncated = false;
2838 }
2839 }
2841 {
2842 result_.certificate_search_truncated = false;
2844 }
2845
2846 return result_;
2847 }
2848};
2849} // namespace planarity_detail
2850
2878template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
2880 const GT &g,
2881 SA sa = SA(),
2883{
2885}
2886
2891template <AlephGraph GT>
2893{
2894 return planarity_test<GT, Dft_Show_Arc<GT>>(g, Dft_Show_Arc<GT>(), options);
2895}
2896
2908template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
2909bool is_planar_graph(const GT &g,
2910 SA sa = SA(),
2912{
2913 return planarity_test<GT, SA>(g, std::move(sa), options).is_planar;
2914}
2915
2920template <AlephGraph GT>
2922{
2923 return is_planar_graph<GT, Dft_Show_Arc<GT>>(g, Dft_Show_Arc<GT>(), options);
2924}
2925
2932template <AlephGraph GT>
2934{
2935 using Node = typename GT::Node;
2936 using Dart_Key = planarity_detail::Dart_Key;
2937 constexpr size_t Null_Edge = planarity_detail::Null_Edge;
2938
2940 << "planar_dual_metadata() requires a planar result with embedding";
2941
2942 const size_t n = result.embedding_rotation.size();
2943 ah_runtime_error_unless(n == result.simplified_num_nodes) << "embedding_rotation size mismatch";
2944
2946 md.has_embedding = true;
2947
2948 if (n == 0)
2949 {
2950 md.num_components = 0;
2951 md.num_faces_local = 0;
2952 md.num_faces_global = 0;
2953 md.faces_are_component_local = false;
2954 return md;
2955 }
2956
2957 Array<Node *> idx_to_node;
2958 idx_to_node.reserve(n);
2959
2960 DynMapTree<Node *, size_t> node_to_idx;
2961 for (size_t i = 0; i < n; ++i)
2962 {
2963 Node *node = result.embedding_rotation[i].node;
2964 ah_runtime_error_unless(node != nullptr) << "embedding_rotation contains null node";
2965 ah_runtime_error_if(node_to_idx.contains(node))
2966 << "embedding_rotation contains duplicated node pointer";
2967
2968 node_to_idx.insert(node, i);
2969 idx_to_node.append(node);
2970 }
2971
2972 Array<Array<size_t>> order;
2973 order.reserve(n);
2974 for (size_t i = 0; i < n; ++i)
2975 order.append(Array<size_t>());
2976
2977 for (size_t i = 0; i < n; ++i)
2978 {
2979 DynSetTree<size_t> seen;
2980 const auto &re = result.embedding_rotation[i];
2981 for (Aleph::const_iterator_t<Array<Node *>> it(re.cw_neighbors); it.has_curr(); it.next_ne())
2982 {
2983 Node *neigh = it.get_curr_ne();
2984 ah_runtime_error_unless(neigh != nullptr) << "embedding_rotation contains null neighbor";
2985 ah_runtime_error_unless(node_to_idx.contains(neigh))
2986 << "embedding_rotation references unknown neighbor node";
2987
2988 const size_t v = node_to_idx.find(neigh);
2989 ah_runtime_error_if(v == i) << "embedding_rotation has self-neighbor in simplified graph";
2991 << "embedding_rotation has duplicated neighbor in same rotation";
2992
2993 seen.insert(v);
2994 order[i].append(v);
2995 }
2996 }
2997
2998 Array<long> comp_id(n, static_cast<long>(-1));
2999 size_t num_components = 0;
3000 size_t isolated_vertices = 0;
3001
3002 for (size_t s = 0; s < n; ++s)
3003 {
3004 if (order[s].is_empty())
3005 ++isolated_vertices;
3006
3007 if (comp_id[s] != -1)
3008 continue;
3009
3010 comp_id[s] = static_cast<long>(num_components);
3011 Array<size_t> stack;
3012 stack.append(s);
3013
3014 while (not stack.is_empty())
3015 {
3016 const size_t u = stack.remove_last();
3017 for (auto it = order[u].get_it(); it.has_curr(); it.next_ne())
3018 {
3019 const size_t v = it.get_curr_ne();
3020 if (comp_id[v] != -1)
3021 continue;
3022 comp_id[v] = static_cast<long>(num_components);
3023 stack.append(v);
3024 }
3025 }
3026
3027 ++num_components;
3028 }
3029
3030 md.num_components = num_components;
3031
3032 Array<size_t> dart_src;
3033 Array<size_t> dart_tgt;
3034 dart_src.reserve(2 * result.simplified_num_edges);
3035 dart_tgt.reserve(2 * result.simplified_num_edges);
3036
3038 for (size_t u = 0; u < n; ++u)
3039 {
3040 for (auto it = order[u].get_it(); it.has_curr(); it.next_ne())
3041 {
3042 const size_t v = it.get_curr_ne();
3043 const Dart_Key key{u, v};
3044 ah_runtime_error_if(dart_id.contains(key))
3045 << "embedding rotation contains repeated directed edge";
3046
3047 const size_t did = dart_src.size();
3048 dart_id.insert(key, did);
3049 dart_src.append(u);
3050 dart_tgt.append(v);
3051 }
3052 }
3053
3054 ah_runtime_error_unless(dart_src.size() % 2 == 0) << "invalid embedding: odd number of darts";
3055
3056 Array<size_t> alpha(dart_src.size(), Null_Edge);
3057 for (size_t d = 0; d < dart_src.size(); ++d)
3058 {
3059 const Dart_Key rev{dart_tgt[d], dart_src[d]};
3060 ah_runtime_error_unless(dart_id.contains(rev)) << "invalid embedding: missing reverse dart";
3061 alpha[d] = dart_id.find(rev);
3062 }
3063
3064 Array<size_t> sigma(dart_src.size(), Null_Edge);
3065 for (size_t u = 0; u < n; ++u)
3066 {
3067 const auto &ord = order[u];
3068 if (ord.is_empty())
3069 continue;
3070
3071 for (size_t i = 0; i < ord.size(); ++i)
3072 {
3073 const size_t to = ord[i];
3074 const size_t next = ord[(i + 1) % ord.size()];
3075 const size_t a = dart_id.find(Dart_Key{u, to});
3076 const size_t b = dart_id.find(Dart_Key{u, next});
3077 sigma[a] = b;
3078 }
3079 }
3080
3081 for (unsigned long d : sigma)
3082 ah_runtime_error_unless(d != Null_Edge) << "invalid embedding: incomplete sigma permutation";
3083
3084 Array<size_t> face_of_dart(dart_src.size(), Null_Edge);
3085 for (size_t d = 0; d < dart_src.size(); ++d)
3086 {
3087 if (face_of_dart[d] != Null_Edge)
3088 continue;
3089
3090 const size_t fid = md.faces.size();
3092
3093 size_t x = d;
3094 while (face_of_dart[x] == Null_Edge)
3095 {
3096 face_of_dart[x] = fid;
3097
3099 fd.src = idx_to_node[dart_src[x]];
3100 fd.tgt = idx_to_node[dart_tgt[x]];
3101 face.darts.append(fd);
3102
3103 x = sigma[alpha[x]];
3104 }
3105
3106 md.faces.append(std::move(face));
3107 }
3108
3109 for (size_t i = 0; i < isolated_vertices; ++i)
3110 md.faces.append(typename Planar_Dual_Metadata<GT>::Face_Boundary());
3111
3112 md.num_faces_local = md.faces.size();
3113
3114 const size_t m = dart_src.size() / 2;
3115 const size_t num_faces_global = m - n + num_components + 1;
3116 md.num_faces_global = num_faces_global;
3118
3119 md.face_adjacency.reserve(md.num_faces_local);
3120 for (size_t i = 0; i < md.num_faces_local; ++i)
3121 md.face_adjacency.append(Array<size_t>());
3122
3123 md.dual_edges.reserve(m);
3124 for (size_t d = 0; d < dart_src.size(); ++d)
3125 {
3126 const size_t rev = alpha[d];
3127 if (d > rev)
3128 continue;
3129
3130 const size_t f0 = face_of_dart[d];
3131 const size_t f1 = face_of_dart[rev];
3132
3134 info.face_a = f0;
3135 info.face_b = f1;
3136 info.primal_src = idx_to_node[dart_src[d]];
3137 info.primal_tgt = idx_to_node[dart_tgt[d]];
3138
3139 md.dual_edges.append(info);
3140 md.face_adjacency[f0].append(f1);
3141 md.face_adjacency[f1].append(f0);
3142 }
3143
3144 for (size_t f = 0; f < md.face_adjacency.size(); ++f)
3145 {
3146 auto &adj = md.face_adjacency[f];
3147 for (size_t i = 1; i < adj.size(); ++i)
3148 {
3149 const size_t key = adj[i];
3150 size_t j = i;
3151 while (j > 0 and key < adj[j - 1])
3152 {
3153 adj[j] = adj[j - 1];
3154 --j;
3155 }
3156 adj[j] = key;
3157 }
3158
3159 if (adj.is_empty())
3160 continue;
3161
3162 Array<size_t> uniq;
3163 uniq.reserve(adj.size());
3164 uniq.append(adj[0]);
3165 for (size_t i = 1; i < adj.size(); ++i)
3166 if (adj[i] != uniq.get_last())
3167 uniq.append(adj[i]);
3168
3169 adj = std::move(uniq);
3170 }
3171
3172 return md;
3173}
3174
3179template <AlephGraph GT, class DGT = Default_Planar_Dual_Graph<GT>>
3181{
3183 << "build_planar_dual_graph() requires metadata with embedding";
3184
3185 DGT dual;
3186 Array<typename DGT::Node *> face_nodes;
3187 face_nodes.reserve(md.num_faces_local);
3188
3189 for (size_t f = 0; f < md.num_faces_local; ++f)
3190 face_nodes.append(dual.insert_node(f));
3191
3192 for (auto it = md.dual_edges.get_it(); it.has_curr(); it.next_ne())
3193 {
3194 const auto &e = it.get_curr_ne();
3195 dual.insert_arc(face_nodes[e.face_a], face_nodes[e.face_b], e);
3196 }
3197
3198 return dual;
3199}
3200
3205template <AlephGraph GT, class DGT = Default_Planar_Dual_Graph<GT>>
3207{
3208 return build_planar_dual_graph<GT, DGT>(planar_dual_metadata(result));
3209}
3210
3222template <AlephGraph GT>
3224 const Planarity_Test_Result<GT> &result,
3226{
3227 using Node = typename GT::Node;
3228 using Face_Metadata = Planar_Dual_Metadata<GT>;
3229
3230 constexpr size_t Null = std::numeric_limits<size_t>::max();
3231 constexpr double Pi = 3.1415926535897932384626433832795;
3232
3234 << "planar_geometric_drawing() requires a planar result with embedding";
3235
3236 const size_t n = result.embedding_rotation.size();
3237 ah_runtime_error_unless(n == result.simplified_num_nodes) << "embedding_rotation size mismatch";
3238
3240 drawing.has_embedding = true;
3241
3242 if (n == 0)
3243 {
3244 drawing.drawing_available = true;
3245 drawing.drawing_validated_no_crossings = true;
3246 return drawing;
3247 }
3248
3249 if (options.max_outer_faces_to_try == 0)
3250 {
3251 drawing.drawing_search_truncated = true;
3252 return drawing;
3253 }
3254
3255 DynMapTree<Node *, size_t> node_to_idx;
3256 Array<Node *> idx_to_node;
3257 idx_to_node.reserve(n);
3258
3259 for (size_t i = 0; i < n; ++i)
3260 {
3261 Node *node = result.embedding_rotation[i].node;
3262 ah_runtime_error_unless(node != nullptr) << "embedding_rotation contains null node";
3263 ah_runtime_error_if(node_to_idx.contains(node))
3264 << "embedding_rotation contains duplicated node pointer";
3265
3266 node_to_idx.insert(node, i);
3267 idx_to_node.append(node);
3268 }
3269
3270 Array<Array<size_t>> order;
3271 order.reserve(n);
3272 for (size_t i = 0; i < n; ++i)
3273 order.append(Array<size_t>());
3274
3275 for (size_t i = 0; i < n; ++i)
3276 {
3277 DynSetTree<size_t> seen;
3278 const auto &re = result.embedding_rotation[i];
3279 for (Aleph::const_iterator_t<Array<Node *>> it(re.cw_neighbors); it.has_curr(); it.next_ne())
3280 {
3281 Node *neigh = it.get_curr_ne();
3282 ah_runtime_error_unless(neigh != nullptr) << "embedding_rotation contains null neighbor";
3283 ah_runtime_error_unless(node_to_idx.contains(neigh))
3284 << "embedding_rotation references unknown node";
3285
3286 const size_t v = node_to_idx.find(neigh);
3287 ah_runtime_error_if(v == i) << "embedding_rotation has self-neighbor";
3288 ah_runtime_error_if(seen.contains(v)) << "embedding_rotation has duplicated neighbor";
3289
3290 seen.insert(v);
3291 order[i].append(v);
3292 }
3293 }
3294
3295 Array<long> comp_id(n, static_cast<long>(-1));
3296 size_t num_components = 0;
3297 for (size_t s = 0; s < n; ++s)
3298 {
3299 if (comp_id[s] != -1)
3300 continue;
3301
3302 comp_id[s] = static_cast<long>(num_components);
3303 Array<size_t> stack;
3304 stack.append(s);
3305
3306 while (not stack.is_empty())
3307 {
3308 const size_t u = stack.remove_last();
3309 for (auto it = order[u].get_it(); it.has_curr(); it.next_ne())
3310 {
3311 const size_t v = it.get_curr_ne();
3312 if (comp_id[v] != -1)
3313 continue;
3314 comp_id[v] = static_cast<long>(num_components);
3315 stack.append(v);
3316 }
3317 }
3318
3319 ++num_components;
3320 }
3321
3322 drawing.num_components = num_components;
3323
3324 Array<Array<size_t>> comp_nodes;
3325 comp_nodes.reserve(num_components);
3326 for (size_t c = 0; c < num_components; ++c)
3327 comp_nodes.append(Array<size_t>());
3328 for (size_t i = 0; i < n; ++i)
3329 comp_nodes[static_cast<size_t>(comp_id[i])].append(i);
3330
3331 struct Drawing_Edge
3332 {
3333 size_t u = 0;
3334 size_t v = 0;
3335 size_t comp = 0;
3336 };
3337
3338 Array<Drawing_Edge> edges;
3339 edges.reserve(result.simplified_num_edges);
3340 for (size_t u = 0; u < n; ++u)
3341 for (auto it = order[u].get_it(); it.has_curr(); it.next_ne())
3342 {
3343 const size_t v = it.get_curr_ne();
3344 if (u < v)
3345 edges.append(Drawing_Edge{u, v, static_cast<size_t>(comp_id[u])});
3346 }
3347
3348 Array<Array<size_t>> comp_edge_ids;
3349 comp_edge_ids.reserve(num_components);
3350 for (size_t c = 0; c < num_components; ++c)
3351 comp_edge_ids.append(Array<size_t>());
3352 for (size_t i = 0; i < edges.size(); ++i)
3353 comp_edge_ids[edges[i].comp].append(i);
3354
3355 const Face_Metadata md = planar_dual_metadata(result);
3356 struct Face_Candidate
3357 {
3358 size_t face_id = Null;
3359 size_t comp = 0;
3360 Array<size_t> boundary_nodes;
3361 size_t score = 0;
3362 };
3363
3364 Array<Face_Candidate> face_candidates;
3365 face_candidates.reserve(md.faces.size());
3366
3367 for (size_t fid = 0; fid < md.faces.size(); ++fid)
3368 {
3369 const auto &face = md.faces[fid];
3370 if (face.darts.is_empty())
3371 continue;
3372
3373 Array<size_t> raw;
3374 raw.reserve(face.darts.size());
3375 for (auto it = face.darts.get_it(); it.has_curr(); it.next_ne())
3376 {
3377 const auto &d = it.get_curr_ne();
3378 ah_runtime_error_unless(node_to_idx.contains(d.src))
3379 << "face metadata references unknown node";
3380 raw.append(node_to_idx.find(d.src));
3381 }
3382
3383 if (raw.is_empty())
3384 continue;
3385
3386 Array<size_t> cleaned;
3387 cleaned.reserve(raw.size());
3388 for (unsigned long i : raw)
3389 if (cleaned.is_empty() or cleaned.get_last() != i)
3390 cleaned.append(i);
3391
3392 if (cleaned.size() > 1 and cleaned[0] == cleaned.get_last())
3393 (void) cleaned.remove_last();
3394
3395 DynSetTree<size_t> seen;
3396 Array<size_t> unique_cycle;
3397 unique_cycle.reserve(cleaned.size());
3398 for (auto it = cleaned.get_it(); it.has_curr(); it.next_ne())
3399 {
3400 const size_t u = it.get_curr_ne();
3401 if (seen.contains(u))
3402 continue;
3403 seen.insert(u);
3404 unique_cycle.append(u);
3405 }
3406
3407 if (unique_cycle.is_empty())
3408 continue;
3409
3410 Face_Candidate cand;
3411 cand.face_id = fid;
3412 cand.comp = static_cast<size_t>(comp_id[unique_cycle[0]]);
3413 cand.boundary_nodes = std::move(unique_cycle);
3414 cand.score = cand.boundary_nodes.size();
3415 face_candidates.append(std::move(cand));
3416 }
3417
3418 Array<Array<size_t>> comp_faces;
3419 comp_faces.reserve(num_components);
3420 for (size_t c = 0; c < num_components; ++c)
3421 comp_faces.append(Array<size_t>());
3422
3423 for (size_t i = 0; i < face_candidates.size(); ++i)
3424 comp_faces[face_candidates[i].comp].append(i);
3425
3426 for (size_t c = 0; c < num_components; ++c)
3427 {
3428 auto &faces = comp_faces[c];
3429 for (size_t i = 1; i < faces.size(); ++i)
3430 {
3431 const size_t key = faces[i];
3432 size_t j = i;
3433 while (j > 0 and face_candidates[key].score > face_candidates[faces[j - 1]].score)
3434 {
3435 faces[j] = faces[j - 1];
3436 --j;
3437 }
3438 faces[j] = key;
3439 }
3440 }
3441
3442 auto count_crossings = [&](const size_t comp, const Array<double> &px,
3443 const Array<double> &py) -> size_t
3444 {
3445 size_t total = 0;
3446 const auto &ce = comp_edge_ids[comp];
3447 for (size_t i = 0; i < ce.size(); ++i)
3448 {
3449 const auto &e1 = edges[ce[i]];
3450 for (size_t j = i + 1; j < ce.size(); ++j)
3451 {
3452 const auto &e2 = edges[ce[j]];
3453 if (e1.u == e2.u or e1.u == e2.v or e1.v == e2.u or e1.v == e2.v)
3454 continue;
3455
3457 px[e1.u], py[e1.u], px[e1.v], py[e1.v], px[e2.u], py[e2.u], px[e2.v], py[e2.v]))
3458 ++total;
3459 }
3460 }
3461 return total;
3462 };
3463
3464 auto build_component_layout = [&](const size_t comp, const Array<size_t> &boundary,
3465 Array<double> &px, Array<double> &py, size_t &iterations) -> void
3466 {
3467 const auto &cnodes = comp_nodes[comp];
3468 Array<char> fixed(n, static_cast<char>(0));
3469
3470 for (auto it = cnodes.get_it(); it.has_curr(); it.next_ne())
3471 {
3472 const size_t u = it.get_curr_ne();
3473 px[u] = 0;
3474 py[u] = 0;
3475 }
3476
3477 Array<size_t> use_boundary = boundary;
3478 if (use_boundary.size() < 3 and cnodes.size() >= 1)
3479 {
3480 use_boundary.empty();
3481 for (auto it = cnodes.get_it(); it.has_curr(); it.next_ne())
3482 use_boundary.append(it.get_curr_ne());
3483 }
3484
3485 const double scale = std::max(1.0, std::sqrt(static_cast<double>(cnodes.size())));
3486 const double radius = options.outer_face_radius * scale;
3487
3488 if (use_boundary.is_empty())
3489 {
3490 iterations = 0;
3491 return;
3492 }
3493
3494 for (size_t i = 0; i < use_boundary.size(); ++i)
3495 {
3496 const size_t u = use_boundary[i];
3497 const double ang =
3498 (2.0 * Pi * static_cast<double>(i)) / static_cast<double>(use_boundary.size());
3499 px[u] = radius * std::cos(ang);
3500 py[u] = radius * std::sin(ang);
3501 fixed[u] = 1;
3502 }
3503
3504 for (auto it = cnodes.get_it(); it.has_curr(); it.next_ne())
3505 {
3506 const size_t u = it.get_curr_ne();
3507 if (fixed[u])
3508 continue;
3509
3510 double sx = 0;
3511 double sy = 0;
3512 size_t cnt = 0;
3513 for (auto nt = order[u].get_it(); nt.has_curr(); nt.next_ne())
3514 {
3515 const size_t v = nt.get_curr_ne();
3516 if (comp_id[v] != static_cast<long>(comp))
3517 continue;
3518 sx += px[v];
3519 sy += py[v];
3520 ++cnt;
3521 }
3522
3523 if (cnt == 0)
3524 {
3525 px[u] = 0.01 * static_cast<double>(u + 1);
3526 py[u] = -0.01 * static_cast<double>(u + 1);
3527 }
3528 else
3529 {
3530 px[u] = sx / static_cast<double>(cnt);
3531 py[u] = sy / static_cast<double>(cnt);
3532 }
3533 }
3534
3535 iterations = 0;
3536 for (size_t iter = 0; iter < options.max_relaxation_iterations; ++iter)
3537 {
3538 ++iterations;
3539 double max_delta = 0;
3540
3541 for (auto it = cnodes.get_it(); it.has_curr(); it.next_ne())
3542 {
3543 const size_t u = it.get_curr_ne();
3544 if (fixed[u])
3545 continue;
3546
3547 double sx = 0;
3548 double sy = 0;
3549 size_t cnt = 0;
3550 for (auto nt = order[u].get_it(); nt.has_curr(); nt.next_ne())
3551 {
3552 const size_t v = nt.get_curr_ne();
3553 if (comp_id[v] != static_cast<long>(comp))
3554 continue;
3555 sx += px[v];
3556 sy += py[v];
3557 ++cnt;
3558 }
3559
3560 if (cnt == 0)
3561 continue;
3562
3563 const double nx = sx / static_cast<double>(cnt);
3564 const double ny = sy / static_cast<double>(cnt);
3565 const double dx = nx - px[u];
3566 const double dy = ny - py[u];
3567 const double delta = std::sqrt(dx * dx + dy * dy);
3568 if (delta > max_delta)
3569 max_delta = delta;
3570
3571 px[u] = nx;
3572 py[u] = ny;
3573 }
3574
3575 if (max_delta <= options.relaxation_tolerance)
3576 break;
3577 }
3578 };
3579
3580 Array<double> gx(n, 0.0);
3581 Array<double> gy(n, 0.0);
3582 double offset_x = 0.0;
3583
3584 for (size_t c = 0; c < num_components; ++c)
3585 {
3586 Array<size_t> candidates = comp_faces[c];
3587
3588 if (options.preferred_outer_face != Null and options.preferred_outer_face < md.faces.size())
3589 {
3590 for (size_t i = 0; i < candidates.size(); ++i)
3591 if (face_candidates[candidates[i]].face_id == options.preferred_outer_face)
3592 {
3593 const size_t fav = candidates[i];
3594 for (size_t j = i; j > 0; --j)
3595 candidates[j] = candidates[j - 1];
3596 candidates[0] = fav;
3597 break;
3598 }
3599 }
3600
3601 size_t num_candidate_evals = 0;
3602 bool has_best = false;
3603 size_t best_crossings = std::numeric_limits<size_t>::max();
3604 size_t best_iters = 0;
3605 size_t best_face_id = Null;
3606 Array<double> best_x(n, 0.0);
3607 Array<double> best_y(n, 0.0);
3608
3609 auto evaluate_boundary = [&](const Array<size_t> &boundary, const size_t face_id) -> bool
3610 {
3611 if (num_candidate_evals >= options.max_outer_faces_to_try)
3612 {
3613 drawing.drawing_search_truncated = true;
3614 return false;
3615 }
3616
3617 ++num_candidate_evals;
3618
3619 Array<double> cx(n, 0.0);
3620 Array<double> cy(n, 0.0);
3621 size_t iters = 0;
3622 build_component_layout(c, boundary, cx, cy, iters);
3623
3624 const size_t crossings = options.validate_crossings ? count_crossings(c, cx, cy) : 0;
3625
3626 if (not has_best or crossings < best_crossings or
3627 (crossings == best_crossings and iters < best_iters))
3628 {
3629 has_best = true;
3630 best_crossings = crossings;
3631 best_iters = iters;
3632 best_face_id = face_id;
3633 best_x = std::move(cx);
3634 best_y = std::move(cy);
3635 }
3636
3637 return crossings == 0;
3638 };
3639
3640 for (auto fit = candidates.get_it(); fit.has_curr(); fit.next_ne())
3641 {
3642 const size_t idx = fit.get_curr_ne();
3643 if (evaluate_boundary(face_candidates[idx].boundary_nodes, face_candidates[idx].face_id))
3644 break;
3645 }
3646
3647 if (not has_best)
3648 {
3649 Array<size_t> fallback;
3650 for (auto it = comp_nodes[c].get_it(); it.has_curr(); it.next_ne())
3651 fallback.append(it.get_curr_ne());
3652 (void) evaluate_boundary(fallback, Null);
3653 }
3654
3655 ah_runtime_error_unless(has_best) << "unable to build component drawing candidate";
3656
3657 double min_x = std::numeric_limits<double>::max();
3658 double max_x = -std::numeric_limits<double>::max();
3659 for (auto it = comp_nodes[c].get_it(); it.has_curr(); it.next_ne())
3660 {
3661 const size_t u = it.get_curr_ne();
3662 min_x = std::min(min_x, best_x[u]);
3663 max_x = std::max(max_x, best_x[u]);
3664 }
3665
3666 const double shift_x = offset_x - min_x;
3667 for (auto it = comp_nodes[c].get_it(); it.has_curr(); it.next_ne())
3668 {
3669 const size_t u = it.get_curr_ne();
3670 gx[u] = best_x[u] + shift_x;
3671 gy[u] = best_y[u];
3672 }
3673
3674 offset_x += (max_x - min_x) + options.component_spacing;
3675 drawing.crossing_count += best_crossings;
3676 drawing.relaxation_iterations += best_iters;
3677
3678 if (num_components == 1)
3679 drawing.chosen_outer_face = best_face_id;
3680 }
3681
3682 drawing.node_positions.reserve(n);
3683 for (size_t i = 0; i < n; ++i)
3684 {
3686 p.node = idx_to_node[i];
3687 p.x = gx[i];
3688 p.y = gy[i];
3689 drawing.node_positions.append(p);
3690 }
3691
3692 drawing.drawing_available = true;
3694 (not options.validate_crossings) or drawing.crossing_count == 0;
3695 return drawing;
3696}
3697
3704template <AlephGraph GT, class Node_Label = Dft_Certificate_Node_Label<GT>>
3706 const Planarity_Test_Result<GT> &result,
3707 Node_Label node_label = Node_Label(),
3709{
3710 using Node = typename GT::Node;
3711 using Arc = typename GT::Arc;
3712
3714 << "nonplanar_certificate_to_json() requires non-planar certificate";
3715
3717 DynMapTree<Node *, size_t> node_to_id;
3719
3720 std::ostringstream out;
3721 auto newline = [&](const size_t indent)
3722 {
3723 if (not options.pretty_json)
3724 return;
3725 out << '\n';
3726 for (size_t i = 0; i < indent; ++i)
3727 out << " ";
3728 };
3729
3730 auto node_ref = [&](Node *node) -> std::string
3731 {
3732 if (node == nullptr or not node_to_id.contains(node))
3733 return "null";
3734 return "\"n" + std::to_string(node_to_id.find(node)) + "\"";
3735 };
3736
3737 auto arc_ref = [&](Arc *arc) -> std::string
3738 {
3739 if (arc == nullptr)
3740 return "null";
3742 "\"";
3743 };
3744
3745 out << "{";
3746 newline(1);
3747 out << "\"is_planar\": false,";
3748 newline(1);
3749 out << "\"certificate_available\": true,";
3750 newline(1);
3751 out << "\"certificate_type\": \""
3753 newline(1);
3754 out << "\"search_truncated\": " << (result.certificate_search_truncated ? "true" : "false") << ",";
3755
3756 newline(1);
3757 out << "\"nodes\": [";
3758 for (size_t i = 0; i < nodes.size(); ++i)
3759 {
3760 if (i > 0)
3761 out << ",";
3762 newline(2);
3763 out << "{";
3764 out << "\"id\": \"n" << i << "\", ";
3765 out << "\"label\": \"" << planarity_detail::json_escape_string(node_label(nodes[i])) << "\", ";
3766 out << "\"ptr\": \""
3768 << "\"";
3769 out << "}";
3770 }
3771 if (not nodes.is_empty())
3772 newline(1);
3773 out << "],";
3774
3775 newline(1);
3776 out << "\"branch_nodes\": [";
3777 for (size_t i = 0; i < result.certificate_branch_nodes.size(); ++i)
3778 {
3779 if (i > 0)
3780 out << ",";
3781 if (options.pretty_json)
3782 out << ' ';
3783 out << node_ref(result.certificate_branch_nodes[i]);
3784 }
3785 out << "],";
3786
3787 newline(1);
3788 out << "\"obstruction_edges\": [";
3789 for (size_t i = 0; i < result.certificate_obstruction_edges.size(); ++i)
3790 {
3791 const auto &e = result.certificate_obstruction_edges[i];
3792 if (i > 0)
3793 out << ",";
3794 newline(2);
3795 out << "{";
3796 out << "\"src\": " << node_ref(e.src) << ", ";
3797 out << "\"tgt\": " << node_ref(e.tgt) << ", ";
3798 out << "\"input_arc_count\": " << e.input_arcs.size() << ", ";
3799 out << "\"representative_input_arc\": " << arc_ref(e.representative_input_arc);
3800 out << "}";
3801 }
3802 if (not result.certificate_obstruction_edges.is_empty())
3803 newline(1);
3804 out << "],";
3805
3806 newline(1);
3807 out << "\"paths\": [";
3808 for (size_t i = 0; i < result.certificate_paths.size(); ++i)
3809 {
3810 const auto &path = result.certificate_paths[i];
3811 if (i > 0)
3812 out << ",";
3813 newline(2);
3814 out << "{";
3815
3816 out << "\"nodes\": [";
3817 for (size_t k = 0; k < path.nodes.size(); ++k)
3818 {
3819 if (k > 0)
3820 out << ", ";
3821 out << node_ref(path.nodes[k]);
3822 }
3823 out << "], ";
3824
3825 out << "\"edges\": [";
3826 for (size_t k = 0; k < path.edges.size(); ++k)
3827 {
3828 const auto &e = path.edges[k];
3829 if (k > 0)
3830 out << ", ";
3831 out << "{";
3832 out << "\"src\": " << node_ref(e.src) << ", ";
3833 out << "\"tgt\": " << node_ref(e.tgt) << ", ";
3834 out << "\"input_arc_count\": " << e.input_arcs.size() << ", ";
3835 out << "\"representative_input_arc\": " << arc_ref(e.representative_input_arc);
3836 out << "}";
3837 }
3838 out << "]";
3839 out << "}";
3840 }
3841 if (not result.certificate_paths.is_empty())
3842 newline(1);
3843 out << "]";
3844
3845 newline(0);
3846 out << "}";
3847 return out.str();
3848}
3849
3856template <AlephGraph GT, class Node_Label = Dft_Certificate_Node_Label<GT>>
3858 const Planarity_Test_Result<GT> &result,
3859 Node_Label node_label = Node_Label(),
3861{
3862 using Node = typename GT::Node;
3863
3865 << "nonplanar_certificate_to_dot() requires non-planar certificate";
3866
3868 DynMapTree<Node *, size_t> node_to_id;
3870
3871 DynSetTree<size_t> branch_ids;
3872 for (auto it = result.certificate_branch_nodes.get_it(); it.has_curr(); it.next_ne())
3873 {
3874 Node *node = it.get_curr_ne();
3875 if (node != nullptr and node_to_id.contains(node))
3876 branch_ids.insert(node_to_id.find(node));
3877 }
3878
3879 std::ostringstream out;
3880 out << "graph NonPlanarCertificate {\n";
3881 out << " graph [labelloc=\"t\", label=\""
3883 out << " node [shape=circle, fontname=\"Helvetica\"];\n";
3884 out << " edge [fontname=\"Helvetica\"];\n";
3885
3886 for (size_t i = 0; i < nodes.size(); ++i)
3887 {
3888 out << " n" << i << " [label=\"n" << i << "\\n"
3889 << planarity_detail::dot_escape_string(node_label(nodes[i])) << "\"";
3890 if (branch_ids.contains(i))
3891 out << ", style=\"filled\", fillcolor=\"#fff3bf\"";
3892 out << "];\n";
3893 }
3894
3895 for (size_t i = 0; i < result.certificate_obstruction_edges.size(); ++i)
3896 {
3897 const auto &e = result.certificate_obstruction_edges[i];
3898 if (e.src == nullptr or e.tgt == nullptr or not node_to_id.contains(e.src) or
3899 not node_to_id.contains(e.tgt))
3900 continue;
3901 const size_t u = node_to_id.find(e.src);
3902 const size_t v = node_to_id.find(e.tgt);
3903 out << " n" << u << " -- n" << v << " [color=\"#d00000\", penwidth=2.2, label=\"obs x"
3904 << e.input_arcs.size() << "\"];\n";
3905 }
3906
3907 if (options.dot_highlight_paths)
3908 {
3909 static const char *kPalette[] = {"#0077b6", "#2a9d8f", "#6a4c93",
3910 "#ef476f", "#ff9f1c", "#588157"};
3911 constexpr size_t palette_size = sizeof(kPalette) / sizeof(kPalette[0]);
3912
3913 for (size_t pid = 0; pid < result.certificate_paths.size(); ++pid)
3914 {
3915 const auto &path = result.certificate_paths[pid];
3916 const char *color = kPalette[pid % palette_size];
3917 for (size_t k = 0; k < path.edges.size(); ++k)
3918 {
3919 const auto &e = path.edges[k];
3920 if (e.src == nullptr or e.tgt == nullptr or not node_to_id.contains(e.src) or
3921 not node_to_id.contains(e.tgt))
3922 continue;
3923 const size_t u = node_to_id.find(e.src);
3924 const size_t v = node_to_id.find(e.tgt);
3925 out << " n" << u << " -- n" << v << " [color=\"" << color
3926 << "\", style=\"dashed\", penwidth=1.4, constraint=false, label=\"p" << pid
3927 << "\"];\n";
3928 }
3929 }
3930 }
3931
3932 out << "}\n";
3933 return out.str();
3934}
3935
3943template <AlephGraph GT>
3945 const Planarity_Test_Result<GT> &result)
3946{
3947 using Node = typename GT::Node;
3948
3953 report.num_paths = result.certificate_paths.size();
3954
3955 if (not result.has_nonplanar_certificate)
3956 return report;
3957
3959 DynMapTree<Node *, size_t> node_to_id;
3961 report.num_nodes = nodes.size();
3962
3963 DynSetTree<size_t> branch_ids;
3964 for (auto it = result.certificate_branch_nodes.get_it(); it.has_curr(); it.next_ne())
3965 {
3966 Node *node = it.get_curr_ne();
3967 if (node == nullptr or not node_to_id.contains(node))
3968 {
3969 ++report.null_branch_nodes;
3970 continue;
3971 }
3972
3973 const size_t id = node_to_id.find(node);
3974 if (branch_ids.contains(id))
3975 ++report.duplicate_branch_nodes;
3976 else
3977 branch_ids.insert(id);
3978 }
3979
3980 auto make_edge_key = [&](Node *src, Node *tgt, planarity_detail::Edge_Key &key) -> bool
3981 {
3982 if (src == nullptr or tgt == nullptr)
3983 return false;
3984 if (not node_to_id.contains(src) or not node_to_id.contains(tgt))
3985 return false;
3986
3987 size_t u = node_to_id.find(src);
3988 size_t v = node_to_id.find(tgt);
3989 if (u > v)
3990 std::swap(u, v);
3991
3992 key.u = u;
3993 key.v = v;
3994 return true;
3995 };
3996
3998 for (auto it = result.certificate_obstruction_edges.get_it(); it.has_curr(); it.next_ne())
3999 {
4000 const auto &e = it.get_curr_ne();
4002 if (not make_edge_key(e.src, e.tgt, key))
4003 {
4005 continue;
4006 }
4007 obstruction_keys.insert(key);
4008 }
4009
4010 for (auto pit = result.certificate_paths.get_it(); pit.has_curr(); pit.next_ne())
4011 {
4012 const auto &path = pit.get_curr_ne();
4013
4014 for (auto nit = path.nodes.get_it(); nit.has_curr(); nit.next_ne())
4015 if (nit.get_curr_ne() == nullptr)
4016 ++report.null_path_nodes;
4017
4018 const size_t expected_nodes = path.edges.size() + (path.nodes.is_empty() ? 0 : 1);
4019 if (path.nodes.size() != expected_nodes)
4021
4022 for (size_t i = 0; i < path.edges.size(); ++i)
4023 {
4024 const auto &e = path.edges[i];
4025 if (e.src == nullptr or e.tgt == nullptr)
4026 {
4027 ++report.null_path_edge_endpoints;
4028 continue;
4029 }
4030
4031 if (i + 1 >= path.nodes.size() or path.nodes[i] != e.src or path.nodes[i + 1] != e.tgt)
4033
4035 if (not make_edge_key(e.src, e.tgt, key))
4036 {
4037 ++report.null_path_edge_endpoints;
4038 continue;
4039 }
4040
4041 if (not obstruction_keys.contains(key))
4043 }
4044 }
4045
4049 {
4050 if (result.certificate_branch_nodes.size() != 5 or result.certificate_paths.is_empty())
4052 }
4054 {
4055 if (result.certificate_branch_nodes.size() != 6 or result.certificate_paths.is_empty())
4057 }
4058
4059 report.is_valid = report.has_certificate and report.null_branch_nodes == 0 and
4061 report.null_path_nodes == 0 and report.null_path_edge_endpoints == 0 and
4064
4065 return report;
4066}
4067
4072template <AlephGraph GT>
4077
4084template <AlephGraph GT, class Node_Label = Dft_Certificate_Node_Label<GT>>
4086 const Planarity_Test_Result<GT> &result,
4087 Node_Label node_label = Node_Label(),
4089{
4090 using Node = typename GT::Node;
4091
4093 << "nonplanar_certificate_to_graphml() requires non-planar certificate";
4094
4096 DynMapTree<Node *, size_t> node_to_id;
4098
4099 DynSetTree<size_t> branch_ids;
4100 for (auto it = result.certificate_branch_nodes.get_it(); it.has_curr(); it.next_ne())
4101 {
4102 Node *node = it.get_curr_ne();
4103 if (node != nullptr and node_to_id.contains(node))
4104 branch_ids.insert(node_to_id.find(node));
4105 }
4106
4107 auto node_ref = [&](Node *node) -> std::string
4108 {
4109 if (node == nullptr or not node_to_id.contains(node))
4110 return "";
4111 return "n" + std::to_string(node_to_id.find(node));
4112 };
4113
4114 std::ostringstream out;
4115 out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4116 out << "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\">\n";
4117 out << " <key id=\"k_node_label\" for=\"node\" attr.name=\"label\" attr.type=\"string\"/>\n";
4118 out << " <key id=\"k_node_branch\" for=\"node\" attr.name=\"branch\" attr.type=\"boolean\"/>\n";
4119 out << " <key id=\"k_node_ptr\" for=\"node\" attr.name=\"ptr\" attr.type=\"string\"/>\n";
4120 out << " <key id=\"k_edge_kind\" for=\"edge\" attr.name=\"kind\" attr.type=\"string\"/>\n";
4121 out << " <key id=\"k_edge_path_id\" for=\"edge\" attr.name=\"path_id\" attr.type=\"int\"/>\n";
4122 out << " <key id=\"k_edge_input_mult\" for=\"edge\" attr.name=\"input_multiplicity\" "
4123 "attr.type=\"int\"/>\n";
4124 out << " <graph id=\"NonPlanarCertificate\" edgedefault=\"undirected\">\n";
4125
4126 for (size_t i = 0; i < nodes.size(); ++i)
4127 {
4128 out << " <node id=\"n" << i << "\">\n";
4129 out << " <data key=\"k_node_label\">"
4130 << planarity_detail::xml_escape_string(node_label(nodes[i])) << "</data>\n";
4131 out << " <data key=\"k_node_branch\">" << (branch_ids.contains(i) ? "true" : "false")
4132 << "</data>\n";
4133 out << " <data key=\"k_node_ptr\">"
4135 << "</data>\n";
4136 out << " </node>\n";
4137 }
4138
4139 size_t edge_id = 0;
4140 for (size_t i = 0; i < result.certificate_obstruction_edges.size(); ++i)
4141 {
4142 const auto &e = result.certificate_obstruction_edges[i];
4143 const std::string u = node_ref(e.src);
4144 const std::string v = node_ref(e.tgt);
4145 if (u.empty() or v.empty())
4146 continue;
4147
4148 out << " <edge id=\"e" << edge_id++ << "\" source=\"" << u << "\" target=\"" << v << "\">\n";
4149 out << " <data key=\"k_edge_kind\">obstruction</data>\n";
4150 out << " <data key=\"k_edge_path_id\">-1</data>\n";
4151 out << " <data key=\"k_edge_input_mult\">" << e.input_arcs.size() << "</data>\n";
4152 out << " </edge>\n";
4153 }
4154
4155 if (options.graphml_include_paths)
4156 for (size_t pid = 0; pid < result.certificate_paths.size(); ++pid)
4157 {
4158 const auto &path = result.certificate_paths[pid];
4159 for (size_t k = 0; k < path.edges.size(); ++k)
4160 {
4161 const auto &e = path.edges[k];
4162 const std::string u = node_ref(e.src);
4163 const std::string v = node_ref(e.tgt);
4164 if (u.empty() or v.empty())
4165 continue;
4166
4167 out << " <edge id=\"e" << edge_id++ << "\" source=\"" << u << "\" target=\"" << v
4168 << "\">\n";
4169 out << " <data key=\"k_edge_kind\">path</data>\n";
4170 out << " <data key=\"k_edge_path_id\">" << pid << "</data>\n";
4171 out << " <data key=\"k_edge_input_mult\">" << e.input_arcs.size() << "</data>\n";
4172 out << " </edge>\n";
4173 }
4174 }
4175
4176 out << " </graph>\n";
4177 out << "</graphml>\n";
4178 return out.str();
4179}
4180
4187template <AlephGraph GT, class Node_Label = Dft_Certificate_Node_Label<GT>>
4189 const Planarity_Test_Result<GT> &result,
4190 Node_Label node_label = Node_Label(),
4192{
4193 using Node = typename GT::Node;
4194
4196 << "nonplanar_certificate_to_gexf() requires non-planar certificate";
4197
4199 DynMapTree<Node *, size_t> node_to_id;
4201
4202 DynSetTree<size_t> branch_ids;
4203 for (auto it = result.certificate_branch_nodes.get_it(); it.has_curr(); it.next_ne())
4204 {
4205 Node *node = it.get_curr_ne();
4206 if (node != nullptr and node_to_id.contains(node))
4207 branch_ids.insert(node_to_id.find(node));
4208 }
4209
4210 auto node_ref = [&](Node *node) -> std::string
4211 {
4212 if (node == nullptr or not node_to_id.contains(node))
4213 return "";
4214 return "n" + std::to_string(node_to_id.find(node));
4215 };
4216
4217 std::ostringstream out;
4218 out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
4219 out << "<gexf xmlns=\"http://www.gexf.net/1.2draft\" version=\"1.2\">\n";
4220 out << " <meta lastmodifieddate=\"2026-02-22\">\n";
4221 out << " <creator>Aleph Planarity_Test.H</creator>\n";
4222 out << " <description>Non-planar certificate</description>\n";
4223 out << " </meta>\n";
4224 out << " <graph mode=\"static\" defaultedgetype=\"undirected\">\n";
4225 out << " <attributes class=\"node\">\n";
4226 out << " <attribute id=\"n_branch\" title=\"branch\" type=\"boolean\"/>\n";
4227 out << " <attribute id=\"n_ptr\" title=\"ptr\" type=\"string\"/>\n";
4228 out << " </attributes>\n";
4229 out << " <attributes class=\"edge\">\n";
4230 out << " <attribute id=\"e_kind\" title=\"kind\" type=\"string\"/>\n";
4231 out << " <attribute id=\"e_path_id\" title=\"path_id\" type=\"integer\"/>\n";
4232 out << " <attribute id=\"e_input_mult\" title=\"input_multiplicity\" type=\"integer\"/>\n";
4233 out << " </attributes>\n";
4234 out << " <nodes>\n";
4235
4236 for (size_t i = 0; i < nodes.size(); ++i)
4237 {
4238 out << " <node id=\"n" << i << "\" label=\""
4239 << planarity_detail::xml_escape_string(node_label(nodes[i])) << "\">\n";
4240 out << " <attvalues>\n";
4241 out << " <attvalue for=\"n_branch\" value=\""
4242 << (branch_ids.contains(i) ? "true" : "false") << "\"/>\n";
4243 out << " <attvalue for=\"n_ptr\" value=\""
4245 << "\"/>\n";
4246 out << " </attvalues>\n";
4247 out << " </node>\n";
4248 }
4249
4250 out << " </nodes>\n";
4251 out << " <edges>\n";
4252
4253 size_t edge_id = 0;
4254 for (size_t i = 0; i < result.certificate_obstruction_edges.size(); ++i)
4255 {
4256 const auto &e = result.certificate_obstruction_edges[i];
4257 const std::string u = node_ref(e.src);
4258 const std::string v = node_ref(e.tgt);
4259 if (u.empty() or v.empty())
4260 continue;
4261
4262 out << " <edge id=\"e" << edge_id++ << "\" source=\"" << u << "\" target=\"" << v
4263 << "\">\n";
4264 out << " <attvalues>\n";
4265 out << " <attvalue for=\"e_kind\" value=\"obstruction\"/>\n";
4266 out << " <attvalue for=\"e_path_id\" value=\"-1\"/>\n";
4267 out << " <attvalue for=\"e_input_mult\" value=\"" << e.input_arcs.size() << "\"/>\n";
4268 out << " </attvalues>\n";
4269 out << " </edge>\n";
4270 }
4271
4272 if (options.gexf_include_paths)
4273 for (size_t pid = 0; pid < result.certificate_paths.size(); ++pid)
4274 {
4275 const auto &path = result.certificate_paths[pid];
4276 for (size_t k = 0; k < path.edges.size(); ++k)
4277 {
4278 const auto &e = path.edges[k];
4279 const std::string u = node_ref(e.src);
4280 const std::string v = node_ref(e.tgt);
4281 if (u.empty() or v.empty())
4282 continue;
4283
4284 out << " <edge id=\"e" << edge_id++ << "\" source=\"" << u << "\" target=\"" << v
4285 << "\">\n";
4286 out << " <attvalues>\n";
4287 out << " <attvalue for=\"e_kind\" value=\"path\"/>\n";
4288 out << " <attvalue for=\"e_path_id\" value=\"" << pid << "\"/>\n";
4289 out << " <attvalue for=\"e_input_mult\" value=\"" << e.input_arcs.size()
4290 << "\"/>\n";
4291 out << " </attvalues>\n";
4292 out << " </edge>\n";
4293 }
4294 }
4295
4296 out << " </edges>\n";
4297 out << " </graph>\n";
4298 out << "</gexf>\n";
4299 return out.str();
4300}
4301
4306template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
4308{
4311
4312public:
4314 : sa_(std::move(sa)), options_(std::move(options))
4315 {
4316 // empty
4317 }
4318
4320 {
4321 return planarity_test<GT, SA>(g, sa_, options_);
4322 }
4323};
4324
4329template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
4331{
4334
4335public:
4337 : sa_(std::move(sa)), options_(std::move(options))
4338 {
4339 // empty
4340 }
4341
4342 bool operator()(const GT &g) const
4343 {
4344 return is_planar_graph<GT, SA>(g, sa_, options_);
4345 }
4346};
4347} // namespace Aleph
4348
4349#endif // PLANARITY_TEST_H
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
Definition ah-errors.H:399
#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.
STL-compatible iterator adapters for Aleph containers.
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
int num_nodes
Definition btreepic.C:410
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
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void empty() noexcept
Empties the container.
Definition tpl_array.H:426
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
T & get_last()
Return a modifiable reference to the last element.
Definition tpl_array.H:483
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
Read-only view of an Aleph iterator: the iterator of a constant container.
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.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Generic key-value map implemented on top of a binary search tree.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
bool contains(const Key &key) const noexcept(nothrow_search)
Same as has().
Data & find(const Key &key)
Find the value associated with key.
Dynamic set backed by balanced binary search trees with automatic memory management.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
bool contains(const Key &key) const
Checks if a key exists in the set.
void empty()
Remove all the elements of the set.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Functor wrapper for is_planar_graph().
Is_Planar_Graph(SA sa=SA(), Planarity_Test_Options options=Planarity_Test_Options())
bool operator()(const GT &g) const
Planarity_Test_Options options_
Graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:439
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
Functor wrapper for planarity_test().
Planarity_Test_Options options_
Planarity_Test(SA sa=SA(), Planarity_Test_Options options=Planarity_Test_Options())
Planarity_Test_Result< GT > operator()(const GT &g) const
static bool classify_k5(const Array< size_t > &branches, const Array< Compressed_Path > &paths)
Orient_Frame orient_frame_of(const size_t v) const noexcept
size_t other_endpoint(const size_t edge_id, const size_t x) const
LR_Planarity_Checker(const GT &g, SA sa, Planarity_Test_Options options=Planarity_Test_Options())
bool finish_child_edge(const size_t v, const size_t first, const size_t ei)
size_t add_oriented_edge(const size_t src, const size_t tgt)
bool simple_edges_are_planar(const Array< Simple_Edge > &simple_edges) const
static void sort_by(Array< size_t > &E, const Key &key)
bool merge_child_edge(const size_t v, const size_t first, const size_t ei)
static size_t factorial_bounded(const size_t n, const size_t cap)
static std::pair< const size_t *, const size_t * > range_of(const Array< size_t > &a) noexcept
bool compute_faces_from_rotation(const Array< Array< size_t > > &order, const size_t isolated_vertices, const size_t num_components, Array< Array< size_t > > &face_idx, size_t &global_faces, const bool enforce_euler=true) const
bool conflicting(const Interval &i, const size_t edge_id) const
void fill_certificate_paths(const Array< size_t > &branches, const Array< Compressed_Path > &paths)
void finish_oriented_edge(const size_t v, const size_t e)
static size_t find_in_array(const Array< size_t > &a, const size_t value)
static bool classify_k33(const Array< size_t > &branches, const Array< Compressed_Path > &paths)
void fill_embedding_result(const Array< Array< size_t > > &order, const Array< Array< size_t > > &face_idx, const size_t global_faces, const bool is_lr_linear)
size_t find_simplified_edge_id(const size_t u, const size_t v) const
Planarity_Test_Result< GT >::Edge_Witness make_edge_witness(const size_t u, const size_t v) const
static void sort_size_t_array(Array< size_t > &a)
long lowest(const Conflict_Pair &p) const
static void generate_permutations(Array< size_t > &tail, const size_t pos, const size_t first, Array< Array< size_t > > &out)
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
static Tree_Node< int > * chain(size_t n)
__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
static constexpr size_t palette_size()
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
std::string nonplanar_certificate_to_gexf(const Planarity_Test_Result< GT > &result, Node_Label node_label=Node_Label(), const NonPlanar_Certificate_Export_Options &options=NonPlanar_Certificate_Export_Options())
Export non-planar certificate as GEXF.
Planar_Geometric_Drawing< GT > planar_geometric_drawing(const Planarity_Test_Result< GT > &result, const Planar_Geometric_Drawing_Options &options=Planar_Geometric_Drawing_Options())
Build embedding-aware 2D node coordinates from a planar result.
Planarity_Test_Result< GT > planarity_test(const GT &g, SA sa=SA(), const Planarity_Test_Options &options=Planarity_Test_Options())
Execute a comprehensive planarity test on an Aleph graph.
Planar_Dual_Metadata< GT > planar_dual_metadata(const Planarity_Test_Result< GT > &result)
Build face and dual-edge metadata from a planar embedding result.
std::string nonplanar_certificate_to_dot(const Planarity_Test_Result< GT > &result, Node_Label node_label=Node_Label(), const NonPlanar_Certificate_Export_Options &options=NonPlanar_Certificate_Export_Options())
Export non-planar certificate as GraphViz DOT.
bool is_planar_graph(const GT &g, SA sa=SA(), const Planarity_Test_Options &options=Planarity_Test_Options())
High-level boolean check for graph planarity.
DGT build_planar_dual_graph(const Planar_Dual_Metadata< GT > &md)
Build an Aleph dual graph from face/dual metadata.
std::string nonplanar_certificate_to_graphml(const Planarity_Test_Result< GT > &result, Node_Label node_label=Node_Label(), const NonPlanar_Certificate_Export_Options &options=NonPlanar_Certificate_Export_Options())
Export non-planar certificate as GraphML.
Planarity_Certificate_Type
Non-planarity witness classification.
std::string nonplanar_certificate_to_json(const Planarity_Test_Result< GT > &result, Node_Label node_label=Node_Label(), const NonPlanar_Certificate_Export_Options &options=NonPlanar_Certificate_Export_Options())
Export non-planar certificate as JSON.
NonPlanar_Certificate_Validation< GT > validate_nonplanar_certificate(const Planarity_Test_Result< GT > &result)
Validate structural consistency of a non-planar certificate.
bool nonplanar_certificate_is_valid(const Planarity_Test_Result< GT > &result)
Convenience predicate over validate_nonplanar_certificate().
static mpfr_t y
Definition mpfr_mul_d.c:3
void collect_certificate_nodes(const Planarity_Test_Result< GT > &result, Array< typename GT::Node * > &nodes, DynMapTree< typename GT::Node *, size_t > &node_to_id)
std::string json_escape_string(const std::string &s)
std::string dot_escape_string(const std::string &s)
bool pair_empty(const Conflict_Pair &p) noexcept
bool interval_empty(const Interval &i) noexcept
double orient2d(const double ax, const double ay, const double bx, const double by, const double cx, const double cy) noexcept
std::string pointer_to_string(const PtrT ptr)
bool segments_properly_intersect(const double ax, const double ay, const double bx, const double by, const double cx, const double cy, const double dx, const double dy) noexcept
std::string xml_escape_string(const std::string &s)
static constexpr size_t Null_Edge
bool bounding_boxes_intersect(const double ax, const double ay, const double bx, const double by, const double cx, const double cy, const double dx, const double dy) noexcept
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
void timsort(T *a, const size_t n, const Compare &cmp=Compare())
Timsort — adaptive, stable, natural merge sort.
and
Check uniqueness with explicit hash + equality functors.
Itor1 search(Itor1 beg, const Itor1 &end, Itor2 searchBeg, const Itor2 &searchEnd, BinaryPredicate op=BinaryPredicate())
Search for a subrange within a range.
Definition ahAlgo.H:309
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
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
static long & color(typename GT::Node *p)
STL namespace.
static struct argp_option options[]
Definition ntreepic.C:1890
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Default node labeler for certificate export.
std::string operator()(typename GT::Node *node) const
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Export options for non-planar certificate serializers.
bool dot_highlight_paths
Include path overlays in DOT output.
bool pretty_json
Pretty-print JSON with indentation/newlines.
bool gexf_include_paths
Include path overlays in GEXF output.
bool graphml_include_paths
Include path overlays in GraphML output.
Structural validation report for non-planar certificates.
Represents a missing value.
Dual-edge payload linked to a primal simplified edge.
Metadata extracted from a planar embedding for face/dual analysis.
Array< Planar_Dual_Edge_Info< GT > > dual_edges
Array< Face_Boundary > faces
Array< Array< size_t > > face_adjacency
Options for embedding-aware 2D drawing extraction.
size_t max_relaxation_iterations
Max relaxation iterations per candidate.
double outer_face_radius
Base radius for boundary-node placement on outer-face polygon.
double component_spacing
Horizontal gap between disconnected component drawings.
double relaxation_tolerance
Relaxation stop threshold in max per-node movement.
size_t preferred_outer_face
Preferred outer-face index (component-local metadata indexing).
size_t max_outer_faces_to_try
Max outer-face candidates evaluated per component.
bool validate_crossings
If true, evaluates straight-edge crossings and keeps best candidate.
Embedding-aware geometric drawing result.
Array< Node_Position > node_positions
Configuration options for planarity testing and auxiliary outputs.
size_t certificate_max_branch_nodes_search
Maximum size of the core subgraph allowed for exhaustive Kuratowski pattern searching.
bool embedding_prefer_lr_linear
If true, the embedding is that of the embedding phase of the Left-Right (LR) algorithm,...
size_t certificate_max_reduction_passes
Maximum number of global passes in the edge-reduction loop for minimal obstruction extraction.
size_t certificate_max_edges
Maximum number of edges in the simplified graph allowed for full non-planarity witness extraction.
bool embedding_allow_bruteforce_fallback
Allows an exact but potentially exponential-time search when the LR embedding is not preferred,...
bool compute_embedding
If true and the graph is found to be planar, computes a combinatorial embedding (rotation system and ...
bool embedding_validate_with_euler
If true, validates the generated rotation system using Euler's formula ( ) to ensure it is a valid pl...
size_t embedding_max_combinations
Maximum number of candidate rotations to evaluate during embedding search or repair.
bool compute_nonplanar_certificate
If true and the graph is found to be non-planar, attempts to extract a Kuratowski subdivision (K5 or ...
Description of an edge participating in a witness.
Node * src
Source node in primal graph.
Array< Arc * > input_arcs
All primal arcs matching this edge.
Node * tgt
Target node in primal graph.
Arc * representative_input_arc
One arc from primal matching this edge.
Description of a path participating in a Kuratowski witness.
Array< Node * > nodes
Nodes along the path (including endpoints).
Array< Edge_Witness > edges
Sequential edges along the path.
Entry in a combinatorial rotation system.
Array< Node * > cw_neighbors
Neighbors in clockwise order.
Node * node
Primal graph node.
Complete result of a planarity test execution.
Planarity_Certificate_Type certificate_type
Array< Rotation_Entry > embedding_rotation
Full rotation system.
Array< Array< Node * > > embedding_faces
Lists of nodes forming each face.
size_t embedding_num_faces
Total number of faces found.
size_t num_nodes
Original number of nodes in the graph.
size_t simplified_num_nodes
Nodes in simple undirected representation.
size_t num_input_arcs
Number of arcs passing the SA filter.
Array< Node * > certificate_branch_nodes
Branch nodes for Kuratowski witness.
size_t simplified_num_edges
Edges in simple undirected representation.
bool has_nonplanar_certificate
True if witness was extracted.
size_t ignored_parallel_arcs
Count of parallel arcs collapsed.
bool failed_euler_bound
True if rejected by Euler necessary condition ( ).
bool certificate_search_truncated
True if search limit was reached.
Array< Edge_Witness > certificate_obstruction_edges
Edges in minimal obstruction.
bool is_planar
True iff the graph can be drawn without crossings.
bool embedding_search_truncated
True if search limit was reached.
bool input_is_digraph
True if the input was a directed graph.
size_t ignored_loops
Count of self-loops filtered out.
bool embedding_is_lr_linear
True if the embedding is that of the LR algorithm.
Array< Path_Witness > certificate_paths
Paths connecting branch nodes.
bool has_combinatorial_embedding
True if embedding is valid.
bool operator==(const Conflict_Pair &other) const noexcept=default
bool operator<(const Dart_Key &other) const noexcept
bool operator<(const Edge_Key &other) const noexcept
bool operator==(const Interval &other) const noexcept=default
TestDigraph::Node * add_node(TestDigraph &g, int value)
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Dynamic array container with automatic resizing.
Stack of the frames of a depth-first search that does not recurse.
Dynamic key-value map based on balanced binary search trees.
Dynamic set implementations based on balanced binary search trees.
Generic graph and digraph implementations.
Comprehensive sorting algorithms and search utilities for Aleph-w.