Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
planarity_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
37# include <gtest/gtest.h>
38
39# include <algorithm>
40# include <array>
41# include <cstdlib>
42# include <cstdint>
43# include <filesystem>
44# include <functional>
45# include <fstream>
46# include <limits>
47# include <optional>
48# include <random>
49# include <sstream>
50# include <string>
51# include <tuple>
52# include <unordered_map>
53# include <utility>
54# include <vector>
55
56# include <Planarity_Test.H>
57# include <ah-errors.H>
58# include <tpl_agraph.H>
59# include <tpl_graph.H>
60
61using namespace Aleph;
62
63namespace
64{
68
69 using UNode = UGraph::Node;
70 using UArc = UGraph::Arc;
71
72 using Edge = std::pair<size_t, size_t>;
73
74 template <class GT>
75 struct Built_Graph
76 {
77 GT g;
78 std::vector<typename GT::Node *> nodes;
79 std::vector<typename GT::Arc *> arcs;
80 };
81
82
83 Built_Graph<UGraph>
84 build_ugraph(const size_t n,
85 const std::vector<Edge> & edges)
86 {
87 Built_Graph<UGraph> built;
88 built.nodes.reserve(n);
89 built.arcs.reserve(edges.size());
90
91 for (size_t i = 0; i < n; ++i)
92 built.nodes.push_back(built.g.insert_node(static_cast<int>(i)));
93
94 for (const auto & [u, v] : edges)
95 if (u < n and v < n)
96 built.arcs.push_back(built.g.insert_arc(built.nodes[u], built.nodes[v], 1));
97
98 return built;
99 }
100
101
102 Built_Graph<DGraph>
103 build_dgraph(const size_t n,
104 const std::vector<Edge> & arcs)
105 {
106 Built_Graph<DGraph> built;
107 built.nodes.reserve(n);
108 built.arcs.reserve(arcs.size());
109
110 for (size_t i = 0; i < n; ++i)
111 built.nodes.push_back(built.g.insert_node(static_cast<int>(i)));
112
113 for (const auto & [u, v] : arcs)
114 if (u < n and v < n)
115 built.arcs.push_back(built.g.insert_arc(built.nodes[u], built.nodes[v], 1));
116
117 return built;
118 }
119
120
121 Built_Graph<ArrayUGraph>
122 build_array_ugraph(const size_t n,
123 const std::vector<Edge> & edges)
124 {
125 Built_Graph<ArrayUGraph> built;
126 built.nodes.reserve(n);
127 built.arcs.reserve(edges.size());
128
129 for (size_t i = 0; i < n; ++i)
130 built.nodes.push_back(built.g.insert_node(static_cast<int>(i)));
131
132 for (const auto & [u, v] : edges)
133 if (u < n and v < n)
134 built.arcs.push_back(built.g.insert_arc(built.nodes[u], built.nodes[v], 1));
135
136 return built;
137 }
138
139
140 std::vector<Edge> complete_graph_edges(const size_t n)
141 {
142 std::vector<Edge> edges;
143 for (size_t u = 0; u < n; ++u)
144 for (size_t v = u + 1; v < n; ++v)
145 edges.emplace_back(u, v);
146 return edges;
147 }
148
149
150 std::vector<Edge> complete_bipartite_edges(const size_t left,
151 const size_t right)
152 {
153 std::vector<Edge> edges;
154 for (size_t u = 0; u < left; ++u)
155 for (size_t v = 0; v < right; ++v)
156 edges.emplace_back(u, left + v);
157 return edges;
158 }
159
160
161 uint64_t dart_key(const int u, const int v)
162 {
163 return (static_cast<uint64_t>(static_cast<uint32_t>(u)) << 32)
164 | static_cast<uint32_t>(v);
165 }
166
167
168 size_t component_count(const size_t n, const std::vector<Edge> & edges)
169 {
170 std::vector<std::vector<int>> adj(n);
171 for (const auto & [u, v] : edges)
172 {
173 adj[u].push_back(static_cast<int>(v));
174 adj[v].push_back(static_cast<int>(u));
175 }
176
177 std::vector<int> vis(n, 0);
178 size_t comps = 0;
179
180 for (size_t s = 0; s < n; ++s)
181 {
182 if (vis[s])
183 continue;
184
185 ++comps;
186 std::vector<int> stack = {static_cast<int>(s)};
187 vis[s] = 1;
188
189 while (not stack.empty())
190 {
191 const int v = stack.back();
192 stack.pop_back();
193 for (const int w : adj[static_cast<size_t>(v)])
194 if (not vis[static_cast<size_t>(w)])
195 {
196 vis[static_cast<size_t>(w)] = 1;
197 stack.push_back(w);
198 }
199 }
200 }
201
202 return comps;
203 }
204
205
206 std::optional<bool>
207 brute_force_planarity_oracle(const size_t n,
208 const std::vector<Edge> & edges,
209 const size_t max_combinations = 200000)
210 {
211 if (n <= 4)
212 return true;
213
214 if (edges.empty())
215 return true;
216
217 std::vector<std::vector<int>> adj(n);
218 for (const auto & [u, v] : edges)
219 {
220 adj[u].push_back(static_cast<int>(v));
221 adj[v].push_back(static_cast<int>(u));
222 }
223
224 const size_t m = edges.size();
225 const size_t c = component_count(n, edges);
226
227 // This bound is valid only for connected simple planar graphs.
228 if (c == 1 and n >= 3 and m > 3 * n - 6)
229 return false;
230
231 std::vector<std::vector<std::vector<int>>> order_options(n);
232 size_t combinations = 1;
233
234 for (size_t v = 0; v < n; ++v)
235 {
236 auto neigh = adj[v];
237 std::sort(neigh.begin(), neigh.end());
238
239 const size_t d = neigh.size();
240 if (d <= 2)
241 {
242 order_options[v].push_back(std::move(neigh));
243 continue;
244 }
245
246 const int first = neigh.front();
247 std::vector<int> tail(neigh.begin() + 1, neigh.end());
248 std::sort(tail.begin(), tail.end());
249
250 do
251 {
252 std::vector<int> order;
253 order.reserve(d);
254 order.push_back(first);
255 order.insert(order.end(), tail.begin(), tail.end());
256 order_options[v].push_back(std::move(order));
257 }
258 while (std::next_permutation(tail.begin(), tail.end()));
259
260 combinations *= order_options[v].size();
261 if (combinations > max_combinations)
262 return std::nullopt;
263 }
264
265 std::vector<std::pair<int, int>> darts;
266 darts.reserve(2 * m);
267 std::unordered_map<uint64_t, int> dart_id;
268
269 for (const auto & [u, v] : edges)
270 {
271 const int duv = static_cast<int>(darts.size());
272 darts.emplace_back(static_cast<int>(u), static_cast<int>(v));
273 dart_id.emplace(dart_key(static_cast<int>(u), static_cast<int>(v)), duv);
274
275 const int dvu = static_cast<int>(darts.size());
276 darts.emplace_back(static_cast<int>(v), static_cast<int>(u));
277 dart_id.emplace(dart_key(static_cast<int>(v), static_cast<int>(u)), dvu);
278 }
279
280 std::vector<int> alpha(darts.size(), -1);
281 for (size_t i = 0; i < darts.size(); ++i)
282 {
283 const auto [u, v] = darts[i];
284 alpha[i] = dart_id.at(dart_key(v, u));
285 }
286
287 std::vector<size_t> selected(n, 0);
288 std::vector<size_t> vars;
289 vars.reserve(n);
290 for (size_t v = 0; v < n; ++v)
291 if (order_options[v].size() > 1)
292 vars.push_back(v);
293
294 std::sort(vars.begin(), vars.end(),
295 [&order_options](const size_t a, const size_t b)
296 {
297 return order_options[a].size() > order_options[b].size();
298 });
299
300 std::function<bool()> evaluate = [&]() -> bool
301 {
302 std::vector<int> sigma(darts.size(), -1);
303
304 for (size_t v = 0; v < n; ++v)
305 {
306 const auto & ord = order_options[v][selected[v]];
307 if (ord.empty())
308 continue;
309
310 for (size_t i = 0; i < ord.size(); ++i)
311 {
312 const int to = ord[i];
313 const int next = ord[(i + 1) % ord.size()];
314
315 const int a = dart_id.at(dart_key(static_cast<int>(v), to));
316 const int b = dart_id.at(dart_key(static_cast<int>(v), next));
317 sigma[a] = b;
318 }
319 }
320
321 for (const int s : sigma)
322 if (s < 0)
323 return false;
324
325 std::vector<int> vis(darts.size(), 0);
326 size_t faces = 0;
327 for (size_t d = 0; d < darts.size(); ++d)
328 {
329 if (vis[d])
330 continue;
331
332 ++faces;
333 size_t x = d;
334 while (not vis[x])
335 {
336 vis[x] = 1;
337 x = static_cast<size_t>(sigma[static_cast<size_t>(alpha[x])]);
338 }
339 }
340
341 size_t isolated_vertices = 0;
342 for (size_t v = 0; v < n; ++v)
343 if (adj[v].empty())
344 ++isolated_vertices;
345 const size_t component_faces = faces + isolated_vertices;
346 const size_t global_faces = component_faces - (c == 0 ? 0 : (c - 1));
347
348 return static_cast<long long>(n)
349 - static_cast<long long>(m)
350 + static_cast<long long>(global_faces)
351 == static_cast<long long>(c) + 1;
352 };
353
354 std::function<bool(size_t)> dfs = [&](const size_t pos) -> bool
355 {
356 if (pos == vars.size())
357 return evaluate();
358
359 const size_t v = vars[pos];
360 for (size_t i = 0; i < order_options[v].size(); ++i)
361 {
362 selected[v] = i;
363 if (dfs(pos + 1))
364 return true;
365 }
366
367 return false;
368 };
369
370 return dfs(0);
371 }
372
373
374 // Whether the rotations of r are a planar embedding of the simple graph
375 // of edges: each rotation is a permutation of the neighbors of its node,
376 // and the faces that they trace satisfy Euler's formula in each component
377 bool is_planar_embedding(const Built_Graph<UGraph> & built,
378 const std::vector<Edge> & edges,
380 {
381 const size_t n = built.nodes.size();
382 std::unordered_map<UNode *, size_t> idx;
383 for (size_t i = 0; i < n; ++i)
384 idx[built.nodes[i]] = i;
385
386 std::vector<std::vector<size_t>> adj(n);
387 std::vector<Edge> simple;
388 for (const auto & [u, v] : edges)
389 if (u != v and std::find(adj[u].begin(), adj[u].end(), v) == adj[u].end())
390 {
391 adj[u].push_back(v);
392 adj[v].push_back(u);
393 simple.emplace_back(u, v);
394 }
395
396 if (r.embedding_rotation.size() != n)
397 return false;
398
399 std::vector<std::vector<size_t>> rot(n);
400 for (size_t i = 0; i < r.embedding_rotation.size(); ++i)
401 {
402 const auto & re = r.embedding_rotation[i];
403 auto & ro = rot[idx.at(re.node)];
404 for (size_t j = 0; j < re.cw_neighbors.size(); ++j)
405 ro.push_back(idx.at(re.cw_neighbors[j]));
406 }
407
408 for (size_t u = 0; u < n; ++u)
409 {
410 auto a = rot[u], b = adj[u];
411 std::sort(a.begin(), a.end());
412 std::sort(b.begin(), b.end());
413 if (a != b)
414 return false;
415 }
416
417 // from the dart u -> v, the face goes on from v to the neighbor that
418 // follows u around v
419 std::unordered_map<uint64_t, bool> seen;
420 size_t faces = 0;
421 for (size_t u = 0; u < n; ++u)
422 for (const size_t v : rot[u])
423 {
424 if (seen.count(dart_key(int(u), int(v))))
425 continue;
426
427 ++faces;
428 size_t a = u, b = v;
429 while (not seen.count(dart_key(int(a), int(b))))
430 {
431 seen[dart_key(int(a), int(b))] = true;
432 const auto & rb = rot[b];
433 const size_t pos = size_t(std::find(rb.begin(), rb.end(), a) - rb.begin());
434 const size_t c = rb[(pos + 1) % rb.size()];
435 a = b;
436 b = c;
437 }
438 }
439
440 size_t isolated = 0;
441 for (size_t u = 0; u < n; ++u)
442 isolated += adj[u].empty();
443
444 const size_t with_edges = component_count(n, simple) - isolated;
445 return long(n - isolated) - long(simple.size()) + long(faces) == 2 * long(with_edges);
446 }
447
448 // A maximal planar graph of n nodes: a triangle, and then each node in a
449 // random face, joined to its three corners
450 std::vector<Edge> random_maximal_planar_edges(const size_t n, std::mt19937 & gen)
451 {
452 std::vector<std::array<size_t, 3>> faces = {{0, 1, 2}, {0, 2, 1}};
453 std::vector<Edge> edges = {{0, 1}, {1, 2}, {2, 0}};
454 for (size_t d = 3; d < n; ++d)
455 {
456 const size_t f = gen() % faces.size();
457 const auto [a, b, c] = faces[f];
458 faces[f] = {a, b, d};
459 faces.push_back({b, c, d});
460 faces.push_back({c, a, d});
461 edges.emplace_back(a, d);
462 edges.emplace_back(b, d);
463 edges.emplace_back(c, d);
464 }
465 return edges;
466 }
467
468
469 std::string
470 shell_quote(const std::string & s)
471 {
472 std::string q = "'";
473 for (size_t i = 0; i < s.size(); ++i)
474 {
475 const char c = s[i];
476 if (c == '\'')
477 q += "'\\''";
478 else
479 q += c;
480 }
481 q += "'";
482 return q;
483 }
484
485
487 std::optional<std::filesystem::path>
488 find_repo_root()
489 {
490 namespace fs = std::filesystem;
491#ifdef ALEPH_TEST_SOURCE_DIR
492 const fs::path configured_root(ALEPH_TEST_SOURCE_DIR);
493 if (fs::exists(configured_root / "Planarity_Test.H")
494 and fs::is_directory(configured_root / "scripts"))
495 return configured_root;
496#endif
497 fs::path p = fs::current_path();
498
499 for (size_t i = 0; i < 12; ++i)
500 {
501 if (fs::exists(p / "Planarity_Test.H") and fs::exists(p / "scripts"))
502 return p;
503
504 if (p == p.root_path())
505 break;
506
507 p = p.parent_path();
508 }
509
510 return std::nullopt;
511 }
512
513
521 class Scratch_Dir
522 {
523 std::filesystem::path path_;
524
525 public:
528 Scratch_Dir()
529 {
530 namespace fs = std::filesystem;
531 std::random_device rd;
532 for (int attempt = 0; attempt < 100; ++attempt)
533 {
534 std::ostringstream name;
535 name << "aleph_planarity_" << std::hex << rd() << '_' << rd();
536 const fs::path candidate = fs::temp_directory_path() / name.str();
537 if (fs::create_directory(candidate)) // false if it exists
538 {
539 path_ = candidate;
540 return;
541 }
542 }
543 ah_runtime_error() << "no directory of its own for the planarity tests";
544 }
545
547 Scratch_Dir(const Scratch_Dir &) = delete;
549 Scratch_Dir & operator=(const Scratch_Dir &) = delete;
550
552 ~Scratch_Dir()
553 {
554 std::error_code ec;
555 std::filesystem::remove_all(path_, ec);
556 }
557
559 [[nodiscard]] const std::filesystem::path & path() const noexcept { return path_; }
560 };
561
562
564 const std::filesystem::path &
565 scratch_dir()
566 {
567 static const Scratch_Dir dir;
568 return dir.path();
569 }
570
571
573 std::string
574 make_tmp_path(const std::string & stem,
575 const std::string & ext)
576 {
577 static size_t seq = 0;
578 std::ostringstream name;
579 name << stem << "_" << ++seq << ext;
580 return (scratch_dir() / name.str()).string();
581 }
582
583
586 std::string
587 validator_stdout_path(const std::string & label = "validator")
588 {
589 return (scratch_dir() / (label + ".stdout")).string();
590 }
591
592
593 void
594 write_text_file(const std::string & path,
595 const std::string & content)
596 {
597 std::ofstream out(path);
598 out << content;
599 }
600
601
602 std::string
603 read_text_file(const std::string & path)
604 {
605 std::ifstream in(path);
606 std::ostringstream out;
607 out << in.rdbuf();
608 return out.str();
609 }
610
611
612 // Run a shell command, redirecting only stdout. Stderr passes through
613 // to the test output so that Ruby script errors are visible in CI logs.
614 // Clears GITHUB_OUTPUT so scripts don't try to write to the CI output
615 // file when invoked as test sub-processes.
616 int
617 run_script_cmd(const std::string & cmd_str, const std::string & label)
618 {
619 const std::string stdout_path = validator_stdout_path(label);
620 const std::string full =
621 "GITHUB_OUTPUT='' " + cmd_str + " > " + shell_quote(stdout_path);
622 return std::system(full.c_str());
623 }
624
625
626 int
627 run_external_certificate_validator(const std::vector<std::string> & inputs,
628 const bool use_networkx = false,
629 const bool require_networkx = false,
630 const bool use_gephi = false,
631 const bool require_gephi = false,
632 const std::string & gephi_cmd = "",
633 const std::string & extra_args = "",
634 const std::string & label = "validator")
635 {
636 namespace fs = std::filesystem;
637 const auto root = find_repo_root();
638 if (not root.has_value())
639 return -999;
640
641 const fs::path script = *root / "scripts" / "planarity_certificate_validator.rb";
642 if (not fs::exists(script))
643 return -998;
644
645 std::ostringstream cmd;
646 cmd << "ruby " << shell_quote(script.string());
647
648 for (size_t i = 0; i < inputs.size(); ++i)
649 cmd << " --input " << shell_quote(inputs[i]);
650
651 if (use_networkx)
652 cmd << " --networkx";
653 if (require_networkx)
654 cmd << " --require-networkx";
655 if (use_gephi)
656 cmd << " --gephi";
657 if (require_gephi)
658 cmd << " --require-gephi";
659 if (not gephi_cmd.empty())
660 cmd << " --gephi-cmd " << shell_quote(gephi_cmd);
661 if (not extra_args.empty())
662 cmd << " " << extra_args;
663
664 return run_script_cmd(cmd.str(), label);
665 }
666
667
668 int
669 run_external_certificate_batch(const std::vector<std::string> & inputs,
670 const std::string & report_path,
671 const std::string & extra_args = "")
672 {
673 namespace fs = std::filesystem;
674 const auto root = find_repo_root();
675 if (not root.has_value())
676 return -997;
677
678 const fs::path script = *root / "scripts" / "planarity_certificate_ci_batch.rb";
679 if (not fs::exists(script))
680 return -996;
681
682 std::ostringstream cmd;
683 cmd << "ruby " << shell_quote(script.string());
684 for (size_t i = 0; i < inputs.size(); ++i)
685 cmd << " --input " << shell_quote(inputs[i]);
686 cmd << " --report " << shell_quote(report_path);
687
688 if (not extra_args.empty())
689 cmd << " " << extra_args;
690
691 return run_script_cmd(cmd.str(), "batch");
692 }
693
694
695 int
696 run_external_certificate_visual_diff(const std::vector<std::string> & inputs,
697 const std::vector<std::string> & profiles,
698 const std::string & report_path,
699 const std::string & extra_args = "")
700 {
701 namespace fs = std::filesystem;
702 const auto root = find_repo_root();
703 if (not root.has_value())
704 return -995;
705
706 const fs::path script = *root / "scripts" / "planarity_certificate_ci_visual_diff.rb";
707 if (not fs::exists(script))
708 return -994;
709
710 std::ostringstream cmd;
711 cmd << "ruby " << shell_quote(script.string());
712
713 for (size_t i = 0; i < inputs.size(); ++i)
714 cmd << " --input " << shell_quote(inputs[i]);
715
716 for (size_t i = 0; i < profiles.size(); ++i)
717 cmd << " --profile " << shell_quote(profiles[i]);
718
719 cmd << " --report " << shell_quote(report_path);
720 if (not extra_args.empty())
721 cmd << " " << extra_args;
722
723 return run_script_cmd(cmd.str(), "visual");
724 }
725
726
727 int
728 run_gephi_nightly_comparison(const std::string & artifacts_root,
729 const std::string & report_json,
730 const std::string & report_md,
731 const std::string & extra_args = "")
732 {
733 namespace fs = std::filesystem;
734 const auto root = find_repo_root();
735 if (not root.has_value())
736 return -993;
737
738 const fs::path script = *root / "scripts" / "planarity_gephi_weekly_comparison.rb";
739 if (not fs::exists(script))
740 return -992;
741
742 std::ostringstream cmd;
743 cmd << "ruby " << shell_quote(script.string())
744 << " --artifacts-root " << shell_quote(artifacts_root)
745 << " --resolved-tags " << shell_quote("v0.9.7,v0.10.1")
746 << " --run-id " << shell_quote("test-run")
747 << " --run-attempt " << shell_quote("1")
748 << " --git-sha " << shell_quote("deadbeef")
749 << " --report-json " << shell_quote(report_json)
750 << " --report-md " << shell_quote(report_md);
751
752 if (not extra_args.empty())
753 cmd << " " << extra_args;
754
755 return run_script_cmd(cmd.str(), "gephi_comparison");
756 }
757
758
759 int
760 run_gephi_regression_notify(const std::string & report_json,
761 const std::string & output_md,
762 const std::string & extra_args = "")
763 {
764 namespace fs = std::filesystem;
765 const auto root = find_repo_root();
766 if (not root.has_value())
767 return -991;
768
769 const fs::path script = *root / "scripts" / "planarity_gephi_regression_notify.rb";
770 if (not fs::exists(script))
771 return -990;
772
773 std::ostringstream cmd;
774 cmd << "ruby " << shell_quote(script.string())
775 << " --report-json " << shell_quote(report_json)
776 << " --output-md " << shell_quote(output_md)
777 << " --repository " << shell_quote("lrleon/Aleph-w")
778 << " --run-url " << shell_quote("https://example.invalid/run/123");
779
780 if (not extra_args.empty())
781 cmd << " " << extra_args;
782
783 return run_script_cmd(cmd.str(), "gephi_notify");
784 }
785
786
787 // Returns true when the planarity_certificate_validator.rb script can be
788 // found in the repository and Ruby is executable on this machine.
789 bool
790 has_ruby_and_validator_script()
791 {
792 namespace fs = std::filesystem;
793 const auto root = find_repo_root();
794 if (not root.has_value())
795 return false;
796 if (not fs::exists(*root / "scripts" / "planarity_certificate_validator.rb"))
797 return false;
798 return std::system("ruby --version > /dev/null 2>&1") == 0;
799 }
800
801
802 // Returns true when python3 is executable on this machine.
803 bool
804 has_python3()
805 {
806 return std::system("python3 --version > /dev/null 2>&1") == 0;
807 }
808
809} // namespace
810
811
812TEST(PlanarityTest, EmptyGraphIsPlanar)
813{
814 UGraph g;
815 const auto r = planarity_test(g);
816
817 EXPECT_TRUE(r.is_planar);
818 EXPECT_EQ(r.num_nodes, 0u);
819 EXPECT_EQ(r.simplified_num_edges, 0u);
820}
821
822
823TEST(PlanarityTest, TreeIsPlanar)
824{
825 const std::vector<Edge> edges = {
826 {0, 1}, {1, 2}, {1, 3}, {3, 4}, {3, 5}
827 };
828
829 auto built = build_ugraph(6, edges);
830 EXPECT_TRUE(is_planar_graph(built.g));
831}
832
833
834TEST(PlanarityTest, K5IsNonPlanar)
835{
836 auto built = build_ugraph(5, complete_graph_edges(5));
837 const auto r = planarity_test(built.g);
838
839 EXPECT_FALSE(r.is_planar);
840 EXPECT_TRUE(r.failed_euler_bound);
841}
842
843
844TEST(PlanarityTest, K33IsNonPlanar)
845{
846 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
847 const auto r = planarity_test(built.g);
848
849 EXPECT_FALSE(r.is_planar);
850}
851
852
853TEST(PlanarityTest, K5CertificateIsExtractedWhenEnabled)
854{
855 auto built = build_ugraph(5, complete_graph_edges(5));
856
859
860 const auto r = planarity_test(built.g, opts);
861
862 EXPECT_FALSE(r.is_planar);
863 EXPECT_TRUE(r.has_nonplanar_certificate);
864 EXPECT_EQ(r.certificate_type, Planarity_Certificate_Type::K5_Subdivision);
865 EXPECT_EQ(r.certificate_branch_nodes.size(), 5u);
866 EXPECT_EQ(r.certificate_paths.size(), 10u);
867}
868
869
870TEST(PlanarityTest, K33CertificateIsExtractedWhenEnabled)
871{
872 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
873
876
877 const auto r = planarity_test(built.g, opts);
878
879 EXPECT_FALSE(r.is_planar);
880 EXPECT_TRUE(r.has_nonplanar_certificate);
881 EXPECT_EQ(r.certificate_type, Planarity_Certificate_Type::K33_Subdivision);
882 EXPECT_EQ(r.certificate_branch_nodes.size(), 6u);
883 EXPECT_EQ(r.certificate_paths.size(), 9u);
884}
885
886
887TEST(PlanarityTest, CertificateObstructionEdgesMapToOriginalInputArcs)
888{
889 auto built = build_ugraph(5, complete_graph_edges(5));
890
891 // Add extra parallel inputs for edge {0,1}.
892 built.arcs.push_back(built.g.insert_arc(built.nodes[0], built.nodes[1], 1));
893 built.arcs.push_back(built.g.insert_arc(built.nodes[1], built.nodes[0], 1));
894
897
898 const auto r = planarity_test(built.g, opts);
899
900 ASSERT_FALSE(r.is_planar);
901 ASSERT_TRUE(r.has_nonplanar_certificate);
902 ASSERT_EQ(r.certificate_type, Planarity_Certificate_Type::K5_Subdivision);
903 ASSERT_EQ(r.certificate_obstruction_edges.size(), 10u);
904
905 bool found_01 = false;
906 for (auto it = r.certificate_obstruction_edges.get_it(); it.has_curr(); it.next_ne())
907 {
908 const auto & w = it.get_curr_ne();
909 EXPECT_NE(w.representative_input_arc, nullptr);
910 EXPECT_GE(w.input_arcs.size(), 1u);
911
912 const bool is_01 = (w.src == built.nodes[0] and w.tgt == built.nodes[1])
913 or (w.src == built.nodes[1] and w.tgt == built.nodes[0]);
914 if (is_01)
915 {
916 found_01 = true;
917 EXPECT_GE(w.input_arcs.size(), 3u);
918 }
919 }
920
921 EXPECT_TRUE(found_01);
922}
923
924
925TEST(PlanarityTest, CertificatePathsExposeTraceableOriginalEdges)
926{
927 auto edges = complete_bipartite_edges(3, 3);
928
929 // Replace edge (0,3) by 0-6-3 to force at least one subdivided witness path.
930 auto it = std::find(edges.begin(), edges.end(), Edge{0, 3});
931 ASSERT_NE(it, edges.end());
932 edges.erase(it);
933 edges.emplace_back(0, 6);
934 edges.emplace_back(6, 3);
935
936 auto built = build_ugraph(7, edges);
937
940
941 const auto r = planarity_test(built.g, opts);
942
943 ASSERT_FALSE(r.is_planar);
944 ASSERT_TRUE(r.has_nonplanar_certificate);
945 ASSERT_EQ(r.certificate_type, Planarity_Certificate_Type::K33_Subdivision);
946 ASSERT_FALSE(r.certificate_paths.is_empty());
947
948 bool found_subdivided_path = false;
949 for (auto pit = r.certificate_paths.get_it(); pit.has_curr(); pit.next_ne())
950 {
951 const auto & p = pit.get_curr_ne();
952 ASSERT_GE(p.nodes.size(), 2u);
953 EXPECT_EQ(p.edges.size(), p.nodes.size() - 1);
954
955 if (p.nodes.size() > 2)
956 found_subdivided_path = true;
957
958 for (auto eit = p.edges.get_it(); eit.has_curr(); eit.next_ne())
959 {
960 const auto & e = eit.get_curr_ne();
961 EXPECT_NE(e.representative_input_arc, nullptr);
962 EXPECT_GE(e.input_arcs.size(), 1u);
963 }
964 }
965
966 EXPECT_TRUE(found_subdivided_path);
967}
968
969
970TEST(PlanarityTest, K5MinusEdgeIsPlanar)
971{
972 auto edges = complete_graph_edges(5);
973 edges.erase(edges.begin());
974
975 auto built = build_ugraph(5, edges);
976 const auto r = planarity_test(built.g);
977
978 EXPECT_TRUE(r.is_planar);
979}
980
981
982TEST(PlanarityTest, PlanarEmbeddingIsExtractedWhenEnabled)
983{
984 auto edges = complete_graph_edges(5);
985 edges.erase(edges.begin()); // K5 - e, planar
986
987 auto built = build_ugraph(5, edges);
988
990 opts.compute_embedding = true;
991
992 const auto r = planarity_test(built.g, opts);
993
994 EXPECT_TRUE(r.is_planar);
995 EXPECT_TRUE(r.has_combinatorial_embedding);
996 EXPECT_FALSE(r.embedding_search_truncated);
997 EXPECT_EQ(r.embedding_rotation.size(), 5u);
998
999 const size_t expected_faces = edges.size() - 5 + 2; // connected Euler
1000 EXPECT_EQ(r.embedding_num_faces, expected_faces);
1001}
1002
1003
1004TEST(PlanarityTest, PlanarDualMetadataConnectedGraph)
1005{
1006 auto built = build_ugraph(5, {
1007 {0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {0, 2}
1008 });
1009
1011 opts.compute_embedding = true;
1012 opts.embedding_allow_bruteforce_fallback = false;
1013
1014 const auto r = planarity_test(built.g, opts);
1015 ASSERT_TRUE(r.is_planar);
1016 ASSERT_TRUE(r.has_combinatorial_embedding);
1017
1018 const auto md = planar_dual_metadata(r);
1019 EXPECT_TRUE(md.has_embedding);
1020 EXPECT_EQ(md.num_components, 1u);
1021 EXPECT_EQ(md.num_faces_local, r.embedding_num_faces);
1022 EXPECT_EQ(md.num_faces_global, r.embedding_num_faces);
1023 EXPECT_FALSE(md.faces_are_component_local);
1024 EXPECT_EQ(md.dual_edges.size(), r.simplified_num_edges);
1025 EXPECT_EQ(md.face_adjacency.size(), md.num_faces_local);
1026}
1027
1028
1029TEST(PlanarityTest, PlanarDualMetadataTreeHasSingleFaceAndLoops)
1030{
1031 auto built = build_ugraph(4, {
1032 {0, 1}, {1, 2}, {1, 3}
1033 });
1034
1036 opts.compute_embedding = true;
1037 opts.embedding_allow_bruteforce_fallback = false;
1038
1039 const auto r = planarity_test(built.g, opts);
1040 ASSERT_TRUE(r.is_planar);
1041 ASSERT_TRUE(r.has_combinatorial_embedding);
1042
1043 const auto md = planar_dual_metadata(r);
1044 EXPECT_EQ(md.num_faces_local, 1u);
1045 EXPECT_EQ(md.num_faces_global, 1u);
1046 EXPECT_EQ(md.dual_edges.size(), 3u);
1047
1048 for (auto it = md.dual_edges.get_it(); it.has_curr(); it.next_ne())
1049 {
1050 const auto & e = it.get_curr_ne();
1051 EXPECT_EQ(e.face_a, 0u);
1052 EXPECT_EQ(e.face_b, 0u);
1053 }
1054
1055 auto dual = build_planar_dual_graph<UGraph>(md);
1056 EXPECT_EQ(dual.get_num_nodes(), 1u);
1057 EXPECT_EQ(dual.get_num_arcs(), 3u);
1058}
1059
1060
1061TEST(PlanarityTest, PlanarDualMetadataDisconnectedUsesComponentLocalFaces)
1062{
1063 auto built = build_ugraph(3, {
1064 {0, 1}
1065 });
1066
1068 opts.compute_embedding = true;
1069 opts.embedding_allow_bruteforce_fallback = false;
1070
1071 const auto r = planarity_test(built.g, opts);
1072 ASSERT_TRUE(r.is_planar);
1073 ASSERT_TRUE(r.has_combinatorial_embedding);
1074
1075 const auto md = planar_dual_metadata(r);
1076 EXPECT_EQ(md.num_components, 2u);
1077 EXPECT_EQ(md.num_faces_local, 2u);
1078 EXPECT_EQ(md.num_faces_global, 1u);
1079 EXPECT_TRUE(md.faces_are_component_local);
1080}
1081
1082
1083TEST(PlanarityTest, PlanarDualMetadataRequiresEmbedding)
1084{
1085 auto built = build_ugraph(4, {
1086 {0, 1}, {1, 2}, {2, 3}
1087 });
1088
1089 const auto r = planarity_test(built.g); // no embedding requested
1090 EXPECT_TRUE(r.is_planar);
1091 EXPECT_FALSE(r.has_combinatorial_embedding);
1092
1093 EXPECT_ANY_THROW((void) planar_dual_metadata(r));
1094}
1095
1096
1097TEST(PlanarityTest, LinearLREmbeddingWorksOnSimplePlanarSample)
1098{
1099 auto built = build_ugraph(5, {
1100 {0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {0, 2}
1101 });
1102
1104 opts.compute_embedding = true;
1105 opts.embedding_allow_bruteforce_fallback = false;
1106
1107 const auto r = planarity_test(built.g, opts);
1108
1109 EXPECT_TRUE(r.is_planar);
1110 EXPECT_TRUE(r.has_combinatorial_embedding);
1111 EXPECT_TRUE(r.embedding_is_lr_linear);
1112}
1113
1114
1115TEST(PlanarityTest, K5MinusEdgeHasStrictLREmbeddingWithoutFallback)
1116{
1117 auto edges = complete_graph_edges(5);
1118 edges.erase(edges.begin()); // K5 - e, planar
1119 auto built = build_ugraph(5, edges);
1120
1121 Planarity_Test_Options strict_opts;
1122 strict_opts.compute_embedding = true;
1123 strict_opts.embedding_allow_bruteforce_fallback = false;
1124
1125 const auto r_strict = planarity_test(built.g, strict_opts);
1126
1127 EXPECT_TRUE(r_strict.is_planar);
1128 EXPECT_TRUE(r_strict.has_combinatorial_embedding);
1129 EXPECT_TRUE(r_strict.embedding_is_lr_linear);
1130 EXPECT_FALSE(r_strict.embedding_search_truncated);
1131
1132 Planarity_Test_Options robust_opts = strict_opts;
1133 robust_opts.embedding_allow_bruteforce_fallback = true;
1134
1135 const auto r_robust = planarity_test(built.g, robust_opts);
1136 EXPECT_TRUE(r_robust.is_planar);
1137 EXPECT_TRUE(r_robust.has_combinatorial_embedding);
1138}
1139
1140
1141// The LR embedding of K5 - e needed local repairs, which a budget of one
1142// combination cut; the embedding phase of the LR algorithm needs none
1143TEST(PlanarityTest, StrictLREmbeddingNeedsNoRepairBudget)
1144{
1145 auto edges = complete_graph_edges(5);
1146 edges.erase(edges.begin()); // K5 - e, planar
1147 auto built = build_ugraph(5, edges);
1148
1150 opts.compute_embedding = true;
1152 opts.embedding_max_combinations = 0; // no local repair at all
1153
1154 const auto r = planarity_test(built.g, opts);
1155
1156 EXPECT_TRUE(r.is_planar);
1157 EXPECT_TRUE(r.has_combinatorial_embedding);
1158 EXPECT_TRUE(r.embedding_is_lr_linear);
1159 EXPECT_FALSE(r.embedding_search_truncated);
1160 EXPECT_EQ(r.embedding_num_faces, edges.size() - 5 + 2);
1161 EXPECT_TRUE(is_planar_embedding(built, edges, r));
1162}
1163
1164
1165namespace
1166{
1167 // The embedding of a planar graph, which the LR algorithm must give alone
1168 Planarity_Test_Result<UGraph> strict_lr_embedding(const Built_Graph<UGraph> & built)
1169 {
1171 opts.compute_embedding = true;
1174 return planarity_test(built.g, opts);
1175 }
1176
1177 std::vector<Edge> grid_edges(const size_t w)
1178 {
1179 std::vector<Edge> edges;
1180 for (size_t i = 0; i < w; ++i)
1181 for (size_t j = 0; j < w; ++j)
1182 {
1183 if (j + 1 < w)
1184 edges.emplace_back(i * w + j, i * w + j + 1);
1185 if (i + 1 < w)
1186 edges.emplace_back(i * w + j, (i + 1) * w + j);
1187 }
1188 return edges;
1189 }
1190}
1191
1192
1193// The LR embedding failed for every grid from 4 x 4 on, and the local
1194// repairs took long to give up: 0.8 s for that grid, 5 min for 40 x 40
1195TEST(PlanarityTest, StrictLREmbeddingOfGrids)
1196{
1197 for (const size_t w : {2u, 3u, 4u, 6u, 20u, 40u})
1198 {
1199 SCOPED_TRACE("grid " + std::to_string(w));
1200 const auto edges = grid_edges(w);
1201 auto built = build_ugraph(w * w, edges);
1202 const auto r = strict_lr_embedding(built);
1203
1204 ASSERT_TRUE(r.is_planar);
1205 ASSERT_TRUE(r.has_combinatorial_embedding);
1206 EXPECT_TRUE(r.embedding_is_lr_linear);
1207 EXPECT_EQ(r.embedding_num_faces, (w - 1) * (w - 1) + 1);
1208 EXPECT_TRUE(is_planar_embedding(built, edges, r));
1209 }
1210}
1211
1212
1213// Maximal planar graphs, with all their edges or some of them, are the
1214// densest: each face of their embeddings is a triangle
1215TEST(PlanarityTest, StrictLREmbeddingOfMaximalPlanarGraphs)
1216{
1217 std::mt19937 gen(0x5EED);
1218 for (size_t trial = 0; trial < 60; ++trial)
1219 {
1220 const size_t n = 4 + gen() % 80;
1221 auto edges = random_maximal_planar_edges(n, gen);
1222 const bool all = trial % 3 == 0;
1223 if (not all)
1224 {
1225 std::shuffle(edges.begin(), edges.end(), gen);
1226 edges.resize(edges.size() - gen() % (edges.size() / 2));
1227 }
1228
1229 SCOPED_TRACE("trial " + std::to_string(trial) + " n " + std::to_string(n));
1230 auto built = build_ugraph(n, edges);
1231 const auto r = strict_lr_embedding(built);
1232
1233 ASSERT_TRUE(r.is_planar);
1234 ASSERT_TRUE(r.has_combinatorial_embedding);
1235 EXPECT_TRUE(r.embedding_is_lr_linear);
1236 EXPECT_TRUE(is_planar_embedding(built, edges, r));
1237 if (all)
1238 {
1239 EXPECT_EQ(r.embedding_num_faces, 2 * n - 4);
1240 }
1241 }
1242}
1243
1244
1245// Grids with a diagonal in each cell, and some of their edges
1246TEST(PlanarityTest, StrictLREmbeddingOfTriangulatedGrids)
1247{
1248 std::mt19937 gen(0xD1A6);
1249 for (size_t trial = 0; trial < 60; ++trial)
1250 {
1251 const size_t w = 2 + gen() % 12, h = 2 + gen() % 12;
1252 std::vector<Edge> edges;
1253 for (size_t i = 0; i < h; ++i)
1254 for (size_t j = 0; j < w; ++j)
1255 {
1256 if (j + 1 < w)
1257 edges.emplace_back(i * w + j, i * w + j + 1);
1258 if (i + 1 < h)
1259 edges.emplace_back(i * w + j, (i + 1) * w + j);
1260 if (i + 1 < h and j + 1 < w)
1261 {
1262 if (gen() % 2)
1263 edges.emplace_back(i * w + j, (i + 1) * w + j + 1);
1264 else
1265 edges.emplace_back(i * w + j + 1, (i + 1) * w + j);
1266 }
1267 }
1268 std::shuffle(edges.begin(), edges.end(), gen);
1269 edges.resize(edges.size() - gen() % (edges.size() / 3 + 1));
1270
1271 SCOPED_TRACE("trial " + std::to_string(trial));
1272 auto built = build_ugraph(w * h, edges);
1273 const auto r = strict_lr_embedding(built);
1274
1275 ASSERT_TRUE(r.is_planar);
1276 ASSERT_TRUE(r.has_combinatorial_embedding);
1277 EXPECT_TRUE(r.embedding_is_lr_linear);
1278 EXPECT_TRUE(is_planar_embedding(built, edges, r));
1279 }
1280}
1281
1282
1283TEST(PlanarityTest, EmbeddingCanBeTruncatedByCombinationBound)
1284{
1285 auto edges = complete_graph_edges(5);
1286 edges.erase(edges.begin()); // still enough rotation combinations
1287 auto built = build_ugraph(5, edges);
1288
1290 opts.compute_embedding = true;
1291 opts.embedding_prefer_lr_linear = false;
1293
1294 const auto r = planarity_test(built.g, opts);
1295
1296 EXPECT_TRUE(r.is_planar);
1297 EXPECT_FALSE(r.has_combinatorial_embedding);
1298 EXPECT_TRUE(r.embedding_search_truncated);
1299}
1300
1301
1302TEST(PlanarityTest, K33MinusEdgeIsPlanar)
1303{
1304 auto edges = complete_bipartite_edges(3, 3);
1305 edges.erase(edges.begin());
1306
1307 auto built = build_ugraph(6, edges);
1308 const auto r = planarity_test(built.g);
1309
1310 EXPECT_TRUE(r.is_planar);
1311}
1312
1313
1314TEST(PlanarityTest, SubdivisionOfK33IsNonPlanar)
1315{
1316 auto edges = complete_bipartite_edges(3, 3);
1317
1318 // Replace edge (0,3) by 0-6-3
1319 auto it = std::find(edges.begin(), edges.end(), Edge{0, 3});
1320 ASSERT_NE(it, edges.end());
1321 edges.erase(it);
1322 edges.emplace_back(0, 6);
1323 edges.emplace_back(6, 3);
1324
1325 auto built = build_ugraph(7, edges);
1326 const auto r = planarity_test(built.g);
1327
1328 EXPECT_FALSE(r.is_planar);
1329}
1330
1331
1332TEST(PlanarityTest, CertificateCanBeTruncatedByEdgeBudget)
1333{
1334 auto built = build_ugraph(5, complete_graph_edges(5));
1335
1338 opts.certificate_max_edges = 5; // K5 has 10 simplified edges
1339
1340 const auto r = planarity_test(built.g, opts);
1341
1342 EXPECT_FALSE(r.is_planar);
1343 EXPECT_FALSE(r.has_nonplanar_certificate);
1344 EXPECT_TRUE(r.certificate_search_truncated);
1345}
1346
1347
1348TEST(PlanarityTest, CertificateDetectsK5InsideBiggerGraph)
1349{
1350 auto built = build_ugraph(8, {
1351 {0, 1}, {0, 2}, {0, 3}, {0, 4},
1352 {1, 2}, {1, 3}, {1, 4},
1353 {2, 3}, {2, 4}, {3, 4}, // K5 on 0..4
1354 {2, 5}, {5, 6}, {6, 7} // extra planar tail
1355 });
1356
1359
1360 const auto r = planarity_test(built.g, opts);
1361
1362 EXPECT_FALSE(r.is_planar);
1363 EXPECT_TRUE(r.has_nonplanar_certificate);
1364 EXPECT_EQ(r.certificate_type, Planarity_Certificate_Type::K5_Subdivision);
1365 EXPECT_EQ(r.certificate_branch_nodes.size(), 5u);
1366 EXPECT_EQ(r.certificate_paths.size(), 10u);
1367}
1368
1369
1370TEST(PlanarityTest, CertificateDetectsK33InsideBiggerGraph)
1371{
1372 auto built = build_ugraph(9, {
1373 {0, 3}, {0, 4}, {0, 5},
1374 {1, 3}, {1, 4}, {1, 5},
1375 {2, 3}, {2, 4}, {2, 5}, // K3,3 on {0,1,2} x {3,4,5}
1376 {0, 8}, {8, 7}, {7, 6} // extra planar tail
1377 });
1378
1381
1382 const auto r = planarity_test(built.g, opts);
1383
1384 EXPECT_FALSE(r.is_planar);
1385 EXPECT_TRUE(r.has_nonplanar_certificate);
1386 EXPECT_EQ(r.certificate_type, Planarity_Certificate_Type::K33_Subdivision);
1387 EXPECT_EQ(r.certificate_branch_nodes.size(), 6u);
1388 EXPECT_EQ(r.certificate_paths.size(), 9u);
1389}
1390
1391
1392TEST(PlanarityTest, CertificateBranchSearchCanBeTruncated)
1393{
1394 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1395
1399
1400 const auto r = planarity_test(built.g, opts);
1401
1402 EXPECT_FALSE(r.is_planar);
1403 EXPECT_TRUE(r.has_nonplanar_certificate);
1404 EXPECT_EQ(r.certificate_type,
1405 Planarity_Certificate_Type::Minimal_NonPlanar_Obstruction);
1406 EXPECT_TRUE(r.certificate_search_truncated);
1407}
1408
1409
1410TEST(PlanarityTest, DisconnectedWithNonPlanarComponentIsNonPlanar)
1411{
1412 std::vector<Edge> edges = complete_graph_edges(5); // non-planar component
1413 edges.emplace_back(6, 7); // independent planar component
1414
1415 auto built = build_ugraph(8, edges);
1416 const auto r = planarity_test(built.g);
1417
1418 EXPECT_FALSE(r.is_planar);
1419}
1420
1421
1422TEST(PlanarityTest, DisconnectedPlanarGraphIsNotRejectedByGlobalEulerBound)
1423{
1424 // Connected component {0,1,2,4} has n=4, m=4 and is planar.
1425 // Node 3 is isolated, so a naive global bound m <= 3n - 6c would fail here.
1426 auto built = build_ugraph(5, {
1427 {0, 2}, {1, 2}, {1, 4}, {2, 4}
1428 });
1429
1430 const auto r = planarity_test(built.g);
1431
1432 EXPECT_TRUE(r.is_planar);
1433 EXPECT_FALSE(r.failed_euler_bound);
1434}
1435
1436
1437TEST(PlanarityTest, LoopsAndParallelArcsAreIgnoredInNormalization)
1438{
1439 auto built = build_ugraph(3, {{0, 1}, {1, 2}, {2, 0}});
1440
1441 // Add loops
1442 built.arcs.push_back(built.g.insert_arc(built.nodes[0], built.nodes[0], 1));
1443 built.arcs.push_back(built.g.insert_arc(built.nodes[2], built.nodes[2], 1));
1444
1445 // Add parallel edges
1446 built.arcs.push_back(built.g.insert_arc(built.nodes[0], built.nodes[1], 1));
1447 built.arcs.push_back(built.g.insert_arc(built.nodes[1], built.nodes[0], 1));
1448
1449 const auto r = planarity_test(built.g);
1450
1451 EXPECT_TRUE(r.is_planar);
1452 EXPECT_GE(r.ignored_loops, 2u);
1453 EXPECT_GE(r.ignored_parallel_arcs, 2u);
1454}
1455
1456
1457TEST(PlanarityTest, DirectedInputUsesUnderlyingUndirectedGraph)
1458{
1459 // Oriented K3,3
1460 auto built = build_dgraph(6, {
1461 {0, 3}, {0, 4}, {0, 5},
1462 {1, 3}, {1, 4}, {1, 5},
1463 {2, 3}, {2, 4}, {2, 5}
1464 });
1465
1466 const auto r = planarity_test(built.g);
1467 EXPECT_TRUE(r.input_is_digraph);
1468 EXPECT_FALSE(r.is_planar);
1469}
1470
1471
1472TEST(PlanarityTest, ArrayGraphBackendWorks)
1473{
1474 auto planar = build_array_ugraph(5, {
1475 {0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {0, 2}
1476 });
1477 auto non_planar = build_array_ugraph(5, complete_graph_edges(5));
1478
1479 EXPECT_TRUE(is_planar_graph(planar.g));
1480 EXPECT_FALSE(is_planar_graph(non_planar.g));
1481}
1482
1483
1484TEST(PlanarityTest, FunctorApisMatchFreeFunctions)
1485{
1486 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1487
1488 const bool b1 = is_planar_graph(built.g);
1489 const bool b2 = Is_Planar_Graph<UGraph>()(built.g);
1490 const auto r1 = planarity_test(built.g);
1491 const auto r2 = Planarity_Test<UGraph>()(built.g);
1492
1493 EXPECT_EQ(b1, b2);
1494 EXPECT_EQ(r1.is_planar, r2.is_planar);
1495}
1496
1497
1498TEST(PlanarityTest, RandomSmallGraphsMatchBruteforceOracle)
1499{
1500 std::mt19937_64 rng(0xA11CE123456789ULL);
1501 std::uniform_int_distribution<int> n_dist(1, 7);
1502 std::bernoulli_distribution has_edge(0.35);
1503
1504 size_t checked = 0;
1505 for (size_t trial = 0; trial < 3000 and checked < 70; ++trial)
1506 {
1507 const size_t n = static_cast<size_t>(n_dist(rng));
1508 std::vector<Edge> edges;
1509
1510 for (size_t u = 0; u < n; ++u)
1511 for (size_t v = u + 1; v < n; ++v)
1512 if (has_edge(rng))
1513 edges.emplace_back(u, v);
1514
1515 const auto oracle = brute_force_planarity_oracle(n, edges);
1516 if (not oracle.has_value())
1517 continue;
1518
1519 auto built = build_ugraph(n, edges);
1520 const auto got = is_planar_graph(built.g);
1521 EXPECT_EQ(got, *oracle) << "trial=" << trial;
1522 ++checked;
1523 }
1524
1525 EXPECT_GE(checked, 50u);
1526}
1527
1528
1529TEST(PlanarityTest, RandomSmallPlanarGraphsHaveStrictLREmbedding)
1530{
1531 std::mt19937_64 rng(0xD00D1234A11CEULL);
1532 std::uniform_int_distribution<int> n_dist(1, 7);
1533 std::bernoulli_distribution has_edge(0.36);
1534
1535 Planarity_Test_Options strict_opts;
1536 strict_opts.compute_embedding = true;
1537 strict_opts.embedding_allow_bruteforce_fallback = false;
1538 Planarity_Test_Options robust_opts = strict_opts;
1539 robust_opts.embedding_allow_bruteforce_fallback = true;
1540
1541 size_t checked = 0;
1542 for (size_t trial = 0; trial < 5000 and checked < 70; ++trial)
1543 {
1544 const size_t n = static_cast<size_t>(n_dist(rng));
1545 std::vector<Edge> edges;
1546
1547 for (size_t u = 0; u < n; ++u)
1548 for (size_t v = u + 1; v < n; ++v)
1549 if (has_edge(rng))
1550 edges.emplace_back(u, v);
1551
1552 const auto oracle = brute_force_planarity_oracle(n, edges);
1553 if (not oracle.has_value() or not *oracle)
1554 continue;
1555
1556 auto built = build_ugraph(n, edges);
1557 const auto r_strict = planarity_test(built.g, strict_opts);
1558 const auto r_robust = planarity_test(built.g, robust_opts);
1559
1560 SCOPED_TRACE("trial=" + std::to_string(trial)
1561 + " n=" + std::to_string(n)
1562 + " m=" + std::to_string(edges.size()));
1563
1564 EXPECT_TRUE(r_strict.is_planar);
1565 EXPECT_TRUE(r_strict.has_combinatorial_embedding);
1566 EXPECT_TRUE(r_strict.embedding_is_lr_linear);
1567 EXPECT_FALSE(r_strict.embedding_search_truncated);
1568
1569 EXPECT_TRUE(r_robust.is_planar);
1570 EXPECT_TRUE(r_robust.has_combinatorial_embedding);
1571
1572 ++checked;
1573 }
1574
1575 EXPECT_GE(checked, 50u);
1576}
1577
1578
1579TEST(PlanarityTest, PlanarGeometricDrawingRequiresEmbedding)
1580{
1581 auto built = build_ugraph(3, {
1582 {0, 1}, {1, 2}, {2, 0}
1583 });
1584
1585 const auto r = planarity_test(built.g); // no embedding requested
1586 EXPECT_TRUE(r.is_planar);
1587 EXPECT_FALSE(r.has_combinatorial_embedding);
1588 EXPECT_ANY_THROW((void) planar_geometric_drawing(r));
1589}
1590
1591
1592TEST(PlanarityTest, PlanarGeometricDrawingConnectedIsCrossingFree)
1593{
1594 auto built = build_ugraph(5, {
1595 {0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {0, 2}
1596 });
1597
1599 opts.compute_embedding = true;
1600 opts.embedding_allow_bruteforce_fallback = false;
1601
1602 const auto r = planarity_test(built.g, opts);
1603 ASSERT_TRUE(r.is_planar);
1604 ASSERT_TRUE(r.has_combinatorial_embedding);
1605
1606 const auto d = planar_geometric_drawing(r);
1607 EXPECT_TRUE(d.drawing_available);
1608 EXPECT_TRUE(d.drawing_validated_no_crossings);
1609 EXPECT_EQ(d.crossing_count, 0u);
1610 EXPECT_EQ(d.node_positions.size(), r.simplified_num_nodes);
1611
1612 bool distinct = false;
1613 for (size_t i = 1; i < d.node_positions.size(); ++i)
1614 if (std::abs(d.node_positions[i].x - d.node_positions[0].x) > 1e-9
1615 or std::abs(d.node_positions[i].y - d.node_positions[0].y) > 1e-9)
1616 {
1617 distinct = true;
1618 break;
1619 }
1620 EXPECT_TRUE(distinct);
1621}
1622
1623
1624TEST(PlanarityTest, PlanarGeometricDrawingDensePlanarSampleWorksInStrictMode)
1625{
1626 auto edges = complete_graph_edges(5);
1627 edges.erase(edges.begin()); // K5 - e
1628 auto built = build_ugraph(5, edges);
1629
1631 opts.compute_embedding = true;
1633
1634 const auto r = planarity_test(built.g, opts);
1635 ASSERT_TRUE(r.is_planar);
1636 ASSERT_TRUE(r.has_combinatorial_embedding);
1637
1638 const auto d = planar_geometric_drawing(r);
1639 EXPECT_TRUE(d.drawing_available);
1640 EXPECT_TRUE(d.drawing_validated_no_crossings);
1641 EXPECT_EQ(d.crossing_count, 0u);
1642 EXPECT_NE(d.chosen_outer_face, std::numeric_limits<size_t>::max());
1643}
1644
1645
1646TEST(PlanarityTest, PlanarGeometricDrawingDisconnectedComponentsAreSeparated)
1647{
1648 auto built = build_ugraph(6, {
1649 {0, 1}, {1, 2}, {2, 0}, // component 1
1650 {3, 4}, {4, 5}, {5, 3} // component 2
1651 });
1652
1654 opts.compute_embedding = true;
1655 opts.embedding_allow_bruteforce_fallback = false;
1656 const auto r = planarity_test(built.g, opts);
1657 ASSERT_TRUE(r.is_planar);
1658 ASSERT_TRUE(r.has_combinatorial_embedding);
1659
1660 const auto d = planar_geometric_drawing(r);
1661 EXPECT_TRUE(d.drawing_available);
1662 EXPECT_TRUE(d.drawing_validated_no_crossings);
1663 EXPECT_EQ(d.num_components, 2u);
1664
1665 double min_x_a = std::numeric_limits<double>::max();
1666 double max_x_a = -std::numeric_limits<double>::max();
1667 double min_x_b = std::numeric_limits<double>::max();
1668 double max_x_b = -std::numeric_limits<double>::max();
1669
1670 for (auto it = d.node_positions.get_it(); it.has_curr(); it.next_ne())
1671 {
1672 const auto & p = it.get_curr_ne();
1673 if (p.node == built.nodes[0] or p.node == built.nodes[1] or p.node == built.nodes[2])
1674 {
1675 min_x_a = std::min(min_x_a, p.x);
1676 max_x_a = std::max(max_x_a, p.x);
1677 }
1678 else
1679 {
1680 min_x_b = std::min(min_x_b, p.x);
1681 max_x_b = std::max(max_x_b, p.x);
1682 }
1683 }
1684
1685 EXPECT_GT(min_x_b - max_x_a, 0.5);
1686}
1687
1688
1689TEST(PlanarityTest, PlanarGeometricDrawingCanBeTruncatedByFaceBudget)
1690{
1691 auto built = build_ugraph(5, {
1692 {0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}, {0, 2}
1693 });
1694
1696 opts.compute_embedding = true;
1697 opts.embedding_allow_bruteforce_fallback = false;
1698 const auto r = planarity_test(built.g, opts);
1699 ASSERT_TRUE(r.is_planar);
1700 ASSERT_TRUE(r.has_combinatorial_embedding);
1701
1703 dopt.max_outer_faces_to_try = 0;
1704
1705 const auto d = planar_geometric_drawing(r, dopt);
1706 EXPECT_FALSE(d.drawing_available);
1707 EXPECT_TRUE(d.drawing_search_truncated);
1708}
1709
1710
1711TEST(PlanarityTest, NonPlanarCertificateExportsToJsonAndDot)
1712{
1713 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1714
1717
1718 const auto r = planarity_test(built.g, opts);
1719 ASSERT_FALSE(r.is_planar);
1720 ASSERT_TRUE(r.has_nonplanar_certificate);
1721
1722 const auto json = nonplanar_certificate_to_json(r);
1723 const auto dot = nonplanar_certificate_to_dot(r);
1724
1725 EXPECT_NE(json.find("\"certificate_type\": \"K33_Subdivision\""), std::string::npos);
1726 EXPECT_NE(json.find("\"obstruction_edges\""), std::string::npos);
1727 EXPECT_NE(dot.find("graph NonPlanarCertificate"), std::string::npos);
1728 EXPECT_NE(dot.find("obs x"), std::string::npos);
1729}
1730
1731
1732TEST(PlanarityTest, NonPlanarCertificateExportSupportsCustomLabelsAndOptions)
1733{
1734 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1735
1738
1739 const auto r = planarity_test(built.g, opts);
1740 ASSERT_FALSE(r.is_planar);
1741 ASSERT_TRUE(r.has_nonplanar_certificate);
1742
1744 eopt.pretty_json = false;
1745 eopt.dot_highlight_paths = false;
1746
1747 const auto labeler = [](UGraph::Node *) -> std::string
1748 {
1749 return "q\"\\\n";
1750 };
1751
1752 const auto json = nonplanar_certificate_to_json(r, labeler, eopt);
1753 const auto dot = nonplanar_certificate_to_dot(r, labeler, eopt);
1754
1755 EXPECT_EQ(json.find('\n'), std::string::npos);
1756 EXPECT_NE(json.find("q\\\"\\\\\\n"), std::string::npos);
1757 EXPECT_NE(dot.find("q\\\"\\\\\\n"), std::string::npos);
1758 EXPECT_EQ(dot.find("label=\"p"), std::string::npos);
1759 EXPECT_NE(dot.find("obs x"), std::string::npos);
1760}
1761
1762
1763TEST(PlanarityTest, NonPlanarCertificateExportsToGraphmlAndGexf)
1764{
1765 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1766
1769 const auto r = planarity_test(built.g, opts);
1770 ASSERT_FALSE(r.is_planar);
1771 ASSERT_TRUE(r.has_nonplanar_certificate);
1772
1773 const auto graphml = nonplanar_certificate_to_graphml(r);
1774 const auto gexf = nonplanar_certificate_to_gexf(r);
1775
1776 EXPECT_NE(graphml.find("<graphml"), std::string::npos);
1777 EXPECT_NE(graphml.find("kind"), std::string::npos);
1778 EXPECT_NE(graphml.find("obstruction"), std::string::npos);
1779
1780 EXPECT_NE(gexf.find("<gexf"), std::string::npos);
1781 EXPECT_NE(gexf.find("defaultedgetype=\"undirected\""), std::string::npos);
1782 EXPECT_NE(gexf.find("obstruction"), std::string::npos);
1783}
1784
1785
1786TEST(PlanarityTest, NonPlanarCertificateExportExchangeFormatsCanDisablePathOverlay)
1787{
1788 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1789
1792 const auto r = planarity_test(built.g, opts);
1793 ASSERT_FALSE(r.is_planar);
1794 ASSERT_TRUE(r.has_nonplanar_certificate);
1795
1797 eopt.graphml_include_paths = false;
1798 eopt.gexf_include_paths = false;
1799
1802
1803 EXPECT_EQ(graphml.find(">path<"), std::string::npos);
1804 EXPECT_EQ(gexf.find("value=\"path\""), std::string::npos);
1805}
1806
1807
1808TEST(PlanarityTest, NonPlanarCertificateValidationAcceptsGeneratedCertificate)
1809{
1810 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1811
1814 const auto r = planarity_test(built.g, opts);
1815 ASSERT_FALSE(r.is_planar);
1816 ASSERT_TRUE(r.has_nonplanar_certificate);
1817
1818 const auto vr = validate_nonplanar_certificate(r);
1819 EXPECT_TRUE(vr.has_certificate);
1820 EXPECT_TRUE(vr.is_valid);
1821 EXPECT_EQ(vr.num_obstruction_edges, r.certificate_obstruction_edges.size());
1822 EXPECT_EQ(vr.num_paths, r.certificate_paths.size());
1823 EXPECT_EQ(vr.path_edge_not_in_obstruction, 0u);
1824}
1825
1826
1827TEST(PlanarityTest, NonPlanarCertificateValidationDetectsTamperedPathEdge)
1828{
1829 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1830
1833 auto r = planarity_test(built.g, opts);
1834 ASSERT_FALSE(r.is_planar);
1835 ASSERT_TRUE(r.has_nonplanar_certificate);
1836 ASSERT_FALSE(r.certificate_paths.is_empty());
1837 ASSERT_FALSE(r.certificate_paths[0].edges.is_empty());
1838
1839 r.certificate_paths[0].edges[0].src = nullptr;
1840
1841 const auto vr = validate_nonplanar_certificate(r);
1842 EXPECT_TRUE(vr.has_certificate);
1843 EXPECT_FALSE(vr.is_valid);
1844 EXPECT_GT(vr.null_path_edge_endpoints, 0u);
1845 EXPECT_FALSE(nonplanar_certificate_is_valid(r));
1846}
1847
1848
1849TEST(PlanarityTest, ExternalCertificateValidatorAcceptsGraphmlAndGexf)
1850{
1851 if (not has_ruby_and_validator_script())
1852 {
1853 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
1854 return;
1855 }
1856
1857 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1858
1861 const auto r = planarity_test(built.g, opts);
1862 ASSERT_FALSE(r.is_planar);
1863 ASSERT_TRUE(r.has_nonplanar_certificate);
1864
1865 const std::string graphml_path = make_tmp_path("external_valid", ".graphml");
1866 const std::string gexf_path = make_tmp_path("external_valid", ".gexf");
1867
1868 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
1869 write_text_file(gexf_path, nonplanar_certificate_to_gexf(r));
1870
1871 const int rc = run_external_certificate_validator({graphml_path, gexf_path});
1872 EXPECT_EQ(rc, 0);
1873}
1874
1875
1876TEST(PlanarityTest, ExternalCertificateValidatorRejectsMissingObstruction)
1877{
1878 if (not has_ruby_and_validator_script())
1879 {
1880 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
1881 return;
1882 }
1883
1884 const std::string broken_graphml = make_tmp_path("external_invalid", ".graphml");
1885 write_text_file(broken_graphml, R"(<?xml version="1.0" encoding="UTF-8"?>
1886<graphml xmlns="http://graphml.graphdrawing.org/xmlns">
1887 <graph id="Broken" edgedefault="undirected">
1888 <node id="n0"/>
1889 <node id="n1"/>
1890 <edge id="e0" source="n0" target="n1">
1891 <data key="k_edge_kind">path</data>
1892 <data key="k_edge_path_id">0</data>
1893 </edge>
1894 </graph>
1895</graphml>
1896)");
1897
1898 const int rc = run_external_certificate_validator({broken_graphml});
1899 EXPECT_NE(rc, 0);
1900}
1901
1902
1903TEST(PlanarityTest, ExternalCertificateValidatorNetworkxModeIsPortable)
1904{
1905
1906 if (not has_ruby_and_validator_script() or not has_python3())
1907 {
1908 GTEST_SKIP() << "Skipped: Ruby, validator script, or python3 not found";
1909 return;
1910 }
1911
1912 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1913
1916 const auto r = planarity_test(built.g, opts);
1917 ASSERT_FALSE(r.is_planar);
1918 ASSERT_TRUE(r.has_nonplanar_certificate);
1919
1920 const std::string graphml_path = make_tmp_path("external_nx", ".graphml");
1921 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
1922
1923 const int rc_optional = run_external_certificate_validator({graphml_path}, true, false);
1924 EXPECT_EQ(rc_optional, 0);
1925
1926 const int has_nx = std::system(
1927 "python3 -c \"import importlib.util,sys; sys.exit(0 if importlib.util.find_spec('networkx') else 1)\"");
1928 const int rc_required = run_external_certificate_validator({graphml_path}, true, true);
1929
1930 if (has_nx == 0)
1931 EXPECT_EQ(rc_required, 0);
1932 else
1933 EXPECT_NE(rc_required, 0);
1934}
1935
1936
1937TEST(PlanarityTest, ExternalCertificateValidatorGephiModeIsPortable)
1938{
1939 if (not has_ruby_and_validator_script())
1940 {
1941 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
1942 return;
1943 }
1944
1945 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1946
1949 const auto r = planarity_test(built.g, opts);
1950 ASSERT_FALSE(r.is_planar);
1951 ASSERT_TRUE(r.has_nonplanar_certificate);
1952
1953 const std::string graphml_path = make_tmp_path("external_gephi", ".graphml");
1954 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
1955
1956 const int rc_optional = run_external_certificate_validator(
1957 {graphml_path}, false, false, true, false);
1958 EXPECT_EQ(rc_optional, 0);
1959
1960 const std::string lbl = "gephi_portable_mode";
1961 const int rc_required = run_external_certificate_validator(
1962 {graphml_path}, false, false, true, true, "", "", lbl);
1963 EXPECT_EQ(rc_required, 0);
1964
1965 const std::string report = read_text_file(validator_stdout_path(lbl));
1966 EXPECT_NE(report.find("overall_valid=true"), std::string::npos);
1967 EXPECT_NE(report.find("running smoke check only"), std::string::npos);
1968}
1969
1970
1971TEST(PlanarityTest, ExternalCertificateValidatorGephiCustomTemplateWorks)
1972{
1973 if (not has_ruby_and_validator_script())
1974 {
1975 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
1976 return;
1977 }
1978
1979 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
1980
1983 const auto r = planarity_test(built.g, opts);
1984 ASSERT_FALSE(r.is_planar);
1985 ASSERT_TRUE(r.has_nonplanar_certificate);
1986
1987 const std::string graphml_path = make_tmp_path("external_gephi_tpl", ".graphml");
1988 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
1989
1990 const std::string cmd_template =
1991 "ruby -e \"File.stat(ARGV[0])\" {input}";
1992
1993 const int rc = run_external_certificate_validator(
1994 {graphml_path}, false, false, true, true, cmd_template);
1995 EXPECT_EQ(rc, 0);
1996}
1997
1998
1999TEST(PlanarityTest, ExternalCertificateValidatorGephiTemplateSupportsInputPathWithSpaces)
2000{
2001 namespace fs = std::filesystem;
2002
2003 if (not has_ruby_and_validator_script())
2004 {
2005 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2006 return;
2007 }
2008
2009 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2010
2013 const auto r = planarity_test(built.g, opts);
2014 ASSERT_FALSE(r.is_planar);
2015 ASSERT_TRUE(r.has_nonplanar_certificate);
2016
2017 const fs::path dir = scratch_dir() / "aleph planarity gephi spaces";
2018 fs::create_directories(dir);
2019 const std::string graphml_path = (dir / "k33 certificate.graphml").string();
2020 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2021
2022 const std::string cmd_template =
2023 "ruby -e \"File.stat(ARGV[0])\" {input}";
2024
2025 const int rc = run_external_certificate_validator(
2026 {graphml_path}, false, false, true, true, cmd_template);
2027 EXPECT_EQ(rc, 0);
2028}
2029
2030
2031TEST(PlanarityTest, ExternalCertificateValidatorCanListGephiTemplates)
2032{
2033 if (not has_ruby_and_validator_script())
2034 {
2035 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2036 return;
2037 }
2038
2039 const std::string lbl = "list_templates";
2040 const int rc = run_external_certificate_validator(
2041 {}, false, false, false, false, "", "--list-gephi-templates --json", lbl);
2042 EXPECT_EQ(rc, 0);
2043
2044 const std::string out = read_text_file(validator_stdout_path(lbl));
2045 EXPECT_NE(out.find("\"templates\""), std::string::npos);
2046 EXPECT_NE(out.find("portable.ruby-file-exists"), std::string::npos);
2047 EXPECT_NE(out.find("linux.gephi-0.10.smoke"), std::string::npos);
2048 EXPECT_NE(out.find("macos.gephi-0.10.smoke"), std::string::npos);
2049 EXPECT_NE(out.find("windows.gephi-0.10.smoke"), std::string::npos);
2050}
2051
2052
2053TEST(PlanarityTest, ExternalCertificateValidatorCanFilterGephiTemplatesByOs)
2054{
2055 if (not has_ruby_and_validator_script())
2056 {
2057 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2058 return;
2059 }
2060
2061 const std::string lbl = "filter_templates_os";
2062 const int rc = run_external_certificate_validator(
2063 {}, false, false, false, false, "",
2064 "--list-gephi-templates --template-os windows --json", lbl);
2065 EXPECT_EQ(rc, 0);
2066
2067 const std::string out = read_text_file(validator_stdout_path(lbl));
2068 EXPECT_NE(out.find("windows.gephi-0.10.smoke"), std::string::npos);
2069 EXPECT_EQ(out.find("linux.gephi-0.10.smoke"), std::string::npos);
2070}
2071
2072
2073TEST(PlanarityTest, ExternalCertificateValidatorCanListGephiRenderProfiles)
2074{
2075 if (not has_ruby_and_validator_script())
2076 {
2077 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2078 return;
2079 }
2080
2081 const std::string lbl = "list_profiles";
2082 const int rc = run_external_certificate_validator(
2083 {}, false, false, false, false, "",
2084 "--list-gephi-render-profiles --json", lbl);
2085 EXPECT_EQ(rc, 0);
2086
2087 const std::string out = read_text_file(validator_stdout_path(lbl));
2088 EXPECT_NE(out.find("\"profiles\""), std::string::npos);
2089 EXPECT_NE(out.find("portable.ruby-render-svg"), std::string::npos);
2090 EXPECT_NE(out.find("linux.gephi-0.10.render-svg"), std::string::npos);
2091 EXPECT_NE(out.find("macos.gephi-0.10.render-svg"), std::string::npos);
2092 EXPECT_NE(out.find("windows.gephi-0.10.render-svg"), std::string::npos);
2093}
2094
2095
2096TEST(PlanarityTest, ExternalCertificateValidatorCanFilterRenderProfilesByOs)
2097{
2098 if (not has_ruby_and_validator_script())
2099 {
2100 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2101 return;
2102 }
2103
2104 const std::string lbl = "filter_profiles_os";
2105 const int rc = run_external_certificate_validator(
2106 {}, false, false, false, false, "",
2107 "--list-gephi-render-profiles --render-os windows --json", lbl);
2108 EXPECT_EQ(rc, 0);
2109
2110 const std::string out = read_text_file(validator_stdout_path(lbl));
2111 EXPECT_NE(out.find("windows.gephi-0.10.render-svg"), std::string::npos);
2112 EXPECT_EQ(out.find("linux.gephi-0.10.render-svg"), std::string::npos);
2113}
2114
2115
2116TEST(PlanarityTest, ExternalCertificateValidatorGephiCatalogTemplateWorks)
2117{
2118 if (not has_ruby_and_validator_script())
2119 {
2120 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2121 return;
2122 }
2123
2124 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2125
2128 const auto r = planarity_test(built.g, opts);
2129 ASSERT_FALSE(r.is_planar);
2130 ASSERT_TRUE(r.has_nonplanar_certificate);
2131
2132 const std::string graphml_path = make_tmp_path("external_gephi_catalog", ".graphml");
2133 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2134
2135 const int rc = run_external_certificate_validator(
2136 {graphml_path}, false, false, true, true, "",
2137 "--gephi-template portable.ruby-file-exists");
2138 EXPECT_EQ(rc, 0);
2139}
2140
2141
2142TEST(PlanarityTest, ExternalCertificateValidatorRenderSvgProfileProducesArtifact)
2143{
2144 namespace fs = std::filesystem;
2145
2146 if (not has_ruby_and_validator_script())
2147 {
2148 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2149 return;
2150 }
2151
2152 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2153
2156 const auto r = planarity_test(built.g, opts);
2157 ASSERT_FALSE(r.is_planar);
2158 ASSERT_TRUE(r.has_nonplanar_certificate);
2159
2160 const std::string graphml_path = make_tmp_path("external_render_svg", ".graphml");
2161 const std::string output_dir = make_tmp_path("external_render_svg_dir", "");
2162 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2163
2164 const std::string lbl = "render_svg";
2165 const int rc = run_external_certificate_validator(
2166 {graphml_path}, false, false, false, false, "",
2167 "--render-gephi --require-render "
2168 "--render-profile portable.ruby-render-svg "
2169 "--render-output-dir " + shell_quote(output_dir),
2170 lbl);
2171 EXPECT_EQ(rc, 0);
2172
2173 const fs::path out_path = fs::path(output_dir) /
2174 (fs::path(graphml_path).stem().string() + ".svg");
2175 EXPECT_TRUE(fs::exists(out_path));
2176 EXPECT_GT(fs::file_size(out_path), 0u);
2177
2178 const std::string out = read_text_file(validator_stdout_path(lbl));
2179 EXPECT_NE(out.find("render_output_kind"), std::string::npos);
2180 EXPECT_NE(out.find("svg"), std::string::npos);
2181}
2182
2183
2184TEST(PlanarityTest, ExternalCertificateValidatorRenderPdfProfileProducesArtifact)
2185{
2186 namespace fs = std::filesystem;
2187
2188 if (not has_ruby_and_validator_script())
2189 {
2190 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2191 return;
2192 }
2193
2194 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2195
2198 const auto r = planarity_test(built.g, opts);
2199 ASSERT_FALSE(r.is_planar);
2200 ASSERT_TRUE(r.has_nonplanar_certificate);
2201
2202 const std::string graphml_path = make_tmp_path("external_render_pdf", ".graphml");
2203 const std::string output_dir = make_tmp_path("external_render_pdf_dir", "");
2204 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2205
2206 const int rc = run_external_certificate_validator(
2207 {graphml_path}, false, false, false, false, "",
2208 "--render-gephi --require-render "
2209 "--render-profile portable.ruby-render-pdf "
2210 "--render-output-dir " + shell_quote(output_dir));
2211 EXPECT_EQ(rc, 0);
2212
2213 const fs::path out_path = fs::path(output_dir) /
2214 (fs::path(graphml_path).stem().string() + ".pdf");
2215 EXPECT_TRUE(fs::exists(out_path));
2216 EXPECT_GT(fs::file_size(out_path), 0u);
2217}
2218
2219
2220TEST(PlanarityTest, ExternalCertificateValidatorRenderSupportsInputPathWithSpaces)
2221{
2222 namespace fs = std::filesystem;
2223
2224 if (not has_ruby_and_validator_script())
2225 {
2226 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2227 return;
2228 }
2229
2230 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2231
2234 const auto r = planarity_test(built.g, opts);
2235 ASSERT_FALSE(r.is_planar);
2236 ASSERT_TRUE(r.has_nonplanar_certificate);
2237
2238 const fs::path dir = scratch_dir() / "aleph planarity render spaces";
2239 fs::create_directories(dir);
2240 const std::string graphml_path = (dir / "k33 certificate.graphml").string();
2241 const std::string output_dir = (dir / "render output").string();
2242 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2243
2244 const int rc = run_external_certificate_validator(
2245 {graphml_path}, false, false, false, false, "",
2246 "--render-gephi --require-render "
2247 "--render-profile portable.ruby-render-svg "
2248 "--render-output-dir " + shell_quote(output_dir));
2249 EXPECT_EQ(rc, 0);
2250
2251 const fs::path out_path = fs::path(output_dir) /
2252 (fs::path(graphml_path).stem().string() + ".svg");
2253 EXPECT_TRUE(fs::exists(out_path));
2254 EXPECT_GT(fs::file_size(out_path), 0u);
2255}
2256
2257
2258TEST(PlanarityTest, ExternalCertificateValidatorRenderFailsOnUnknownProfile)
2259{
2260 if (not has_ruby_and_validator_script())
2261 {
2262 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2263 return;
2264 }
2265
2266 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2267
2270 const auto r = planarity_test(built.g, opts);
2271 ASSERT_FALSE(r.is_planar);
2272 ASSERT_TRUE(r.has_nonplanar_certificate);
2273
2274 const std::string graphml_path = make_tmp_path("external_render_bad", ".graphml");
2275 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2276
2277 const int rc = run_external_certificate_validator(
2278 {graphml_path}, false, false, false, false, "",
2279 "--render-gephi --require-render --render-profile missing.profile");
2280 EXPECT_NE(rc, 0);
2281}
2282
2283
2284TEST(PlanarityTest, ExternalCertificateBatchRunnerProducesReport)
2285{
2286 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2287
2290 const auto r = planarity_test(built.g, opts);
2291 ASSERT_FALSE(r.is_planar);
2292 ASSERT_TRUE(r.has_nonplanar_certificate);
2293
2294 const std::string graphml_path = make_tmp_path("external_batch", ".graphml");
2295 const std::string gexf_path = make_tmp_path("external_batch", ".gexf");
2296 const std::string report_path = make_tmp_path("external_batch_report", ".json");
2297
2298 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2299 write_text_file(gexf_path, nonplanar_certificate_to_gexf(r));
2300
2301 const int rc = run_external_certificate_batch(
2302 {graphml_path, gexf_path}, report_path,
2303 "--gephi --require-gephi --gephi-template portable.ruby-file-exists --print-summary");
2304 EXPECT_EQ(rc, 0);
2305
2306 const std::string report = read_text_file(report_path);
2307 EXPECT_NE(report.find("\"num_inputs\": 2"), std::string::npos);
2308 EXPECT_NE(report.find("\"overall_valid\": true"), std::string::npos);
2309 EXPECT_NE(report.find("\"gephi_template\": \"portable.ruby-file-exists\""),
2310 std::string::npos);
2311}
2312
2313
2314TEST(PlanarityTest, ExternalCertificateBatchRunnerSupportsRenderProfiles)
2315{
2316 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2317
2320 const auto r = planarity_test(built.g, opts);
2321 ASSERT_FALSE(r.is_planar);
2322 ASSERT_TRUE(r.has_nonplanar_certificate);
2323
2324 const std::string graphml_path = make_tmp_path("external_batch_render", ".graphml");
2325 const std::string report_path = make_tmp_path("external_batch_render_report", ".json");
2326 const std::string output_dir = make_tmp_path("external_batch_render_dir", "");
2327 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2328
2329 const int rc = run_external_certificate_batch(
2330 {graphml_path}, report_path,
2331 "--render-gephi --require-render "
2332 "--render-profile portable.ruby-render-svg "
2333 "--render-output-dir " + shell_quote(output_dir));
2334 EXPECT_EQ(rc, 0);
2335
2336 const std::string report = read_text_file(report_path);
2337 EXPECT_NE(report.find("\"render_profile\": \"portable.ruby-render-svg\""),
2338 std::string::npos);
2339 EXPECT_NE(report.find("\"overall_valid\": true"), std::string::npos);
2340}
2341
2342
2343TEST(PlanarityTest, ExternalCertificateVisualDiffRunnerPassesWithGoldenManifest)
2344{
2345 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2346
2349 const auto r = planarity_test(built.g, opts);
2350 ASSERT_FALSE(r.is_planar);
2351 ASSERT_TRUE(r.has_nonplanar_certificate);
2352
2353 const std::string graphml_path = make_tmp_path("external_visual", ".graphml");
2354 const std::string report_path = make_tmp_path("external_visual_report", ".json");
2355 const std::string output_dir = make_tmp_path("external_visual_render_dir", "");
2356 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2357
2358 const int rc = run_external_certificate_visual_diff(
2359 {graphml_path},
2360 {"portable.ruby-render-svg", "portable.ruby-render-pdf"},
2361 report_path,
2362 "--render-output-dir " + shell_quote(output_dir) + " --print-summary");
2363 EXPECT_EQ(rc, 0);
2364
2365 const std::string report = read_text_file(report_path);
2366 EXPECT_NE(report.find("\"overall_passed\": true"), std::string::npos);
2367 EXPECT_NE(report.find("\"profile_id\": \"portable.ruby-render-svg\""),
2368 std::string::npos);
2369 EXPECT_NE(report.find("\"profile_id\": \"portable.ruby-render-pdf\""),
2370 std::string::npos);
2371}
2372
2373
2374TEST(PlanarityTest, ExternalCertificateVisualDiffRunnerDetectsGoldenMismatch)
2375{
2376 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2377
2380 const auto r = planarity_test(built.g, opts);
2381 ASSERT_FALSE(r.is_planar);
2382 ASSERT_TRUE(r.has_nonplanar_certificate);
2383
2384 const std::string graphml_path = make_tmp_path("external_visual_bad", ".graphml");
2385 const std::string report_path = make_tmp_path("external_visual_bad_report", ".json");
2386 const std::string output_dir = make_tmp_path("external_visual_bad_render_dir", "");
2387 const std::string manifest_path = make_tmp_path("external_visual_bad_manifest", ".json");
2388 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2389 write_text_file(
2390 manifest_path,
2391 R"({
2392 "schema_version": 1,
2393 "entries": [
2394 {
2395 "profile_id": "portable.ruby-render-svg",
2396 "output_ext": "svg",
2397 "sha256": "0000000000000000000000000000000000000000000000000000000000000000",
2398 "bytes": 1
2399 }
2400 ]
2401}
2402)");
2403
2404 const int rc = run_external_certificate_visual_diff(
2405 {graphml_path},
2406 {"portable.ruby-render-svg"},
2407 report_path,
2408 "--render-output-dir " + shell_quote(output_dir)
2409 + " --golden-manifest " + shell_quote(manifest_path));
2410 EXPECT_NE(rc, 0);
2411
2412 const std::string report = read_text_file(report_path);
2413 EXPECT_NE(report.find("\"overall_passed\": false"), std::string::npos);
2414 EXPECT_NE(report.find("Golden hash mismatch"), std::string::npos);
2415}
2416
2417
2418TEST(PlanarityTest, ExternalCertificateVisualDiffRunnerCanUpdateGoldenManifest)
2419{
2420 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2421
2424 const auto r = planarity_test(built.g, opts);
2425 ASSERT_FALSE(r.is_planar);
2426 ASSERT_TRUE(r.has_nonplanar_certificate);
2427
2428 const std::string graphml_path = make_tmp_path("external_visual_upd", ".graphml");
2429 const std::string report_path = make_tmp_path("external_visual_upd_report", ".json");
2430 const std::string output_dir = make_tmp_path("external_visual_upd_render_dir", "");
2431 const std::string manifest_path = make_tmp_path("external_visual_upd_manifest", ".json");
2432 write_text_file(graphml_path, nonplanar_certificate_to_graphml(r));
2433
2434 const int rc = run_external_certificate_visual_diff(
2435 {graphml_path},
2436 {"portable.ruby-render-svg"},
2437 report_path,
2438 "--render-output-dir " + shell_quote(output_dir)
2439 + " --golden-manifest " + shell_quote(manifest_path)
2440 + " --update-golden");
2441 EXPECT_EQ(rc, 0);
2442
2443 const std::string report = read_text_file(report_path);
2444 const std::string manifest = read_text_file(manifest_path);
2445
2446 if (manifest.find("portable.ruby-render-svg") == std::string::npos)
2447 {
2448 std::cerr << "[diag] manifest_path=" << manifest_path << "\n"
2449 << "[diag] manifest content (" << manifest.size() << " bytes):\n"
2450 << manifest << "\n"
2451 << "[diag] report content (" << report.size() << " bytes):\n"
2452 << report << "\n";
2453 }
2454
2455 EXPECT_NE(manifest.find("\"profile_id\": \"portable.ruby-render-svg\""),
2456 std::string::npos);
2457 EXPECT_NE(manifest.find("0459f595d6268e7bdf9e8e273d4394fa50d23a89ec3d2449d10b7b47941b1327"),
2458 std::string::npos);
2459}
2460
2461
2462TEST(PlanarityTest, ExternalGephiNightlyComparisonReportHasNoRegressions)
2463{
2464 namespace fs = std::filesystem;
2465
2466 const fs::path artifacts_root =
2467 fs::path(make_tmp_path("gephi_nightly_artifacts_ok", ""));
2468 fs::create_directories(artifacts_root);
2469
2470 const auto write_case = [&](const std::string & dir_name,
2471 const std::string & os_name,
2472 const std::string & tag,
2473 const int validator_exit_code,
2474 const bool overall_valid,
2475 const std::string & probe_kind = "launcher")
2476 {
2477 const fs::path dir = artifacts_root / dir_name;
2478 fs::create_directories(dir);
2479
2480 write_text_file((dir / "downloaded_gephi_asset.txt").string(),
2481 "tag=" + tag + "\n"
2482 "runner_os=" + os_name + "\n"
2483 "asset_name=gephi-package-" + tag + ".zip\n"
2484 "gephi_probe_kind=" + probe_kind + "\n"
2485 "gephi_executable=/tmp/gephi\n");
2486
2487 std::ostringstream summary;
2488 summary << "{\n"
2489 << " \"os\": \"" << os_name << "\",\n"
2490 << " \"gephi_tag\": \"" << tag << "\",\n"
2491 << " \"asset_name\": \"gephi-package-" << tag << ".zip\",\n"
2492 << " \"gephi_probe_kind\": \"" << probe_kind << "\",\n"
2493 << " \"validator_exit_code\": " << validator_exit_code << ",\n"
2494 << " \"overall_valid\": " << (overall_valid ? "true" : "false") << "\n"
2495 << "}\n";
2496 write_text_file((dir / "weekly_case_summary.json").string(), summary.str());
2497 };
2498
2499 write_case("gephi-nightly-ubuntu-24.04-v0.9.7", "ubuntu-24.04", "v0.9.7", 0, true);
2500 write_case("gephi-nightly-ubuntu-24.04-v0.10.1", "ubuntu-24.04", "v0.10.1", 0, true);
2501 write_case("gephi-nightly-windows-2022-v0.9.7", "windows-2022", "v0.9.7", 0, true,
2502 "installer");
2503 write_case("gephi-nightly-windows-2022-v0.10.1", "windows-2022", "v0.10.1", 0, true,
2504 "installer");
2505
2506 const std::string report_json = make_tmp_path("gephi_nightly_report_ok", ".json");
2507 const std::string report_md = make_tmp_path("gephi_nightly_report_ok", ".md");
2508
2509 const int rc = run_gephi_nightly_comparison(
2510 artifacts_root.string(), report_json, report_md, "--print-summary");
2511 EXPECT_EQ(rc, 0);
2512
2513 const std::string json = read_text_file(report_json);
2514 EXPECT_NE(json.find("\"num_entries\": 4"), std::string::npos);
2515 EXPECT_NE(json.find("\"num_regressions\": 0"), std::string::npos);
2516 EXPECT_NE(json.find("\"has_regressions\": false"), std::string::npos);
2517 EXPECT_NE(json.find("\"gephi_probe_kind\": \"launcher\""), std::string::npos);
2518 EXPECT_NE(json.find("\"gephi_probe_kind\": \"installer\""), std::string::npos);
2519
2520 const std::string markdown = read_text_file(report_md);
2521 EXPECT_NE(markdown.find("### Regression Alerts"), std::string::npos);
2522 EXPECT_NE(markdown.find("- none"), std::string::npos);
2523 EXPECT_NE(markdown.find("| Gephi tag | OS | valid | exit_code | probe |"),
2524 std::string::npos);
2525}
2526
2527
2528TEST(PlanarityTest, ExternalGephiNightlyComparisonDetectsRegressionAndCanFail)
2529{
2530 namespace fs = std::filesystem;
2531
2532 const fs::path artifacts_root =
2533 fs::path(make_tmp_path("gephi_nightly_artifacts_bad", ""));
2534 fs::create_directories(artifacts_root);
2535
2536 const auto write_case = [&](const std::string & dir_name,
2537 const std::string & os_name,
2538 const std::string & tag,
2539 const int validator_exit_code,
2540 const bool overall_valid,
2541 const std::string & probe_kind = "launcher")
2542 {
2543 const fs::path dir = artifacts_root / dir_name;
2544 fs::create_directories(dir);
2545
2546 write_text_file((dir / "downloaded_gephi_asset.txt").string(),
2547 "tag=" + tag + "\n"
2548 "runner_os=" + os_name + "\n"
2549 "asset_name=gephi-package-" + tag + ".zip\n"
2550 "gephi_probe_kind=" + probe_kind + "\n"
2551 "gephi_executable=/tmp/gephi\n");
2552
2553 std::ostringstream summary;
2554 summary << "{\n"
2555 << " \"os\": \"" << os_name << "\",\n"
2556 << " \"gephi_tag\": \"" << tag << "\",\n"
2557 << " \"asset_name\": \"gephi-package-" << tag << ".zip\",\n"
2558 << " \"gephi_probe_kind\": \"" << probe_kind << "\",\n"
2559 << " \"validator_exit_code\": " << validator_exit_code << ",\n"
2560 << " \"overall_valid\": " << (overall_valid ? "true" : "false") << "\n"
2561 << "}\n";
2562 write_text_file((dir / "weekly_case_summary.json").string(), summary.str());
2563 };
2564
2565 write_case("gephi-nightly-ubuntu-24.04-v0.9.7", "ubuntu-24.04", "v0.9.7", 0, true);
2566 write_case("gephi-nightly-ubuntu-24.04-v0.10.1", "ubuntu-24.04", "v0.10.1", 2, false);
2567
2568 const std::string report_json = make_tmp_path("gephi_nightly_report_bad", ".json");
2569 const std::string report_md = make_tmp_path("gephi_nightly_report_bad", ".md");
2570
2571 const int rc = run_gephi_nightly_comparison(
2572 artifacts_root.string(), report_json, report_md, "--print-summary");
2573 EXPECT_EQ(rc, 0);
2574
2575 const std::string json = read_text_file(report_json);
2576 EXPECT_NE(json.find("\"num_regressions\": 1"), std::string::npos);
2577 EXPECT_NE(json.find("\"has_regressions\": true"), std::string::npos);
2578 EXPECT_NE(json.find("overall_valid_regressed"), std::string::npos);
2579 EXPECT_NE(json.find("exit_code_regressed"), std::string::npos);
2580
2581 const int rc_fail = run_gephi_nightly_comparison(
2582 artifacts_root.string(), report_json, report_md, "--fail-on-regressions");
2583 EXPECT_NE(rc_fail, 0);
2584}
2585
2586
2587TEST(PlanarityTest, ExternalGephiRegressionNotifierNoRegressionProducesSummary)
2588{
2589 const std::string report_json = make_tmp_path("gephi_notify_ok_report", ".json");
2590 const std::string output_md = make_tmp_path("gephi_notify_ok_alert", ".md");
2591
2592 write_text_file(
2593 report_json,
2594 R"({
2595 "schema_version": 1,
2596 "run_id": "r1",
2597 "run_attempt": "1",
2598 "git_sha": "abc123",
2599 "resolved_tags": "v0.9.7,v0.10.1",
2600 "num_entries": 4,
2601 "entries": [],
2602 "num_regressions": 0,
2603 "has_regressions": false,
2604 "regressions": []
2605}
2606)");
2607
2608 const int rc = run_gephi_regression_notify(report_json, output_md, "--print-summary");
2609 EXPECT_EQ(rc, 0);
2610
2611 const std::string markdown = read_text_file(output_md);
2612 EXPECT_NE(markdown.find("Gephi Nightly Regression Alert"), std::string::npos);
2613 EXPECT_NE(markdown.find("No regressions detected."), std::string::npos);
2614}
2615
2616
2617TEST(PlanarityTest, ExternalGephiRegressionNotifierRegressionAndRequiredWebhookFailsWithoutWebhook)
2618{
2619 const std::string report_json = make_tmp_path("gephi_notify_bad_report", ".json");
2620 const std::string output_md = make_tmp_path("gephi_notify_bad_alert", ".md");
2621
2622 write_text_file(
2623 report_json,
2624 R"({
2625 "schema_version": 1,
2626 "run_id": "r2",
2627 "run_attempt": "1",
2628 "git_sha": "def456",
2629 "resolved_tags": "v0.9.7,v0.10.1",
2630 "num_entries": 2,
2631 "entries": [],
2632 "num_regressions": 1,
2633 "has_regressions": true,
2634 "regressions": [
2635 {
2636 "os": "ubuntu-24.04",
2637 "from_tag": "v0.9.7",
2638 "to_tag": "v0.10.1",
2639 "from_overall_valid": true,
2640 "to_overall_valid": false,
2641 "from_exit_code": 0,
2642 "to_exit_code": 2,
2643 "reason_codes": ["overall_valid_regressed", "exit_code_regressed"]
2644 }
2646}
2647)");
2648
2649 const int rc_optional = run_gephi_regression_notify(
2650 report_json, output_md, "--print-summary");
2651 EXPECT_EQ(rc_optional, 0);
2652
2653 const std::string markdown = read_text_file(output_md);
2654 EXPECT_NE(markdown.find("Detected regression(s):"), std::string::npos);
2655 EXPECT_NE(markdown.find("overall_valid_regressed"), std::string::npos);
2656 EXPECT_NE(markdown.find("exit_code_regressed"), std::string::npos);
2657 EXPECT_NE(markdown.find("https://example.invalid/run/123"), std::string::npos);
2658
2659 const int rc_required = run_gephi_regression_notify(
2660 report_json, output_md, "--require-webhook-success");
2661 EXPECT_NE(rc_required, 0);
2662}
2663
2664
2665TEST(PlanarityTest, ExternalCertificateBatchRunnerFailsOnInvalidInput)
2666{
2667 const std::string broken_graphml = make_tmp_path("external_batch_invalid", ".graphml");
2668 const std::string report_path = make_tmp_path("external_batch_invalid_report", ".json");
2669
2670 write_text_file(broken_graphml, R"(<?xml version="1.0" encoding="UTF-8"?>
2671<graphml xmlns="http://graphml.graphdrawing.org/xmlns">
2672 <graph id="Broken" edgedefault="undirected">
2673 <node id="n0"/>
2674 <node id="n1"/>
2675 <edge id="e0" source="n0" target="n1">
2676 <data key="k_edge_kind">path</data>
2677 </edge>
2678 </graph>
2679</graphml>
2680)");
2681
2682 const int rc = run_external_certificate_batch({broken_graphml}, report_path);
2683 EXPECT_NE(rc, 0);
2684
2685 const std::string report = read_text_file(report_path);
2686 EXPECT_NE(report.find("\"num_inputs\": 1"), std::string::npos);
2687 EXPECT_NE(report.find("\"overall_valid\": false"), std::string::npos);
2688}
2689
2690
2691TEST(PlanarityTest, ExternalCertificateFixtureGraphmlIsValid)
2692{
2693 namespace fs = std::filesystem;
2694
2695 if (not has_ruby_and_validator_script())
2696 {
2697 GTEST_SKIP() << "Skipped: Ruby or planarity_certificate_validator.rb not found";
2698 return;
2699 }
2700
2701 const auto root = find_repo_root();
2702 ASSERT_TRUE(root.has_value());
2703
2704 const fs::path fixture =
2705 *root / "scripts" / "fixtures" / "planarity_k33_certificate.graphml";
2706 ASSERT_TRUE(fs::exists(fixture));
2707
2708 const int rc = run_external_certificate_validator({fixture.string()});
2709 EXPECT_EQ(rc, 0);
2710}
2711
2712
2713// The files of a run go to a directory of its own under the temporary one
2714// of the system, made once; another run gets another one, which goes with
2715// what it holds when it ends. Two runs at once, as those of two runners of
2716// a CI on one machine, write no file of the other
2717TEST(PlanarityTest, TheFilesOfARunAreInADirectoryOfItsOwn)
2718{
2719 namespace fs = std::filesystem;
2720 const std::string prefix = "aleph_planarity_";
2721
2722 const fs::path & dir = scratch_dir();
2723 ASSERT_TRUE(fs::is_directory(dir));
2724 EXPECT_TRUE(fs::equivalent(dir.parent_path(), fs::temp_directory_path()));
2725 EXPECT_EQ(dir.filename().string().rfind(prefix, 0), 0u);
2726 EXPECT_GT(dir.filename().string().size(), prefix.size());
2727 EXPECT_EQ(&scratch_dir(), &dir);
2728
2729 const fs::path a = make_tmp_path("own_directory", ".txt");
2730 const fs::path b = make_tmp_path("own_directory", ".txt");
2731 EXPECT_NE(a, b);
2732 EXPECT_TRUE(fs::equivalent(a.parent_path(), dir));
2733 EXPECT_TRUE(fs::equivalent(b.parent_path(), dir));
2734 EXPECT_TRUE(fs::equivalent(fs::path(validator_stdout_path("own_directory")).parent_path(), dir));
2735
2736 fs::path other_dir;
2737 {
2738 const Scratch_Dir other; // as the directory of another run
2739 other_dir = other.path();
2740 ASSERT_TRUE(fs::is_directory(other_dir));
2741 EXPECT_FALSE(fs::equivalent(other_dir, dir));
2742 EXPECT_EQ(other_dir.filename().string().rfind(prefix, 0), 0u);
2743 write_text_file((other_dir / "file").string(), "content");
2744 EXPECT_EQ(read_text_file((other_dir / "file").string()), "content");
2745 }
2746 EXPECT_FALSE(fs::exists(other_dir)); // removed with what it held
2747 EXPECT_TRUE(fs::is_directory(dir));
2748}
2749
2750
2751TEST(PlanarityTest, FindRepoRootUsesConfiguredSourceDirOutsideTheTree)
2752{
2753#ifndef ALEPH_TEST_SOURCE_DIR
2754 GTEST_SKIP() << "Skipped: ALEPH_TEST_SOURCE_DIR is not defined for this build";
2755#else
2756 namespace fs = std::filesystem;
2757
2758 // Restore the working directory even when an assertion below fails.
2759 struct Cwd_Guard
2760 {
2761 fs::path saved = fs::current_path();
2762 ~Cwd_Guard() { fs::current_path(saved); }
2763 } guard;
2764
2765 const fs::path outside = fs::temp_directory_path();
2766 const fs::path configured(ALEPH_TEST_SOURCE_DIR);
2767 ASSERT_FALSE(fs::exists(outside / "Planarity_Test.H"));
2768
2769 fs::current_path(outside);
2770 const auto root = find_repo_root();
2771
2772 ASSERT_TRUE(root.has_value());
2773 EXPECT_TRUE(fs::equivalent(*root, configured));
2774 EXPECT_TRUE(fs::equivalent(fs::current_path(), outside));
2775#endif
2776}
2777
2778
2779TEST(PlanarityTest, NonPlanarCertificateExportRequiresCertificate)
2780{
2781 auto built = build_ugraph(6, complete_bipartite_edges(3, 3));
2782
2783 const auto r = planarity_test(built.g); // no certificate requested
2784 ASSERT_FALSE(r.is_planar);
2785 ASSERT_FALSE(r.has_nonplanar_certificate);
2786
2787 EXPECT_ANY_THROW((void) nonplanar_certificate_to_json(r));
2788 EXPECT_ANY_THROW((void) nonplanar_certificate_to_dot(r));
2789 EXPECT_ANY_THROW((void) nonplanar_certificate_to_graphml(r));
2790 EXPECT_ANY_THROW((void) nonplanar_certificate_to_gexf(r));
2791
2792 const auto vr = validate_nonplanar_certificate(r);
2793 EXPECT_FALSE(vr.has_certificate);
2794 EXPECT_FALSE(vr.is_valid);
2795 EXPECT_FALSE(nonplanar_certificate_is_valid(r));
2796}
2797// satisfy CI policy
Planarity testing on Aleph graphs.
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error()
Throws std::runtime_error unconditionally.
Definition ah-errors.H:431
long double vr
Definition btreepic.C:150
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
size_t size_t int32_t * out
Definition ca-c-api.h:120
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Functor wrapper for is_planar_graph().
Graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:439
_Graph_Node Node
The graph type.
Definition tpl_graph.H:443
_Graph_Arc Arc
The node class type.
Definition tpl_graph.H:444
Functor wrapper for planarity_test().
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
#define TEST(name)
static mt19937 rng
__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
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.
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.
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().
std::filesystem::path make_tmp_path(const std::filesystem::path &target)
Generate a temporary sibling path for atomic writes.
std::string shell_quote(const std::string &s)
DFSResult< typename Domain::Distance > dfs(Domain &domain, typename Domain::State &state, SearchPath< typename Domain::Move > &path, const typename Domain::Distance g, const typename Domain::Distance threshold, const size_t depth, IDAStarResult< Solution, typename Domain::Distance > &result, OnSolution &on_solution)
Core recursive DFS used by IDA* for a single threshold pass.
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
static void prefix(Node *root, DynList< Node * > &acc)
Itor find(const Itor &beg, const Itor &end, const T &value)
Find the first element equal to a value.
Definition ahAlgo.H:230
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
STL namespace.
Default node labeler for certificate export.
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.
Options for embedding-aware 2D drawing extraction.
size_t max_outer_faces_to_try
Max outer-face candidates evaluated per component.
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_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 ...
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 ...
Complete result of a planarity test execution.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
CmdLine cmd
Definition testHash.C:48
Gsl_Compatible_Rng r
Array-based graph implementation.
Generic graph and digraph implementations.