92#ifndef PLANARITY_TEST_H
93#define PLANARITY_TEST_H
138 return "K5_Subdivision";
140 return "K33_Subdivision";
142 return "Minimal_NonPlanar_Obstruction";
221template <AlephGraph GT>
286template <AlephGraph GT>
304template <AlephGraph GT>
366template <AlephGraph GT>
414template <AlephGraph GT>
447 std::ostringstream
out;
457namespace planarity_detail {
459static constexpr size_t Null_Edge = std::numeric_limits<size_t>::max();
532 std::ostringstream
out;
533 for (
const char i : s)
534 switch (
const auto c =
static_cast<unsigned char>(i))
561 const char *hex =
"0123456789abcdef";
562 out << hex[(c >> 4) & 0xF] << hex[c & 0xF];
565 out << static_cast<char>(c);
574 std::ostringstream
out;
575 for (
const char c : s)
576 if (c ==
'\"' or c ==
'\\')
587 std::ostringstream
out;
588 for (
const char i : s)
589 switch (
const auto c =
static_cast<unsigned char>(i))
607 if (c < 0x20
and c !=
'\n' and c !=
'\r' and c !=
'\t')
609 const char *hex =
"0123456789ABCDEF";
611 out << hex[(c >> 4) & 0xF] << hex[c & 0xF] <<
";";
614 out << static_cast<char>(c);
623 std::ostringstream
out;
628template <AlephGraph GT>
640 if (node ==
nullptr or node_to_id.
contains(node))
642 const size_t id =
nodes.size();
643 node_to_id.
insert(node,
id);
656 for (
auto pit = result.
certificate_paths.get_it(); pit.has_curr(); pit.next_ne())
658 const auto &path = pit.get_curr_ne();
659 for (
auto nit = path.nodes.get_it(); nit.has_curr(); nit.next_ne())
662 for (
auto eit = path.edges.get_it(); eit.has_curr(); eit.next_ne())
675 const double cy)
noexcept
677 return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
687 const double dy)
noexcept
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);
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);
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;
710 const double dy)
noexcept
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);
722 return (o1 * o2 < -eps)
and (o3 * o4 < -eps);
725template <AlephGraph GT, ArcFilter<GT> SA>
786 return e.
u == x ? e.
v : e.
u;
791 for (
size_t i = 1; i < a.
size(); ++i)
793 const size_t key = a[i];
795 while (j > 0
and key < a[j - 1])
813 for (
size_t i = 2; i <= n; ++i)
825 if (
result_.simplified_num_nodes == 0)
831 for (
size_t s = 0; s <
result_.simplified_num_nodes; ++s)
846 for (
auto it =
incident_edges_[v].get_it(); it.has_curr(); it.next_ne())
848 const size_t eid = it.get_curr_ne();
864 for (
size_t i = 0; i < a.
size(); ++i)
876 if (pos >= tail.
size())
881 for (
unsigned long i : tail)
883 out.append(std::move(order));
887 for (
size_t i = pos; i < tail.
size(); ++i)
889 std::swap(tail[pos], tail[i]);
891 std::swap(tail[pos], tail[i]);
896 const size_t isolated_vertices,
897 const size_t num_components,
899 size_t &global_faces,
900 const bool enforce_euler =
true)
const
909 for (
auto it =
edges_.get_it(); it.has_curr(); it.next_ne())
912 const size_t d1 = dart_src.
size();
924 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
926 const auto &ord = order[v];
930 for (
size_t i = 0; i < ord.size(); ++i)
932 const size_t to = ord[i];
933 const size_t next = ord[(i + 1) % ord.size()];
941 for (
const unsigned long d : sigma)
948 size_t local_faces = 0;
949 for (
size_t d = 0; d < dart_src.
size(); ++d)
965 face_idx.
append(std::move(f));
968 global_faces = local_faces + isolated_vertices - (num_components == 0 ? 0 : (num_components - 1));
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);
976 const long long rhs =
static_cast<long long>(num_components) + 1;
983 const size_t global_faces,
984 const bool is_lr_linear)
986 result_.has_combinatorial_embedding =
true;
987 result_.embedding_is_lr_linear = is_lr_linear;
988 result_.embedding_num_faces = global_faces;
990 result_.embedding_rotation.empty();
992 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
997 const auto &ord = order[v];
999 for (
auto it = ord.get_it(); it.has_curr(); it.next_ne())
1002 result_.embedding_rotation.append(std::move(re));
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())
1009 const auto &f = fit.get_curr_ne();
1012 for (
auto it = f.get_it(); it.has_curr(); it.next_ne())
1014 result_.embedding_faces.append(std::move(mapped));
1017 while (
result_.embedding_faces.size() <
result_.embedding_num_faces)
1033 if (left_empty
and right_empty)
1034 return std::numeric_limits<long>::max();
1046 [[gnu::always_inline]]
1068 static std::pair<const size_t *, const size_t *>
1072 return {
nullptr,
nullptr};
1074 const size_t *first = &a.base();
1075 return {first, first + a.size()};
1108 const size_t v = f.
v;
1115 bool descends =
false;
1118 const size_t uedge = *f.
next++;
1153 template <
class Key>
1156 timsort(E, [&key](
const size_t x,
const size_t y) {
return key(x) < key(
y); });
1170 [[gnu::always_inline]]
1199 (void)
stack_.remove_last();
1229 (void)
stack_.remove_last();
1307 const size_t h_left = top.
left.
high;
1348 const size_t v = f.
v;
1351 const size_t ei = *f.
next;
1387 if (
result_.simplified_num_edges == 0)
1391 size_t next_comp = 0;
1393 for (
size_t s = 0; s <
result_.simplified_num_nodes; ++s)
1395 if (comp_id[s] != -1)
1400 comp_id[s] =
static_cast<long>(next_comp);
1402 size_t num_vertices = 0;
1403 size_t degree_sum = 0;
1411 for (
auto it =
incident_edges_[v].get_it(); it.has_curr(); it.next_ne())
1413 const size_t uedge = it.get_curr_ne();
1415 if (comp_id[
w] != -1)
1418 comp_id[
w] =
static_cast<long>(next_comp);
1423 const size_t num_edges = degree_sum / 2;
1424 if (num_vertices >= 3
and num_edges > 3 * num_vertices - 6)
1441 Node *node = it.get_curr_ne();
1448 for (
size_t i = 0; i <
result_.num_nodes; ++i)
1460 Arc *arc = it.get_curr_ne();
1470 const size_t u = std::min(src, tgt);
1471 const size_t v = std::max(src, tgt);
1476 ++
result_.ignored_parallel_arcs;
1477 const size_t eid = edge_to_idx.
find(key);
1483 const size_t eid =
edges_.size();
1484 edge_to_idx.
insert(key, eid);
1499 if (
result_.simplified_num_edges == 0)
1507 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
1517 for (
auto it =
roots_.
get_it(); it.has_curr(); it.next_ne())
1519 const size_t root = it.get_curr_ne();
1536 static_cast<typename Tmp_Graph::Node *
>(
nullptr));
1538 for (
size_t i = 0; i <
result_.simplified_num_nodes; ++i)
1539 tmp_nodes[i] = tg.insert_node(i);
1541 for (
auto it = simple_edges.
get_it(); it.has_curr(); it.next_ne())
1544 tg.insert_arc(tmp_nodes[e.
u], tmp_nodes[e.
v], 1);
1557 return checker.
run().is_planar;
1562 if (branches.
size() != 5 or paths.
size() != 10)
1567 for (
size_t i = 0; i < 5; ++i)
1570 Array<size_t> deg(
static_cast<size_t>(5),
static_cast<size_t>(0));
1572 for (
auto it = paths.
get_it(); it.has_curr(); it.next_ne())
1589 for (
size_t i = 0; i < 5; ++i)
1594 for (
size_t j = i + 1; j < 5; ++j)
1604 if (branches.
size() != 6 or paths.
size() != 9)
1609 for (
size_t i = 0; i < 6; ++i)
1614 for (
size_t i = 0; i < 6; ++i)
1617 Array<size_t> deg(
static_cast<size_t>(6),
static_cast<size_t>(0));
1619 for (
auto it = paths.
get_it(); it.has_curr(); it.next_ne())
1638 for (
size_t i = 0; i < 6; ++i)
1643 for (
size_t s = 0; s < 6; ++s)
1655 for (
auto it = adj[u].get_it(); it.has_curr(); it.next_ne())
1657 const size_t v = it.get_curr_ne();
1669 size_t left_count = 0;
1670 size_t right_count = 0;
1671 for (
size_t i = 0; i < 6; ++i)
1677 if (left_count != 3 or right_count != 3)
1680 for (
size_t i = 0; i < 6; ++i)
1681 for (
size_t j = i + 1; j < 6; ++j)
1695 const size_t a = std::min(u, v);
1696 const size_t b = std::max(u, v);
1698 for (
size_t i = 0; i <
edges_.size(); ++i)
1706 const size_t v)
const
1719 if (not
arcs.is_empty())
1720 w.representative_input_arc =
arcs[0];
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());
1731 result_.certificate_branch_nodes.empty();
1732 result_.certificate_paths.empty();
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()]);
1739 for (
auto it = paths.
get_it(); it.has_curr(); it.next_ne())
1744 for (
auto pit = p.
nodes.
get_it(); pit.has_curr(); pit.next_ne())
1750 for (
size_t i = 1; i < p.
nodes.
size(); ++i)
1754 result_.certificate_paths.append(std::move(witness));
1768 result_.certificate_search_truncated =
true;
1775 result_.certificate_search_truncated =
true;
1778 size_t pass_count = 0;
1782 bool changed =
false;
1785 while (i < witness.
size())
1789 for (
size_t j = 0; j < witness.
size(); ++j)
1791 trial.
append(witness[j]);
1797 witness = std::move(trial);
1803 for (
auto it = witness.
get_it(); it.has_curr(); it.next_ne())
1805 const auto &e = it.get_curr_ne();
1811 while (v <
result_.simplified_num_nodes)
1821 for (
auto it = witness.
get_it(); it.has_curr(); it.next_ne())
1823 const auto &e = it.get_curr_ne();
1824 if (e.u == v or e.v == v)
1829 if (trial.
size() == witness.
size())
1839 witness = std::move(trial);
1843 for (
auto wit = witness.
get_it(); wit.has_curr(); wit.next_ne())
1845 const auto &e = wit.get_curr_ne();
1859 result_.certificate_search_truncated =
true;
1865 result_.has_nonplanar_certificate =
true;
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())
1879 for (
size_t i = 0; i <
result_.simplified_num_nodes; ++i)
1882 for (
size_t i = 0; i < witness.
size(); ++i)
1884 const auto &e = witness[i];
1892 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
1893 if (degree[v] > 0
and degree[v] != 2)
1896 if (branches.
size() < 5)
1901 result_.certificate_search_truncated =
true;
1906 for (
auto it = branches.
get_it(); it.has_curr(); it.next_ne())
1907 is_branch[it.get_curr_ne()] = 1;
1912 for (
auto bit = branches.
get_it(); bit.has_curr(); bit.next_ne())
1914 const size_t b = bit.get_curr_ne();
1916 for (
auto eit = inc[b].get_it(); eit.has_curr(); eit.next_ne())
1918 const size_t first_edge = eit.get_curr_ne();
1919 if (used[first_edge])
1922 used[first_edge] = 1;
1928 size_t curr = witness[first_edge].u == b ? witness[first_edge].v : witness[first_edge].u;
1929 size_t prev_edge = first_edge;
1932 while (curr <
result_.simplified_num_nodes
and not is_branch[curr])
1936 if (inc[curr].
size() != 2)
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;
1943 if (used[next_edge])
1946 used[next_edge] = 1;
1947 prev_edge = next_edge;
1949 const auto &ne = witness[next_edge];
1950 curr = ne.u == curr ? ne.v : ne.u;
1953 if (guard > witness.
size())
1963 paths.
append(std::move(p));
1970 const size_t bcount = branches.
size();
1973 for (
size_t i = 0; i < bcount; ++i)
1976 for (
size_t i = 0; i < paths.
size(); ++i)
1984 if (first_path[iu][iv] == -1)
1986 first_path[iu][iv] =
static_cast<long>(i);
1987 first_path[iv][iu] =
static_cast<long>(i);
1991 auto has_pair = [&](
const size_t a,
const size_t b) ->
bool
1993 return first_path[a][b] != -1;
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)
2004 const size_t idx[5] = {a, b, c, d, e};
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]))
2016 for (
unsigned long i : idx)
2017 chosen_branches.
append(branches[i]);
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]])]);
2025 if (not
classify_k5(chosen_branches, chosen_paths))
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)
2043 const size_t six[6] = {a, b, c, d, e, f};
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}};
2049 for (
const auto &part : partitions)
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;
2060 for (
size_t i = 0; i < 6; ++i)
2062 left[li++] = six[i];
2064 right[ri++] = six[i];
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))
2077 for (
unsigned long i : left)
2078 chosen_branches.
append(branches[i]);
2079 for (
unsigned long i : right)
2080 chosen_branches.
append(branches[i]);
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])]);
2101 if (
result_.simplified_num_nodes == 0)
2103 result_.has_combinatorial_embedding =
true;
2104 result_.embedding_is_lr_linear =
true;
2105 result_.embedding_num_faces = 0;
2111 for (
size_t i = 0; i <
result_.simplified_num_nodes; ++i)
2114 if (
result_.simplified_num_edges == 0)
2117 size_t global_faces = 0;
2119 result_.simplified_num_nodes, faces, global_faces))
2141 auto sign_of = [&](
const size_t e) ->
long
2143 for (
size_t x = e; vis[x] == 0; x =
ref_[x])
2151 while (not
chain.is_empty())
2153 const size_t y =
chain.remove_last();
2155 final_side[
y] *= final_side[
ref_[
y]];
2159 return final_side[e];
2165 const long s = sign_of(e);
2185 auto put_after = [&](
const size_t v,
const size_t h,
const size_t ref)
2194 const size_t next = cw[ref];
2202 auto put_before = [&](
const size_t v,
const size_t h,
const size_t ref)
2206 put_after(v,
h, ref);
2210 put_after(v,
h, ccw[ref]);
2211 if (ref == first[v])
2222 for (
size_t i = 0; i < E.size(); ++i)
2224 put_after(v, 2 * E[i], prev);
2242 for (
auto rit =
roots_.
get_it(); rit.has_curr(); rit.next_ne())
2244 const size_t root = rit.get_curr_ne();
2246 frames.
push(Embed_Frame{
root, root_first, root_end});
2249 Embed_Frame &f = frames.
top();
2250 if (f.next == f.end)
2256 const size_t v = f.v;
2257 const size_t e = *f.next++;
2261 put_before(
w, 2 * e + 1, first[
w]);
2262 left_ref[v] = right_ref[v] = 2 * e;
2264 frames.
push(Embed_Frame{
w, w_first, w_end});
2266 else if (final_side[e] > 0)
2267 put_after(
w, 2 * e + 1, right_ref[
w]);
2270 put_before(
w, 2 * e + 1, left_ref[
w]);
2271 left_ref[
w] = 2 * e + 1;
2276 size_t isolated_vertices = 0;
2281 ++isolated_vertices;
2285 auto &ord = order[v];
2287 size_t h = first[v];
2290 const size_t e =
h / 2;
2294 while (
h != first[v]);
2300 size_t global_faces = 0;
2310 result_.embedding_search_truncated =
true;
2316 if (ord.size() <= 1)
2320 size_t j = ord.size() - 1;
2323 std::swap(ord[i], ord[j]);
2331 if (a.
size() != b.size())
2334 for (
size_t i = 0; i < a.
size(); ++i)
2343 for (
auto it = opts.
get_it(); it.has_curr(); it.next_ne())
2344 if (same_order(it.get_curr_ne(), cand))
2355 for (
size_t i = 0; i + 1 < src.size(); ++i)
2358 std::swap(cand[i], cand[i + 1]);
2359 append_unique_order(opts, cand);
2368 for (
size_t i = 0; i + 1 < src.size(); ++i)
2369 for (
size_t j = i + 1; j < src.size(); ++j)
2372 std::swap(cand[i], cand[j]);
2373 append_unique_order(opts, cand);
2380 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
2385 if (order[v].
size() >= 2)
2389 append_unique_order(opts, rev);
2391 add_adjacent_swaps(opts, order[v]);
2392 add_adjacent_swaps(opts, rev);
2396 if (order[v].
size() <= 5)
2398 add_pair_swaps(opts, order[v]);
2399 add_pair_swaps(opts, rev);
2403 repair_options.
append(std::move(opts));
2408 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
2409 if (repair_options[v].
size() > 1)
2415 for (
size_t i = 1; i < vars.
size(); ++i)
2417 const size_t key = vars[i];
2419 while (j > 0
and repair_options[key].
size() > repair_options[vars[j - 1]].
size())
2421 vars[j] = vars[j - 1];
2427 struct Repair_Quality
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;
2436 size_t evaluated = 0;
2437 bool truncated =
false;
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]]);
2447 auto materialize_embedding = [&](
const Array<size_t> &sel) ->
bool
2450 build_candidate_order(sel, candidate);
2453 size_t global_faces = 0;
2462 auto evaluate_quality = [&](
const Array<size_t> &sel, Repair_Quality &
out) ->
bool
2473 build_candidate_order(sel, candidate);
2476 size_t global_faces = 0;
2478 global_faces,
false))
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;
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;
2491 long long delta = lhs - rhs;
2495 out.available =
true;
2497 out.abs_euler_delta = delta;
2498 out.global_faces = global_faces;
2502 auto run_coordinate_descent = [&](
const Array<size_t> &seed_selected) ->
bool
2504 selected = seed_selected;
2506 Repair_Quality current_quality;
2507 if (not evaluate_quality(selected, current_quality))
2510 if (current_quality.valid_embedding
and materialize_embedding(selected))
2513 const size_t max_passes = vars.
size() == 0 ? 0 : 2 * vars.
size();
2514 bool budget_hit =
false;
2516 for (
size_t pass = 0; pass < max_passes; ++pass)
2518 bool improved =
false;
2520 for (
auto vit = vars.
get_it(); vit.has_curr(); vit.next_ne())
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;
2527 for (
size_t i = 0; i < repair_options[v].
size(); ++i)
2533 Repair_Quality cand_quality;
2534 if (not evaluate_quality(selected, cand_quality))
2540 if (not cand_quality.available)
2543 if (cand_quality.valid_embedding
and materialize_embedding(selected))
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))
2551 best_quality = cand_quality;
2558 selected[v] = best_opt;
2559 if (best_opt != prev_opt)
2561 current_quality = best_quality;
2566 if (budget_hit or not improved)
2574 if (run_coordinate_descent(base_seed))
2579 result_.embedding_search_truncated =
true;
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)
2588 reverse_seed[v] = 1;
2589 has_reverse_seed =
true;
2592 if (has_reverse_seed
and run_coordinate_descent(reverse_seed))
2597 result_.embedding_search_truncated =
true;
2601 for (
auto vit = vars.
get_it(); vit.has_curr(); vit.next_ne())
2603 const size_t v = vit.get_curr_ne();
2604 for (
size_t i = 1; i < repair_options[v].
size(); ++i)
2608 if (run_coordinate_descent(
seed))
2613 result_.embedding_search_truncated =
true;
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)
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)
2631 if (run_coordinate_descent(
seed))
2636 result_.embedding_search_truncated =
true;
2643 result_.embedding_search_truncated =
true;
2650 if (
result_.simplified_num_nodes == 0)
2652 result_.has_combinatorial_embedding =
true;
2653 result_.embedding_is_lr_linear =
false;
2654 result_.embedding_num_faces = 0;
2661 size_t isolated_vertices = 0;
2662 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
2666 for (
auto it =
incident_edges_[v].get_it(); it.has_curr(); it.next_ne())
2671 ++isolated_vertices;
2673 neighbors.
append(std::move(ng));
2676 if (
result_.simplified_num_edges == 0)
2680 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
2683 const size_t num_components =
result_.simplified_num_nodes;
2685 size_t global_faces = 0;
2697 result_.embedding_search_truncated =
true;
2704 size_t combinations = 1;
2705 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
2707 const auto &neigh = neighbors[v];
2708 const size_t d = neigh.
size();
2719 result_.embedding_search_truncated =
true;
2723 combinations *= cnt;
2725 const size_t first = neigh[0];
2728 for (
size_t i = 1; i < d; ++i)
2734 order_options.
append(std::move(opts));
2739 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
2740 if (order_options[v].
size() > 1)
2743 for (
size_t i = 1; i < vars.
size(); ++i)
2745 const size_t key = vars[i];
2747 while (j > 0
and order_options[key].
size() > order_options[vars[j - 1]].
size())
2749 vars[j] = vars[j - 1];
2758 auto evaluate = [&]() ->
bool
2762 for (
size_t v = 0; v <
result_.simplified_num_nodes; ++v)
2763 order.
append(order_options[v][selected[v]]);
2766 size_t global_faces = 0;
2775 auto search = [&](
auto &&self,
const size_t pos) ->
bool
2777 if (pos == vars.
size())
2780 const size_t v = vars[pos];
2781 for (
size_t i = 0; i < order_options[v].
size(); ++i)
2784 if (self(self, pos + 1))
2801 result_.embedding_search_truncated =
true;
2822 result_.failed_euler_bound =
true;
2836 result_.embedding_search_truncated =
false;
2842 result_.certificate_search_truncated =
false;
2878template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
2891template <AlephGraph GT>
2908template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
2920template <AlephGraph GT>
2932template <AlephGraph GT>
2940 <<
"planar_dual_metadata() requires a planar result with embedding";
2961 for (
size_t i = 0; i < n; ++i)
2966 <<
"embedding_rotation contains duplicated node pointer";
2968 node_to_idx.
insert(node, i);
2969 idx_to_node.
append(node);
2974 for (
size_t i = 0; i < n; ++i)
2977 for (
size_t i = 0; i < n; ++i)
2983 Node *neigh = it.get_curr_ne();
2986 <<
"embedding_rotation references unknown neighbor node";
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";
2999 size_t num_components = 0;
3000 size_t isolated_vertices = 0;
3002 for (
size_t s = 0; s < n; ++s)
3004 if (order[s].is_empty())
3005 ++isolated_vertices;
3007 if (comp_id[s] != -1)
3010 comp_id[s] =
static_cast<long>(num_components);
3017 for (
auto it = order[u].get_it(); it.has_curr(); it.next_ne())
3019 const size_t v = it.get_curr_ne();
3020 if (comp_id[v] != -1)
3022 comp_id[v] =
static_cast<long>(num_components);
3038 for (
size_t u = 0; u < n; ++u)
3040 for (
auto it = order[u].get_it(); it.has_curr(); it.next_ne())
3042 const size_t v = it.get_curr_ne();
3043 const Dart_Key key{u, v};
3045 <<
"embedding rotation contains repeated directed edge";
3047 const size_t did = dart_src.
size();
3048 dart_id.
insert(key, did);
3057 for (
size_t d = 0; d < dart_src.
size(); ++d)
3059 const Dart_Key rev{dart_tgt[d], dart_src[d]};
3061 alpha[d] = dart_id.
find(rev);
3065 for (
size_t u = 0; u < n; ++u)
3067 const auto &ord = order[u];
3071 for (
size_t i = 0; i < ord.size(); ++i)
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});
3081 for (
unsigned long d : sigma)
3085 for (
size_t d = 0; d < dart_src.
size(); ++d)
3087 if (face_of_dart[d] != Null_Edge)
3090 const size_t fid = md.
faces.size();
3094 while (face_of_dart[x] == Null_Edge)
3096 face_of_dart[x] = fid;
3099 fd.
src = idx_to_node[dart_src[x]];
3100 fd.
tgt = idx_to_node[dart_tgt[x]];
3101 face.
darts.append(fd);
3103 x = sigma[alpha[x]];
3106 md.
faces.append(std::move(face));
3109 for (
size_t i = 0; i < isolated_vertices; ++i)
3114 const size_t m = dart_src.
size() / 2;
3115 const size_t num_faces_global =
m - n + num_components + 1;
3124 for (
size_t d = 0; d < dart_src.
size(); ++d)
3126 const size_t rev = alpha[d];
3130 const size_t f0 = face_of_dart[d];
3131 const size_t f1 = face_of_dart[rev];
3147 for (
size_t i = 1; i < adj.size(); ++i)
3149 const size_t key = adj[i];
3151 while (j > 0
and key < adj[j - 1])
3153 adj[j] = adj[j - 1];
3165 for (
size_t i = 1; i < adj.size(); ++i)
3169 adj = std::move(uniq);
3179template <AlephGraph GT,
class DGT = Default_Planar_Dual_Graph<GT>>
3183 <<
"build_planar_dual_graph() requires metadata with embedding";
3190 face_nodes.
append(dual.insert_node(f));
3192 for (
auto it = md.
dual_edges.get_it(); it.has_curr(); it.next_ne())
3194 const auto &e = it.get_curr_ne();
3195 dual.insert_arc(face_nodes[e.face_a], face_nodes[e.face_b], e);
3205template <AlephGraph GT,
class DGT = Default_Planar_Dual_Graph<GT>>
3222template <AlephGraph GT>
3230 constexpr size_t Null = std::numeric_limits<size_t>::max();
3231 constexpr double Pi = 3.1415926535897932384626433832795;
3234 <<
"planar_geometric_drawing() requires a planar result with embedding";
3249 if (
options.max_outer_faces_to_try == 0)
3259 for (
size_t i = 0; i < n; ++i)
3264 <<
"embedding_rotation contains duplicated node pointer";
3266 node_to_idx.
insert(node, i);
3267 idx_to_node.
append(node);
3272 for (
size_t i = 0; i < n; ++i)
3275 for (
size_t i = 0; i < n; ++i)
3281 Node *neigh = it.get_curr_ne();
3284 <<
"embedding_rotation references unknown node";
3286 const size_t v = node_to_idx.
find(neigh);
3296 size_t num_components = 0;
3297 for (
size_t s = 0; s < n; ++s)
3299 if (comp_id[s] != -1)
3302 comp_id[s] =
static_cast<long>(num_components);
3309 for (
auto it = order[u].get_it(); it.has_curr(); it.next_ne())
3311 const size_t v = it.get_curr_ne();
3312 if (comp_id[v] != -1)
3314 comp_id[v] =
static_cast<long>(num_components);
3325 comp_nodes.
reserve(num_components);
3326 for (
size_t c = 0; c < num_components; ++c)
3328 for (
size_t i = 0; i < n; ++i)
3329 comp_nodes[
static_cast<size_t>(comp_id[i])].
append(i);
3340 for (
size_t u = 0; u < n; ++u)
3341 for (
auto it = order[u].get_it(); it.has_curr(); it.next_ne())
3343 const size_t v = it.get_curr_ne();
3345 edges.
append(Drawing_Edge{u, v,
static_cast<size_t>(comp_id[u])});
3349 comp_edge_ids.
reserve(num_components);
3350 for (
size_t c = 0; c < num_components; ++c)
3352 for (
size_t i = 0; i < edges.
size(); ++i)
3353 comp_edge_ids[edges[i].comp].append(i);
3356 struct Face_Candidate
3358 size_t face_id = Null;
3365 face_candidates.
reserve(md.faces.size());
3367 for (
size_t fid = 0; fid < md.faces.size(); ++fid)
3369 const auto &face = md.faces[fid];
3370 if (face.darts.is_empty())
3374 raw.
reserve(face.darts.size());
3375 for (
auto it = face.darts.get_it(); it.has_curr(); it.next_ne())
3377 const auto &d = it.get_curr_ne();
3379 <<
"face metadata references unknown node";
3388 for (
unsigned long i : raw)
3398 for (
auto it = cleaned.
get_it(); it.has_curr(); it.next_ne())
3400 const size_t u = it.get_curr_ne();
3410 Face_Candidate cand;
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));
3419 comp_faces.
reserve(num_components);
3420 for (
size_t c = 0; c < num_components; ++c)
3423 for (
size_t i = 0; i < face_candidates.
size(); ++i)
3424 comp_faces[face_candidates[i].comp].append(i);
3426 for (
size_t c = 0; c < num_components; ++c)
3428 auto &faces = comp_faces[c];
3429 for (
size_t i = 1; i < faces.size(); ++i)
3431 const size_t key = faces[i];
3433 while (j > 0
and face_candidates[key].score > face_candidates[faces[j - 1]].score)
3435 faces[j] = faces[j - 1];
3442 auto count_crossings = [&](
const size_t comp,
const Array<double> &px,
3446 const auto &ce = comp_edge_ids[comp];
3447 for (
size_t i = 0; i < ce.size(); ++i)
3449 const auto &e1 = edges[ce[i]];
3450 for (
size_t j = i + 1; j < ce.size(); ++j)
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)
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]))
3464 auto build_component_layout = [&](
const size_t comp,
const Array<size_t> &boundary,
3467 const auto &cnodes = comp_nodes[comp];
3470 for (
auto it = cnodes.get_it(); it.has_curr(); it.next_ne())
3472 const size_t u = it.get_curr_ne();
3478 if (use_boundary.
size() < 3
and cnodes.size() >= 1)
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());
3485 const double scale = std::max(1.0, std::sqrt(
static_cast<double>(cnodes.size())));
3486 const double radius =
options.outer_face_radius * scale;
3494 for (
size_t i = 0; i < use_boundary.
size(); ++i)
3496 const size_t u = use_boundary[i];
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);
3504 for (
auto it = cnodes.get_it(); it.has_curr(); it.next_ne())
3506 const size_t u = it.get_curr_ne();
3513 for (
auto nt = order[u].get_it(); nt.has_curr(); nt.next_ne())
3515 const size_t v = nt.get_curr_ne();
3516 if (comp_id[v] !=
static_cast<long>(comp))
3525 px[u] = 0.01 *
static_cast<double>(u + 1);
3526 py[u] = -0.01 *
static_cast<double>(u + 1);
3530 px[u] = sx /
static_cast<double>(cnt);
3531 py[u] = sy /
static_cast<double>(cnt);
3536 for (
size_t iter = 0; iter <
options.max_relaxation_iterations; ++iter)
3539 double max_delta = 0;
3541 for (
auto it = cnodes.get_it(); it.has_curr(); it.next_ne())
3543 const size_t u = it.get_curr_ne();
3550 for (
auto nt = order[u].get_it(); nt.has_curr(); nt.next_ne())
3552 const size_t v = nt.get_curr_ne();
3553 if (comp_id[v] !=
static_cast<long>(comp))
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)
3575 if (max_delta <=
options.relaxation_tolerance)
3582 double offset_x = 0.0;
3584 for (
size_t c = 0; c < num_components; ++c)
3588 if (
options.preferred_outer_face != Null
and options.preferred_outer_face < md.faces.size())
3590 for (
size_t i = 0; i < candidates.
size(); ++i)
3591 if (face_candidates[candidates[i]].face_id ==
options.preferred_outer_face)
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;
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;
3609 auto evaluate_boundary = [&](
const Array<size_t> &boundary,
const size_t face_id) ->
bool
3611 if (num_candidate_evals >=
options.max_outer_faces_to_try)
3617 ++num_candidate_evals;
3622 build_component_layout(c, boundary, cx, cy, iters);
3624 const size_t crossings =
options.validate_crossings ? count_crossings(c, cx, cy) : 0;
3626 if (not has_best or crossings < best_crossings or
3627 (crossings == best_crossings
and iters < best_iters))
3630 best_crossings = crossings;
3632 best_face_id = face_id;
3633 best_x = std::move(cx);
3634 best_y = std::move(cy);
3637 return crossings == 0;
3640 for (
auto fit = candidates.
get_it(); fit.has_curr(); fit.next_ne())
3642 const size_t idx = fit.get_curr_ne();
3643 if (evaluate_boundary(face_candidates[idx].boundary_nodes, face_candidates[idx].face_id))
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);
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())
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]);
3666 const double shift_x = offset_x - min_x;
3667 for (
auto it = comp_nodes[c].get_it(); it.has_curr(); it.next_ne())
3669 const size_t u = it.get_curr_ne();
3670 gx[u] = best_x[u] + shift_x;
3674 offset_x += (max_x - min_x) +
options.component_spacing;
3678 if (num_components == 1)
3683 for (
size_t i = 0; i < n; ++i)
3686 p.
node = idx_to_node[i];
3704template <AlephGraph GT,
class Node_Label = Dft_Certificate_Node_Label<GT>>
3707 Node_Label node_label = Node_Label(),
3714 <<
"nonplanar_certificate_to_json() requires non-planar certificate";
3720 std::ostringstream
out;
3721 auto newline = [&](
const size_t indent)
3726 for (
size_t i = 0; i < indent; ++i)
3730 auto node_ref = [&](
Node *node) -> std::string
3732 if (node ==
nullptr or not node_to_id.
contains(node))
3734 return "\"n" + std::to_string(node_to_id.
find(node)) +
"\"";
3737 auto arc_ref = [&](
Arc *arc) -> std::string
3747 out <<
"\"is_planar\": false,";
3749 out <<
"\"certificate_available\": true,";
3751 out <<
"\"certificate_type\": \""
3757 out <<
"\"nodes\": [";
3758 for (
size_t i = 0; i <
nodes.size(); ++i)
3764 out <<
"\"id\": \"n" << i <<
"\", ";
3766 out <<
"\"ptr\": \""
3771 if (not
nodes.is_empty())
3776 out <<
"\"branch_nodes\": [";
3788 out <<
"\"obstruction_edges\": [";
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);
3807 out <<
"\"paths\": [";
3816 out <<
"\"nodes\": [";
3817 for (
size_t k = 0;
k < path.nodes.size(); ++
k)
3821 out << node_ref(path.nodes[
k]);
3825 out <<
"\"edges\": [";
3826 for (
size_t k = 0;
k < path.edges.size(); ++
k)
3828 const auto &e = path.edges[
k];
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);
3856template <AlephGraph GT,
class Node_Label = Dft_Certificate_Node_Label<GT>>
3859 Node_Label node_label = Node_Label(),
3865 <<
"nonplanar_certificate_to_dot() requires non-planar certificate";
3874 Node *node = it.get_curr_ne();
3875 if (node !=
nullptr and node_to_id.
contains(node))
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";
3886 for (
size_t i = 0; i <
nodes.size(); ++i)
3888 out <<
" n" << i <<
" [label=\"n" << i <<
"\\n"
3891 out <<
", style=\"filled\", fillcolor=\"#fff3bf\"";
3898 if (e.src ==
nullptr or e.tgt ==
nullptr or not node_to_id.
contains(e.src) or
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";
3907 if (
options.dot_highlight_paths)
3909 static const char *kPalette[] = {
"#0077b6",
"#2a9d8f",
"#6a4c93",
3910 "#ef476f",
"#ff9f1c",
"#588157"};
3911 constexpr size_t palette_size =
sizeof(kPalette) /
sizeof(kPalette[0]);
3917 for (
size_t k = 0;
k < path.edges.size(); ++
k)
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
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
3943template <AlephGraph GT>
3966 Node *node = it.get_curr_ne();
3967 if (node ==
nullptr or not node_to_id.
contains(node))
3973 const size_t id = node_to_id.
find(node);
3982 if (src ==
nullptr or tgt ==
nullptr)
3987 size_t u = node_to_id.
find(src);
3988 size_t v = node_to_id.
find(tgt);
4000 const auto &e = it.get_curr_ne();
4002 if (not make_edge_key(e.src, e.tgt, key))
4007 obstruction_keys.
insert(key);
4010 for (
auto pit = result.
certificate_paths.get_it(); pit.has_curr(); pit.next_ne())
4012 const auto &path = pit.get_curr_ne();
4014 for (
auto nit = path.nodes.get_it(); nit.has_curr(); nit.next_ne())
4015 if (nit.get_curr_ne() ==
nullptr)
4018 const size_t expected_nodes = path.edges.size() + (path.nodes.is_empty() ? 0 : 1);
4019 if (path.nodes.size() != expected_nodes)
4022 for (
size_t i = 0; i < path.edges.size(); ++i)
4024 const auto &e = path.edges[i];
4025 if (e.src ==
nullptr or e.tgt ==
nullptr)
4031 if (i + 1 >= path.nodes.size() or path.nodes[i] != e.src or path.nodes[i + 1] != e.tgt)
4035 if (not make_edge_key(e.src, e.tgt, key))
4041 if (not obstruction_keys.
contains(key))
4072template <AlephGraph GT>
4084template <AlephGraph GT,
class Node_Label = Dft_Certificate_Node_Label<GT>>
4087 Node_Label node_label = Node_Label(),
4093 <<
"nonplanar_certificate_to_graphml() requires non-planar certificate";
4102 Node *node = it.get_curr_ne();
4103 if (node !=
nullptr and node_to_id.
contains(node))
4107 auto node_ref = [&](
Node *node) -> std::string
4109 if (node ==
nullptr or not node_to_id.
contains(node))
4111 return "n" + std::to_string(node_to_id.
find(node));
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";
4126 for (
size_t i = 0; i <
nodes.size(); ++i)
4128 out <<
" <node id=\"n" << i <<
"\">\n";
4129 out <<
" <data key=\"k_node_label\">"
4131 out <<
" <data key=\"k_node_branch\">" << (branch_ids.
contains(i) ?
"true" :
"false")
4133 out <<
" <data key=\"k_node_ptr\">"
4136 out <<
" </node>\n";
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())
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";
4155 if (
options.graphml_include_paths)
4159 for (
size_t k = 0;
k < path.edges.size(); ++
k)
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())
4167 out <<
" <edge id=\"e" << edge_id++ <<
"\" source=\"" << u <<
"\" target=\"" << v
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";
4176 out <<
" </graph>\n";
4177 out <<
"</graphml>\n";
4187template <AlephGraph GT,
class Node_Label = Dft_Certificate_Node_Label<GT>>
4190 Node_Label node_label = Node_Label(),
4196 <<
"nonplanar_certificate_to_gexf() requires non-planar certificate";
4205 Node *node = it.get_curr_ne();
4206 if (node !=
nullptr and node_to_id.
contains(node))
4210 auto node_ref = [&](
Node *node) -> std::string
4212 if (node ==
nullptr or not node_to_id.
contains(node))
4214 return "n" + std::to_string(node_to_id.
find(node));
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";
4236 for (
size_t i = 0; i <
nodes.size(); ++i)
4238 out <<
" <node id=\"n" << i <<
"\" label=\""
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=\""
4246 out <<
" </attvalues>\n";
4247 out <<
" </node>\n";
4250 out <<
" </nodes>\n";
4251 out <<
" <edges>\n";
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())
4262 out <<
" <edge id=\"e" << edge_id++ <<
"\" source=\"" << u <<
"\" target=\"" << v
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";
4272 if (
options.gexf_include_paths)
4276 for (
size_t k = 0;
k < path.edges.size(); ++
k)
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())
4284 out <<
" <edge id=\"e" << edge_id++ <<
"\" source=\"" << u <<
"\" target=\"" << v
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()
4291 out <<
" </attvalues>\n";
4292 out <<
" </edge>\n";
4296 out <<
" </edges>\n";
4297 out <<
" </graph>\n";
4306template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
4329template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
C++20 concepts for the protocol shared by graph algorithms.
STL-compatible iterator adapters for Aleph containers.
WeightedDigraph::Node Node
size_t size_t int32_t value
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
void empty() noexcept
Empties the container.
constexpr bool is_empty() const noexcept
Checks if the container is empty.
T & get_last()
Return a modifiable reference to the last element.
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
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.
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.
Graph_Node< Node_Info > Node
The graph type.
Graph_Arc< Arc_Info > Arc
The node class type.
Filtered iterator on the nodes of a graph.
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)
bool build_combinatorial_embedding_bruteforce()
Orient_Frame orient_frame_of(const size_t v) const noexcept
bool fails_component_euler_bound() const
size_t other_endpoint(const size_t edge_id, const size_t x) const
void orient_dfs(const size_t root)
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)
Array< Array< Arc * > > simplified_edge_input_arcs_
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)
Array< size_t > oriented_src_
Array< long > nesting_depth_
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
Array< char > undirected_edge_seen_
void build_underlying_simple_graph()
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)
Planarity_Test_Result< GT > result_
bool build_combinatorial_embedding_linear_lr()
Array< Simple_Edge > edges_
bool run_lr_planarity_test()
void finish_oriented_edge(const size_t v, const size_t e)
void sort_child_edges(const size_t v)
void finish_test(const size_t v)
Array< size_t > undirected_to_oriented_
Array< Conflict_Pair > stack_bottom_
void build_nonplanar_certificate()
bool build_combinatorial_embedding()
static size_t find_in_array(const Array< size_t > &a, const size_t value)
Planarity_Test_Result< GT > run()
Array< size_t > lowpt_edge_
Array< size_t > parent_edge_
static bool classify_k33(const Array< size_t > &branches, const Array< Compressed_Path > &paths)
Array< size_t > oriented_tgt_
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)
Planarity_Test_Options options_
size_t find_simplified_edge_id(const size_t u, const size_t v) const
Array< Conflict_Pair > stack_
void test_dfs(const size_t root)
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)
DynMapTree< Node *, size_t > node_to_idx_
size_t count_components() const
Test_Frame test_frame_of(const size_t v)
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)
Array< Array< size_t > > child_edges_
Array< Array< size_t > > incident_edges_
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
bool is_digraph() const noexcept
Return true if the graph this is directed.
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
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)
static constexpr size_t palette_size()
DynArray< Graph::Node * > nodes
DynArray< Graph::Arc * > arcs
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().
@ Minimal_NonPlanar_Obstruction
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.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
void next()
Advance all underlying iterators (bounds-checked).
static long & color(typename GT::Node *p)
static struct argp_option options[]
Filtered iterator on all the arcs of a graph.
Default node labeler for certificate export.
std::string operator()(typename GT::Node *node) const
Default filter for filtered iterators on arcs.
Arc of graph implemented with double-linked adjacency lists.
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.
size_t kuratowski_shape_mismatch
size_t path_node_edge_length_mismatch
size_t null_path_edge_endpoints
size_t path_edge_not_in_obstruction
size_t duplicate_branch_nodes
size_t path_edge_endpoint_mismatch
size_t num_obstruction_edges
size_t null_obstruction_edge_endpoints
Represents a missing value.
Dual-edge payload linked to a primal simplified edge.
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.
bool drawing_validated_no_crossings
Array< Node_Position > node_positions
bool drawing_search_truncated
size_t relaxation_iterations
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)
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.