diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index c1b1bb964..46d1f11cc 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -46,7 +46,7 @@ substantial implementation so its maintenance value and scope can be agreed upon just ci ``` - `just check` is the fast, non-mutating source and tooling gate. `just ci` adds the supported build and 11-test smoke + `just check` is the fast, non-mutating source and tooling gate. `just ci` adds the supported build and 22-test smoke suite. When changing C++ behavior, also run `just clang-tidy` with the pinned LLVM 22 toolchain and review its advisory diagnostics. diff --git a/README.md b/README.md index 3baafd352..f6ee23c32 100644 --- a/README.md +++ b/README.md @@ -360,9 +360,10 @@ If you do not have GraphViz installed, set this option to **NO** ## Testing -Run `just build`; it delegates to `./scripts/build.sh`, builds the test target, and executes the eleven supported smoke -tests. These include focused doctest runs for the Boost.Compat `function_ref` migration and the causal-foliation -construction code used as a regression oracle. Run `just ci` for the complete local validation gate. +Run `just build`; it delegates to `./scripts/build.sh`, builds the test target, and executes the 22 supported smoke tests. +These include two focused doctest runs for the Boost.Compat `function_ref` migration and causal-foliation construction, +plus 20 executable integration tests covering normal CLI use and invalid-boundary rejection. Run `just ci` for the +complete local validation gate. The doctest executable can also be run directly: diff --git a/cmake/ExpectCommandFailure.cmake b/cmake/ExpectCommandFailure.cmake new file mode 100644 index 000000000..3a9360a06 --- /dev/null +++ b/cmake/ExpectCommandFailure.cmake @@ -0,0 +1,32 @@ +if(NOT DEFINED TEST_EXECUTABLE OR NOT EXISTS "${TEST_EXECUTABLE}") + message(FATAL_ERROR "TEST_EXECUTABLE must name a built executable") +endif() + +if(NOT DEFINED EXPECTED_REGEX OR EXPECTED_REGEX STREQUAL "") + message(FATAL_ERROR "EXPECTED_REGEX must describe the expected diagnostic") +endif() + +execute_process( + COMMAND "${TEST_EXECUTABLE}" ${TEST_ARGUMENTS} + RESULT_VARIABLE test_result + OUTPUT_VARIABLE test_output + ERROR_VARIABLE test_error) + +if(NOT test_result MATCHES "^[0-9]+$") + message( + FATAL_ERROR + "Command did not exit normally (${test_result}):\n${test_output}\n${test_error}") +endif() + +if(test_result EQUAL 0) + message( + FATAL_ERROR + "Command unexpectedly succeeded:\n${test_output}\n${test_error}") +endif() + +set(combined_output "${test_output}\n${test_error}") +if(NOT combined_output MATCHES "${EXPECTED_REGEX}") + message( + FATAL_ERROR + "Command failed without the expected diagnostic '${EXPECTED_REGEX}':\n${combined_output}") +endif() diff --git a/include/Apply_move.hpp b/include/Apply_move.hpp index 48cd32758..ce0ead27f 100644 --- a/include/Apply_move.hpp +++ b/include/Apply_move.hpp @@ -28,15 +28,11 @@ * \param t_move The Pachner move * \return The expected or unexpected result in a std::expected */ -template , - typename FunctionType = - boost::compat::function_ref> -auto constexpr apply_move(ManifoldType&& t_manifold, FunctionType t_move) +template +auto constexpr apply_move(ManifoldType const& t_manifold, FunctionType t_move) -> decltype(auto) { - if (auto result = std::invoke(t_move, std::forward(t_manifold)); - result.has_value()) + if (auto result = std::invoke(t_move, t_manifold); result.has_value()) { return result; } diff --git a/include/Ergodic_moves_3.hpp b/include/Ergodic_moves_3.hpp index 68e4c717a..72a91a565 100644 --- a/include/Ergodic_moves_3.hpp +++ b/include/Ergodic_moves_3.hpp @@ -35,6 +35,17 @@ namespace ergodic_moves namespace detail { + /// @brief Rebuild all derived topology and geometry state around a value. + [[nodiscard]] inline auto make_manifold(Delaunay triangulation, + Manifold const& source) -> Manifold + { + return Manifold{ + foliated_triangulations::FoliatedTriangulation<3>{ + std::move(triangulation), source.initial_radius(), + source.foliation_spacing()} + }; + } + /// @brief Check an edge handle without dereferencing its cell handle. /// @details A tetrahedral cell has four local vertex indices in [0, 4). [[nodiscard]] inline auto is_well_formed_edge( @@ -54,8 +65,7 @@ namespace ergodic_moves /// /// @param t_manifold The simplicial manifold /// @returns The null-moved manifold - [[nodiscard]] inline auto null_move(Manifold const& t_manifold) noexcept - -> Expected + [[nodiscard]] inline auto null_move(Manifold const& t_manifold) -> Expected { return t_manifold; } // null_move /// @brief Perform a TriangulationDataStructure_3::flip on a facet @@ -64,12 +74,11 @@ namespace ergodic_moves /// @returns True if move succeeded /// @see /// https://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html#a2ad2941984c1eac5561665700bfd60b4 - [[nodiscard]] inline auto try_23_move(Manifold& t_manifold, + [[nodiscard]] inline auto try_23_move(Delaunay& triangulation, Cell_handle const& to_be_moved) -> bool { if (to_be_moved->info() != 22) { return false; } // NOLINT - auto& triangulation = t_manifold.triangulation(); - auto flipped = false; + auto flipped = false; // Try every facet of the (2,2) cell for (auto i = 0; i < 4; ++i) { @@ -115,20 +124,24 @@ namespace ergodic_moves /// /// @param t_manifold The simplicial manifold /// @returns The Expected (2,3) moved manifold or an Unexpected - [[nodiscard]] inline auto do_23_move(Manifold& t_manifold) -> Expected + [[nodiscard]] inline auto do_23_move(Manifold const& t_manifold) -> Expected { #ifndef NDEBUG spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); #endif - auto two_two = t_manifold.get_triangulation().get_two_two(); + Delaunay triangulation{t_manifold.delaunay_snapshot()}; + auto two_two = foliated_triangulations::filter_cells<3>( + foliated_triangulations::collect_cells<3>(triangulation), + Cell_type::TWO_TWO); // Shuffle the container to create a random sequence of (2,2) cells std::ranges::shuffle(two_two, utilities::make_random_generator()); // Try a (2,3) move on successive cells in the sequence - if (std::ranges::any_of( - two_two, [&](auto& cell) { return try_23_move(t_manifold, cell); })) + if (std::ranges::any_of(two_two, [&](auto& cell) { + return try_23_move(triangulation, cell); + })) { - return t_manifold; + return detail::make_manifold(std::move(triangulation), t_manifold); } // We've run out of (2,2) cells std::string const msg = "No (2,3) move possible.\n"; @@ -142,11 +155,11 @@ namespace ergodic_moves /// @returns True if move succeeded /// @see /// https://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html#a5837d666e4198f707f862003c1ffa033 - [[nodiscard]] inline auto try_32_move(Manifold& t_manifold, + [[nodiscard]] inline auto try_32_move(Delaunay& triangulation, Edge_handle const& to_be_moved) -> bool { - return t_manifold.triangulation().flip( - to_be_moved.first, to_be_moved.second, to_be_moved.third); + return triangulation.flip(to_be_moved.first, to_be_moved.second, + to_be_moved.third); } // try_32_move /// @brief Perform a (3,2) move @@ -157,20 +170,22 @@ namespace ergodic_moves /// If successful, the triangulation is no longer Delaunay. /// @param t_manifold The simplicial manifold /// @returns The Expected (3,2) moved manifold or an Unexpected - [[nodiscard]] inline auto do_32_move(Manifold& t_manifold) -> Expected + [[nodiscard]] inline auto do_32_move(Manifold const& t_manifold) -> Expected { #ifndef NDEBUG spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); #endif - auto timelike_edges = t_manifold.get_timelike_edges(); + Delaunay triangulation{t_manifold.delaunay_snapshot()}; + auto timelike_edges = foliated_triangulations::filter_edges<3>( + foliated_triangulations::collect_edges<3>(triangulation), true); // Shuffle the container to create a random sequence of edges std::ranges::shuffle(timelike_edges, utilities::make_random_generator()); // Try a (3,2) move on successive timelike edges in the sequence if (std::ranges::any_of(timelike_edges, [&](auto& edge) { - return try_32_move(t_manifold, edge); + return try_32_move(triangulation, edge); })) { - return t_manifold; + return detail::make_manifold(std::move(triangulation), t_manifold); } // We've run out of edges to try std::string const msg = "No (3,2) move possible.\n"; @@ -216,13 +231,16 @@ namespace ergodic_moves /// @image latex 26.eps width=7cm /// @param t_manifold The simplicial manifold /// @returns The Expected (2,6) moved manifold or an Unexpected - [[nodiscard]] inline auto do_26_move(Manifold& t_manifold) -> Expected + [[nodiscard]] inline auto do_26_move(Manifold const& t_manifold) -> Expected { #ifndef NDEBUG spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); #endif static auto constexpr INCIDENT_CELLS_FOR_6_2_MOVE = 6; - auto one_three = t_manifold.get_triangulation().get_one_three(); + Delaunay triangulation{t_manifold.delaunay_snapshot()}; + auto one_three = foliated_triangulations::filter_cells<3>( + foliated_triangulations::collect_cells<3>(triangulation), + Cell_type::ONE_THREE); // Shuffle the container to pick a random sequence of (1,3) cells to try std::ranges::shuffle(one_three, utilities::make_random_generator()); for (auto const& bottom : one_three) @@ -273,13 +291,12 @@ namespace ergodic_moves // Do the (2,6) move // Insert new vertex Vertex_handle const v_center = - t_manifold.triangulation().delaunay().tds().insert_in_facet( - bottom, *neighboring_31_index); + triangulation.tds().insert_in_facet(bottom, *neighboring_31_index); // Checks Cell_container incident_cells; - t_manifold.triangulation().delaunay().tds().incident_cells( - v_center, std::back_inserter(incident_cells)); + triangulation.tds().incident_cells(v_center, + std::back_inserter(incident_cells)); // the (2,6) center vertex should be bounded by 6 simplices if (incident_cells.size() != INCIDENT_CELLS_FOR_6_2_MOVE) { @@ -294,11 +311,8 @@ namespace ergodic_moves // Each incident cell should be combinatorially and geometrically valid if (auto check_cells = std::ranges::all_of(incident_cells, - [&t_manifold](auto const& cell) { - return t_manifold.get_triangulation() - .get_delaunay() - .tds() - .is_cell(cell); + [&triangulation](auto const& cell) { + return triangulation.tds().is_cell(cell); }); !check_cells) { @@ -323,14 +337,6 @@ namespace ergodic_moves v_center->info() = timevalue; #ifndef NDEBUG - if (t_manifold.is_vertex(v_center)) - { - spdlog::trace("It's a vertex in the TDS.\n"); - } - else - { - spdlog::trace("It's not a vertex in the TDS.\n"); - } spdlog::trace("Spacelike face timevalue is {}.\n", timevalue); spdlog::trace("Inserted vertex ({}) with timevalue {}.\n", utilities::point_to_str(v_center->point()), @@ -339,7 +345,7 @@ namespace ergodic_moves // Final checks // is_valid() checks for combinatorial and geometric validity - if (!t_manifold.get_delaunay().tds().is_valid(v_center, true, 1)) + if (!triangulation.tds().is_valid(v_center, true, 1)) { std::string const msg = "v_center is invalid.\n"; #ifndef NDEBUG @@ -348,7 +354,7 @@ namespace ergodic_moves return std::unexpected(msg); } - return t_manifold; + return detail::make_manifold(std::move(triangulation), t_manifold); } // Try next cell #ifndef NDEBUG @@ -366,14 +372,14 @@ namespace ergodic_moves /// with a vertex, it checks all incident cells. There must be 6 /// incident cells; 3 should be (3,1) simplices, 3 should be (1,3) simplices, /// and there should be no (2,2) simplices. - /// @param manifold The simplicial manifold + /// @param triangulation The triangulation containing the candidate /// @param candidate The vertex to check /// @returns True if (6,2) move is possible - [[nodiscard]] inline auto is_62_movable(Manifold const& manifold, + [[nodiscard]] inline auto is_62_movable(Delaunay const& triangulation, Vertex_handle const& candidate) -> bool { - if (manifold.dimensionality() != 3) + if (triangulation.dimension() != 3) { #ifndef NDEBUG spdlog::trace("Manifold is not 3-dimensional.\n"); @@ -381,7 +387,7 @@ namespace ergodic_moves return false; } - if (!manifold.is_vertex(candidate)) + if (!triangulation.tds().is_vertex(candidate)) { #ifndef NDEBUG spdlog::trace("Candidate is not a vertex.\n"); @@ -390,7 +396,7 @@ namespace ergodic_moves } // We must have 5 incident edges to have 6 incident cells - if (auto incident_edges = manifold.degree(candidate); + if (auto incident_edges = triangulation.degree(candidate); incident_edges != 5) // NOLINT { #ifndef NDEBUG @@ -400,7 +406,9 @@ namespace ergodic_moves } // Obtain all incident cells - auto const incident_cells = manifold.incident_cells(candidate); + Cell_container incident_cells; + triangulation.tds().incident_cells(candidate, + std::back_inserter(incident_cells)); // We must have 6 cells incident to the vertex to make a (6,2) move if (incident_cells.size() != 6) // NOLINT @@ -414,7 +422,7 @@ namespace ergodic_moves // Check that none of the incident cells are infinite for (auto const& cell : incident_cells) { - if (manifold.get_triangulation().is_infinite(cell)) + if (triangulation.is_infinite(cell)) { #ifndef NDEBUG spdlog::trace("Cell is infinite.\n"); @@ -423,37 +431,17 @@ namespace ergodic_moves } } - // Run until all vertices are fixed - while (foliated_triangulations::fix_vertices<3>( - manifold.get_delaunay(), manifold.initial_radius(), - manifold.foliation_spacing())) - { - spdlog::warn("Fixing vertices found by is_62_movable().\n"); - } - - // Run until all cells fixed or 50 passes - // for (auto passes = 1; passes < foliated_triangulations::MAX_FIX_PASSES - // + 1; - // ++passes) - // { - // if (!foliated_triangulations::fix_cells<3>(manifold.get_delaunay())) - // { - // break; - // } - // spdlog::warn("Fixing cells found by is_62_movable() pass {}.\n", - // passes); - // } - - auto const incident_31 = foliated_triangulations::filter_cells<3>( - incident_cells, Cell_type::THREE_ONE); - auto const incident_22 = foliated_triangulations::filter_cells<3>( - incident_cells, Cell_type::TWO_TWO); - auto const incident_13 = foliated_triangulations::filter_cells<3>( - incident_cells, Cell_type::ONE_THREE); + auto const cell_type_count = [&](Cell_type const type) { + return std::ranges::count_if(incident_cells, [&](auto const& cell) { + return foliated_triangulations::expected_cell_type<3>(cell) == type; + }); + }; + auto const incident_31 = cell_type_count(Cell_type::THREE_ONE); + auto const incident_22 = cell_type_count(Cell_type::TWO_TWO); + auto const incident_13 = cell_type_count(Cell_type::ONE_THREE); // All cells should be classified - if (incident_13.size() + incident_22.size() + incident_31.size() != - 6) // NOLINT + if (incident_13 + incident_22 + incident_31 != 6) // NOLINT { spdlog::warn("Some incident cells on this vertex need to be fixed.\n"); } @@ -462,12 +450,10 @@ namespace ergodic_moves spdlog::trace( "Vertex has {} incident cells with {} incident (3,1) simplices and {} " "incident (2,2) simplices and {} incident (1,3) simplices.\n", - incident_cells.size(), incident_31.size(), incident_22.size(), - incident_13.size()); + incident_cells.size(), incident_31, incident_22, incident_13); foliated_triangulations::debug_print_cells<3>(std::span{incident_cells}); #endif - return incident_31.size() == 3 && incident_22.empty() && - incident_13.size() == 3; + return incident_31 == 3 && incident_22 == 0 && incident_13 == 3; } // find_62_moves() @@ -558,22 +544,22 @@ namespace ergodic_moves /// /// @param t_manifold The simplicial manifold /// @returns The Expected (6,2) moved manifold or Unexpected - [[nodiscard]] inline auto do_62_move(Manifold& t_manifold) -> Expected + [[nodiscard]] inline auto do_62_move(Manifold const& t_manifold) -> Expected { #ifndef NDEBUG spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); #endif - auto vertices = t_manifold.get_vertices(); + auto triangulation = t_manifold.delaunay_snapshot(); + auto vertices = foliated_triangulations::collect_vertices<3>(triangulation); // Shuffle the container to create a random sequence of vertices std::ranges::shuffle(vertices, utilities::make_random_generator()); // Try a (6,2) move on successive vertices in the sequence for (auto const& vertex : vertices) { - if (!is_62_movable(t_manifold, vertex)) { continue; } - if (auto moved = try_62_move(t_manifold.get_delaunay(), vertex)) + if (!is_62_movable(triangulation, vertex)) { continue; } + if (auto moved = try_62_move(triangulation, vertex)) { - t_manifold.triangulation().delaunay().swap(*moved); - return t_manifold; + return detail::make_manifold(std::move(*moved), t_manifold); } } // We've run out of vertices to try @@ -853,14 +839,16 @@ namespace ergodic_moves #ifndef NDEBUG spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); #endif - auto spacelike_edges = t_manifold.get_spacelike_edges(); + auto triangulation = t_manifold.delaunay_snapshot(); + auto spacelike_edges = foliated_triangulations::filter_edges<3>( + foliated_triangulations::collect_edges<3>(triangulation), false); // Shuffle the container to pick a random sequence of edges to try std::ranges::shuffle(spacelike_edges, utilities::make_random_generator()); for (auto const& edge : spacelike_edges) { // Obtain all incident cells - if (auto const incident_cells = find_bistellar_flip_location( - t_manifold.get_triangulation().get_delaunay(), edge); + if (auto const incident_cells = + find_bistellar_flip_location(triangulation, edge); incident_cells) { #ifndef NDEBUG @@ -901,21 +889,11 @@ namespace ergodic_moves // Try the bistellar flip if (auto flipped_triangulation = - bistellar_flip(t_manifold.get_triangulation().get_delaunay(), - edge, top, bottom); + bistellar_flip(triangulation, edge, top, bottom); flipped_triangulation.has_value()) { - // Create a new foliated triangulation with the flipped Delaunay - // triangulation - auto new_triangulation = - foliated_triangulations::FoliatedTriangulation<3>( - flipped_triangulation.value(), t_manifold.initial_radius(), - t_manifold.foliation_spacing()); - - // Create a new manifold with the updated triangulation - auto new_manifold = Manifold(new_triangulation); - - return new_manifold; + return detail::make_manifold(std::move(*flipped_triangulation), + t_manifold); } // If we get here, the flip failed but we found potential cells diff --git a/include/Foliated_triangulation.hpp b/include/Foliated_triangulation.hpp index a835c85fe..5af196723 100644 --- a/include/Foliated_triangulation.hpp +++ b/include/Foliated_triangulation.hpp @@ -21,6 +21,14 @@ #ifndef CDT_PLUSPLUS_FOLIATEDTRIANGULATION_HPP #define CDT_PLUSPLUS_FOLIATEDTRIANGULATION_HPP +#include +#include +#include +#include +#include +#include +#include + #include "Triangulation_traits.hpp" #include "Utilities.hpp" @@ -187,7 +195,10 @@ namespace foliated_triangulations [[nodiscard]] auto find_max_timevalue(Container&& t_vertices) -> Int_precision { auto vertices = std::forward(t_vertices); - assert(!vertices.empty()); + if (vertices.empty()) + { + throw std::invalid_argument("Cannot classify an empty triangulation."); + } auto max_element = std::max_element(vertices.begin(), vertices.end(), compare_v_info); auto result_index = std::distance(vertices.begin(), max_element); @@ -205,7 +216,10 @@ namespace foliated_triangulations [[nodiscard]] auto find_min_timevalue(Container&& t_vertices) -> Int_precision { auto vertices = std::forward(t_vertices); - assert(!vertices.empty()); + if (vertices.empty()) + { + throw std::invalid_argument("Cannot classify an empty triangulation."); + } auto min_element = std::min_element(vertices.begin(), vertices.end(), compare_v_info); auto result_index = std::distance(vertices.begin(), min_element); @@ -482,8 +496,8 @@ namespace foliated_triangulations /// @param t_foliation_spacing The spacing between successive leaves /// @return True if any vertex->info() was fixed template - [[nodiscard]] auto fix_vertices(Delaunay_t const& t_triangulation, - double const t_initial_radius, + [[nodiscard]] auto fix_vertices(Delaunay_t& t_triangulation, + double const t_initial_radius, double const t_foliation_spacing) -> bool { return fix_vertices(collect_cells(t_triangulation), @@ -703,22 +717,27 @@ namespace foliated_triangulations t_edge.first->vertex(t_edge.third)->info()); } // print_edge - /// @brief Collect spacelike facets into a container indexed by time value + /// @brief Collect spacelike facets into a contiguous container ordered by + /// time value /// @details *Warning!* Turning on debugging info will generate gigabytes /// of logs. /// @tparam dimension The dimensionality of the simplices /// @param t_facets A container of facets - /// @return Container with spacelike facets per timeslice + /// @return Contiguous container with spacelike facets per timeslice template - [[nodiscard]] auto volume_per_timeslice(Container&& t_facets) - -> std::multimap> + [[nodiscard]] auto collect_spacelike_facets(Container&& t_facets) + -> std::vector>> { #ifndef NDEBUG spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); #endif - std::multimap> space_faces; - for (auto facets = std::forward(t_facets); - auto const& face : facets) + using Volume_entry = std::pair>; + std::vector space_faces; + if constexpr (std::ranges::sized_range) + { + space_faces.reserve(std::ranges::size(t_facets)); + } + for (auto const& face : t_facets) { Cell_handle_t const cell = face.first; auto index_of_facet = face.second; @@ -746,7 +765,7 @@ namespace foliated_triangulations spdlog::trace("Facet is spacelike on timevalue {}.\n", *facet_timevalues.begin()); #endif - space_faces.insert({*facet_timevalues.begin(), face}); + space_faces.emplace_back(*facet_timevalues.begin(), face); } else { @@ -755,7 +774,24 @@ namespace foliated_triangulations #endif } } + std::ranges::stable_sort( + space_faces, std::ranges::less{}, + [](Volume_entry const& entry) noexcept { return entry.first; }); return space_faces; + } // collect_spacelike_facets + + /// @brief Collect spacelike facets into a container indexed by time value + /// @tparam dimension The dimensionality of the simplices + /// @param t_facets A container of facets + /// @return Container with spacelike facets per timeslice + template + [[nodiscard]] auto volume_per_timeslice(Container&& t_facets) + -> std::multimap> + { + auto space_faces = + collect_spacelike_facets(std::forward(t_facets)); + return {std::make_move_iterator(space_faces.begin()), + std::make_move_iterator(space_faces.end())}; } // volume_per_timeslice /// @brief Check cells for correct foliation @@ -873,24 +909,70 @@ namespace foliated_triangulations double const initial_radius = INITIAL_RADIUS, double const foliation_spacing = FOLIATION_SPACING) { + if (t_simplices < 2 || t_timeslices < 2) + { + throw std::invalid_argument( + "Simplices and timeslices must each be at least 2."); + } + if (!std::isfinite(initial_radius) || initial_radius <= 0.0) + { + throw std::invalid_argument( + "Initial radius must be finite and positive."); + } + if (!std::isfinite(foliation_spacing) || foliation_spacing <= 0.0) + { + throw std::invalid_argument( + "Foliation spacing must be finite and positive."); + } + + auto const population = utilities::generated_population_bounds( + dimension, t_simplices, t_timeslices, initial_radius, + foliation_spacing); + if (population.points_per_timeslice < 2) + { + throw std::invalid_argument( + "Simplices and timeslices would create an empty triangulation."); + } + if (!std::isfinite(population.last_layer_points) || + population.last_layer_points > + static_cast(std::numeric_limits::max())) + { + throw std::out_of_range( + "Foliation parameters generate too many points per timeslice."); + } + Causal_vertices_t causal_vertices; causal_vertices.reserve(static_cast(t_simplices)); - auto const points_per_timeslice = utilities::expected_points_per_timeslice( - dimension, t_simplices, t_timeslices); - assert(points_per_timeslice >= 2); for (gsl::index i = 0; i < t_timeslices; ++i) { auto const radius = initial_radius + static_cast(i) * foliation_spacing; + auto const generated_points = + static_cast(population.points_per_timeslice) * radius; + if (!std::isfinite(radius) || generated_points < 2.0L) + { + throw std::invalid_argument( + "Foliation parameters do not populate every timeslice."); + } + if (generated_points > + static_cast(std::numeric_limits::max())) + { + throw std::out_of_range( + "Foliation parameters generate too many points per timeslice."); + } Spherical_points_generator_t gen{radius}; // Generate random points at the radius - for (gsl::index j = 0; - j < static_cast(points_per_timeslice * radius); ++j) + for (gsl::index j = 0; j < static_cast(generated_points); + ++j) { causal_vertices.emplace_back(*gen++, i + 1); } // j } // i + if (causal_vertices.size() < static_cast(dimension + 1)) + { + throw std::invalid_argument("Parameters create an empty triangulation."); + } return causal_vertices; } // make_foliated_ball @@ -990,7 +1072,47 @@ namespace foliated_triangulations using Edge_container = std::vector>; using Vertex_handle = Vertex_handle_t<3>; using Vertex_container = std::vector; - using Volume_by_timeslice = std::multimap>; + using Volume_entry = std::pair>; + using Volume_by_timeslice = std::vector; + + static_assert( + noexcept(std::declval().swap(std::declval())), + "FoliatedTriangulation swap requires CGAL's swap to be noexcept."); + static_assert(std::is_nothrow_swappable_v, + "FoliatedTriangulation swap requires non-throwing scalars."); + static_assert( + std::is_nothrow_swappable_v && + std::is_nothrow_swappable_v && + std::is_nothrow_swappable_v && + std::is_nothrow_swappable_v && + std::is_nothrow_swappable_v, + "FoliatedTriangulation swap requires non-throwing container swaps."); + static_assert(std::is_nothrow_swappable_v, + "FoliatedTriangulation swap requires non-throwing bounds."); + static_assert( + std::is_nothrow_move_constructible_v && + std::is_nothrow_move_constructible_v && + std::is_nothrow_move_constructible_v && + std::is_nothrow_move_constructible_v && + std::is_nothrow_move_constructible_v && + std::is_nothrow_move_constructible_v, + "FoliatedTriangulation move construction requires non-throwing member " + "moves."); + + [[nodiscard]] static auto cache_spacelike_facets( + Face_container const& faces) -> Volume_by_timeslice + { return collect_spacelike_facets<3>(std::span{faces}); } + + [[nodiscard]] static auto require_nonempty(Delaunay triangulation) + -> Delaunay + { + if (triangulation.number_of_vertices() == 0) + { + throw std::invalid_argument( + "A foliated triangulation must contain at least one vertex."); + } + return triangulation; + } /// Data members initialized in order of declaration (Working Draft, /// Standard for C++ Programming Language, 11.9.3 section 13.3) @@ -1018,24 +1140,43 @@ namespace foliated_triangulations FoliatedTriangulation() = default; /// @brief Copy Constructor - FoliatedTriangulation(FoliatedTriangulation const& other) noexcept - : FoliatedTriangulation( - static_cast(other.get_delaunay()), - other.m_initial_radius, other.m_foliation_spacing) - {} + FoliatedTriangulation(FoliatedTriangulation const& other) + : FoliatedTriangulation{} + { + if (other.m_triangulation.number_of_vertices() == 0) + { + m_initial_radius = other.m_initial_radius; + m_foliation_spacing = other.m_foliation_spacing; + return; + } + FoliatedTriangulation copy{Delaunay{other.m_triangulation}, + other.m_initial_radius, + other.m_foliation_spacing}; + swap(copy, *this); + } - /// @brief Copy/Move Assignment operator - auto operator=(FoliatedTriangulation other) noexcept - -> FoliatedTriangulation& + /// @brief Copy assignment operator + /// @details Builds a complete copy before replacing the current value. + auto operator=(FoliatedTriangulation const& other) -> FoliatedTriangulation& { - swap(other, *this); + if (this == &other) { return *this; } + FoliatedTriangulation copy{other}; + swap(copy, *this); return *this; } - /// @brief Move ctor - FoliatedTriangulation(FoliatedTriangulation&& other) noexcept - : FoliatedTriangulation{} - { swap(other, *this); } + /// @brief Move constructor + /// @details Moves the triangulation and all handle caches directly, without + /// first performing the potentially throwing default construction. + FoliatedTriangulation(FoliatedTriangulation&& other) noexcept = default; + + /// @brief Move assignment operator + auto operator=(FoliatedTriangulation&& other) noexcept + -> FoliatedTriangulation& + { + if (this != &other) { swap(other, *this); } + return *this; + } /// @brief Non-member swap function for Foliated Triangulations. /// @details Note that this function calls swap() from CGAL's @@ -1046,9 +1187,6 @@ namespace foliated_triangulations friend void swap(FoliatedTriangulation& swap_from, FoliatedTriangulation& swap_into) noexcept { -#ifndef NDEBUG - spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); -#endif // Uses the triangulation swap method in CGAL // This assumes that the first triangulation is not used afterward! // See @@ -1081,7 +1219,7 @@ namespace foliated_triangulations explicit FoliatedTriangulation( Delaunay triangulation, double const initial_radius = INITIAL_RADIUS, double const foliation_spacing = FOLIATION_SPACING) - : m_triangulation{std::move(triangulation)} + : m_triangulation{require_nonempty(std::move(triangulation))} , m_initial_radius{initial_radius} , m_foliation_spacing{foliation_spacing} , m_vertices{classify_vertices(collect_vertices<3>(m_triangulation))} @@ -1090,7 +1228,7 @@ namespace foliated_triangulations , m_two_two{filter_cells<3>(m_cells, Cell_type::TWO_TWO)} , m_one_three{filter_cells<3>(m_cells, Cell_type::ONE_THREE)} , m_faces{collect_faces()} - , m_spacelike_facets{volume_per_timeslice<3>(std::span{m_faces})} + , m_spacelike_facets{cache_spacelike_facets(m_faces)} , m_edges{collect_edges()} , m_timelike_edges{filter_edges<3>(m_edges, true)} , m_spacelike_edges{filter_edges<3>(m_edges, false)} @@ -1136,16 +1274,16 @@ namespace foliated_triangulations /// @return True if foliated correctly [[nodiscard]] auto is_foliated() const -> bool { - return !static_cast(check_timevalues<3>(this->get_delaunay())); + return !static_cast(check_timevalues<3>(m_triangulation)); } // is_foliated /// @return True if the triangulation is Delaunay [[nodiscard]] auto is_delaunay() const -> bool - { return get_delaunay().is_valid(); } // is_delaunay + { return m_triangulation.is_valid(); } // is_delaunay /// @return True if the triangulation data structure is valid [[nodiscard]] auto is_tds_valid() const -> bool - { return get_delaunay().tds().is_valid(); } // is_tds_valid + { return m_triangulation.tds().is_valid(); } // is_tds_valid /// @return True if the Foliated Triangulation class invariants hold [[nodiscard]] auto is_correct() const -> bool @@ -1161,21 +1299,27 @@ namespace foliated_triangulations /// @return True if fixes were done on the Delaunay triangulation [[nodiscard]] auto is_fixed() -> bool { + Delaunay updated{m_triangulation}; auto const fixed_vertices = foliated_triangulations::fix_vertices<3>( - m_triangulation, m_initial_radius, m_foliation_spacing); - auto const fixed_cells = - foliated_triangulations::fix_cells<3>(m_triangulation); + updated, m_initial_radius, m_foliation_spacing); + auto const fixed_cells = foliated_triangulations::fix_cells<3>(updated); auto const fixed_timeslices = - foliated_triangulations::fix_timevalues<3>(m_triangulation); - return fixed_vertices || fixed_cells || fixed_timeslices; + foliated_triangulations::fix_timevalues<3>(updated); + auto const changed = fixed_vertices || fixed_cells || fixed_timeslices; + if (changed) + { + FoliatedTriangulation replacement{std::move(updated), m_initial_radius, + m_foliation_spacing}; + swap(replacement, *this); + } + return changed; } // is_fixed - /// @return A mutable reference to the Delaunay triangulation - [[nodiscard]] auto delaunay() -> Delaunay& { return m_triangulation; } - - /// @return A read-only reference to the Delaunay triangulation - [[nodiscard]] auto get_delaunay() const -> Delaunay const& - { return m_triangulation; } // get_delaunay + /// @return An owning snapshot of the Delaunay triangulation + /// @details Mutating the returned value cannot invalidate this object's + /// cached topology classifications. + [[nodiscard]] auto delaunay_snapshot() const -> Delaunay + { return m_triangulation; } // delaunay_snapshot /// @return Number of 3D simplices in triangulation data structure [[nodiscard]] auto number_of_finite_cells() const @@ -1199,37 +1343,22 @@ namespace foliated_triangulations [[nodiscard]] auto number_of_vertices() const { return m_triangulation.number_of_vertices(); } // number_of_vertices - /// @return If a cell or vertex contains or is the infinite vertex - /// Forward parameters (see F.19 of C++ Core Guidelines) - template - [[nodiscard]] auto is_infinite(VertexHandle&& t_vertex) const - { - return m_triangulation.is_infinite(std::forward(t_vertex)); - } // is_infinite - - /// @brief Call one of the TSD3.flip functions - /// - /// See - /// https://doc.cgal.org/latest/Triangulation_3/classCGAL_1_1Triangulation__3.html#a883fed00b53cae9e85feb20230f54dd9 - /// - /// @tparam Ts Variadic template of types of the arguments - /// @param args Parameter pack of arguments to TDS3.flip - /// @return True if the flip occurred - template - [[nodiscard]] auto flip(Ts&&... args) - { return m_triangulation.flip(std::forward(args)...); } // flip - - /// @return Returns the infinite vertex in the triangulation - [[maybe_unused]] [[nodiscard]] auto infinite_vertex() const - { return m_triangulation.infinite_vertex(); } // infinite_vertex - /// @return Dimensionality of triangulation data structure (int) [[nodiscard]] auto dimension() const { return m_triangulation.dimension(); } - /// @return Container of spacelike facets indexed by time value - [[nodiscard]] auto N2_SL() const - -> std::multimap::Facet> const& - { return m_spacelike_facets; } // N2_SL + /// @return Number of spacelike facets on a timeslice + [[nodiscard]] auto spacelike_face_count( + Int_precision const timevalue) const noexcept -> std::size_t + { + auto const matching_facets = std::ranges::equal_range( + m_spacelike_facets, timevalue, std::ranges::less{}, + [](Volume_entry const& entry) noexcept { return entry.first; }); + return static_cast(matching_facets.size()); + } + + /// @return Total number of spacelike facets + [[nodiscard]] auto number_of_spacelike_faces() const noexcept -> std::size_t + { return m_spacelike_facets.size(); } /// @return Number of timelike edges [[nodiscard]] auto N1_TL() const @@ -1239,24 +1368,6 @@ namespace foliated_triangulations [[nodiscard]] auto N1_SL() const { return static_cast(m_spacelike_edges.size()); } // N1_SL - /// @return Container of timelike edges - [[nodiscard]] auto get_timelike_edges() const noexcept - -> Edge_container const& - { return m_timelike_edges; } // get_timelike_edges - - /// @return Container of spacelike edges - [[nodiscard]] auto get_spacelike_edges() const -> Edge_container const& - { return m_spacelike_edges; } // get_spacelike_edges - - /// @return Container of vertices - [[nodiscard]] auto get_vertices() const noexcept -> Vertex_container const& - { return m_vertices; } // get_vertices - - /// @return A span of vertices - [[nodiscard]] auto get_vertices_span() const noexcept - -> std::span - { return std::span{m_vertices}; } // get_vertices_span - /// @return Maximum time value in triangulation [[nodiscard]] auto max_time() const { return m_max_timevalue; } @@ -1269,48 +1380,6 @@ namespace foliated_triangulations /// @return The spacing between timeslices [[nodiscard]] auto foliation_spacing() const { return m_foliation_spacing; } - /// @brief Perfect forwarding to TriangulationDataStructure_3::degree - /// @return The number of incident edges to a vertex - /// @see - /// https://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html#a51fce32aa7abf3d757bcabcebd22f2fe - template - [[nodiscard]] auto degree(VertexHandle&& t_vertex) const - { - return m_triangulation.degree(std::forward(t_vertex)); - } // degree - - /// @brief Perfect forwarding to - /// TriangulationDataStructure_3::incident_cells - /// @details If there are n incident edges there are 2(n-2) incident cells - /// @tparam VertexHandle Template parameter used to forward - /// @param t_vh Vertex - /// @return A container of incident cells - /// @see - /// https://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html#a93f8ab30228b2a515a5c9cdacd9d4d36 - template - [[nodiscard]] auto incident_cells(VertexHandle&& t_vh) const noexcept - -> decltype(auto) - { - Cell_container inc_cells; - get_delaunay().tds().incident_cells(std::forward(t_vh), - std::back_inserter(inc_cells)); - return inc_cells; - } // incident_cells - - /// @brief Perfect forwarding to - /// TriangulationDataStructure_3::incident_cells - /// @tparam Ts Variadic template used to forward - /// @param args Parameter pack of arguments to call incident_cells() - /// @return A Cell_circulator - /// @see - /// https://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html#a93f8ab30228b2a515a5c9cdacd9d4d36 - template - [[nodiscard]] auto incident_cells(Ts&&... args) const noexcept - -> decltype(auto) - { - return get_delaunay().tds().incident_cells(std::forward(args)...); - } // incident_cells - /// @brief Check the radius of a vertex from the origin with its timevalue /// @param t_vertex The vertex to check /// @return True if the effective radial distance squared matches timevalue @@ -1359,18 +1428,19 @@ namespace foliated_triangulations m_triangulation, m_initial_radius, m_foliation_spacing); } // check_all_vertices - /// @return A container of incorrect vertices - [[nodiscard]] auto find_incorrect_vertices() const - { - return foliated_triangulations::find_incorrect_vertices<3>( - m_triangulation, m_initial_radius, m_foliation_spacing); - } // find_incorrect_vertices - /// @brief Fix vertices with wrong timevalues after foliation - [[nodiscard]] auto fix_vertices() const -> bool + [[nodiscard]] auto fix_vertices() -> bool { - return foliated_triangulations::fix_vertices<3>( - m_triangulation, m_initial_radius, m_foliation_spacing); + Delaunay updated{m_triangulation}; + auto const changed = foliated_triangulations::fix_vertices<3>( + updated, m_initial_radius, m_foliation_spacing); + if (changed) + { + FoliatedTriangulation replacement{std::move(updated), m_initial_radius, + m_foliation_spacing}; + swap(replacement, *this); + } + return changed; } // fix_vertices /// @brief Print values of a vertex @@ -1404,29 +1474,21 @@ namespace foliated_triangulations for (auto j = min_time(); j <= max_time(); ++j) { fmt::print("Timeslice {} has {} spacelike faces.\n", j, - m_spacelike_facets.count(j)); + spacelike_face_count(j)); } } // print_volume_per_timeslice - /// @return Container of cells - [[nodiscard]] auto get_cells() const -> Cell_container const& - { - assert(m_cells.size() == number_of_finite_cells()); - return m_cells; - } // get_cells - - /// @return Container of (3,1) cells - [[nodiscard]] auto get_three_one() const noexcept - -> std::span - { return std::span{m_three_one}; } // get_three_one + /// @return Number of classified (3,1) cells + [[nodiscard]] auto number_of_three_one_cells() const noexcept -> std::size_t + { return m_three_one.size(); } - /// @return Container of (2,2) cells - [[nodiscard]] auto get_two_two() const noexcept -> Cell_container const& - { return m_two_two; } // get_two_two + /// @return Number of classified (2,2) cells + [[nodiscard]] auto number_of_two_two_cells() const noexcept -> std::size_t + { return m_two_two.size(); } - /// @return Container of (1,3) cells - [[nodiscard]] auto get_one_three() const noexcept -> Cell_container const& - { return m_one_three; } // get_one_three + /// @return Number of classified (1,3) cells + [[nodiscard]] auto number_of_one_three_cells() const noexcept -> std::size_t + { return m_one_three.size(); } /// @brief Check that all cells are correctly classified /// @details A default triangulation will have no cells, and for this case @@ -1435,13 +1497,21 @@ namespace foliated_triangulations /// @return True if there are no cells or all cells are validly classified [[nodiscard]] auto check_all_cells() const -> bool { - return foliated_triangulations::check_cells<3>(get_delaunay()); + return foliated_triangulations::check_cells<3>(m_triangulation); } // check_all_cells /// @brief Fix all cells in the triangulation - auto fix_cells() const -> bool + auto fix_cells() -> bool { - return foliated_triangulations::fix_cells<3>(get_delaunay()); + Delaunay updated{m_triangulation}; + auto const changed = foliated_triangulations::fix_cells<3>(updated); + if (changed) + { + FoliatedTriangulation replacement{std::move(updated), m_initial_radius, + m_foliation_spacing}; + swap(replacement, *this); + } + return changed; } // fix_cells /// @brief Print timevalues of each vertex in the cell and the resulting @@ -1491,17 +1561,17 @@ namespace foliated_triangulations // Somewhere in bistellar_flip_really a vertex is rendered invalid assert(is_tds_valid()); Face_container init_faces; - init_faces.reserve(get_delaunay().number_of_finite_facets()); - for (auto fit = get_delaunay().finite_facets_begin(); - fit != get_delaunay().finite_facets_end(); ++fit) + init_faces.reserve(m_triangulation.number_of_finite_facets()); + for (auto fit = m_triangulation.finite_facets_begin(); + fit != m_triangulation.finite_facets_end(); ++fit) { Cell_handle_t<3> const cell = fit->first; // Each face is valid in the triangulation - assert(get_delaunay().tds().is_facet(cell, fit->second)); + assert(m_triangulation.tds().is_facet(cell, fit->second)); Face_handle_t<3> const thisFacet{std::make_pair(cell, fit->second)}; init_faces.emplace_back(thisFacet); } - assert(init_faces.size() == get_delaunay().number_of_finite_facets()); + assert(init_faces.size() == m_triangulation.number_of_finite_facets()); return init_faces; } // collect_faces @@ -1511,16 +1581,16 @@ namespace foliated_triangulations assert(is_tds_valid()); Edge_container init_edges; init_edges.reserve(number_of_finite_edges()); - for (auto eit = get_delaunay().finite_edges_begin(); - eit != get_delaunay().finite_edges_end(); ++eit) + for (auto eit = m_triangulation.finite_edges_begin(); + eit != m_triangulation.finite_edges_end(); ++eit) { Cell_handle_t<3> const cell = eit->first; Edge_handle_t<3> const thisEdge{cell, cell->index(cell->vertex(eit->second)), cell->index(cell->vertex(eit->third))}; // Each edge is valid in the triangulation - assert(get_delaunay().tds().is_valid(thisEdge.first, thisEdge.second, - thisEdge.third)); + assert(m_triangulation.tds().is_valid(thisEdge.first, thisEdge.second, + thisEdge.third)); init_edges.emplace_back(thisEdge); } assert(init_edges.size() == number_of_finite_edges()); diff --git a/include/Geometry.hpp b/include/Geometry.hpp index 774ccb689..e79e49e50 100644 --- a/include/Geometry.hpp +++ b/include/Geometry.hpp @@ -14,6 +14,8 @@ #ifndef CDT_PLUSPLUS_GEOMETRY_HPP #define CDT_PLUSPLUS_GEOMETRY_HPP +#include + #include "Foliated_triangulation.hpp" /// Geometry class template @@ -25,6 +27,9 @@ struct Geometry; template <> struct [[nodiscard("This contains data!")]] Geometry<3> { + static_assert(std::is_nothrow_swappable_v, + "Geometry swap requires non-throwing scalar swaps."); + /// @brief Number of 3D simplices Int_precision N3{0}; // NOLINT @@ -65,10 +70,13 @@ struct [[nodiscard("This contains data!")]] Geometry<3> foliated_triangulations::FoliatedTriangulation_3 const& triangulation) : N3{static_cast(triangulation.number_of_finite_cells())} - , N3_31{static_cast(triangulation.get_three_one().size())} - , N3_13{static_cast(triangulation.get_one_three().size())} + , N3_31{static_cast( + triangulation.number_of_three_one_cells())} + , N3_13{static_cast( + triangulation.number_of_one_three_cells())} , N3_31_13{N3_31 + N3_13} - , N3_22{static_cast(triangulation.get_two_two().size())} + , N3_22{static_cast( + triangulation.number_of_two_two_cells())} , N2{static_cast(triangulation.number_of_finite_facets())} , N1{static_cast(triangulation.number_of_finite_edges())} , N1_TL{triangulation.N1_TL()} @@ -78,15 +86,12 @@ struct [[nodiscard("This contains data!")]] Geometry<3> {} /// @brief Non-member swap function for Geometry - /// @details Used for no-except updates of geometry data structures. + /// @details Used for noexcept updates of geometry data structures. /// Usually called from a Manifold swap. /// @param swap_from The value to be swapped from. Assumed to be discarded. /// @param swap_into The value to be swapped into. friend void swap(Geometry& swap_from, Geometry& swap_into) noexcept { -#ifndef NDEBUG - spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); -#endif using std::swap; swap(swap_from.N3, swap_into.N3); swap(swap_from.N3_31, swap_into.N3_31); diff --git a/include/Manifold.hpp b/include/Manifold.hpp index ba1cfc3fc..35734b0cf 100644 --- a/include/Manifold.hpp +++ b/include/Manifold.hpp @@ -12,6 +12,7 @@ #define CDT_PLUSPLUS_MANIFOLD_HPP #include +#include #include #include "Geometry.hpp" @@ -44,6 +45,14 @@ namespace manifolds using Triangulation = foliated_triangulations::FoliatedTriangulation_3; using Geometry = Geometry_3; + static_assert(std::is_nothrow_swappable_v, + "Manifold swap requires a non-throwing triangulation swap."); + static_assert(std::is_nothrow_swappable_v, + "Manifold swap requires a non-throwing geometry swap."); + static_assert( + std::is_nothrow_move_constructible_v && + std::is_nothrow_move_constructible_v, + "Manifold move construction requires non-throwing member moves."); /// @brief The data structure of geometric and combinatorial relationships Triangulation m_triangulation; @@ -71,20 +80,21 @@ namespace manifolds auto operator=(Manifold const& other) -> Manifold& = default; /// @brief Default move ctor - Manifold(Manifold&& other) = default; + Manifold(Manifold&& other) noexcept = default; /// @brief Default move assignment - auto operator=(Manifold&& other) -> Manifold& = default; + auto operator=(Manifold&& other) noexcept -> Manifold& + { + if (this != &other) { swap(other, *this); } + return *this; + } /// @brief Non-member swap function for Manifolds. - /// @details Used for no-except updates of manifolds after moves. + /// @details Used for noexcept updates of manifolds after moves. /// @param swap_from The value to be swapped from. Assumed to be discarded. /// @param swap_into The value to be swapped into. friend void swap(Manifold& swap_from, Manifold& swap_into) noexcept { -#ifndef NDEBUG - spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); -#endif using std::swap; swap(swap_from.m_triangulation, swap_into.m_triangulation); swap(swap_from.m_geometry, swap_into.m_geometry); @@ -94,7 +104,7 @@ namespace manifolds /// @param t_foliated_triangulation Triangulation used to construct manifold explicit Manifold(Triangulation t_foliated_triangulation) : m_triangulation{std::move(t_foliated_triangulation)} - , m_geometry{get_triangulation()} + , m_geometry{m_triangulation} {} /// @brief Construct manifold using arguments @@ -126,33 +136,28 @@ namespace manifolds } {} - /// @brief Update the Manifold data structures - void update() - try + /// @brief Return a manifold rebuilt from the current canonical topology. + /// @details The source remains unchanged. The returned triangulation caches + /// and geometry are constructed together, so failure cannot publish a + /// partially updated state. + [[nodiscard]] auto updated() const -> Manifold { #ifndef NDEBUG spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); #endif - update_triangulation(); - update_geometry(); - } - catch (std::system_error const& ex) - { - spdlog::trace("Exception thrown: {}\n", ex.what()); - } // update - - /// @returns A read-only reference to the triangulation - [[nodiscard]] auto get_triangulation() const noexcept - -> Triangulation const& - { return m_triangulation; } // get_triangulation - - /// @returns A read-only reference to the Delaunay triangulation - [[nodiscard]] auto get_delaunay() const noexcept -> Delaunay_t<3> const& - { return get_triangulation().get_delaunay(); } // get_delaunay - - /// @returns A mutable reference to the triangulation - [[nodiscard]] auto triangulation() -> Triangulation& - { return m_triangulation; } // triangulation + if (m_triangulation.number_of_vertices() == 0) { return Manifold{}; } + return Manifold{ + Triangulation{m_triangulation.delaunay_snapshot(), + m_triangulation.initial_radius(), + m_triangulation.foliation_spacing()} + }; + } // updated + + /// @returns An owning snapshot of the canonical Delaunay triangulation + /// @details Handles obtained from the snapshot cannot mutate this manifold + /// or invalidate its derived geometry and topology caches. + [[nodiscard]] auto delaunay_snapshot() const -> Delaunay_t<3> + { return m_triangulation.delaunay_snapshot(); } /// @returns A read-only reference to the Geometry [[nodiscard]] auto get_geometry() const -> Geometry const& @@ -177,28 +182,6 @@ namespace manifolds [[nodiscard]] auto is_correct() const -> bool { return m_triangulation.is_correct(); } // is_correct - /// @brief Perfect forwarding to FoliatedTriangulation_3.is_vertex() - /// @tparam VertexType The vertex type - /// @param t_vertex_candidate The vertex to check - /// @returns True if the vertex candidate is a vertex - template - [[nodiscard]] auto is_vertex(VertexType&& t_vertex_candidate) const -> bool - { - return m_triangulation.get_delaunay().is_vertex( - std::forward(t_vertex_candidate)); - } // is_vertex - - /// @brief Forwarding to FoliatedTriangulation_3.is_edge() - /// @param t_edge_candidate The edge to test - /// @returns True if the candidate is an edge - [[nodiscard]] auto is_edge( - Edge_handle_t<3> const& t_edge_candidate) const noexcept -> bool - { - return m_triangulation.get_delaunay().tds().is_edge( - t_edge_candidate.first, t_edge_candidate.second, - t_edge_candidate.third); - } // is_edge - /// @returns Run-time dimensionality of the triangulation data structure [[nodiscard]] auto dimensionality() const { return m_triangulation.dimension(); } @@ -229,16 +212,17 @@ namespace manifolds /// @returns Number of 3D simplices in triangulation data structure [[nodiscard]] auto simplices() const { - return static_cast(m_triangulation.get_cells().size()); + return static_cast( + m_triangulation.number_of_finite_cells()); } // number_of_simplices /// @returns Number of 2D faces in geometry data structure [[nodiscard]] auto N2() const { return m_geometry.N2; } - /// @returns An associative container of spacelike faces indexed by - /// timevalue - [[nodiscard]] auto N2_SL() const -> auto const& - { return m_triangulation.N2_SL(); } // N2_SL + /// @returns Number of spacelike faces on a timeslice + [[nodiscard]] auto spacelike_face_count( + Int_precision const timevalue) const noexcept -> std::size_t + { return m_triangulation.spacelike_face_count(timevalue); } /// @returns Number of 2D faces in triangulation data structure [[nodiscard]] auto faces() const @@ -280,37 +264,6 @@ namespace manifolds [[nodiscard]] auto max_time() const { return m_triangulation.max_time(); } // max_time - /// @brief Perfect forwarding to FoliatedTriangulation_3.degree() - template - [[nodiscard]] auto degree(VertexHandle&& t_vertex) const -> decltype(auto) - { - return m_triangulation.degree(std::forward(t_vertex)); - } // degree - - /// @brief Perfect forwarding to FoliatedTriangulation_3.incident_cells() - template - [[nodiscard]] auto incident_cells(Ts&&... args) const noexcept - -> decltype(auto) - { - return m_triangulation.incident_cells(std::forward(args)...); - } // incident_cells - - /// @brief Call to triangulation_.get_timelike_edges() - [[nodiscard]] auto get_timelike_edges() const noexcept -> auto const& - { return m_triangulation.get_timelike_edges(); } // get_timelike_edges - - /// @brief Call triangulation.get_spacelike_edges() - [[nodiscard]] auto get_spacelike_edges() const -> auto const& - { return m_triangulation.get_spacelike_edges(); } // get_spacelike_edges - - /// @brief Call FoliatedTriangulation_3.get_vertices() - [[nodiscard]] auto get_vertices() const noexcept -> auto const& - { return m_triangulation.get_vertices(); } // get_vertices - - /// @brief Call FoliatedTriangulation_3.get_vertices_span() - [[nodiscard]] auto get_vertices_span() const noexcept -> auto - { return m_triangulation.get_vertices_span(); } // get_vertices_span - /// @returns True if all cells in triangulation are classified and match /// number in geometry [[nodiscard]] auto check_simplices() const -> bool @@ -319,6 +272,10 @@ namespace manifolds m_triangulation.check_all_cells(); } // check_simplices + /// @returns True if every vertex carries the expected timevalue + [[nodiscard]] auto check_vertices() const -> bool + { return m_triangulation.check_all_vertices(); } + /// @brief Print the codimension 1 volume of simplices (faces) per timeslice void print_volume_per_timeslice() const { @@ -363,62 +320,6 @@ namespace manifolds fmt::print(stderr, "print_details() went wrong ...\n"); throw; } // print_details - - /// @brief Obtains a vertex handle from a point - /// @param point The point to search for - /// @return The vertex handle to the vertex containing the point - auto get_vertex(Point_t<3> const& point) const -> Vertex_handle_t<3> - { - Vertex_handle_t<3> result; - m_triangulation.get_delaunay().is_vertex(point, result); - return result; - } // get_vertex - - /// @brief Get a cell handle from 4 vertex handles - /// @param vh1 The first vertex handle - /// @param vh2 The second vertex handle - /// @param vh3 The third vertex handle - /// @param vh4 The fourth vertex handle - /// @return The cell handle containing the vertex handles - auto get_cell(Vertex_handle_t<3> const& vh1, Vertex_handle_t<3> const& vh2, - Vertex_handle_t<3> const& vh3, - Vertex_handle_t<3> const& vh4) const -> Cell_handle_t<3> - { - Cell_handle_t<3> result; - m_triangulation.get_delaunay().is_cell(vh1, vh2, vh3, vh4, result); - return result; - } // get_cell_handle - - private: - /// @brief Update the triangulation - void update_triangulation() - try - { -#ifndef NDEBUG - spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); -#endif - // Constructing a new triangulation updates all data structures - Triangulation local_triangulation(m_triangulation.get_delaunay(), - m_triangulation.initial_radius(), - m_triangulation.foliation_spacing()); - swap(local_triangulation, m_triangulation); - } - catch (std::system_error const& ex) - { - fmt::print("Exception thrown: {}\n", ex.what()); - } // update_triangulation - - /// @brief Update geometry data of the manifold when the triangulation has - /// been changed - void update_geometry() noexcept - { -#ifndef NDEBUG - spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); -#endif - // constructing a new geometry updates all data structures - Geometry geom(m_triangulation); - swap(geom, m_geometry); - } // update_geometry }; using Manifold_3 = Manifold<3>; diff --git a/include/Metropolis.hpp b/include/Metropolis.hpp index 805536be9..7536fb783 100644 --- a/include/Metropolis.hpp +++ b/include/Metropolis.hpp @@ -106,16 +106,16 @@ class MoveStrategy Int_precision const passes, Int_precision const checkpoint, bool const write_files = true) - : m_Alpha(Alpha) - , m_K(K) - , m_Lambda(Lambda) - , m_passes(passes) - , m_checkpoint{checkpoint} - , m_write_files{write_files} + : m_passes(passes), m_checkpoint{checkpoint}, m_write_files{write_files} { - if (m_passes < 0) + auto const parameters = + s3_action::make_physical_parameters(Alpha, K, Lambda); + m_Alpha = parameters.alpha; + m_K = parameters.k; + m_Lambda = parameters.lambda; + if (m_passes <= 0) { - throw std::invalid_argument{"Metropolis passes cannot be negative"}; + throw std::invalid_argument{"Metropolis passes must be positive"}; } if (m_checkpoint <= 0) { @@ -170,30 +170,14 @@ class MoveStrategy /// /// @param move The type of move /// @returns \f$a_1=\frac{move[i]}{\sum\limits_{i}move[i]}\f$ - auto CalculateA1(move_tracker::move_type move) const noexcept + [[nodiscard]] auto CalculateA1(move_tracker::move_type move) const { - auto all_moves = m_proposed_moves.total(); - auto this_move = m_proposed_moves[move]; - // Set precision for initialization and assignment functions - mpfr_set_default_prec(PRECISION); - - // Initialize for MPFR - mpfr_t r_1; - mpfr_t r_2; - mpfr_t a_1; - mpfr_inits2(PRECISION, a_1, nullptr); // NOLINT - - mpfr_init_set_si(r_1, this_move, MPFR_RNDD); // r_1 = this_move NOLINT - mpfr_init_set_si(r_2, all_moves, MPFR_RNDD); // r_2 = total_moves NOLINT - - // The result - mpfr_div(a_1, r_1, r_2, MPFR_RNDD); // a_1 = r_1/r_2 NOLINT - - // Convert mpfr_t total to Gmpzf result by using Gmpzf(double d) - auto result = mpfr_get_ld(a_1, MPFR_RNDD); // NOLINT - - // Free memory - mpfr_clears(r_1, r_2, a_1, nullptr); // NOLINT + auto const all_moves = m_proposed_moves.total(); + auto const this_move = m_proposed_moves[move]; + auto const proposed_move = mpfr_values::from_integer(this_move); + auto const proposed_total = mpfr_values::from_integer(all_moves); + auto const probability = mpfr_values::divide(proposed_move, proposed_total); + auto const result = mpfr_values::to_long_double(probability); #ifndef NDEBUG spdlog::debug("{} called.\n", __PRETTY_FUNCTION__); @@ -208,7 +192,7 @@ class MoveStrategy /// @details Calculate \f$a_2=e^{\Delta S}\f$ /// @param move The type of move /// @returns \f$a_2=e^{-\Delta S}\f$ - auto CalculateA2(move_tracker::move_type const move) const noexcept + [[nodiscard]] auto CalculateA2(move_tracker::move_type const move) const { auto currentS3Action = S3_bulk_action(m_geometry.N1_TL, m_geometry.N3_31_13, m_geometry.N3_22, @@ -261,26 +245,9 @@ class MoveStrategy // algorithm return A2=1 if (exponent >= 0) { return static_cast(1); } - // Set precision for initialization and assignment functions - mpfr_set_default_prec(PRECISION); - - // Initialize for MPFR - mpfr_t r_1; - mpfr_t a_2; - mpfr_inits2(PRECISION, a_2, nullptr); // NOLINT - - // Set input parameters and constants to mpfr_t equivalents - mpfr_init_set_ld(r_1, exponent_double, // NOLINT - MPFR_RNDD); // r1 = exponent - - // e^exponent - mpfr_exp(a_2, r_1, MPFR_RNDD); // NOLINT - - // Convert mpfr_t total to Gmpzf result by using Gmpzf(double d) - auto result = mpfr_get_ld(a_2, MPFR_RNDD); // NOLINT - - // Free memory - mpfr_clears(r_1, a_2, nullptr); // NOLINT + auto const exponent_value = mpfr_values::from_long_double(exponent_double); + auto const probability = mpfr_values::exponential(exponent_value); + auto const result = mpfr_values::to_long_double(probability); #ifndef NDEBUG spdlog::trace("A2 is {}\n", result); diff --git a/include/Move_command.hpp b/include/Move_command.hpp index a82518330..76e49cb9e 100644 --- a/include/Move_command.hpp +++ b/include/Move_command.hpp @@ -17,7 +17,7 @@ template , typename FunctionType = - boost::compat::function_ref> + boost::compat::function_ref> requires(ManifoldType::dimension == 3) class MoveCommand { @@ -135,12 +135,9 @@ class MoveCommand ++m_attempted[as_integer(move_type)]; // Convert move_type to function auto move_function = as_move_function(move_type); - // Execute each move on a private candidate so rejection is atomic even - // when a move discovers an error after beginning a topology mutation. - ManifoldType candidate{m_manifold}; - if (auto result = apply_move(candidate, move_function); result) + if (auto result = apply_move(std::as_const(m_manifold), move_function); + result) { - result->update(); if (result->is_correct()) { swap(result.value(), m_manifold); diff --git a/include/Mpfr_value.hpp b/include/Mpfr_value.hpp new file mode 100644 index 000000000..d7757e0bb --- /dev/null +++ b/include/Mpfr_value.hpp @@ -0,0 +1,140 @@ +/******************************************************************************* + Causal Dynamical Triangulations in C++ using CGAL + + Copyright © 2026 Adam Getchell + ******************************************************************************/ + +/// @file Mpfr_value.hpp +/// @brief Scope-owned, value-returning MPFR operations + +#ifndef CDT_PLUSPLUS_MPFR_VALUE_HPP +#define CDT_PLUSPLUS_MPFR_VALUE_HPP + +#include + +#include +#include + +#include "Settings.hpp" + +namespace mpfr_values +{ + using Value = CGAL::Gmpfr; + + static_assert(std::is_nothrow_destructible_v, + "MPFR values must release their resources without throwing."); + + inline auto constexpr precision = + static_cast(PRECISION); + + [[nodiscard]] inline auto zero() -> Value { return Value{0, precision}; } + + [[nodiscard]] inline auto from_integer(long const value) -> Value + { + auto result = zero(); + mpfr_set_si(result.fr(), value, MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto from_long_double(long double const value) -> Value + { + auto result = zero(); + mpfr_set_ld(result.fr(), value, MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto from_decimal(char const* value) -> Value + { + if (value == nullptr) + { + throw std::invalid_argument("MPFR decimal value must not be null."); + } + auto result = zero(); + if (mpfr_set_str(result.fr(), value, 10, MPFR_RNDD) != 0) + { + throw std::invalid_argument("Invalid decimal MPFR value."); + } + return result; + } + + [[nodiscard]] inline auto pi() -> Value + { + auto result = zero(); + mpfr_const_pi(result.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto add(Value const& left, Value const& right) -> Value + { + auto result = zero(); + mpfr_add(result.fr(), left.fr(), right.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto subtract(Value const& left, Value const& right) + -> Value + { + auto result = zero(); + mpfr_sub(result.fr(), left.fr(), right.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto multiply(Value const& left, Value const& right) + -> Value + { + auto result = zero(); + mpfr_mul(result.fr(), left.fr(), right.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto divide(Value const& numerator, + Value const& denominator) -> Value + { + auto result = zero(); + mpfr_div(result.fr(), numerator.fr(), denominator.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto square_root(Value const& value) -> Value + { + auto result = zero(); + mpfr_sqrt(result.fr(), value.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto inverse_hyperbolic_sine(Value const& value) -> Value + { + auto result = zero(); + mpfr_asinh(result.fr(), value.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto arc_cosine(Value const& value) -> Value + { + auto result = zero(); + mpfr_acos(result.fr(), value.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto negate(Value const& value) -> Value + { + auto result = zero(); + mpfr_neg(result.fr(), value.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto exponential(Value const& value) -> Value + { + auto result = zero(); + mpfr_exp(result.fr(), value.fr(), MPFR_RNDD); + return result; + } + + [[nodiscard]] inline auto to_double(Value const& value) -> double + { return mpfr_get_d(value.fr(), MPFR_RNDD); } + + [[nodiscard]] inline auto to_long_double(Value const& value) -> long double + { return mpfr_get_ld(value.fr(), MPFR_RNDD); } +} // namespace mpfr_values + +#endif // CDT_PLUSPLUS_MPFR_VALUE_HPP diff --git a/include/Periodic_3_complex.hpp b/include/Periodic_3_complex.hpp index 098bd80e0..afb648547 100644 --- a/include/Periodic_3_complex.hpp +++ b/include/Periodic_3_complex.hpp @@ -26,8 +26,7 @@ using GT = CGAL::Periodic_3_triangulation_traits_3; using PDT = CGAL::Periodic_3_Delaunay_triangulation_3; /// Make 3D toroidal (periodic in 3D) simplicial complexes -void make_random_T3_simplicial_complex(PDT* T3, - int number_of_simplices) noexcept +void make_random_T3_simplicial_complex(PDT* T3, int number_of_simplices) { typedef CGAL::Creator_uniform_3 Creator; CGAL::Random random(7); diff --git a/include/Periodic_3_triangulations.hpp b/include/Periodic_3_triangulations.hpp index 34be7017b..25ba89a1f 100644 --- a/include/Periodic_3_triangulations.hpp +++ b/include/Periodic_3_triangulations.hpp @@ -43,7 +43,7 @@ using Point = Kd::Point_d; /// Make 3D toroidal (periodic) triangulations template -void make_random_T3_triangulation(T* T3, int simplices, int timeslices) noexcept +void make_random_T3_triangulation(T* T3, int simplices, int timeslices) { std::cout << "make_random_T3_triangulation() called" << std::endl; diff --git a/include/Runtime_config.hpp b/include/Runtime_config.hpp new file mode 100644 index 000000000..ffaeced31 --- /dev/null +++ b/include/Runtime_config.hpp @@ -0,0 +1,300 @@ +/******************************************************************************* + Causal Dynamical Triangulations in C++ using CGAL + + Copyright © 2026 Adam Getchell + ******************************************************************************/ + +/// @file Runtime_config.hpp +/// @brief Validated runtime configuration for CDT++ command-line programs + +#ifndef CDT_PLUSPLUS_RUNTIME_CONFIG_HPP +#define CDT_PLUSPLUS_RUNTIME_CONFIG_HPP + +#include +#include +#include +#include +#include + +#include "Utilities.hpp" + +namespace runtime_config +{ + /// Parameters shared by triangulation-producing command-line programs. + /// @details Instances can only be created by make_triangulation(), so the + /// stored values carry the complete validated boundary contract. + class Triangulation + { + friend auto make_triangulation(bool spherical, bool toroidal, + long long simplices, long long timeslices, + long long dimensions, double initial_radius, + double foliation_spacing) -> Triangulation; + + topology_type m_topology; + Int_precision m_simplices; + Int_precision m_timeslices; + Int_precision m_dimensions; + double m_initial_radius; + double m_foliation_spacing; + + explicit Triangulation(topology_type const topology, + Int_precision const simplices, + Int_precision const timeslices, + Int_precision const dimensions, + double const initial_radius, + double const foliation_spacing) noexcept + : m_topology{topology} + , m_simplices{simplices} + , m_timeslices{timeslices} + , m_dimensions{dimensions} + , m_initial_radius{initial_radius} + , m_foliation_spacing{foliation_spacing} + {} + + public: + Triangulation(Triangulation const&) = default; + Triangulation(Triangulation&&) noexcept = default; + auto operator=(Triangulation const&) -> Triangulation& = default; + auto operator=(Triangulation&&) noexcept -> Triangulation& = default; + ~Triangulation() = default; + + [[nodiscard]] auto topology() const noexcept -> topology_type + { return m_topology; } + + [[nodiscard]] auto simplices() const noexcept -> Int_precision + { return m_simplices; } + + [[nodiscard]] auto timeslices() const noexcept -> Int_precision + { return m_timeslices; } + + [[nodiscard]] auto dimensions() const noexcept -> Int_precision + { return m_dimensions; } + + [[nodiscard]] auto initial_radius() const noexcept -> double + { return m_initial_radius; } + + [[nodiscard]] auto foliation_spacing() const noexcept -> double + { return m_foliation_spacing; } + }; + + /// Complete validated configuration for the Metropolis simulation. + /// @details Instances can only be created by make_simulation(), and retain a + /// validated Triangulation value rather than raw triangulation options. + class Simulation + { + friend auto make_simulation(Triangulation const& triangulation, + long double alpha, long double k, + long double lambda, long long passes, + long long checkpoint, bool write_files) + -> Simulation; + + Triangulation m_triangulation; + long double m_alpha; + long double m_k; + long double m_lambda; + Int_precision m_passes; + Int_precision m_checkpoint; + bool m_write_files; + + explicit Simulation(Triangulation const& triangulation, + long double const alpha, long double const k, + long double const lambda, Int_precision const passes, + Int_precision const checkpoint, + bool const write_files) noexcept + : m_triangulation{triangulation} + , m_alpha{alpha} + , m_k{k} + , m_lambda{lambda} + , m_passes{passes} + , m_checkpoint{checkpoint} + , m_write_files{write_files} + {} + + public: + Simulation(Simulation const&) = default; + Simulation(Simulation&&) noexcept = default; + auto operator=(Simulation const&) -> Simulation& = default; + auto operator=(Simulation&&) noexcept -> Simulation& = default; + ~Simulation() = default; + + [[nodiscard]] auto triangulation() const noexcept -> Triangulation const& + { return m_triangulation; } + + [[nodiscard]] auto alpha() const noexcept -> long double { return m_alpha; } + + [[nodiscard]] auto k() const noexcept -> long double { return m_k; } + + [[nodiscard]] auto lambda() const noexcept -> long double + { return m_lambda; } + + [[nodiscard]] auto passes() const noexcept -> Int_precision + { return m_passes; } + + [[nodiscard]] auto checkpoint() const noexcept -> Int_precision + { return m_checkpoint; } + + [[nodiscard]] auto write_files() const noexcept -> bool + { return m_write_files; } + }; + + namespace detail + { + template + [[nodiscard]] auto checked_finite(char const* name, + FloatingPoint const value) + -> FloatingPoint + { + if (!std::isfinite(value)) + { + throw std::invalid_argument(std::string{name} + " must be finite."); + } + return value; + } + + [[nodiscard]] inline auto checked_int(char const* name, + long long const value) + -> Int_precision + { + if (!std::in_range(value)) + { + throw std::out_of_range(std::string{name} + + " exceeds the supported integer range."); + } + return static_cast(value); + } + + [[nodiscard]] inline auto select_topology(bool const spherical, + bool const toroidal) + -> topology_type + { + if (spherical == toroidal) + { + throw std::invalid_argument( + "Specify exactly one topology: --spherical or --toroidal."); + } + if (toroidal) + { + throw std::invalid_argument( + "Toroidal triangulations are not yet supported."); + } + return topology_type::SPHERICAL; + } + + using GeneratedPopulation = utilities::Generated_population_bounds; + + [[nodiscard]] inline auto make_generated_population( + Int_precision const simplices, Int_precision const timeslices, + double const initial_radius, double const foliation_spacing) + -> GeneratedPopulation + { + auto const bounds = utilities::generated_population_bounds( + Int_precision{3}, simplices, timeslices, initial_radius, + foliation_spacing); + if (bounds.points_per_timeslice < 2) + { + throw std::invalid_argument( + "Simplices and timeslices would create an empty triangulation; " + "increase the simplices per timeslice."); + } + + auto const first_layer_points = + static_cast(bounds.points_per_timeslice) * + initial_radius; + if (first_layer_points < 2.0L) + { + throw std::invalid_argument( + "Initial radius is too small to populate the first timeslice."); + } + + if (!std::isfinite(bounds.last_layer_points) || + bounds.last_layer_points > + static_cast( + std::numeric_limits::max())) + { + throw std::out_of_range( + "Foliation parameters generate too many points per timeslice."); + } + return bounds; + } + } // namespace detail + + /// Validate raw triangulation options and narrow them into project types. + [[nodiscard]] inline auto make_triangulation( + bool const spherical, bool const toroidal, long long const simplices, + long long const timeslices, long long const dimensions, + double const initial_radius, double const foliation_spacing) + -> Triangulation + { + auto const topology = detail::select_topology(spherical, toroidal); + auto const checked_simplices = + detail::checked_int("Number of simplices", simplices); + auto const checked_timeslices = + detail::checked_int("Number of timeslices", timeslices); + auto const checked_dimensions = + detail::checked_int("Dimensionality", dimensions); + + if (checked_dimensions != 3) + { + throw std::invalid_argument( + "Only three-dimensional triangulations are supported."); + } + if (checked_simplices < 2 || checked_timeslices < 2) + { + throw std::invalid_argument( + "Simplices and timeslices must each be at least 2."); + } + + auto const checked_initial_radius = + detail::checked_finite("Initial radius", initial_radius); + auto const checked_foliation_spacing = + detail::checked_finite("Foliation spacing", foliation_spacing); + if (checked_initial_radius <= 0.0) + { + throw std::invalid_argument("Initial radius must be positive."); + } + if (checked_foliation_spacing <= 0.0) + { + throw std::invalid_argument("Foliation spacing must be positive."); + } + + [[maybe_unused]] auto const population = detail::make_generated_population( + checked_simplices, checked_timeslices, checked_initial_radius, + checked_foliation_spacing); + return Triangulation{ + topology, checked_simplices, checked_timeslices, + checked_dimensions, checked_initial_radius, checked_foliation_spacing}; + } + + /// Validate the complete simulation configuration. + [[nodiscard]] inline auto make_simulation( + Triangulation const& triangulation, long double const alpha, + long double const k, long double const lambda, long long const passes, + long long const checkpoint, bool const write_files) -> Simulation + { + auto const checked_alpha = detail::checked_finite("Alpha", alpha); + auto const checked_k = detail::checked_finite("K", k); + auto const checked_lambda = detail::checked_finite("Lambda", lambda); + if (checked_alpha <= 0.5L) + { + throw std::domain_error("Alpha in 3D must be greater than 1/2."); + } + + auto const checked_passes = detail::checked_int("Passes", passes); + auto const checked_checkpoint = + detail::checked_int("Checkpoint interval", checkpoint); + if (checked_passes <= 0) + { + throw std::invalid_argument("Passes must be positive."); + } + if (checked_checkpoint <= 0) + { + throw std::invalid_argument("Checkpoint interval must be positive."); + } + + return Simulation{triangulation, checked_alpha, checked_k, + checked_lambda, checked_passes, checked_checkpoint, + write_files}; + } +} // namespace runtime_config + +#endif // CDT_PLUSPLUS_RUNTIME_CONFIG_HPP diff --git a/include/S3Action.hpp b/include/S3Action.hpp index 19e465ccc..d5f614349 100644 --- a/include/S3Action.hpp +++ b/include/S3Action.hpp @@ -17,13 +17,52 @@ #ifndef INCLUDE_S3ACTION_HPP_ #define INCLUDE_S3ACTION_HPP_ -#include +#include +#include +#include -#include +#include "Mpfr_value.hpp" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcomment" +namespace s3_action +{ + struct PhysicalParameters + { + long double alpha; + long double k; + long double lambda; + }; + + [[nodiscard]] inline auto make_physical_parameters(long double const alpha, + long double const k, + long double const lambda) + -> PhysicalParameters + { + if (!std::isfinite(alpha) || !std::isfinite(k) || !std::isfinite(lambda)) + { + throw std::invalid_argument("Physical parameters must be finite."); + } + if (alpha <= 0.5L) + { + throw std::domain_error("Alpha in 3D must be greater than 1/2."); + } + return {alpha, k, lambda}; + } + + [[nodiscard]] inline auto make_finite_couplings(long double const k, + long double const lambda) + -> std::pair + { + if (!std::isfinite(k) || !std::isfinite(lambda)) + { + throw std::invalid_argument("Physical parameters must be finite."); + } + return {k, lambda}; + } +} // namespace s3_action + /// @brief Calculates S3 bulk action for \f$\alpha\f$=-1. /// /// This result is i* the action for Euclidean dynamically triangulated @@ -46,82 +85,48 @@ /// value [[nodiscard]] inline auto S3_bulk_action_alpha_minus_one( Int_precision const N1_TL, Int_precision const N3_31_13, - Int_precision const N3_22, long double const K, - long double const Lambda) noexcept -> Gmpzf + Int_precision const N3_22, long double const K, long double const Lambda) + -> Gmpzf { - // Set precision for initialization and assignment functions - mpfr_set_default_prec(PRECISION); - - // Initialize for MPFR - mpfr_t n1_tl; - mpfr_t n3_31; - mpfr_t n3_22; - mpfr_t k; - mpfr_t lambda; - mpfr_t two; - mpfr_t pi; - mpfr_t r1; - mpfr_t r2; - mpfr_t r3; - mpfr_t const2673; - mpfr_t const118; - mpfr_t r4; - mpfr_t r5; - mpfr_t r6; - mpfr_t r7; - mpfr_t const7386; - mpfr_t r8; - mpfr_t r9; - mpfr_t r10; - mpfr_t r11; - mpfr_t r12; - mpfr_t total; - mpfr_inits2(PRECISION, pi, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, - total, nullptr); - - // Set input parameters and constants to mpfr_t equivalents - mpfr_init_set_si(n1_tl, N1_TL, MPFR_RNDD); - mpfr_init_set_si(n3_31, N3_31_13, MPFR_RNDD); - mpfr_init_set_si(n3_22, N3_22, MPFR_RNDD); - mpfr_init_set_ld(k, K, MPFR_RNDD); - mpfr_init_set_ld(lambda, Lambda, MPFR_RNDD); - mpfr_init_set_str(two, "2.0", 10, MPFR_RNDD); - mpfr_const_pi(pi, MPFR_RNDD); - mpfr_init_set_str(const2673, "2.673", 10, MPFR_RNDD); - mpfr_init_set_str(const118, "0.118", 10, MPFR_RNDD); - mpfr_init_set_str(const7386, "7.386", 10, MPFR_RNDD); + auto const [checked_k, checked_lambda] = + s3_action::make_finite_couplings(K, Lambda); + + // Set input parameters and constants to MPFR equivalents + auto const n1_tl = mpfr_values::from_integer(N1_TL); + auto const n3_31 = mpfr_values::from_integer(N3_31_13); + auto const n3_22 = mpfr_values::from_integer(N3_22); + auto const k = mpfr_values::from_long_double(checked_k); + auto const lambda = mpfr_values::from_long_double(checked_lambda); + auto const two = mpfr_values::from_integer(2); + auto const pi = mpfr_values::pi(); + auto const const2673 = mpfr_values::from_decimal("2.673"); + auto const const118 = mpfr_values::from_decimal("0.118"); + auto const const7386 = mpfr_values::from_decimal("7.386"); // First term accumulates in r3 - mpfr_mul(r1, two, pi, MPFR_RNDD); // r1 = 2*pi - mpfr_mul(r2, r1, k, MPFR_RNDD); // r2 = 2*pi*k - mpfr_mul(r3, r2, n1_tl, MPFR_RNDD); // r3 = 2*pi*k*n1_tl + auto const r1 = mpfr_values::multiply(two, pi); // r1 = 2*pi + auto const r2 = mpfr_values::multiply(r1, k); // r2 = 2*pi*k + auto const r3 = mpfr_values::multiply(r2, n1_tl); // r3 = 2*pi*k*n1_tl // Second term accumulates in r7 - mpfr_mul(r4, const2673, k, MPFR_RNDD); // r4 = 2.673*k - mpfr_mul(r5, const118, lambda, MPFR_RNDD); // r5 = 0.118*lambda - mpfr_add(r6, r4, r5, MPFR_RNDD); // r6 = r4 + r5 - mpfr_mul(r7, n3_31, r6, MPFR_RNDD); // r7 = n3_31*r6 + auto const r4 = mpfr_values::multiply(const2673, k); // r4 = 2.673*k + auto const r5 = mpfr_values::multiply(const118, lambda); // r5 = 0.118*lambda + auto const r6 = mpfr_values::add(r4, r5); // r6 = r4 + r5 + auto const r7 = mpfr_values::multiply(n3_31, r6); // r7 = n3_31*r6 // Third term accumulates in r11 - mpfr_mul(r8, const7386, k, MPFR_RNDD); // r8 = 7.386*k - mpfr_mul(r9, const118, lambda, MPFR_RNDD); // r9 = 0.118*lambda - mpfr_add(r10, r8, r9, MPFR_RNDD); // r10 = r8+r9 - mpfr_mul(r11, n3_22, r10, MPFR_RNDD); // r11 = n3_22*r10 + auto const r8 = mpfr_values::multiply(const7386, k); // r8 = 7.386*k + auto const r9 = mpfr_values::multiply(const118, lambda); // r9 = 0.118*lambda + auto const r10 = mpfr_values::add(r8, r9); // r10 = r8+r9 + auto const r11 = mpfr_values::multiply(n3_22, r10); // r11 = n3_22*r10 // Result is r3+r7+r11 - mpfr_sub(r12, r7, r3, MPFR_RNDD); // r12 = r7-r3 - mpfr_add(total, r11, r12, MPFR_RNDD); // total = r11+r12 + auto const r12 = mpfr_values::subtract(r7, r3); // r12 = r7-r3 + auto const total = mpfr_values::add(r11, r12); // total = r11+r12 - // Convert mpfr_t total to Gmpzf result by using Gmpzf(double d) + // Convert MPFR total to Gmpzf result by using Gmpzf(double d) // Perhaps fixable later by switching to MP_Float - auto const result = mpfr_get_d(total, MPFR_RNDD); - - // Free memory - mpfr_clears(n1_tl, n3_31, n3_22, k, lambda, two, pi, r1, r2, r3, const2673, - const118, r4, r5, r6, r7, const7386, r8, r9, r10, r11, r12, total, - nullptr); - - return result; + return Gmpzf{mpfr_values::to_double(total)}; } // S3_bulk_action_alpha_minus_one() /// @brief Calculates S3 bulk action for \f$\alpha\f$=1. @@ -141,86 +146,55 @@ /// @returns \f$S^{(3)}(\alpha=1)\f$ as a /// Gmpzf /// value -[[nodiscard]] inline auto S3_bulk_action_alpha_one( - Int_precision const N1_TL, Int_precision const N3_31_13, - Int_precision const N3_22, long double const K, - long double const Lambda) noexcept -> Gmpzf +[[nodiscard]] inline auto S3_bulk_action_alpha_one(Int_precision const N1_TL, + Int_precision const N3_31_13, + Int_precision const N3_22, + long double const K, + long double const Lambda) + -> Gmpzf { - // Set precision for initialization and assignment functions - mpfr_set_default_prec(PRECISION); - - // Initialize for MPFR - mpfr_t n1_tl; - mpfr_t n3_31; - mpfr_t n3_22; - mpfr_t k; - mpfr_t lambda; - mpfr_t two; - mpfr_t pi; - mpfr_t r1; - mpfr_t r2; - mpfr_t r3; - mpfr_t const3548; - mpfr_t const167; - mpfr_t r4; - mpfr_t r5; - mpfr_t r6; - mpfr_t r7; - mpfr_t const5355; - mpfr_t const204; - mpfr_t r8; - mpfr_t r9; - mpfr_t r10; - mpfr_t r11; - mpfr_t r12; - mpfr_t total; - mpfr_inits2(PRECISION, pi, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, - total, nullptr); - - // Set input parameters and constants to mpfr_t equivalents - mpfr_init_set_si(n1_tl, N1_TL, MPFR_RNDD); - mpfr_init_set_si(n3_31, N3_31_13, MPFR_RNDD); - mpfr_init_set_si(n3_22, N3_22, MPFR_RNDD); - mpfr_init_set_ld(k, K, MPFR_RNDD); - mpfr_init_set_ld(lambda, Lambda, MPFR_RNDD); - mpfr_init_set_str(two, "2.0", 10, MPFR_RNDD); - mpfr_const_pi(pi, MPFR_RNDD); - mpfr_init_set_str(const3548, "-3.548", 10, MPFR_RNDD); - mpfr_init_set_str(const167, "-0.167", 10, MPFR_RNDD); - mpfr_init_set_str(const5355, "-5.355", 10, MPFR_RNDD); - mpfr_init_set_str(const204, "-0.204", 10, MPFR_RNDD); + auto const [checked_k, checked_lambda] = + s3_action::make_finite_couplings(K, Lambda); + + // Set input parameters and constants to MPFR equivalents + auto const n1_tl = mpfr_values::from_integer(N1_TL); + auto const n3_31 = mpfr_values::from_integer(N3_31_13); + auto const n3_22 = mpfr_values::from_integer(N3_22); + auto const k = mpfr_values::from_long_double(checked_k); + auto const lambda = mpfr_values::from_long_double(checked_lambda); + auto const two = mpfr_values::from_integer(2); + auto const pi = mpfr_values::pi(); + auto const const3548 = mpfr_values::from_decimal("-3.548"); + auto const const167 = mpfr_values::from_decimal("-0.167"); + auto const const5355 = mpfr_values::from_decimal("-5.355"); + auto const const204 = mpfr_values::from_decimal("-0.204"); // First term accumulates in r3 - mpfr_mul(r1, two, pi, MPFR_RNDD); // r1 = 2*pi - mpfr_mul(r2, r1, k, MPFR_RNDD); // r2 = 2*pi*k - mpfr_mul(r3, r2, n1_tl, MPFR_RNDD); // r3 = 2*pi*k*n1_tl + auto const r1 = mpfr_values::multiply(two, pi); // r1 = 2*pi + auto const r2 = mpfr_values::multiply(r1, k); // r2 = 2*pi*k + auto const r3 = mpfr_values::multiply(r2, n1_tl); // r3 = 2*pi*k*n1_tl // Second term accumulates in r7 - mpfr_mul(r4, const3548, k, MPFR_RNDD); // r4 = -3.548*k - mpfr_mul(r5, const167, lambda, MPFR_RNDD); // r5 = -0.167*lambda - mpfr_add(r6, r4, r5, MPFR_RNDD); // r6 = r4 + r5 - mpfr_mul(r7, n3_31, r6, MPFR_RNDD); // r7 = n3_31*r6 + auto const r4 = mpfr_values::multiply(const3548, k); // r4 = -3.548*k + auto const r5 = + mpfr_values::multiply(const167, lambda); // r5 = -0.167*lambda + auto const r6 = mpfr_values::add(r4, r5); // r6 = r4 + r5 + auto const r7 = mpfr_values::multiply(n3_31, r6); // r7 = n3_31*r6 // Third term accumulates in r11 - mpfr_mul(r8, const5355, k, MPFR_RNDD); // r8 = -5.355*k - mpfr_mul(r9, const204, lambda, MPFR_RNDD); // r9 = -0.204*lambda - mpfr_add(r10, r8, r9, MPFR_RNDD); // r10 = r8+r9 - mpfr_mul(r11, n3_22, r10, MPFR_RNDD); // r11 = n3_22*r10 + auto const r8 = mpfr_values::multiply(const5355, k); // r8 = -5.355*k + auto const r9 = + mpfr_values::multiply(const204, lambda); // r9 = -0.204*lambda + auto const r10 = mpfr_values::add(r8, r9); // r10 = r8+r9 + auto const r11 = mpfr_values::multiply(n3_22, r10); // r11 = n3_22*r10 // Result is r3+r7+r11 - mpfr_add(r12, r3, r7, MPFR_RNDD); // r12 = r3+r7 - mpfr_add(total, r11, r12, MPFR_RNDD); // total = r11+r12 + auto const r12 = mpfr_values::add(r3, r7); // r12 = r3+r7 + auto const total = mpfr_values::add(r11, r12); // total = r11+r12 - // Convert mpfr_t total to Gmpzf result by using Gmpzf(double d) + // Convert MPFR total to Gmpzf result by using Gmpzf(double d) // Perhaps fixable later by switching to MP_Float - auto const result = mpfr_get_d(total, MPFR_RNDD); - - // Free memory - mpfr_clears(n1_tl, n3_31, n3_22, k, lambda, two, pi, r1, r2, r3, const3548, - const167, r4, r5, r6, r7, const5355, const204, r8, r9, r10, r11, - r12, total, nullptr); - - return result; + return Gmpzf{mpfr_values::to_double(total)}; } // Gmpzf S3_bulk_action_alpha_one() /// @brief Calculates the generalized S3 bulk action in terms of \f$\alpha\f$, @@ -249,186 +223,116 @@ /// @returns \f$S^{(3)}(\alpha)\f$ as a /// Gmpzf /// value -[[nodiscard]] inline auto S3_bulk_action( - Int_precision const N1_TL, Int_precision const N3_31_13, - Int_precision const N3_22, long double const Alpha, long double const K, - long double const Lambda) noexcept -> Gmpzf +[[nodiscard]] inline auto S3_bulk_action(Int_precision const N1_TL, + Int_precision const N3_31_13, + Int_precision const N3_22, + long double const Alpha, + long double const K, + long double const Lambda) -> Gmpzf { - // Set precision for initialization and assignment functions - mpfr_set_default_prec(PRECISION); - - // Initialize for MPFR - mpfr_t n1_tl; - mpfr_t n3_31; - mpfr_t n3_22; - mpfr_t alpha; - mpfr_t k; - mpfr_t lambda; - mpfr_t two; - mpfr_t pi; - mpfr_t r1; - mpfr_t r2; - mpfr_t r3; - mpfr_t r4; - mpfr_t r5; - mpfr_t r6; - mpfr_t three; - mpfr_t r7; - mpfr_t four; - mpfr_t r8; - mpfr_t one; - mpfr_t r9; - mpfr_t r10; - mpfr_t r11; - mpfr_t r12; - mpfr_t r13; - mpfr_t r14; - mpfr_t r15; - mpfr_t r16; - mpfr_t r17; - mpfr_t r18; - mpfr_t r19; - mpfr_t r20; - mpfr_t r21; - mpfr_t twelve; - mpfr_t r22; - mpfr_t r23; - mpfr_t r24; - mpfr_t r25; - mpfr_t r26; - mpfr_t r27; - mpfr_t r28; - mpfr_t r29; - mpfr_t r30; - mpfr_t r31; - mpfr_t r32; - mpfr_t r33; - mpfr_t r34; - mpfr_t r35; - mpfr_t r36; - mpfr_t r37; - mpfr_t r38; - mpfr_t r39; - mpfr_t r40; - mpfr_t r41; - mpfr_t r42; - mpfr_t r43; - mpfr_t r44; - mpfr_t r45; - mpfr_t r46; - mpfr_t r47; - mpfr_t r48; - mpfr_t r49; - mpfr_t r50; - mpfr_t r51; - mpfr_t r52; - mpfr_t total; - mpfr_inits2(PRECISION, pi, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, - r13, r14, r15, r16, r17, r18, r19, r20, r21, r22, r23, r24, r25, - r26, r27, r28, r29, r30, r31, r32, r33, r34, r35, r36, r37, r38, - r39, r40, r41, r42, r43, r44, r45, r46, r47, r48, r49, r50, r51, - r52, total, nullptr); - - // Set input parameters and constants to mpfr_t equivalents - mpfr_init_set_si(n1_tl, N1_TL, MPFR_RNDD); - mpfr_init_set_si(n3_31, N3_31_13, MPFR_RNDD); - mpfr_init_set_si(n3_22, N3_22, MPFR_RNDD); - mpfr_init_set_ld(alpha, Alpha, MPFR_RNDD); - mpfr_init_set_ld(k, K, MPFR_RNDD); - mpfr_init_set_ld(lambda, Lambda, MPFR_RNDD); - mpfr_init_set_str(two, "2.0", 10, MPFR_RNDD); - mpfr_const_pi(pi, MPFR_RNDD); - mpfr_init_set_str(three, "3.0", 10, MPFR_RNDD); - mpfr_init_set_str(four, "4.0", 10, MPFR_RNDD); - mpfr_init_set_str(one, "1.0", 10, MPFR_RNDD); - mpfr_init_set_str(twelve, "12.0", 10, MPFR_RNDD); + auto const parameters = s3_action::make_physical_parameters(Alpha, K, Lambda); + + // Set input parameters and constants to MPFR equivalents + auto const n1_tl = mpfr_values::from_integer(N1_TL); + auto const n3_31 = mpfr_values::from_integer(N3_31_13); + auto const n3_22 = mpfr_values::from_integer(N3_22); + auto const alpha = mpfr_values::from_long_double(parameters.alpha); + auto const k = mpfr_values::from_long_double(parameters.k); + auto const lambda = mpfr_values::from_long_double(parameters.lambda); + auto const two = mpfr_values::from_integer(2); + auto const pi = mpfr_values::pi(); + auto const three = mpfr_values::from_integer(3); + auto const four = mpfr_values::from_integer(4); + auto const one = mpfr_values::from_integer(1); + auto const twelve = mpfr_values::from_integer(12); // First term accumulates in r5 - mpfr_mul(r1, two, pi, MPFR_RNDD); // r1 = 2*pi - mpfr_mul(r2, r1, k, MPFR_RNDD); // r2 = 2*pi*k - mpfr_sqrt(r3, alpha, MPFR_RNDD); // r3 = sqrt(alpha) - mpfr_mul(r4, r3, r2, MPFR_RNDD); // r4 = r3*r2 = 2*pi*k*sqrt(alpha) - mpfr_mul(r5, r4, n1_tl, MPFR_RNDD); // r5 = r4*n1_tl + auto const r1 = mpfr_values::multiply(two, pi); // r1 = 2*pi + auto const r2 = mpfr_values::multiply(r1, k); // r2 = 2*pi*k + auto const r3 = mpfr_values::square_root(alpha); // r3 = sqrt(alpha) + auto const r4 = + mpfr_values::multiply(r3, r2); // r4 = r3*r2 = 2*pi*k*sqrt(alpha) + auto const r5 = mpfr_values::multiply(r4, n1_tl); // r5 = r4*n1_tl // Second term accumulates in r30 - mpfr_sqrt(r6, three, MPFR_RNDD); // r6 = sqrt(3) - mpfr_mul(r7, four, alpha, MPFR_RNDD); // r7 = 4*alpha - mpfr_add(r8, one, r7, MPFR_RNDD); // r8 = r7+1 = 4*alpha+1 - mpfr_sqrt(r9, r8, MPFR_RNDD); // r9 = sqrt(r8) = sqrt(4*alpha+1) - mpfr_mul(r10, r6, r9, MPFR_RNDD); // r10 = r6*r9 - mpfr_div(r11, one, r10, MPFR_RNDD); // r11 = 1/r10 - mpfr_asinh(r12, r11, MPFR_RNDD); // r12 = arcsinh(r11) - mpfr_neg(r13, three, MPFR_RNDD); // r13 = -3 - mpfr_mul(r14, r13, k, MPFR_RNDD); // r14 = r13*k = -3*k - mpfr_mul(r15, r14, r12, MPFR_RNDD); // r15 = r14*r12 = -3*k*arcsinh(r11) - - mpfr_mul(r16, two, alpha, MPFR_RNDD); // r16 = 2*alpha - mpfr_add(r17, r16, one, MPFR_RNDD); // r17 = 2*alpha+1 - mpfr_div(r18, r17, r8, MPFR_RNDD); // r18 = (2*alpha+1)/(4*alpha+1) - mpfr_acos(r19, r18, MPFR_RNDD); // r19 = arccos(r18) - mpfr_mul(r20, r14, r3, MPFR_RNDD); // r20 = -3*k*sqrt(alpha) - mpfr_mul(r21, r20, r19, MPFR_RNDD); // r21 = -3*k*sqrt(alpha)*arccos(r18) - - mpfr_mul(r22, three, alpha, MPFR_RNDD); // r22 = 3*alpha - mpfr_add(r23, r22, one, MPFR_RNDD); // r23 = 3*alpha+1 - mpfr_sqrt(r24, r23, MPFR_RNDD); // r24 = sqrt(3*alpha+1) - mpfr_neg(r25, lambda, MPFR_RNDD); // r25 = -lambda - mpfr_div(r26, r25, twelve, MPFR_RNDD); // r26 = -lambda/12 - mpfr_mul(r27, r26, r24, MPFR_RNDD); // r27 = (-lambda/12)*sqrt(3*alpha+1) + auto const r6 = mpfr_values::square_root(three); // r6 = sqrt(3) + auto const r7 = mpfr_values::multiply(four, alpha); // r7 = 4*alpha + auto const r8 = mpfr_values::add(one, r7); // r8 = r7+1 = 4*alpha+1 + auto const r9 = + mpfr_values::square_root(r8); // r9 = sqrt(r8) = sqrt(4*alpha+1) + auto const r10 = mpfr_values::multiply(r6, r9); // r10 = r6*r9 + auto const r11 = mpfr_values::divide(one, r10); // r11 = 1/r10 + auto const r12 = + mpfr_values::inverse_hyperbolic_sine(r11); // r12 = arcsinh(r11) + auto const r13 = mpfr_values::negate(three); // r13 = -3 + auto const r14 = mpfr_values::multiply(r13, k); // r14 = r13*k = -3*k + // r15 = r14*r12 = -3*k*arcsinh(r11) + auto const r15 = mpfr_values::multiply(r14, r12); + + auto const r16 = mpfr_values::multiply(two, alpha); // r16 = 2*alpha + auto const r17 = mpfr_values::add(r16, one); // r17 = 2*alpha+1 + auto const r18 = + mpfr_values::divide(r17, r8); // r18 = (2*alpha+1)/(4*alpha+1) + auto const r19 = mpfr_values::arc_cosine(r18); // r19 = arccos(r18) + auto const r20 = mpfr_values::multiply(r14, r3); // r20 = -3*k*sqrt(alpha) + auto const r21 = + mpfr_values::multiply(r20, r19); // r21 = -3*k*sqrt(alpha)*arccos(r18) + + auto const r22 = mpfr_values::multiply(three, alpha); // r22 = 3*alpha + auto const r23 = mpfr_values::add(r22, one); // r23 = 3*alpha+1 + auto const r24 = mpfr_values::square_root(r23); // r24 = sqrt(3*alpha+1) + auto const r25 = mpfr_values::negate(lambda); // r25 = -lambda + auto const r26 = mpfr_values::divide(r25, twelve); // r26 = -lambda/12 + auto const r27 = + mpfr_values::multiply(r26, r24); // r27 = (-lambda/12)*sqrt(3*alpha+1) // Accumulate partial sums of second term - mpfr_add(r28, r15, r21, MPFR_RNDD); // r28 = r15+r21 - mpfr_add(r29, r28, r27, MPFR_RNDD); // r29 = r28+r27 + auto const r28 = mpfr_values::add(r15, r21); // r28 = r15+r21 + auto const r29 = mpfr_values::add(r28, r27); // r29 = r28+r27 // Multiply by overall factor of n3_31 - mpfr_mul(r30, n3_31, r29, MPFR_RNDD); // r30 = n3_31*r29 + auto const r30 = mpfr_values::multiply(n3_31, r29); // r30 = n3_31*r29 // Third term accumulates in r51 - mpfr_mul(r31, two, k, MPFR_RNDD); // r31 = 2*k - mpfr_sqrt(r32, two, MPFR_RNDD); // r32 = sqrt(2) - mpfr_mul(r33, two, r32, MPFR_RNDD); // r33 = 2*sqrt(2) - mpfr_sqrt(r34, r17, MPFR_RNDD); // r34 = sqrt(2*alpha+1) - mpfr_mul(r35, r33, r34, MPFR_RNDD); // r35 = r33*r34 - mpfr_div(r36, r35, r8, MPFR_RNDD); // r36 = 2*sqrt(2)*sqrt(2*alpha+1)/ - // 4*alpha+1 - mpfr_asinh(r37, r36, MPFR_RNDD); // r37 = arcsinh(r36) - mpfr_mul(r38, r31, r37, MPFR_RNDD); // r38 = 2*k*arcsinh(r36) - - mpfr_neg(r39, one, MPFR_RNDD); // r39 = -1 - mpfr_div(r40, r39, r8, MPFR_RNDD); // r40 = -1/(4*alpha+1) - mpfr_acos(r41, r40, MPFR_RNDD); // r41 = arccos(r40) - mpfr_neg(r42, four, MPFR_RNDD); // r42 = -4 - mpfr_mul(r43, r42, k, MPFR_RNDD); // r43 = -4*k - mpfr_mul(r44, r43, r3, MPFR_RNDD); // r44 = -4*k*sqrt(alpha) - mpfr_mul(r45, r44, r41, MPFR_RNDD); // r45 = -4*k*sqrt(alpha)*arccos(r40) - - mpfr_add(r46, r7, two, MPFR_RNDD); // r46 = 4*alpha+2 - mpfr_sqrt(r47, r46, MPFR_RNDD); // r47 = sqrt(4*alpha+2) - mpfr_mul(r48, r26, r47, MPFR_RNDD); // r48 = (-lambda/12)*sqrt(4*alpha+2) + auto const r31 = mpfr_values::multiply(two, k); // r31 = 2*k + auto const r32 = mpfr_values::square_root(two); // r32 = sqrt(2) + auto const r33 = mpfr_values::multiply(two, r32); // r33 = 2*sqrt(2) + auto const r34 = mpfr_values::square_root(r17); // r34 = sqrt(2*alpha+1) + auto const r35 = mpfr_values::multiply(r33, r34); // r35 = r33*r34 + auto const r36 = + mpfr_values::divide(r35, r8); // r36 = 2*sqrt(2)*sqrt(2*alpha+1)/ + // 4*alpha+1 + auto const r37 = + mpfr_values::inverse_hyperbolic_sine(r36); // r37 = arcsinh(r36) + auto const r38 = mpfr_values::multiply(r31, r37); // r38 = 2*k*arcsinh(r36) + + auto const r39 = mpfr_values::negate(one); // r39 = -1 + auto const r40 = mpfr_values::divide(r39, r8); // r40 = -1/(4*alpha+1) + auto const r41 = mpfr_values::arc_cosine(r40); // r41 = arccos(r40) + auto const r42 = mpfr_values::negate(four); // r42 = -4 + auto const r43 = mpfr_values::multiply(r42, k); // r43 = -4*k + auto const r44 = mpfr_values::multiply(r43, r3); // r44 = -4*k*sqrt(alpha) + auto const r45 = + mpfr_values::multiply(r44, r41); // r45 = -4*k*sqrt(alpha)*arccos(r40) + + auto const r46 = mpfr_values::add(r7, two); // r46 = 4*alpha+2 + auto const r47 = mpfr_values::square_root(r46); // r47 = sqrt(4*alpha+2) + auto const r48 = + mpfr_values::multiply(r26, r47); // r48 = (-lambda/12)*sqrt(4*alpha+2) // Accumulate partial sums of third term - mpfr_add(r49, r38, r45, MPFR_RNDD); // r49 = r38+r45 - mpfr_add(r50, r49, r48, MPFR_RNDD); // r50 = r49+r48 + auto const r49 = mpfr_values::add(r38, r45); // r49 = r38+r45 + auto const r50 = mpfr_values::add(r49, r48); // r50 = r49+r48 // Multiply by overall factor of n3_22 - mpfr_mul(r51, n3_22, r50, MPFR_RNDD); // r51 = n3_22*r50 + auto const r51 = mpfr_values::multiply(n3_22, r50); // r51 = n3_22*r50 - mpfr_add(r52, r5, r30, MPFR_RNDD); // r52 = r5+r30 - mpfr_add(total, r51, r52, MPFR_RNDD); // total = r51+r52 + auto const r52 = mpfr_values::add(r5, r30); // r52 = r5+r30 + auto const total = mpfr_values::add(r51, r52); // total = r51+r52 - // Convert mpfr_t total to Gmpzf result by using Gmpzf(double d) + // Convert MPFR total to Gmpzf result by using Gmpzf(double d) // Perhaps fixable later by switching to MP_Float - auto const result = mpfr_get_d(total, MPFR_RNDD); - - // Free memory - mpfr_clears(n1_tl, n3_31, n3_22, alpha, k, lambda, two, pi, r1, r2, r3, r4, - r5, r6, three, r7, four, r8, one, r9, r10, r11, r12, r13, r14, - r15, r16, r17, r18, r19, r20, r21, twelve, r22, r23, r24, r25, - r26, r27, r28, r29, r30, r31, r32, r33, r34, r35, r36, r37, r38, - r39, r40, r41, r42, r43, r44, r45, r46, r47, r48, r49, r50, r51, - r52, total, nullptr); - - return result; + return Gmpzf{mpfr_values::to_double(total)}; } // Gmpzf S3_bulk_action() #pragma GCC diagnostic pop diff --git a/include/Utilities.hpp b/include/Utilities.hpp index a5fee511a..c1be346d0 100644 --- a/include/Utilities.hpp +++ b/include/Utilities.hpp @@ -23,6 +23,13 @@ // H. Hinnant date and time library #include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + /// clang-15 does not support std::format // #include @@ -63,6 +70,64 @@ inline auto operator<<(std::ostream& t_os, topology_type const& t_topology) namespace utilities { + namespace detail + { + [[nodiscard]] inline auto write_file_mutex() -> std::mutex& + { + static std::mutex mutex; + return mutex; + } + + [[nodiscard]] inline auto write_file_active() noexcept -> bool& + { + static thread_local bool active{false}; + return active; + } + + class WriteFileOperation final + { + public: + WriteFileOperation() + { + if (write_file_active()) + { + throw std::logic_error("write_file is not reentrant."); + } + write_file_active() = true; + } + + ~WriteFileOperation() noexcept { write_file_active() = false; } + + WriteFileOperation(WriteFileOperation const&) = delete; + auto operator=(WriteFileOperation const&) -> WriteFileOperation& = delete; + WriteFileOperation(WriteFileOperation&&) = delete; + auto operator=(WriteFileOperation&&) -> WriteFileOperation& = delete; + }; + + inline void replace_file(std::filesystem::path const& temporary, + std::filesystem::path const& destination) + { +#ifdef _WIN32 + if (!::MoveFileExW(temporary.c_str(), destination.c_str(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) + { + throw std::filesystem::filesystem_error( + "Could not atomically replace file", temporary, destination, + std::error_code(static_cast(::GetLastError()), + std::system_category())); + } +#else + std::error_code error; + std::filesystem::rename(temporary, destination, error); + if (error) + { + throw std::filesystem::filesystem_error( + "Could not atomically replace file", temporary, destination, error); + } +#endif + } + } // namespace detail + /// @brief Return current date and time /// @details Return current date and time in ISO 8601 format /// Use Howard Hinnant's date library to format UTC without requiring an @@ -92,7 +157,7 @@ namespace utilities Int_precision t_number_of_simplices, Int_precision t_number_of_timeslices, double t_initial_radius, - double t_foliation_spacing) noexcept + double t_foliation_spacing) -> std::filesystem::path { std::string filename; @@ -167,17 +232,51 @@ namespace utilities void write_file(std::filesystem::path const& filename, TriangulationType const& triangulation) { - static std::mutex mutex; + detail::WriteFileOperation const operation; fmt::print("Writing to file {}\n", filename.string()); - std::scoped_lock const lock(mutex); - std::ofstream file(filename, std::ios::out); - if (!file.is_open()) + std::scoped_lock const lock(detail::write_file_mutex()); + auto temporary = filename; + temporary += ".tmp"; + + std::error_code cleanup_error; + std::filesystem::remove(temporary, cleanup_error); + try { - throw std::filesystem::filesystem_error( - "Could not open file for writing", filename, - std::make_error_code(std::errc::bad_file_descriptor)); + std::ofstream file(temporary, std::ios::out | std::ios::trunc); + if (!file.is_open()) + { + throw std::filesystem::filesystem_error( + "Could not open temporary file for writing", filename, + std::make_error_code(std::errc::bad_file_descriptor)); + } + file << triangulation; + if (!file) + { + throw std::filesystem::filesystem_error( + "Could not serialize triangulation", filename, + std::make_error_code(std::errc::io_error)); + } + file.flush(); + if (!file) + { + throw std::filesystem::filesystem_error( + "Could not flush serialized triangulation", filename, + std::make_error_code(std::errc::io_error)); + } + file.close(); + if (!file) + { + throw std::filesystem::filesystem_error( + "Could not close serialized triangulation", filename, + std::make_error_code(std::errc::io_error)); + } + detail::replace_file(temporary, filename); + } + catch (...) + { + std::filesystem::remove(temporary, cleanup_error); + throw; } - file << triangulation; } // write_file /// @brief Write the runtime results to a file @@ -191,7 +290,7 @@ namespace utilities { std::filesystem::path filename; filename.assign(make_filename(t_universe)); - write_file(filename, t_universe.get_delaunay()); + write_file(filename, t_universe.delaunay_snapshot()); } // write_file /// @brief Read triangulation from file @@ -213,6 +312,19 @@ namespace utilities } TriangulationType triangulation; file >> triangulation; + if (!file) + { + throw std::filesystem::filesystem_error( + "Could not parse triangulation", filename, + std::make_error_code(std::errc::illegal_byte_sequence)); + } + file >> std::ws; + if (!file.eof()) + { + throw std::filesystem::filesystem_error( + "Unexpected trailing data after triangulation", filename, + std::make_error_code(std::errc::illegal_byte_sequence)); + } return triangulation; } // read_file @@ -323,41 +435,75 @@ namespace utilities t_number_of_simplices, t_number_of_timeslices); #endif + if (t_dimension != 3) + { + throw std::invalid_argument( + "Only three-dimensional triangulations are supported."); + } + if (t_number_of_simplices <= 0 || t_number_of_timeslices <= 0) + { + throw std::invalid_argument( + "Simplices and timeslices must both be positive."); + } + auto const simplices_per_timeslice = t_number_of_simplices / t_number_of_timeslices; - if (t_dimension == 3) + // Avoid segfaults for small values + if (t_number_of_simplices == t_number_of_timeslices) + { + return 2 * simplices_per_timeslice; + } + if (t_number_of_simplices < 1000) // NOLINT + { + return static_cast( + 0.4L * // NOLINT + static_cast(simplices_per_timeslice)); + } + if (t_number_of_simplices < 10000) // NOLINT { - // Avoid segfaults for small values - if (t_number_of_simplices == t_number_of_timeslices) - { - return 2 * simplices_per_timeslice; - } - if (t_number_of_simplices < 1000) // NOLINT - { - return static_cast( - 0.4L * // NOLINT - static_cast(simplices_per_timeslice)); - } - if (t_number_of_simplices < 10000) // NOLINT - { - return static_cast( - 0.2L * // NOLINT - static_cast(simplices_per_timeslice)); - } - if (t_number_of_simplices < 100000) // NOLINT - { - return static_cast( - 0.15L * // NOLINT - static_cast(simplices_per_timeslice)); - } - return static_cast( - 0.1L * static_cast(simplices_per_timeslice)); // NOLINT + 0.2L * // NOLINT + static_cast(simplices_per_timeslice)); } - throw std::invalid_argument("Currently, dimensions cannot be >3."); + if (t_number_of_simplices < 100000) // NOLINT + { + return static_cast( + 0.15L * // NOLINT + static_cast(simplices_per_timeslice)); + } + + return static_cast( + 0.1L * static_cast(simplices_per_timeslice)); // NOLINT } // expected_points_per_timeslice + struct Generated_population_bounds + { + Int_precision points_per_timeslice; + long double last_layer_points; + }; + + /// @brief Calculate the generated point count and its upper bound + /// @param dimension Number of dimensions + /// @param simplices Number of desired simplices + /// @param timeslices Number of desired timeslices + /// @param initial_radius Radius of the first timeslice + /// @param foliation_spacing Distance between successive timeslices + /// @return Points per timeslice and the last-layer point count + [[nodiscard]] inline auto generated_population_bounds( + Int_precision const dimension, Int_precision const simplices, + Int_precision const timeslices, double const initial_radius, + double const foliation_spacing) -> Generated_population_bounds + { + auto const points_per_timeslice = + expected_points_per_timeslice(dimension, simplices, timeslices); + auto const last_radius = + static_cast(initial_radius) + + static_cast(timeslices - 1) * foliation_spacing; + return {points_per_timeslice, + static_cast(points_per_timeslice) * last_radius}; + } + /// @brief Convert Gmpzf into a double /// /// This function is mainly for testing, since to_double() diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ce9a8f65f..c3de3d100 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -28,6 +28,16 @@ target_compile_features(cdt PRIVATE cxx_std_23) # Tests ## # +function(add_cli_failure_test test_name target expected_regex) + add_test( + NAME ${test_name} + COMMAND + ${CMAKE_COMMAND} "-DTEST_EXECUTABLE=$" + "-DTEST_ARGUMENTS=${ARGN}" "-DEXPECTED_REGEX=${expected_regex}" + -P ${PROJECT_SOURCE_DIR}/cmake/ExpectCommandFailure.cmake) + set_tests_properties(${test_name} PROPERTIES LABELS "cli-boundary") +endfunction() + add_test(NAME cdt COMMAND $ -s -n127 -t4 -a0.6 -k1.1 -l0.1 -p10) set_tests_properties(cdt PROPERTIES PASS_REGULAR_EXPRESSION "Writing to file S3-[0-9]+-") @@ -38,14 +48,25 @@ add_test( -DTEST_DIRECTORY=${CMAKE_CURRENT_BINARY_DIR}/cdt-no-output -P ${PROJECT_SOURCE_DIR}/cmake/RunCdtNoOutputTest.cmake) -add_test(NAME cdt-triangle-inequalities COMMAND $ -s -n64 -t3 -a0.4 -k1.1 -l0.1) -set_tests_properties(cdt-triangle-inequalities PROPERTIES PASS_REGULAR_EXPRESSION "Triangle inequalities violated") - -add_test(NAME cdt-dimensionality COMMAND $ -s -n64 -t3 -d4 -a0.4 -k1.1 -l0.1) -set_tests_properties(cdt-dimensionality PROPERTIES PASS_REGULAR_EXPRESSION "Currently, dimensions cannot be >3.") - -add_test(NAME cdt-toroidal COMMAND $ -e -n64 -t3 -a0.6 -k1.1 -l0.1) -set_tests_properties(cdt-toroidal PROPERTIES PASS_REGULAR_EXPRESSION "Toroidal triangulations not yet supported.") +add_cli_failure_test(cdt-triangle-inequalities cdt "Triangle inequalities violated" -s -n64 -t3 -a0.4 + -k1.1 -l0.1) +add_cli_failure_test(cdt-dimensionality cdt "Only three-dimensional triangulations are supported." -s -n64 -t3 + -d4 -a0.4 -k1.1 -l0.1) +add_cli_failure_test(cdt-toroidal cdt "Toroidal triangulations are not yet supported." -e -n64 -t3 -a0.6 -k1.1 + -l0.1) +add_cli_failure_test(cdt-alpha-negative cdt "Alpha in 3D must be greater than 1/2." -s -n64 -t3 -a-0.6 -k1.1 + -l0.1) +add_cli_failure_test(cdt-alpha-boundary cdt "Alpha in 3D must be greater than 1/2." -s -n64 -t3 -a0.5 -k1.1 + -l0.1) +add_cli_failure_test(cdt-alpha-nonfinite cdt "Alpha must be finite." -s -n64 -t3 -anan -k1.1 -l0.1) +add_cli_failure_test(cdt-passes-zero cdt "Passes must be positive." -s -n64 -t3 -a0.6 -k1.1 -l0.1 -p0) +add_cli_failure_test(cdt-checkpoint-zero cdt "Checkpoint interval must be positive." -s -n64 -t3 -a0.6 -k1.1 + -l0.1 -c0) +add_cli_failure_test(cdt-radius-zero cdt "Initial radius must be positive." -s -n64 -t3 -a0.6 -k1.1 -l0.1 -i0) +add_cli_failure_test(cdt-spacing-zero cdt "Foliation spacing must be positive." -s -n64 -t3 -a0.6 -k1.1 -l0.1 -f0) +add_cli_failure_test(cdt-empty-population cdt "would create an empty triangulation" -s -n3 -t2 -a0.6 -k1.1 -l0.1) +add_cli_failure_test(cdt-integer-narrowing cdt "exceeds the supported integer range" -s -n2147483648 -t3 -a0.6 + -k1.1 -l0.1) add_test(NAME initialize COMMAND $ -s -n640 -t4 -o) set_tests_properties(initialize PROPERTIES PASS_REGULAR_EXPRESSION "Writing to file S3-4") @@ -54,14 +75,10 @@ if(WIN32) set_tests_properties(initialize PROPERTIES LABELS "reference-smoke-exclude") endif() -add_test(NAME initialize-minimum-simplices COMMAND $ -s -n1 -t1 -o) -set_tests_properties(initialize-minimum-simplices - PROPERTIES PASS_REGULAR_EXPRESSION "Simplices and timeslices should be greater or equal to 2.") - -add_test(NAME initialize-dimensionality COMMAND $ -s -n64 -t3 -d2 -o) -set_tests_properties(initialize-dimensionality - PROPERTIES PASS_REGULAR_EXPRESSION "Only three-dimensional triangulations are supported.") - -add_test(NAME initialize-toroidal COMMAND $ -e -n64 -t3 -o) -set_tests_properties(initialize-toroidal PROPERTIES PASS_REGULAR_EXPRESSION - "Toroidal triangulations not yet supported.") +add_cli_failure_test(initialize-minimum-simplices initialize "Simplices and timeslices must each be at least 2." -s -n1 + -t1 -o) +add_cli_failure_test(initialize-dimensionality initialize "Only three-dimensional triangulations are supported." -s + -n64 -t3 -d2 -o) +add_cli_failure_test(initialize-toroidal initialize "Toroidal triangulations are not yet supported." -e -n64 -t3 -o) +add_cli_failure_test(initialize-integer-narrowing initialize "exceeds the supported integer range" -s -n2147483648 -t3) +add_cli_failure_test(initialize-spacing-zero initialize "Foliation spacing must be positive." -s -n64 -t3 -f0) diff --git a/src/cdt.cpp b/src/cdt.cpp index 39db7c472..3ac1b7df6 100644 --- a/src/cdt.cpp +++ b/src/cdt.cpp @@ -16,6 +16,8 @@ #include #include +#include "Runtime_config.hpp" + using Timer = CGAL::Real_timer; using namespace std; @@ -61,17 +63,16 @@ try { std::string const intro{USAGE}; // Parsed arguments - topology_type topology; - long long simplices; - long long timeslices; - long long dimensions; - double initial_radius; - double foliation_spacing; - long double alpha; - long double k; - long double lambda; - long long passes; - long long checkpoint; + long long simplices{}; + long long timeslices{}; + long long dimensions{}; + double initial_radius{}; + double foliation_spacing{}; + long double alpha{}; + long double k{}; + long double lambda{}; + long long passes{}; + long long checkpoint{}; po::options_description description(intro); description.add_options()("help,h", "Show this message")( @@ -114,118 +115,58 @@ try } po::notify(args); - auto const write_files = !args.count("no-output"); - - if (args.count("spherical")) { topology = topology_type::SPHERICAL; } - else if (args.count("toroidal")) { topology = topology_type::TOROIDAL; } - else - { - fmt::print("Topology not specified.\n"); - return EXIT_FAILURE; - } - - if (args.count("simplices")) + if (!args.count("simplices")) { - simplices = args["simplices"].as(); + throw invalid_argument("Number of simplices not specified."); } - else + if (!args.count("timeslices")) { - fmt::print("Number of simplices not specified.\n"); - return EXIT_FAILURE; + throw invalid_argument("Number of timeslices not specified."); } - if (args.count("timeslices")) - { - timeslices = args["timeslices"].as(); - } - else - { - fmt::print("Number of timeslices not specified.\n"); - return EXIT_FAILURE; - } + auto const triangulation_config = runtime_config::make_triangulation( + args.count("spherical") != 0, args.count("toroidal") != 0, simplices, + timeslices, dimensions, initial_radius, foliation_spacing); + auto const config = runtime_config::make_simulation( + triangulation_config, alpha, k, lambda, passes, checkpoint, + !args.count("no-output")); // Display job parameters - fmt::print("Topology is {}\n", utilities::topology_to_str(topology)); - fmt::print("Dimensionality: {}+{}\n", dimensions - 1, 1); - fmt::print("Initial radius: {}\n", initial_radius); - fmt::print("Foliation spacing: {}\n", foliation_spacing); - fmt::print("Number of desired simplices: {}\n", simplices); - fmt::print("Number of desired timeslices: {}\n", timeslices); - fmt::print("Number of passes: {}\n", passes); - fmt::print("Checkpoint every {} passes.\n", checkpoint); + fmt::print("Topology is {}\n", + utilities::topology_to_str(config.triangulation().topology())); + fmt::print("Dimensionality: {}+{}\n", config.triangulation().dimensions() - 1, + 1); + fmt::print("Initial radius: {}\n", config.triangulation().initial_radius()); + fmt::print("Foliation spacing: {}\n", + config.triangulation().foliation_spacing()); + fmt::print("Number of desired simplices: {}\n", + config.triangulation().simplices()); + fmt::print("Number of desired timeslices: {}\n", + config.triangulation().timeslices()); + fmt::print("Number of passes: {}\n", config.passes()); + fmt::print("Checkpoint every {} passes.\n", config.checkpoint()); fmt::print("=== Parameters ===\n"); - fmt::print("Alpha: {}\n", alpha); - fmt::print("K: {}\n", k); - fmt::print("Lambda: {}\n", lambda); + fmt::print("Alpha: {}\n", config.alpha()); + fmt::print("K: {}\n", config.k()); + fmt::print("Lambda: {}\n", config.lambda()); // Start running time Timer timer; timer.start(); fmt::print("cdt started at {}\n", utilities::current_date_time()); - if (simplices < 2 || timeslices < 2) - { - timer.stop(); - throw invalid_argument( - "Simplices and timeslices should be greater or equal to 2."); - } - - if (passes < 0) - { - timer.stop(); - throw invalid_argument("Passes cannot be negative."); - } - if (checkpoint <= 0) - { - timer.stop(); - throw invalid_argument("Checkpoint interval must be positive."); - } - if (!std::in_range(simplices) || - !std::in_range(timeslices) || - !std::in_range(passes) || - !std::in_range(checkpoint)) - { - timer.stop(); - throw out_of_range("Integer argument exceeds the supported range."); - } - - // Ensure Triangle inequalities hold - // See http://arxiv.org/abs/hep-th/0105267 for details - if (dimensions == 3 && abs(alpha) < static_cast(0.5)) // NOLINT - { - timer.stop(); // End running time counter - throw domain_error("Alpha in 3D should be greater than 1/2."); - } - // Initialize the Metropolis algorithm - Metropolis_3 run(alpha, k, lambda, static_cast(passes), - static_cast(checkpoint), write_files); + Metropolis_3 run(config.alpha(), config.k(), config.lambda(), config.passes(), + config.checkpoint(), config.write_files()); // Make a triangulation manifolds::Manifold_3 universe; - switch (topology) - { - case topology_type::SPHERICAL: - if (dimensions == 3) - { - manifolds::Manifold_3 populated_universe( - static_cast(simplices), - static_cast(timeslices), initial_radius, - foliation_spacing); - // Manifold no-throw swapperator - swap(populated_universe, universe); - } - else - { - timer.stop(); // End running time counter - throw invalid_argument("Currently, dimensions cannot be >3."); - } - break; - case topology_type::TOROIDAL: - timer.stop(); // End running time counter - throw invalid_argument("Toroidal triangulations not yet supported."); - } + manifolds::Manifold_3 populated_universe( + config.triangulation().simplices(), config.triangulation().timeslices(), + config.triangulation().initial_radius(), + config.triangulation().foliation_spacing()); + swap(populated_universe, universe); // Look at triangulation universe.print(); @@ -236,10 +177,11 @@ try auto const result = run(universe); // Do we have enough timeslices? - if (auto max_timevalue = result.max_time(); max_timevalue < timeslices) + if (auto max_timevalue = result.max_time(); + max_timevalue < config.triangulation().timeslices()) { - fmt::print("You wanted {} timeslices, but only got {}.\n", timeslices, - max_timevalue); + fmt::print("You wanted {} timeslices, but only got {}.\n", + config.triangulation().timeslices(), max_timevalue); } if (!result.is_valid()) { throw runtime_error("Result is invalid!\n"); } @@ -253,7 +195,7 @@ try result.print_volume_per_timeslice(); // Write results to file - if (write_files) { utilities::write_file(result); } + if (config.write_files()) { utilities::write_file(result); } return EXIT_SUCCESS; } diff --git a/src/initialize.cpp b/src/initialize.cpp index f82eee387..3a6c4181b 100644 --- a/src/initialize.cpp +++ b/src/initialize.cpp @@ -11,6 +11,7 @@ #include #include "Manifold.hpp" +#include "Runtime_config.hpp" using namespace std; namespace po = boost::program_options; @@ -44,13 +45,11 @@ try { std::string const intro{USAGE}; // Parsed arguments - topology_type topology; - long long simplices; - long long timeslices; - long long dimensions; - double initial_radius; - double foliation_spacing; - bool save_file; + long long simplices{}; + long long timeslices{}; + long long dimensions{}; + double initial_radius{}; + double foliation_spacing{}; po::options_description description(intro); description.add_options()("help,h", "Show this message")( @@ -69,7 +68,6 @@ try po::variables_map args; po::store(po::parse_command_line(argc, argv, description), args); - po::notify(args); if (args.count("help")) { @@ -83,80 +81,35 @@ try return EXIT_SUCCESS; } - if (args.count("spherical")) { topology = topology_type::SPHERICAL; } - else if (args.count("toroidal")) { topology = topology_type::TOROIDAL; } - else - { - fmt::print("Topology not specified.\n"); - return EXIT_FAILURE; - } - - if (args.count("simplices")) - { - simplices = args["simplices"].as(); - } - else - { - fmt::print("Number of simplices not specified.\n"); - return EXIT_FAILURE; - } + po::notify(args); - if (args.count("timeslices")) - { - timeslices = args["timeslices"].as(); - } - else + if (!args.count("simplices")) { - fmt::print("Number of timeslices not specified.\n"); - return EXIT_FAILURE; + throw invalid_argument("Number of simplices not specified."); } - - if (args.count("output")) { save_file = true; } - else + if (!args.count("timeslices")) { - save_file = false; + throw invalid_argument("Number of timeslices not specified."); } - // Initialize triangulation - manifolds::Manifold_3 universe; + auto const config = runtime_config::make_triangulation( + args.count("spherical") != 0, args.count("toroidal") != 0, simplices, + timeslices, dimensions, initial_radius, foliation_spacing); + auto const save_file = args.count("output") != 0; // Display job parameters - fmt::print("Topology is {}\n", utilities::topology_to_str(topology)); - fmt::print("Number of dimensions = {}\n", dimensions); - fmt::print("Number of desired simplices = {}\n", simplices); - fmt::print("Number of desired timeslices = {}\n", timeslices); - fmt::print("Initial radius = {}\n", initial_radius); - fmt::print("Foliation spacing = {}\n", foliation_spacing); + fmt::print("Topology is {}\n", utilities::topology_to_str(config.topology())); + fmt::print("Number of dimensions = {}\n", config.dimensions()); + fmt::print("Number of desired simplices = {}\n", config.simplices()); + fmt::print("Number of desired timeslices = {}\n", config.timeslices()); + fmt::print("Initial radius = {}\n", config.initial_radius()); + fmt::print("Foliation spacing = {}\n", config.foliation_spacing()); if (save_file) { fmt::print("Output will be saved.\n"); } - if (simplices < 2 || timeslices < 2) - { - throw invalid_argument( - "Simplices and timeslices should be greater or equal to 2."); - } - - switch (topology) - { - case topology_type::SPHERICAL: - if (dimensions == 3) - { - // Start your run - manifolds::Manifold_3 populated_universe( - static_cast(simplices), - static_cast(timeslices), initial_radius, - foliation_spacing); - swap(populated_universe, universe); - } - else - { - throw invalid_argument( - "Only three-dimensional triangulations are supported."); - } - break; - case topology_type::TOROIDAL: - throw invalid_argument("Toroidal triangulations not yet supported."); - } + manifolds::Manifold_3 universe(config.simplices(), config.timeslices(), + config.initial_radius(), + config.foliation_spacing()); universe.print(); universe.print_volume_per_timeslice(); fmt::print("Final number of simplices: {}\n", universe.N3()); @@ -169,6 +122,11 @@ catch (invalid_argument const& InvalidArgument) spdlog::critical("Invalid parameter ... Exiting.\n"); return EXIT_FAILURE; } +catch (std::exception const& Exception) +{ + spdlog::critical("{}\n", Exception.what()); + return EXIT_FAILURE; +} catch (...) { spdlog::critical("Something went wrong ... Exiting.\n"); diff --git a/tests/Apply_move_test.cpp b/tests/Apply_move_test.cpp index fe8694ac6..aeaf09c43 100644 --- a/tests/Apply_move_test.cpp +++ b/tests/Apply_move_test.cpp @@ -34,8 +34,6 @@ SCENARIO("Apply an ergodic move to 2+1 manifolds" * if (auto result = apply_move(manifold, ergodic_moves::null_move); result) { manifold = result.value(); - // Update Geometry and Foliated_triangulation with new info - manifold.update(); } else { @@ -62,8 +60,6 @@ SCENARIO("Apply an ergodic move to 2+1 manifolds" * if (auto result = apply_move(manifold, ergodic_moves::do_23_move); result) { manifold = result.value(); - // Update Geometry and Foliated_triangulation with new info - manifold.update(); } else { @@ -87,8 +83,6 @@ SCENARIO("Apply an ergodic move to 2+1 manifolds" * if (auto result = apply_move(manifold, ergodic_moves::do_32_move); result) { manifold = result.value(); - // Update Geometry and Foliated_triangulation with new info - manifold.update(); } else { @@ -113,8 +107,6 @@ SCENARIO("Apply an ergodic move to 2+1 manifolds" * if (auto result = apply_move(manifold, ergodic_moves::do_26_move); result) { manifold = result.value(); - // Update Geometry and Foliated_triangulation with new info - manifold.update(); } else { @@ -140,8 +132,6 @@ SCENARIO("Apply an ergodic move to 2+1 manifolds" * if (result) { manifold = result.value(); - // Update Geometry and Foliated_triangulation with new info - manifold.update(); THEN("The resulting manifold has the applied move.") { CHECK(ergodic_moves::check_move(manifold_before, manifold, @@ -171,8 +161,6 @@ SCENARIO("Apply an ergodic move to 2+1 manifolds" * if (result) { manifold = result.value(); - // Update Geometry and Foliated_triangulation with new info - manifold.update(); THEN("The resulting manifold has the applied move.") { CHECK(ergodic_moves::check_move(manifold_before, manifold, diff --git a/tests/Bistellar_flip_test.cpp b/tests/Bistellar_flip_test.cpp index 78bd1c2c0..4a5e0fa76 100644 --- a/tests/Bistellar_flip_test.cpp +++ b/tests/Bistellar_flip_test.cpp @@ -113,10 +113,12 @@ SCENARIO("Perform basic bistellar flip on Delaunay triangulation" * AND_THEN("We can perform a bistellar flip") { - auto flipped_triangulation = + auto const original = triangulation; + auto flipped_triangulation = bistellar_flip(triangulation, pivot_edge.value(), top, bottom); REQUIRE_MESSAGE(flipped_triangulation, "Bistellar flip failed."); + CHECK_EQ(triangulation, original); // Basic validity check CHECK(flipped_triangulation->is_valid()); @@ -268,7 +270,10 @@ SCENARIO("Test edge cases and error conditions for bistellar flip" * auto result = bistellar_flip(triangulation, invalid_edge, top, bottom); THEN("The bistellar flip should fail") - { CHECK_FALSE(result.has_value()); } + { + CHECK_FALSE(result.has_value()); + CHECK(triangulation.is_valid()); + } } WHEN("We provide invalid edge indices") diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2b0d8a6e9..795c65266 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -12,6 +12,7 @@ add_executable( Move_always_test.cpp Move_command_test.cpp Move_tracker_test.cpp + Runtime_config_test.cpp S3Action_test.cpp Settings_test.cpp Tetrahedron_test.cpp diff --git a/tests/Ergodic_moves_3_test.cpp b/tests/Ergodic_moves_3_test.cpp index d185612f7..80f7c6663 100644 --- a/tests/Ergodic_moves_3_test.cpp +++ b/tests/Ergodic_moves_3_test.cpp @@ -48,8 +48,6 @@ SCENARIO("Use check_move to validate successful move" * if (auto result = ergodic_moves::do_23_move(manifold); result) { manifold = result.value(); - // Update geometry with new triangulation - manifold.update(); } else { @@ -113,8 +111,6 @@ SCENARIO( if (auto result = ergodic_moves::do_23_move(manifold); result) { manifold = result.value(); - // Update geometry with new triangulation info - manifold.update(); } else { @@ -149,8 +145,6 @@ SCENARIO( if (auto start = ergodic_moves::do_23_move(manifold); start) { manifold = start.value(); - // Update geometry with new triangulation info - manifold.update(); } else { @@ -176,8 +170,6 @@ SCENARIO( if (auto result = ergodic_moves::do_32_move(manifold); result) { manifold = result.value(); - // Update geometry with new triangulation info - manifold.update(); } else { @@ -247,59 +239,59 @@ SCENARIO( REQUIRE_EQ(manifold.N1_SL(), 3); REQUIRE_EQ(manifold.N1_TL(), 6); REQUIRE(manifold.is_delaunay()); - WHEN("A (2,6) move is performed") + WHEN("A (2,6) move is proposed") { - spdlog::debug("When a (2,6) move is performed.\n"); - // Copy manifold - auto manifold_before = manifold; - // Do move and check results - if (auto result = ergodic_moves::do_26_move(manifold); result) - { - manifold = result.value(); - // Update geometry with new triangulation info - manifold.update(); - } - else + spdlog::debug("When a (2,6) move is proposed.\n"); + auto const manifold_before = manifold; + auto result = ergodic_moves::do_26_move(manifold); + if (!result) { spdlog::debug("The (2,6) move failed.\n"); } + REQUIRE(result.has_value()); + + THEN("The proposal leaves the source manifold unchanged") { - spdlog::debug("The (2,6) move failed.\n"); - // Stop further tests - REQUIRE(result.has_value()); + CHECK_EQ(manifold.delaunay_snapshot(), + manifold_before.delaunay_snapshot()); + CHECK_EQ(manifold.N3(), manifold_before.N3()); } - THEN("The move is correct and the manifold invariants are maintained") + AND_WHEN("The proposed value is accepted") { - CHECK(ergodic_moves::check_move(manifold_before, manifold, - move_tracker::move_type::TWO_SIX)); - // Manual check - REQUIRE(manifold.is_correct()); - CHECK_EQ(manifold.vertices(), 6); // +1 vertex - CHECK_EQ(manifold.edges(), 14); // +3 spacelike and +2 timelike edges - CHECK_EQ(manifold.faces(), 15); // +8 faces - CHECK_EQ(manifold.simplices(), 6); // +2 (3,1) and +2 (1,3) simplices - CHECK_EQ(manifold.N3_31(), 3); - CHECK_EQ(manifold.N3_22(), 0); - CHECK_EQ(manifold.N3_13(), 3); - CHECK_EQ(manifold.N3_31_13(), 6); - CHECK_EQ(manifold.N1_SL(), 6); // +3 spacelike edges - CHECK_EQ(manifold.N1_TL(), 8); // +2 timelike edges - CHECK(manifold.is_delaunay()); - // Human-readable output - fmt::print("Manifold before (2,6):\n"); - manifold_before.print_details(); - manifold_before.print_cells(); - fmt::print("Manifold after (2,6):\n"); - manifold.print_details(); - manifold.print_cells(); + manifold = std::move(result).value(); + THEN("The move is correct and the manifold invariants are maintained") + { + CHECK(ergodic_moves::check_move(manifold_before, manifold, + move_tracker::move_type::TWO_SIX)); + // Manual check + REQUIRE(manifold.is_correct()); + CHECK_EQ(manifold.vertices(), 6); // +1 vertex + CHECK_EQ(manifold.edges(), + 14); // +3 spacelike and +2 timelike edges + CHECK_EQ(manifold.faces(), 15); // +8 faces + CHECK_EQ(manifold.simplices(), + 6); // +2 (3,1) and +2 (1,3) simplices + CHECK_EQ(manifold.N3_31(), 3); + CHECK_EQ(manifold.N3_22(), 0); + CHECK_EQ(manifold.N3_13(), 3); + CHECK_EQ(manifold.N3_31_13(), 6); + CHECK_EQ(manifold.N1_SL(), 6); // +3 spacelike edges + CHECK_EQ(manifold.N1_TL(), 8); // +2 timelike edges + CHECK(manifold.is_delaunay()); + // Human-readable output + fmt::print("Manifold before (2,6):\n"); + manifold_before.print_details(); + manifold_before.print_cells(); + fmt::print("Manifold after (2,6):\n"); + manifold.print_details(); + manifold.print_cells(); + } } } - WHEN("A (6,2) move is performed") + WHEN("A (6,2) move is proposed") { - spdlog::debug("When a (6,2) move is performed.\n"); + spdlog::debug("When a (6,2) move is proposed.\n"); // First, do a (2,6) move to set up the manifold if (auto start = ergodic_moves::do_26_move(manifold); start) { manifold = start.value(); - // Update geometry with new triangulation info - manifold.update(); } else { @@ -323,44 +315,49 @@ SCENARIO( REQUIRE(manifold.is_delaunay()); // Copy manifold - auto manifold_before = manifold; - // Do move and check results - if (auto result = ergodic_moves::do_62_move(manifold); result) - { - manifold.update(); - } - else + auto const manifold_before = manifold; + auto result = ergodic_moves::do_62_move(manifold); + if (!result) { spdlog::info("The (6,2) move failed.\n"); } + REQUIRE(result.has_value()); + + THEN("The proposal leaves the source manifold unchanged") { - spdlog::info("The (6,2) move failed.\n"); + CHECK_EQ(manifold.delaunay_snapshot(), + manifold_before.delaunay_snapshot()); + CHECK_EQ(manifold.N3(), manifold_before.N3()); } - THEN("The move is correct and the manifold invariants are maintained") + AND_WHEN("The proposed value is accepted") { - // Check the move - CHECK(ergodic_moves::check_move(manifold_before, manifold, - move_tracker::move_type::SIX_TWO)); - // Manual check - REQUIRE(manifold.is_correct()); - CHECK(manifold.get_triangulation().is_foliated()); - CHECK(manifold.get_triangulation().is_tds_valid()); - CHECK(manifold.get_triangulation().check_all_cells()); - CHECK_EQ(manifold.vertices(), 5); - CHECK_EQ(manifold.edges(), 9); - CHECK_EQ(manifold.faces(), 7); - CHECK_EQ(manifold.simplices(), 2); - CHECK_EQ(manifold.N3_31(), 1); - CHECK_EQ(manifold.N3_22(), 0); - CHECK_EQ(manifold.N3_13(), 1); - CHECK_EQ(manifold.N3_31_13(), 2); - CHECK_EQ(manifold.N1_SL(), 3); - CHECK_EQ(manifold.N1_TL(), 6); - CHECK(manifold.is_delaunay()); - // Human-readable output - fmt::print("Manifold before (6,2):\n"); - manifold_before.print_details(); - manifold_before.print_cells(); - fmt::print("Manifold after (6,2):\n"); - manifold.print_details(); - manifold.print_cells(); + manifold = std::move(result).value(); + THEN("The move is correct and the manifold invariants are maintained") + { + // Check the move + CHECK(ergodic_moves::check_move(manifold_before, manifold, + move_tracker::move_type::SIX_TWO)); + // Manual check + REQUIRE(manifold.is_correct()); + CHECK(manifold.is_foliated()); + CHECK(manifold.is_valid()); + CHECK(manifold.check_simplices()); + CHECK_EQ(manifold.vertices(), 5); + CHECK_EQ(manifold.edges(), 9); + CHECK_EQ(manifold.faces(), 7); + CHECK_EQ(manifold.simplices(), 2); + CHECK_EQ(manifold.N3_31(), 1); + CHECK_EQ(manifold.N3_22(), 0); + CHECK_EQ(manifold.N3_13(), 1); + CHECK_EQ(manifold.N3_31_13(), 2); + CHECK_EQ(manifold.N1_SL(), 3); + CHECK_EQ(manifold.N1_TL(), 6); + CHECK(manifold.is_delaunay()); + // Human-readable output + fmt::print("Manifold before (6,2):\n"); + manifold_before.print_details(); + manifold_before.print_cells(); + fmt::print("Manifold after (6,2):\n"); + manifold.print_details(); + manifold.print_cells(); + } } } WHEN("An improperly prepared (6,2) move is performed") @@ -408,36 +405,40 @@ SCENARIO("Perform ergodic moves on the minimal manifold necessary (4,4) moves" * REQUIRE(manifold.is_delaunay()); REQUIRE(manifold.is_correct()); - WHEN("A (4,4) move is performed") + WHEN("A (4,4) move is proposed") { - spdlog::debug("When a (4,4) move is performed.\n"); - // Copy manifold - auto manifold_before = manifold; + spdlog::debug("When a (4,4) move is proposed.\n"); + auto const manifold_before = manifold; // Human verification fmt::print("Manifold before (4,4):\n"); manifold_before.print_details(); manifold_before.print_cells(); - // Do move and check results - if (auto result = ergodic_moves::do_44_move(manifold); result) - { - manifold = std::move(result).value(); - manifold.update(); - } - else + auto result = ergodic_moves::do_44_move(manifold); + if (!result) { spdlog::info("The (4,4) move failed.\n"); } + REQUIRE(result.has_value()); + + THEN("The proposal leaves the source manifold unchanged") { - spdlog::info("The (4,4) move failed.\n"); + CHECK_EQ(manifold.delaunay_snapshot(), + manifold_before.delaunay_snapshot()); + CHECK_EQ(manifold.N3(), manifold_before.N3()); } - fmt::print("Manifold after (4,4):\n"); - manifold.print_details(); - manifold.print_cells(); - THEN("The move is correct and the manifold invariants are maintained") + AND_WHEN("The proposed value is accepted") { - // Check the move - CHECK(ergodic_moves::check_move(manifold_before, manifold, - move_tracker::move_type::FOUR_FOUR)); - CHECK_EQ(manifold.initial_radius(), manifold_before.initial_radius()); - CHECK_EQ(manifold.foliation_spacing(), - manifold_before.foliation_spacing()); + manifold = std::move(result).value(); + fmt::print("Manifold after (4,4):\n"); + manifold.print_details(); + manifold.print_cells(); + + THEN("The move is correct and the manifold invariants are maintained") + { + // Check the move + CHECK(ergodic_moves::check_move(manifold_before, manifold, + move_tracker::move_type::FOUR_FOUR)); + CHECK_EQ(manifold.initial_radius(), manifold_before.initial_radius()); + CHECK_EQ(manifold.foliation_spacing(), + manifold_before.foliation_spacing()); + } } } } @@ -523,6 +524,45 @@ SCENARIO("Test convenience functions needed for bistellar flip" * } } +SCENARIO("Rejected topology moves preserve the source value" * + doctest::test_suite("ergodic")) +{ + GIVEN("An empty manifold and an independent snapshot of its state") + { + Manifold_3 const source; + auto const before = source; + + WHEN("A (2,6) move is proposed") + { + auto const result = ergodic_moves::do_26_move(source); + + THEN("The move is rejected without changing the source") + { + CHECK_FALSE(result.has_value()); + CHECK_EQ(source.delaunay_snapshot(), before.delaunay_snapshot()); + CHECK_EQ(source.N3(), before.N3()); + CHECK_EQ(source.N2(), before.N2()); + CHECK_EQ(source.N1(), before.N1()); + CHECK_EQ(source.N0(), before.N0()); + } + } + WHEN("A (4,4) move is proposed") + { + auto const result = ergodic_moves::do_44_move(source); + + THEN("The move is rejected without changing the source") + { + CHECK_FALSE(result.has_value()); + CHECK_EQ(source.delaunay_snapshot(), before.delaunay_snapshot()); + CHECK_EQ(source.N3(), before.N3()); + CHECK_EQ(source.N2(), before.N2()); + CHECK_EQ(source.N1(), before.N1()); + CHECK_EQ(source.N0(), before.N0()); + } + } + } +} + SCENARIO("Perform bistellar flip on Delaunay triangulation" * doctest::test_suite("ergodic")) { diff --git a/tests/Foliated_triangulation_test.cpp b/tests/Foliated_triangulation_test.cpp index 0d20bbb99..191e249b8 100644 --- a/tests/Foliated_triangulation_test.cpp +++ b/tests/Foliated_triangulation_test.cpp @@ -14,10 +14,16 @@ #include #include +#include +#include using namespace std; using namespace foliated_triangulations; +static_assert(std::is_nothrow_swappable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); + static inline auto constexpr RADIUS_2 = 2.0 * std::numbers::inv_sqrt3_v; static inline std::floating_point auto constexpr SQRT_2 = std::numbers::sqrt2_v; @@ -55,26 +61,14 @@ SCENARIO("FoliatedTriangulation special member and swap properties" * CHECK_FALSE( is_nothrow_default_constructible_v); } - THEN("It is no-throw copy constructible.") - { - REQUIRE(is_nothrow_copy_constructible_v); - spdlog::debug("It is no-throw copy constructible.\n"); - } - THEN("It is no-throw copy assignable.") - { - REQUIRE(is_nothrow_copy_assignable_v); - spdlog::debug("It is no-throw copy assignable.\n"); - } + THEN("Copy construction may report a cache rebuild failure.") + { CHECK_FALSE(is_nothrow_copy_constructible_v); } + THEN("Copy assignment may report a cache rebuild failure.") + { CHECK_FALSE(is_nothrow_copy_assignable_v); } THEN("It is no-throw move constructible.") - { - REQUIRE(is_nothrow_move_constructible_v); - spdlog::debug("It is no-throw move constructible.\n"); - } + { REQUIRE(is_nothrow_move_constructible_v); } THEN("It is no-throw move assignable.") - { - REQUIRE(is_nothrow_move_assignable_v); - spdlog::debug("It is no-throw move assignable.\n"); - } + { REQUIRE(is_nothrow_move_assignable_v); } THEN("It is no-throw swappable.") { REQUIRE(is_nothrow_swappable_v); @@ -171,30 +165,28 @@ SCENARIO("FoliatedTriangulation free functions" * vector timevalues{1, 1, 1, 2}; auto vertices = make_causal_vertices<3>(Vertices, timevalues); FoliatedTriangulation_3 triangulation(vertices); - auto print = [&triangulation](auto& vertex) { + auto snapshot = triangulation.delaunay_snapshot(); + auto all_vertices = collect_vertices<3>(snapshot); + auto all_cells = collect_cells<3>(snapshot); + auto print = [&snapshot](auto& vertex) { fmt::print( "Vertex: ({}) Timevalue: {} is a vertex: {} and is " "infinite: {}\n", utilities::point_to_str(vertex->point()), vertex->info(), - triangulation.get_delaunay().tds().is_vertex(vertex), - triangulation.is_infinite(vertex)); + snapshot.tds().is_vertex(vertex), snapshot.is_infinite(vertex)); }; REQUIRE(triangulation.is_initialized()); WHEN("check_vertices() is called.") { THEN("The vertices are correct.") - { - CHECK(foliated_triangulations::check_vertices<3>( - triangulation.get_delaunay(), 1.0, 1.0)); - } + { CHECK(foliated_triangulations::check_vertices<3>(snapshot, 1.0, 1.0)); } } WHEN("check_cells() is called.") { THEN("Cells are correctly classified.") { - CHECK(foliated_triangulations::check_cells<3>( - triangulation.get_delaunay())); + CHECK(foliated_triangulations::check_cells<3>(snapshot)); // Human verification triangulation.print_cells(); } @@ -203,20 +195,17 @@ SCENARIO("FoliatedTriangulation free functions" * WHEN("We print a cell in the triangulation.") { THEN("A cell is printed correctly.") - { - foliated_triangulations::print_cell<3>(triangulation.get_cells().at(0)); - } + { foliated_triangulations::print_cell<3>(all_cells.at(0)); } } WHEN("We ask for a container of vertices given a container of cells.") { - auto&& all_vertices = - get_vertices_from_cells<3>(triangulation.get_cells()); + auto vertices_from_cells = get_vertices_from_cells<3>(all_cells); THEN("We get back the correct number of vertices.") { - REQUIRE_EQ(all_vertices.size(), 4); + REQUIRE_EQ(vertices_from_cells.size(), 4); // Human verification - ranges::for_each(all_vertices, print); + ranges::for_each(vertices_from_cells, print); } } } @@ -245,8 +234,8 @@ SCENARIO("FoliatedTriangulation free functions" * } THEN("Each vertex has a valid timevalue.") { - for (std::span const checked_vertices(triangulation.get_vertices()); - auto const& vertex : checked_vertices) + auto snapshot = triangulation.delaunay_snapshot(); + for (auto const& vertex : collect_vertices<3>(snapshot)) { CHECK(triangulation.does_vertex_radius_match_timevalue(vertex)); fmt::print( @@ -272,6 +261,8 @@ SCENARIO("FoliatedTriangulation free functions" * vector timevalue{1, 2, 2, 2, 2, 3}; auto causal_vertices = make_causal_vertices<3>(vertices, timevalue); FoliatedTriangulation_3 const triangulation(causal_vertices, 0, 1); + auto snapshot = triangulation.delaunay_snapshot(); + auto all_cells = collect_cells<3>(snapshot); // Verify we have 6 vertices, 13 edges, 12 facets, and 4 cells REQUIRE_EQ(triangulation.number_of_vertices(), 6); REQUIRE_EQ(triangulation.number_of_finite_edges(), 13); @@ -283,8 +274,7 @@ SCENARIO("FoliatedTriangulation free functions" * REQUIRE(triangulation.is_correct()); WHEN("We collect edges.") { - auto edges = foliated_triangulations::collect_edges<3>( - triangulation.get_delaunay()); + auto edges = foliated_triangulations::collect_edges<3>(snapshot); THEN("We have 13 edges.") { REQUIRE_EQ(edges.size(), 13); } } WHEN("We have a point in the triangulation.") @@ -292,7 +282,7 @@ SCENARIO("FoliatedTriangulation free functions" * THEN("We can obtain the vertex") { auto vertex = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), Point_t<3>{0, 0, 0}); + snapshot, Point_t<3>{0, 0, 0}); REQUIRE_MESSAGE(vertex, "Vertex not found."); if (vertex) { @@ -310,7 +300,7 @@ SCENARIO("FoliatedTriangulation free functions" * THEN("No vertex is found.") { auto vertex = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), Point_t<3>{3, 3, 3}); + snapshot, Point_t<3>{3, 3, 3}); REQUIRE_FALSE(vertex); // Human verification fmt::print("Point(3,3,3) was not found.\n"); @@ -321,16 +311,13 @@ SCENARIO("FoliatedTriangulation free functions" * THEN("The correct vertices yields the correct cell.") { auto v_1 = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), Point_t<3>{0, 0, 0}); + snapshot, Point_t<3>{0, 0, 0}); auto v_2 = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), - Point_t<3>{0, INV_SQRT_2, INV_SQRT_2}); + snapshot, Point_t<3>{0, INV_SQRT_2, INV_SQRT_2}); auto v_3 = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), - Point_t<3>{0, -INV_SQRT_2, INV_SQRT_2}); + snapshot, Point_t<3>{0, -INV_SQRT_2, INV_SQRT_2}); auto v_4 = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), - Point_t<3>{-INV_SQRT_2, 0, INV_SQRT_2}); + snapshot, Point_t<3>{-INV_SQRT_2, 0, INV_SQRT_2}); REQUIRE_MESSAGE(v_1, "Vertex v_1 not found."); REQUIRE_MESSAGE(v_2, "Vertex v_2 not found."); REQUIRE_MESSAGE(v_3, "Vertex v_3 not found."); @@ -338,8 +325,7 @@ SCENARIO("FoliatedTriangulation free functions" * if (v_1 && v_2 && v_3 && v_4) { auto cell = foliated_triangulations::find_cell<3>( - triangulation.get_delaunay(), v_1.value(), v_2.value(), - v_3.value(), v_4.value()); + snapshot, v_1.value(), v_2.value(), v_3.value(), v_4.value()); CHECK(cell); // Human verification triangulation.print_cells(); @@ -348,15 +334,13 @@ SCENARIO("FoliatedTriangulation free functions" * THEN("The incorrect vertices do not return a cell.") { auto v_1 = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), Point_t<3>{0, 0, 0}); + snapshot, Point_t<3>{0, 0, 0}); auto v_2 = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), - Point_t<3>{INV_SQRT_2, 0, INV_SQRT_2}); + snapshot, Point_t<3>{INV_SQRT_2, 0, INV_SQRT_2}); auto v_3 = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), - Point_t<3>{0, INV_SQRT_2, INV_SQRT_2}); + snapshot, Point_t<3>{0, INV_SQRT_2, INV_SQRT_2}); auto v_4 = foliated_triangulations::find_vertex<3>( - triangulation.get_delaunay(), Point_t<3>{0, 0, 2}); + snapshot, Point_t<3>{0, 0, 2}); REQUIRE_MESSAGE(v_1, "Vertex v_1 not found."); REQUIRE_MESSAGE(v_2, "Vertex v_2 not found."); REQUIRE_MESSAGE(v_3, "Vertex v_3 not found."); @@ -364,8 +348,7 @@ SCENARIO("FoliatedTriangulation free functions" * if (v_1 && v_2 && v_3 && v_4) { auto cell = foliated_triangulations::find_cell<3>( - triangulation.get_delaunay(), v_1.value(), v_2.value(), - v_3.value(), v_4.value()); + snapshot, v_1.value(), v_2.value(), v_3.value(), v_4.value()); REQUIRE_FALSE(cell); } } @@ -374,11 +357,11 @@ SCENARIO("FoliatedTriangulation free functions" * WHEN("A container of cells is printed.") { THEN("The container is printed correctly.") - { foliated_triangulations::print_cells<3>(triangulation.get_cells()); } + { foliated_triangulations::print_cells<3>(all_cells); } } WHEN("We choose a cell in the triangulation.") { - auto cell = triangulation.get_cells().at(0); + auto cell = all_cells.at(0); THEN("We can print it's neighbors.") { foliated_triangulations::print_cell<3>(cell); @@ -460,10 +443,12 @@ SCENARIO("FoliatedTriangulation_3 initialization" * } THEN("The vertices have correct timevalues.") { + auto snapshot = triangulation.delaunay_snapshot(); + auto snapshot_vertices = collect_vertices<3>(snapshot); auto check = [&triangulation](Vertex_handle_t<3> const& vertex) { CHECK(triangulation.does_vertex_radius_match_timevalue(vertex)); }; - ranges::for_each(triangulation.get_vertices(), check); + ranges::for_each(snapshot_vertices, check); // Human verification auto print = [&triangulation](Vertex_handle_t<3> const& vertex) { fmt::print( @@ -475,7 +460,7 @@ SCENARIO("FoliatedTriangulation_3 initialization" * std::pow(triangulation.expected_radius(vertex), 2), triangulation.expected_timevalue(vertex)); }; - ranges::for_each(triangulation.get_vertices(), print); + ranges::for_each(snapshot_vertices, print); } } WHEN( @@ -532,27 +517,31 @@ SCENARIO("FoliatedTriangulation_3 initialization" * { triangulation.print(); // Every cell is classified as (3,1), (2,2), or (1,3) - CHECK_EQ(triangulation.get_cells().size(), - triangulation.get_three_one().size() + - triangulation.get_two_two().size() + - triangulation.get_one_three().size()); + CHECK_EQ(triangulation.number_of_finite_cells(), + triangulation.number_of_three_one_cells() + + triangulation.number_of_two_two_cells() + + triangulation.number_of_one_three_cells()); // Every cell is properly labelled CHECK(triangulation.check_all_cells()); - CHECK_FALSE(triangulation.N2_SL().empty()); + CHECK_GT(triangulation.number_of_spacelike_faces(), 0); CHECK_GT(triangulation.max_time(), 0); CHECK_GT(triangulation.min_time(), 0); CHECK_GT(triangulation.max_time(), triangulation.min_time()); - auto check_timelike = [](Edge_handle_t<3> const& edge) { + auto snapshot = triangulation.delaunay_snapshot(); + auto edges = collect_edges<3>(snapshot); + auto timelike_edges = filter_edges<3>(edges, true); + auto spacelike_edges = filter_edges<3>(edges, false); + auto check_timelike = [](Edge_handle_t<3> const& edge) { CHECK(classify_edge<3>(edge)); }; - ranges::for_each(triangulation.get_timelike_edges(), check_timelike); + ranges::for_each(timelike_edges, check_timelike); auto check_spacelike = [](Edge_handle_t<3> const& edge) { CHECK(!classify_edge<3>(edge)); }; - ranges::for_each(triangulation.get_spacelike_edges(), check_spacelike); + ranges::for_each(spacelike_edges, check_spacelike); // Human verification fmt::print("There are {} edges.\n", triangulation.number_of_finite_edges()); @@ -594,13 +583,72 @@ SCENARIO("FoliatedTriangulation_3 copying" * CHECK_EQ(triangulation.number_of_finite_cells(), ft2.number_of_finite_cells()); CHECK_EQ(triangulation.min_time(), ft2.min_time()); - CHECK_EQ(triangulation.get_cells().size(), ft2.get_cells().size()); - CHECK_EQ(triangulation.get_three_one().size(), - ft2.get_three_one().size()); - CHECK_EQ(triangulation.get_two_two().size(), ft2.get_two_two().size()); - CHECK_EQ(triangulation.get_one_three().size(), - ft2.get_one_three().size()); - CHECK_EQ(triangulation.N2_SL().size(), ft2.N2_SL().size()); + CHECK_EQ(triangulation.number_of_three_one_cells(), + ft2.number_of_three_one_cells()); + CHECK_EQ(triangulation.number_of_two_two_cells(), + ft2.number_of_two_two_cells()); + CHECK_EQ(triangulation.number_of_one_three_cells(), + ft2.number_of_one_three_cells()); + CHECK_EQ(triangulation.number_of_spacelike_faces(), + ft2.number_of_spacelike_faces()); + } + } + } +} + +SCENARIO("FoliatedTriangulation_3 moving" * + doctest::test_suite("foliated_triangulation")) +{ + GIVEN("A foliated triangulation with known simplex classifications.") + { + auto constexpr desired_simplices = 64; + auto constexpr desired_timeslices = 4; + FoliatedTriangulation_3 source(desired_simplices, desired_timeslices); + auto const expected_cells = source.number_of_finite_cells(); + auto const expected_vertices = source.number_of_vertices(); + auto const expected_three_one = source.number_of_three_one_cells(); + auto const expected_two_two = source.number_of_two_two_cells(); + auto const expected_one_three = source.number_of_one_three_cells(); + auto const expected_spacelike_faces = source.number_of_spacelike_faces(); + + WHEN("It is move constructed.") + { + auto moved = FoliatedTriangulation_3{std::move(source)}; + + THEN("The destination preserves its triangulation and classifications.") + { + CHECK(moved.is_initialized()); + CHECK_EQ(moved.number_of_finite_cells(), expected_cells); + CHECK_EQ(moved.number_of_vertices(), expected_vertices); + CHECK_EQ(moved.number_of_three_one_cells(), expected_three_one); + CHECK_EQ(moved.number_of_two_two_cells(), expected_two_two); + CHECK_EQ(moved.number_of_one_three_cells(), expected_one_three); + CHECK_EQ(moved.number_of_spacelike_faces(), expected_spacelike_faces); + } + } + WHEN("It is move assigned over another foliated triangulation.") + { + FoliatedTriangulation_3 assigned(desired_simplices * 2, + desired_timeslices); + auto const replaced_cells = assigned.number_of_finite_cells(); + assigned = std::move(source); + + THEN("The destination preserves the source triangulation and caches.") + { + CHECK(assigned.is_initialized()); + CHECK_EQ(assigned.number_of_finite_cells(), expected_cells); + CHECK_EQ(assigned.number_of_finite_cells(), + assigned.number_of_three_one_cells() + + assigned.number_of_two_two_cells() + + assigned.number_of_one_three_cells()); + } + AND_THEN("The source owns the replaced value and remains reusable.") + { + CHECK(source.is_initialized()); + CHECK_EQ(source.number_of_finite_cells(), replaced_cells); + + source = FoliatedTriangulation_3{desired_simplices, desired_timeslices}; + CHECK(source.is_initialized()); } } } @@ -631,67 +679,65 @@ SCENARIO("Detecting and fixing problems with vertices and cells" * } THEN("No errors in the simplex are detected.") { + auto snapshot = triangulation.delaunay_snapshot(); CHECK(triangulation.is_correct()); - CHECK_FALSE(check_timevalues<3>(triangulation.get_delaunay())); + CHECK_FALSE(check_timevalues<3>(snapshot)); // Human verification triangulation.print_cells(); } THEN("No errors in the triangulation foliation are detected") { - CHECK_FALSE(foliated_triangulations::fix_timevalues<3>( - triangulation.delaunay())); + auto candidate = triangulation.delaunay_snapshot(); + CHECK_FALSE(foliated_triangulations::fix_timevalues<3>(candidate)); // Human verification - utilities::print_delaunay(triangulation.get_delaunay()); + utilities::print_delaunay(candidate); } - AND_WHEN("The vertices are mis-labelled.") + AND_WHEN("Vertices in an owning snapshot are mis-labelled.") { + auto candidate = triangulation.delaunay_snapshot(); auto break_vertices = [](Vertex_handle_t<3> const& vertex) { vertex->info() = 0; }; - ranges::for_each(triangulation.get_vertices(), break_vertices); + ranges::for_each(collect_vertices<3>(candidate), break_vertices); - THEN("The incorrect vertex labelling is identified.") + THEN("The source remains valid while the snapshot records the change.") { - CHECK_FALSE(triangulation.check_all_vertices()); - auto bad_vertices = triangulation.find_incorrect_vertices(); + CHECK(triangulation.check_all_vertices()); + auto bad_vertices = find_incorrect_vertices<3>(candidate, 1.0, 1.0); CHECK_FALSE(bad_vertices.empty()); - // Human verification - fmt::print("=== Wrong vertex info! ===\n"); - triangulation.print_vertices(); } - AND_THEN("The incorrect vertex labelling is fixed.") + AND_WHEN("The changed snapshot is published as a replacement value.") { - CHECK_FALSE(triangulation.check_all_vertices()); - auto bad_vertices = triangulation.find_incorrect_vertices(); - CHECK_FALSE(bad_vertices.empty()); + auto replacement = FoliatedTriangulation_3{std::move(candidate)}; - CHECK(triangulation.fix_vertices()); - CHECK(triangulation.check_all_vertices()); - fmt::print("=== Corrected vertex info ===\n"); - triangulation.print_vertices(); + THEN("Construction synchronizes the replacement without mutation.") + { + CHECK(replacement.is_initialized()); + CHECK(triangulation.is_initialized()); + } } } - AND_WHEN("The cells are mis-labelled.") + AND_WHEN("Cells in an owning snapshot are mis-labelled.") { + auto candidate = triangulation.delaunay_snapshot(); auto break_cells = [](Cell_handle_t<3> const& cell) { cell->info() = 0; }; - ranges::for_each(triangulation.get_cells(), break_cells); - THEN("The incorrect cell labelling is identified.") + ranges::for_each(collect_cells<3>(candidate), break_cells); + THEN("The source remains valid while the snapshot records the change.") { - CHECK_FALSE(triangulation.check_all_cells()); - // Human verification - fmt::print("=== Wrong cell info! ===\n"); - triangulation.print_cells(); + CHECK(triangulation.check_all_cells()); + CHECK_FALSE(check_cells<3>(candidate)); } - THEN("The incorrect cell labelling is fixed.") + AND_WHEN("The changed snapshot is published as a replacement value.") { - CHECK_FALSE(triangulation.check_all_cells()); - CHECK(triangulation.fix_cells()); - // Human verification - fmt::print("=== Corrected cell info ===\n"); - triangulation.print_cells(); - CHECK(triangulation.check_all_cells()); + auto replacement = FoliatedTriangulation_3{std::move(candidate)}; + + THEN("Construction synchronizes the replacement without mutation.") + { + CHECK(replacement.is_initialized()); + CHECK(triangulation.is_initialized()); + } } } } @@ -707,7 +753,7 @@ SCENARIO("Detecting and fixing problems with vertices and cells" * }; vector timevalues{1, 1, 1, std::numeric_limits::max()}; auto causal_vertices = make_causal_vertices<3>(vertices, timevalues); - FoliatedTriangulation_3 const triangulation(causal_vertices); + FoliatedTriangulation_3 triangulation(causal_vertices); THEN("The vertex is fixed on construction.") { CHECK_FALSE(triangulation.fix_vertices()); @@ -725,7 +771,7 @@ SCENARIO("Detecting and fixing problems with vertices and cells" * }; vector timevalues{0, 2, 2, 2}; auto causal_vertices = make_causal_vertices<3>(vertices, timevalues); - FoliatedTriangulation_3 const triangulation(causal_vertices); + FoliatedTriangulation_3 triangulation(causal_vertices); THEN("The vertex is fixed on construction.") { CHECK_FALSE(triangulation.fix_vertices()); @@ -745,7 +791,7 @@ SCENARIO("Detecting and fixing problems with vertices and cells" * }; vector timevalues{0, 0, 2, 2}; auto causal_vertices = make_causal_vertices<3>(vertices, timevalues); - FoliatedTriangulation_3 const triangulation(causal_vertices); + FoliatedTriangulation_3 triangulation(causal_vertices); THEN("The vertices are fixed on construction.") { CHECK_FALSE(triangulation.fix_vertices()); @@ -775,7 +821,8 @@ SCENARIO("Detecting and fixing problems with vertices and cells" * THEN("The vertex error is detected.") { CHECK_FALSE(triangulation.is_initialized()); - auto cell = triangulation.get_delaunay().finite_cells_begin(); + auto snapshot = triangulation.delaunay_snapshot(); + auto cell = snapshot.finite_cells_begin(); CHECK_EQ(expected_cell_type<3>(cell), Cell_type::ACAUSAL); // Human verification triangulation.print_cells(); @@ -826,11 +873,13 @@ SCENARIO("Detecting and fixing problems with vertices and cells" * { fmt::print("Unfixed triangulation:\n"); triangulation.print_cells(); - CHECK(foliated_triangulations::fix_timevalues<3>( - triangulation.delaunay())); + auto candidate = triangulation.delaunay_snapshot(); + CHECK(foliated_triangulations::fix_timevalues<3>(candidate)); + triangulation = FoliatedTriangulation_3{std::move(candidate)}; CHECK(triangulation.is_initialized()); fmt::print("Fixed triangulation:\n"); - print_cells<3>(collect_cells<3>(triangulation.delaunay())); + auto snapshot = triangulation.delaunay_snapshot(); + print_cells<3>(collect_cells<3>(snapshot)); } } } @@ -887,7 +936,7 @@ SCENARIO("FoliatedTriangulation_3 functions from Delaunay3" * triangulation.dimension()); // Human verification #ifndef NDEBUG - utilities::print_delaunay(triangulation.delaunay()); + utilities::print_delaunay(triangulation.delaunay_snapshot()); #endif } } @@ -897,11 +946,12 @@ SCENARIO("FoliatedTriangulation_3 functions from Delaunay3" * REQUIRE(triangulation.is_initialized()); THEN("is_infinite() identifies a single infinite vertex.") { - auto&& vertices = triangulation.get_delaunay().tds().vertices(); + auto snapshot = triangulation.delaunay_snapshot(); + auto&& vertices = snapshot.tds().vertices(); auto&& vertex = vertices.begin(); CHECK_EQ(vertices.size(), 1); - CHECK(triangulation.get_delaunay().tds().is_vertex(vertex)); - CHECK(triangulation.is_infinite(vertex)); + CHECK(snapshot.tds().is_vertex(vertex)); + CHECK(snapshot.is_infinite(vertex)); } } WHEN("Constructing a triangulation with 4 causal vertices.") @@ -918,10 +968,11 @@ SCENARIO("FoliatedTriangulation_3 functions from Delaunay3" * REQUIRE(triangulation.is_initialized()); THEN("The degree of each vertex is 4 (including infinite vertex).") { - auto check = [&triangulation](Vertex_handle_t<3> const& vertex) { - CHECK_EQ(triangulation.degree(vertex), 4); + auto snapshot = triangulation.delaunay_snapshot(); + auto check = [&snapshot](Vertex_handle_t<3> const& vertex) { + CHECK_EQ(snapshot.degree(vertex), 4); }; - ranges::for_each(triangulation.get_vertices(), check); + ranges::for_each(collect_vertices<3>(snapshot), check); } } } diff --git a/tests/Function_ref_test.cpp b/tests/Function_ref_test.cpp index 414a4bd58..69b79bad8 100644 --- a/tests/Function_ref_test.cpp +++ b/tests/Function_ref_test.cpp @@ -70,14 +70,13 @@ SCENARIO("Complex lambda operations" * doctest::test_suite("function_ref")) REQUIRE(manifold.is_correct()); WHEN("A lambda is constructed for a move.") { - auto const move23 = [](Manifold_3& m) { // NOLINT + auto const move23 = [](Manifold_3 const& m) { return ergodic_moves::do_23_move(m).value(); }; THEN("Running the lambda makes the move.") { auto const manifold_before = manifold; auto result = move23(manifold); - result.update(); CHECK(ergodic_moves::check_move(manifold_before, result, move_tracker::move_type::TWO_THREE)); // Human verification @@ -106,13 +105,13 @@ SCENARIO("Function_ref operations" * doctest::test_suite("function_ref")) auto manifold = make_23_move_manifold(); REQUIRE(manifold.is_correct()); boost::compat::function_ref const complex_ref(ergodic_moves::do_23_move); + ergodic_moves::Manifold const&)> const + complex_ref(ergodic_moves::do_23_move); WHEN("The function_ref is invoked.") { auto const manifold_before = manifold; auto result = complex_ref(manifold); REQUIRE(result.has_value()); - result->update(); THEN("The move from the function_ref is correct.") { CHECK(ergodic_moves::check_move(manifold_before, result.value(), @@ -129,16 +128,15 @@ SCENARIO("Function_ref operations" * doctest::test_suite("function_ref")) { auto manifold = make_23_move_manifold(); REQUIRE(manifold.is_correct()); - auto const move23 = [](Manifold_3& t_manifold) { + auto const move23 = [](Manifold_3 const& t_manifold) { return ergodic_moves::do_23_move(t_manifold).value(); }; - boost::compat::function_ref const complex_ref( - move23); + boost::compat::function_ref const + complex_ref(move23); WHEN("The function_ref is invoked.") { auto const manifold_before = manifold; auto result = complex_ref(manifold); - result.update(); THEN( "The move stored in the lambda invoked by the function_ref is " "correct.") diff --git a/tests/Geometry_test.cpp b/tests/Geometry_test.cpp index be9508243..8b5dac466 100644 --- a/tests/Geometry_test.cpp +++ b/tests/Geometry_test.cpp @@ -12,9 +12,13 @@ #include +#include + using namespace std; using namespace foliated_triangulations; +static_assert(std::is_nothrow_swappable_v); + SCENARIO("Geometry special member and swap properties" * doctest::test_suite("geometry")) { @@ -84,13 +88,15 @@ SCENARIO("3-Geometry classification" * doctest::test_suite("geometry")) CHECK_GT(geometry.N3, 2); CHECK_EQ(geometry.N3, static_cast( triangulation.number_of_finite_cells())); - CHECK_EQ(geometry.N3_31, static_cast( - triangulation.get_three_one().size())); - CHECK_EQ(geometry.N3_13, static_cast( - triangulation.get_one_three().size())); + CHECK_EQ(geometry.N3_31, + static_cast( + triangulation.number_of_three_one_cells())); + CHECK_EQ(geometry.N3_13, + static_cast( + triangulation.number_of_one_three_cells())); CHECK_EQ(geometry.N3_31 + geometry.N3_22 + geometry.N3_13, geometry.N3); CHECK_EQ(geometry.N3_22, static_cast( - triangulation.get_two_two().size())); + triangulation.number_of_two_two_cells())); CHECK_EQ(geometry.N2, static_cast( triangulation.number_of_finite_facets())); CHECK_EQ(geometry.N1, static_cast( @@ -153,13 +159,15 @@ SCENARIO("3-Geometry initialization" * doctest::test_suite("geometry")) { CHECK_EQ(geometry.N3, static_cast( triangulation.number_of_finite_cells())); - CHECK_EQ(geometry.N3_31, static_cast( - triangulation.get_three_one().size())); - CHECK_EQ(geometry.N3_13, static_cast( - triangulation.get_one_three().size())); + CHECK_EQ(geometry.N3_31, + static_cast( + triangulation.number_of_three_one_cells())); + CHECK_EQ(geometry.N3_13, + static_cast( + triangulation.number_of_one_three_cells())); CHECK_EQ(geometry.N3_31 + geometry.N3_22 + geometry.N3_13, geometry.N3); CHECK_EQ(geometry.N3_22, static_cast( - triangulation.get_two_two().size())); + triangulation.number_of_two_two_cells())); CHECK_EQ(geometry.N2, static_cast( triangulation.number_of_finite_facets())); CHECK_EQ(geometry.N1, static_cast( diff --git a/tests/Manifold_test.cpp b/tests/Manifold_test.cpp index dc437a8a5..82505547a 100644 --- a/tests/Manifold_test.cpp +++ b/tests/Manifold_test.cpp @@ -13,10 +13,16 @@ #include #include +#include +#include using namespace std; using namespace manifolds; +static_assert(std::is_nothrow_swappable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); + static inline auto constexpr RADIUS_2 = 2.0 * std::numbers::inv_sqrt3_v; SCENARIO("Manifold special member and swap properties" * @@ -41,26 +47,14 @@ SCENARIO("Manifold special member and swap properties" * { CHECK_FALSE(is_trivially_constructible_v); } THEN("It is NOT trivially default constructible.") { CHECK_FALSE(is_trivially_default_constructible_v); } - THEN("It is no-throw copy constructible.") - { - REQUIRE(is_nothrow_copy_constructible_v); - spdlog::debug("It is no-throw copy constructible.\n"); - } - THEN("It is no-throw copy assignable.") - { - REQUIRE(is_nothrow_copy_assignable_v); - spdlog::debug("It is no-throw copy assignable.\n"); - } + THEN("Copy construction may report a rebuild failure.") + { CHECK_FALSE(is_nothrow_copy_constructible_v); } + THEN("Copy assignment may report a rebuild failure.") + { CHECK_FALSE(is_nothrow_copy_assignable_v); } THEN("It is no-throw move constructible.") - { - REQUIRE(is_nothrow_move_constructible_v); - spdlog::debug("It is no-throw move constructible.\n"); - } + { REQUIRE(is_nothrow_move_constructible_v); } THEN("It is no-throw move assignable.") - { - REQUIRE(is_nothrow_move_assignable_v); - spdlog::debug("It is no-throw move assignable.\n"); - } + { REQUIRE(is_nothrow_move_assignable_v); } THEN("It is no-throw swappable.") { REQUIRE(is_nothrow_swappable_v); @@ -176,24 +170,31 @@ SCENARIO("Manifold free functions" * doctest::test_suite("manifold")) } THEN("We can obtain the vertices from the points.") { - Vertex_handle_t<3> const v_1 = manifold.get_vertex(p_1); - CHECK(v_1->is_valid()); - cout << "v_1 contains point " << v_1->point() << '\n'; - /// @todo Why is this false? - // CHECK(manifold.get_delaunay().is_vertex(v_1)); + auto snapshot = manifold.delaunay_snapshot(); + auto v_1 = foliated_triangulations::find_vertex<3>(snapshot, p_1); + REQUIRE(v_1); + CHECK(v_1.value()->is_valid()); + CHECK(snapshot.tds().is_vertex(v_1.value())); + cout << "v_1 contains point " << v_1.value()->point() << '\n'; } THEN("We can obtain the cell from the vertices.") { - Vertex_handle_t<3> const v_1 = manifold.get_vertex(p_1); - Vertex_handle_t<3> const v_2 = manifold.get_vertex(p_2); - Vertex_handle_t<3> const v_3 = manifold.get_vertex(p_3); - Vertex_handle_t<3> const v_4 = manifold.get_vertex(p_4); - auto const& cell = manifold.get_cell(v_1, v_2, v_3, v_4); - CHECK(cell->is_valid()); - /// @todo Why is this false? - // CHECK(manifold.get_delaunay().is_cell(cell)); + auto snapshot = manifold.delaunay_snapshot(); + auto v_1 = foliated_triangulations::find_vertex<3>(snapshot, p_1); + auto v_2 = foliated_triangulations::find_vertex<3>(snapshot, p_2); + auto v_3 = foliated_triangulations::find_vertex<3>(snapshot, p_3); + auto v_4 = foliated_triangulations::find_vertex<3>(snapshot, p_4); + REQUIRE(v_1); + REQUIRE(v_2); + REQUIRE(v_3); + REQUIRE(v_4); + auto cell = foliated_triangulations::find_cell<3>(snapshot, *v_1, *v_2, + *v_3, *v_4); + REQUIRE(cell); + CHECK(cell.value()->is_valid()); + CHECK(snapshot.tds().is_cell(cell.value())); // We have to have a valid Cell handle to obtain a tetrahedron - auto tetrahedron = manifold.get_delaunay().tetrahedron(cell); + auto tetrahedron = snapshot.tetrahedron(cell.value()); CHECK_FALSE(tetrahedron.is_degenerate()); cout << "Vertex 0 of tetrahedron is " << tetrahedron.vertex(0) << '\n'; cout << "Vertex 1 of tetrahedron is " << tetrahedron.vertex(1) << '\n'; @@ -241,18 +242,19 @@ SCENARIO("Manifold functions" * doctest::test_suite("manifold")) manifold.print_vertices(); } } - AND_WHEN("The vertices are mis-labelled.") + AND_WHEN("Vertices in an owning snapshot are mis-labelled.") { - for (std::span const vertices(manifold.get_vertices()); - auto const& vertex : vertices) + auto snapshot = manifold.delaunay_snapshot(); + for (auto const& vertex : + foliated_triangulations::collect_vertices<3>(snapshot)) { vertex->info() = std::numeric_limits::max(); } - THEN("The incorrect vertex time-values are identified.") + THEN("The source remains correct and the snapshot records the change.") { - CHECK_FALSE(manifold.is_correct()); - // Human verification - manifold.print_vertices(); + CHECK(manifold.is_correct()); + CHECK_FALSE( + foliated_triangulations::check_vertices<3>(snapshot, 1.0, 1.0)); } } } @@ -269,12 +271,6 @@ SCENARIO("3-Manifold initialization" * doctest::test_suite("manifold")) Manifold_3 const manifold; THEN("The triangulation is valid.") { - auto const& manifold_type = typeid(manifold.get_triangulation()).name(); - std::string manifold_string{manifold_type}; - CHECK_NE(manifold_string.find("FoliatedTriangulation"), - std::string::npos); - fmt::print("The triangulation data structure is of type {}\n", - manifold_string); REQUIRE(manifold.is_delaunay()); REQUIRE(manifold.is_valid()); } @@ -298,12 +294,6 @@ SCENARIO("3-Manifold initialization" * doctest::test_suite("manifold")) Manifold_3 const manifold(causal_vertices, 0, 1.0); THEN("The triangulation is valid.") { - auto const& manifold_type = typeid(manifold.get_triangulation()).name(); - std::string manifold_string{manifold_type}; - CHECK_NE(manifold_string.find("FoliatedTriangulation"), - std::string::npos); - fmt::print("The triangulation data structure is of type {}\n", - manifold_string); REQUIRE(manifold.is_delaunay()); REQUIRE(manifold.is_valid()); } @@ -322,10 +312,10 @@ SCENARIO("3-Manifold initialization" * doctest::test_suite("manifold")) REQUIRE_EQ(manifold.N1_SL(), 3); REQUIRE_EQ(manifold.N1_TL(), 6); // How many spacelike facets have a timevalue of 2? Should be 1. - REQUIRE_EQ(manifold.N2_SL().count(2), 1); + REQUIRE_EQ(manifold.spacelike_face_count(2), 1); // There shouldn't be spacelike facets with other time values. - REQUIRE_EQ(manifold.N2_SL().count(1), 0); - REQUIRE_EQ(manifold.N2_SL().count(3), 0); + REQUIRE_EQ(manifold.spacelike_face_count(1), 0); + REQUIRE_EQ(manifold.spacelike_face_count(3), 0); REQUIRE_EQ(manifold.N3(), 2); REQUIRE_EQ(manifold.min_time(), 1); REQUIRE_EQ(manifold.max_time(), 3); @@ -346,15 +336,10 @@ SCENARIO("3-Manifold initialization" * doctest::test_suite("manifold")) foliated_triangulations::FoliatedTriangulation_3 const foliated_triangulation(causal_vertices, 0, 1.0); Manifold_3 const manifold(foliated_triangulation); - CHECK_EQ(manifold.get_delaunay(), foliated_triangulation.get_delaunay()); + CHECK_EQ(manifold.delaunay_snapshot(), + foliated_triangulation.delaunay_snapshot()); THEN("The triangulation is valid.") { - auto const& manifold_type = typeid(manifold.get_triangulation()).name(); - std::string manifold_string{manifold_type}; - CHECK_NE(manifold_string.find("FoliatedTriangulation"), - std::string::npos); - fmt::print("The triangulation data structure is of type {}\n", - manifold_string); REQUIRE(manifold.is_delaunay()); REQUIRE(manifold.is_valid()); } @@ -373,10 +358,10 @@ SCENARIO("3-Manifold initialization" * doctest::test_suite("manifold")) REQUIRE_EQ(manifold.N1_SL(), 3); REQUIRE_EQ(manifold.N1_TL(), 6); // How many spacelike facets have a timevalue of 2? Should be 1. - CHECK_EQ(manifold.N2_SL().count(2), 1); + CHECK_EQ(manifold.spacelike_face_count(2), 1); // There shouldn't be spacelike facets with other time values. - CHECK_EQ(manifold.N2_SL().count(1), 0); - REQUIRE_EQ(manifold.N2_SL().count(3), 0); + CHECK_EQ(manifold.spacelike_face_count(1), 0); + REQUIRE_EQ(manifold.spacelike_face_count(3), 0); REQUIRE_EQ(manifold.N3(), 2); CHECK_EQ(manifold.min_time(), 1); CHECK_EQ(manifold.max_time(), 3); @@ -462,13 +447,13 @@ SCENARIO("3-Manifold function checks" * doctest::test_suite("manifold")) THEN("There is only one vertex, the infinite vertex.") { Manifold_3 const manifold; - auto&& vertices = - manifold.get_triangulation().get_delaunay().tds().vertices(); - auto&& vertex = vertices.begin(); + auto snapshot = manifold.delaunay_snapshot(); + auto&& vertices = snapshot.tds().vertices(); + auto&& vertex = vertices.begin(); CHECK_EQ(vertices.size(), 1); - CHECK(manifold.is_vertex(vertex)); - CHECK(manifold.get_triangulation().is_infinite(vertex)); + CHECK(snapshot.tds().is_vertex(vertex)); + CHECK(snapshot.is_infinite(vertex)); } } @@ -531,15 +516,12 @@ SCENARIO("3-Manifold copying" * doctest::test_suite("manifold")) fmt::print("Manifold properties:\n"); manifold.print(); manifold.print_volume_per_timeslice(); - auto cells = manifold.get_delaunay().tds().cells(); + auto snapshot = manifold.delaunay_snapshot(); + auto cells = snapshot.tds().cells(); fmt::print("Cell compact container size == {}\n", cells.size()); fmt::print("Now compact container size == {}\n", cells.size()); fmt::print("Vertex compact container size == {}\n", - manifold.get_triangulation() - .get_delaunay() - .tds() - .vertices() - .size()); + snapshot.tds().vertices().size()); fmt::print("Copied manifold properties:\n"); manifold2.print(); manifold2.print_volume_per_timeslice(); @@ -548,7 +530,63 @@ SCENARIO("3-Manifold copying" * doctest::test_suite("manifold")) } } -SCENARIO("3-Manifold update geometry" * doctest::test_suite("manifold")) +SCENARIO("3-Manifold moving" * doctest::test_suite("manifold")) +{ + GIVEN("A 3-manifold with known geometry.") + { + auto constexpr desired_simplices = 64; + auto constexpr desired_timeslices = 4; + Manifold_3 source(desired_simplices, desired_timeslices); + auto const expected_simplices = source.simplices(); + auto const expected_faces = source.faces(); + auto const expected_edges = source.edges(); + auto const expected_vertices = source.vertices(); + + WHEN("It is move constructed.") + { + auto moved = Manifold_3{std::move(source)}; + + THEN("The destination preserves its geometry and cached counts.") + { + CHECK(moved.is_correct()); + CHECK_EQ(moved.simplices(), expected_simplices); + CHECK_EQ(moved.faces(), expected_faces); + CHECK_EQ(moved.edges(), expected_edges); + CHECK_EQ(moved.vertices(), expected_vertices); + CHECK_EQ(moved.simplices(), moved.N3()); + CHECK_EQ(moved.faces(), moved.N2()); + CHECK_EQ(moved.edges(), moved.N1()); + CHECK_EQ(moved.vertices(), moved.N0()); + } + } + WHEN("It is move assigned over another manifold.") + { + Manifold_3 assigned(desired_simplices * 2, desired_timeslices); + auto const replaced_simplices = assigned.simplices(); + assigned = std::move(source); + + THEN("The destination preserves the source geometry and cached counts.") + { + CHECK(assigned.is_correct()); + CHECK_EQ(assigned.simplices(), expected_simplices); + CHECK_EQ(assigned.simplices(), assigned.N3()); + CHECK_EQ(assigned.faces(), assigned.N2()); + CHECK_EQ(assigned.edges(), assigned.N1()); + CHECK_EQ(assigned.vertices(), assigned.N0()); + } + AND_THEN("The source owns the replaced value and remains reusable.") + { + CHECK(source.is_correct()); + CHECK_EQ(source.simplices(), replaced_simplices); + + source = Manifold_3{desired_simplices, desired_timeslices}; + CHECK(source.is_correct()); + } + } + } +} + +SCENARIO("3-Manifold value rebuild" * doctest::test_suite("manifold")) { spdlog::debug("3-Manifold update geometry.\n"); GIVEN("A 3-manifold.") @@ -556,7 +594,7 @@ SCENARIO("3-Manifold update geometry" * doctest::test_suite("manifold")) auto constexpr desired_simplices = 640; auto constexpr desired_timeslices = 4; Manifold_3 manifold(desired_simplices, desired_timeslices); - WHEN("We call update().") + WHEN("We rebuild it as a new value.") { // Get values for manifold1 auto manifold_N3 = manifold.N3(); @@ -567,17 +605,16 @@ SCENARIO("3-Manifold update geometry" * doctest::test_suite("manifold")) fmt::print("Manifold N2 = {}\n", manifold_N2); fmt::print("Manifold N1 = {}\n", manifold_N1); fmt::print("Manifold N0 = {}\n", manifold_N0); - manifold.update(); - fmt::print("update() called.\n"); - THEN("We get back the same values.") + auto const rebuilt = manifold.updated(); + THEN("The rebuilt value and source have the same geometry.") { - fmt::print("Manifold N3 is still {}\n", manifold.N3()); + CHECK_EQ(rebuilt.N3(), manifold_N3); + CHECK_EQ(rebuilt.N2(), manifold_N2); + CHECK_EQ(rebuilt.N1(), manifold_N1); + CHECK_EQ(rebuilt.N0(), manifold_N0); CHECK_EQ(manifold.N3(), manifold_N3); - fmt::print("Manifold N2 is still {}\n", manifold.N2()); CHECK_EQ(manifold.N2(), manifold_N2); - fmt::print("Manifold N1 is still {}\n", manifold.N1()); CHECK_EQ(manifold.N1(), manifold_N1); - fmt::print("Manifold N0 is still {}\n", manifold.N0()); CHECK_EQ(manifold.N0(), manifold_N0); } } @@ -593,7 +630,7 @@ SCENARIO("3-Manifold mutation" * doctest::test_suite("manifold")) auto constexpr desired_timeslices = 4; Manifold_3 manifold1(desired_simplices, desired_timeslices); Manifold_3 const manifold2(desired_simplices, desired_timeslices); - WHEN("We swap the triangulation of one manifold for another.") + WHEN("We construct a replacement value from the second triangulation.") { // Get values for manifold1 auto manifold1_N3 = manifold1.N3(); @@ -613,32 +650,25 @@ SCENARIO("3-Manifold mutation" * doctest::test_suite("manifold")) fmt::print("Manifold 2 N2 = {}\n", manifold2_N2); fmt::print("Manifold 2 N1 = {}\n", manifold2_N1); fmt::print("Manifold 2 N0 = {}\n", manifold2_N0); - // Change manifold1's triangulation to manifold2's - manifold1.triangulation() = manifold2.get_triangulation(); - fmt::print("Manifolds swapped.\n"); - THEN("Not calling update() gives old values.") + auto const replacement = Manifold_3{ + foliated_triangulations::FoliatedTriangulation_3{ + manifold2.delaunay_snapshot(), manifold2.initial_radius(), + manifold2.foliation_spacing()} + }; + THEN("The replacement geometry is synchronized at construction.") { CHECK_EQ(manifold1.N3(), manifold1_N3); CHECK_EQ(manifold1.N2(), manifold1_N2); CHECK_EQ(manifold1.N1(), manifold1_N1); CHECK_EQ(manifold1.N0(), manifold1_N0); - - AND_WHEN("We call update().") - { - manifold1.update(); - fmt::print("update() called.\n"); - THEN("The geometry matches the new triangulation.") - { - fmt::print("Manifold 1 N3 is now {}\n", manifold1.N3()); - CHECK_EQ(manifold1.N3(), manifold2_N3); - fmt::print("Manifold 1 N2 is now {}\n", manifold1.N2()); - CHECK_EQ(manifold1.N2(), manifold2_N2); - fmt::print("Manifold 1 N1 is now {}\n", manifold1.N1()); - CHECK_EQ(manifold1.N1(), manifold2_N1); - fmt::print("Manifold 1 N0 is now {}\n", manifold1.N0()); - CHECK_EQ(manifold1.N0(), manifold2_N0); - } - } + CHECK_EQ(replacement.N3(), manifold2_N3); + CHECK_EQ(replacement.N2(), manifold2_N2); + CHECK_EQ(replacement.N1(), manifold2_N1); + CHECK_EQ(replacement.N0(), manifold2_N0); + CHECK_EQ(replacement.simplices(), replacement.N3()); + CHECK_EQ(replacement.faces(), replacement.N2()); + CHECK_EQ(replacement.edges(), replacement.N1()); + CHECK_EQ(replacement.vertices(), replacement.N0()); } } } @@ -656,14 +686,6 @@ SCENARIO("3-Manifold validation and fixing" * doctest::test_suite("manifold")) auto causal_vertices = manifolds::make_causal_vertices<3>(Vertices, Timevalues); Manifold_3 manifold(causal_vertices, 0.0, 1.0); - auto print = [&manifold](auto& vertex) { - fmt::print( - "Vertex: ({}) Timevalue: {} is a vertex: {} and is " - "infinite: {}\n", - utilities::point_to_str(vertex->point()), vertex->info(), - manifold.is_vertex(vertex), - manifold.get_triangulation().is_infinite(vertex)); - }; WHEN("It is constructed.") { @@ -675,7 +697,7 @@ SCENARIO("3-Manifold validation and fixing" * doctest::test_suite("manifold")) THEN("Every vertex in the manifold has a correct timevalue.") { manifold.print_vertices(); - REQUIRE(manifold.get_triangulation().check_all_vertices()); + REQUIRE(manifold.check_vertices()); } THEN("Every cell in the manifold is correctly classified.") { @@ -683,28 +705,34 @@ SCENARIO("3-Manifold validation and fixing" * doctest::test_suite("manifold")) REQUIRE(manifold.check_simplices()); } } - WHEN("We insert an invalid timevalue into a vertex.") + WHEN("We insert an invalid timevalue into an owning snapshot.") { - auto cells = manifold.get_triangulation().get_cells(); + auto candidate = manifold.delaunay_snapshot(); + auto cells = foliated_triangulations::collect_cells<3>(candidate); auto broken_cell = cells[0]; auto broken_vertex = broken_cell->vertex(0); fmt::print("Info on vertex was {}\n", broken_vertex->info()); broken_vertex->info() = std::numeric_limits::max(); fmt::print("Info on vertex is now {}\n", broken_vertex->info()); - THEN("We can detect invalid vertex timevalues.") + THEN("The snapshot is invalid while the source remains correct.") { - CHECK_FALSE(manifold.is_correct()); - // Human verification - auto bad_vertices = - manifold.get_triangulation().find_incorrect_vertices(); - ranges::for_each(bad_vertices, print); - } - THEN("But the invalid cell is fixed on update.") - { - CHECK_FALSE(manifold.check_simplices()); - manifold.update(); - manifold.print_cells(); - CHECK(manifold.check_simplices()); + CHECK(manifold.is_correct()); + CHECK_FALSE( + foliated_triangulations::check_vertices<3>(candidate, 0.0, 1.0)); + auto bad_vertices = foliated_triangulations::find_incorrect_vertices<3>( + candidate, 0.0, 1.0); + CHECK_FALSE(bad_vertices.empty()); + } + THEN("Publishing the snapshot builds a synchronized replacement value.") + { + auto replacement = Manifold_3{ + foliated_triangulations::FoliatedTriangulation_3{ + std::move(candidate), manifold.initial_radius(), + manifold.foliation_spacing()} + }; + CHECK(replacement.is_correct()); + CHECK(replacement.check_vertices()); + CHECK(manifold.is_correct()); } } } @@ -731,7 +759,7 @@ SCENARIO("3-Manifold validation and fixing" * doctest::test_suite("manifold")) REQUIRE_EQ(manifold.max_time(), desired_timeslices); } THEN("Every vertex in the manifold has a correct timevalue.") - { REQUIRE(manifold.get_triangulation().check_all_vertices()); } + { REQUIRE(manifold.check_vertices()); } THEN("Every cell in the manifold is correctly classified.") { REQUIRE(manifold.check_simplices()); } } diff --git a/tests/Metropolis_test.cpp b/tests/Metropolis_test.cpp index ec80682c6..003977d44 100644 --- a/tests/Metropolis_test.cpp +++ b/tests/Metropolis_test.cpp @@ -12,9 +12,14 @@ #include +#include +#include + using namespace std; using namespace manifolds; +static_assert(std::is_nothrow_swappable_v); + SCENARIO("MoveStrategy special member and swap properties" * doctest::test_suite("metropolis")) { @@ -79,15 +84,15 @@ SCENARIO("Metropolis member functions" * doctest::test_suite("metropolis")) auto constexpr Lambda = static_cast(0.1); GIVEN("A correctly-constructed Manifold_3.") { - auto constexpr simplices = 640; - auto constexpr timeslices = 4; + auto constexpr simplices = 640; + auto constexpr timeslices = 4; + auto constexpr output_every_n_passes = 1; + auto constexpr passes = 10; Manifold_3 const universe(simplices, timeslices); // It is correctly constructed REQUIRE(universe.is_correct()); WHEN("A Metropolis function object is constructed.") { - auto constexpr output_every_n_passes = 1; - auto constexpr passes = 10; Metropolis_3 testrun(Alpha, K, Lambda, passes, output_every_n_passes); THEN("The Metropolis function object is initialized correctly.") { @@ -111,10 +116,6 @@ SCENARIO("Metropolis member functions" * doctest::test_suite("metropolis")) CHECK_EQ(no_file_output_run.checkpoint(), output_every_n_passes); CHECK_FALSE(no_file_output_run.writes_files()); } - CHECK_THROWS_AS(Metropolis_3(Alpha, K, Lambda, -1, output_every_n_passes), - std::invalid_argument); - CHECK_THROWS_AS(Metropolis_3(Alpha, K, Lambda, passes, 0), - std::invalid_argument); THEN("The initial moves are made correctly.") { auto result = testrun.initialize(universe); @@ -153,6 +154,33 @@ SCENARIO("Metropolis member functions" * doctest::test_suite("metropolis")) } } } + WHEN("A nonpositive pass or checkpoint count is supplied.") + { + THEN("Construction rejects the invalid cadence.") + { + CHECK_THROWS_AS( + Metropolis_3(Alpha, K, Lambda, -1, output_every_n_passes), + std::invalid_argument); + CHECK_THROWS_AS( + Metropolis_3(Alpha, K, Lambda, 0, output_every_n_passes), + std::invalid_argument); + CHECK_THROWS_AS(Metropolis_3(Alpha, K, Lambda, passes, 0), + std::invalid_argument); + } + } + WHEN("Alpha is outside its finite physical domain.") + { + THEN("Construction reports the corresponding parameter error.") + { + CHECK_THROWS_AS( + Metropolis_3(0.5L, K, Lambda, passes, output_every_n_passes), + std::domain_error); + CHECK_THROWS_AS( + Metropolis_3(std::numeric_limits::infinity(), K, + Lambda, passes, output_every_n_passes), + std::invalid_argument); + } + } } } diff --git a/tests/Move_always_test.cpp b/tests/Move_always_test.cpp index dee26be5d..85fb27041 100644 --- a/tests/Move_always_test.cpp +++ b/tests/Move_always_test.cpp @@ -12,9 +12,13 @@ #include +#include + using namespace std; using namespace manifolds; +static_assert(std::is_nothrow_swappable_v); + SCENARIO("MoveStrategy special member and swap properties" * doctest::test_suite("move_always")) { diff --git a/tests/Move_command_test.cpp b/tests/Move_command_test.cpp index de0aaf649..b45afa28b 100644 --- a/tests/Move_command_test.cpp +++ b/tests/Move_command_test.cpp @@ -40,8 +40,9 @@ namespace { std::vector states; states.reserve(static_cast(manifold.vertices())); - for (auto vertex = manifold.get_delaunay().finite_vertices_begin(); - vertex != manifold.get_delaunay().finite_vertices_end(); ++vertex) + auto snapshot = manifold.delaunay_snapshot(); + for (auto vertex = snapshot.finite_vertices_begin(); + vertex != snapshot.finite_vertices_end(); ++vertex) { states.push_back(vertex_state(vertex)); } @@ -53,8 +54,9 @@ namespace { std::vector states; states.reserve(static_cast(manifold.simplices())); - for (auto cell = manifold.get_delaunay().finite_cells_begin(); - cell != manifold.get_delaunay().finite_cells_end(); ++cell) + auto snapshot = manifold.delaunay_snapshot(); + for (auto cell = snapshot.finite_cells_begin(); + cell != snapshot.finite_cells_end(); ++cell) { std::array vertices; for (auto index = 0; index < 4; ++index) @@ -117,7 +119,7 @@ namespace } else { - CHECK(result.get_delaunay() == before.get_delaunay()); + CHECK(result.delaunay_snapshot() == before.delaunay_snapshot()); CHECK(vertex_states(result) == vertex_states(before)); CHECK(cell_states(result) == cell_states(before)); CHECK(manifold_counts(result) == manifold_counts(before)); @@ -189,7 +191,6 @@ SCENARIO("Invoking a move with a function pointer" * THEN("Running the function makes the move.") { auto result = move23(manifold); - result->update(); CHECK(ergodic_moves::check_move(manifold, result.value(), move_tracker::move_type::TWO_THREE)); // Human verification @@ -213,13 +214,12 @@ SCENARIO("Invoking a move with a lambda" * doctest::test_suite("move_command")) REQUIRE(manifold.is_correct()); WHEN("A lambda is constructed for a move.") { - auto const move23 = [](Manifold_3& manifold_3) { + auto const move23 = [](Manifold_3 const& manifold_3) { return ergodic_moves::do_23_move(manifold_3).value(); }; THEN("Running the lambda makes the move.") { auto result = move23(manifold); - result.update(); CHECK(ergodic_moves::check_move(manifold, result, move_tracker::move_type::TWO_THREE)); // Human verification @@ -248,7 +248,6 @@ SCENARIO("Invoking a move with apply_move and a function pointer" * THEN("Invoking apply_move() makes the move.") { auto result = apply_move(manifold, move); - result->update(); CHECK(ergodic_moves::check_move(manifold, result.value(), move_tracker::move_type::TWO_THREE)); // Human verification @@ -439,7 +438,7 @@ SCENARIO("Rejected moves preserve manifold state" * causal_vertices.emplace_back(Point_t<3>{radius_2, radius_2, radius_2}, 2); Manifold_3 const manifold(causal_vertices); REQUIRE(manifold.is_correct()); - REQUIRE(manifold.get_triangulation().get_two_two().empty()); + REQUIRE_EQ(manifold.N3_22(), 0); MoveCommand command(manifold); command.enqueue(move_tracker::move_type::TWO_THREE); diff --git a/tests/Move_tracker_test.cpp b/tests/Move_tracker_test.cpp index e27a0fac6..ce33078ed 100644 --- a/tests/Move_tracker_test.cpp +++ b/tests/Move_tracker_test.cpp @@ -12,12 +12,16 @@ #include +#include + #include "Manifold.hpp" using namespace std; using namespace manifolds; using namespace move_tracker; +static_assert(std::is_nothrow_swappable_v>); + SCENARIO("MoveTracker special members" * doctest::test_suite("move_tracker")) { spdlog::debug("MoveTracker special members.\n"); diff --git a/tests/Runtime_config_test.cpp b/tests/Runtime_config_test.cpp new file mode 100644 index 000000000..634f657ff --- /dev/null +++ b/tests/Runtime_config_test.cpp @@ -0,0 +1,239 @@ +/******************************************************************************* + Causal Dynamical Triangulations in C++ using CGAL + + Copyright © 2026 Adam Getchell + ******************************************************************************/ + +/// @file Runtime_config_test.cpp +/// @brief Tests for validated command-line configuration values + +#include "Runtime_config.hpp" + +#include + +#include +#include + +namespace +{ + auto test_make_triangulation(bool const spherical, bool const toroidal, + long long const simplices, + long long const timeslices, + long long const dimensions, + double const initial_radius, + double const foliation_spacing) + -> runtime_config::Triangulation + { + return runtime_config::make_triangulation( + spherical, toroidal, simplices, timeslices, dimensions, initial_radius, + foliation_spacing); + } + + auto test_make_simulation(runtime_config::Triangulation const& triangulation, + long double const alpha, long double const k, + long double const lambda, long long const passes, + long long const checkpoint, bool const write_files) + -> runtime_config::Simulation + { + return runtime_config::make_simulation(triangulation, alpha, k, lambda, + passes, checkpoint, write_files); + } +} // namespace + +static_assert(!std::is_aggregate_v); +static_assert(!std::is_default_constructible_v); +static_assert(!std::is_constructible_v< + runtime_config::Triangulation, topology_type, Int_precision, + Int_precision, Int_precision, double, double>); +static_assert(!std::is_aggregate_v); +static_assert(!std::is_default_constructible_v); +static_assert( + !std::is_constructible_v< + runtime_config::Simulation, runtime_config::Triangulation, long double, + long double, long double, Int_precision, Int_precision, bool>); + +SCENARIO("Runtime triangulation options parse into a validated value" * + doctest::test_suite("runtime_config")) +{ + GIVEN("Supported finite spherical parameters.") + { + WHEN("The raw options are parsed.") + { + auto const config = + test_make_triangulation(true, false, 64, 3, 3, 1.0, 1.0); + + THEN("The narrowed value contains the supported configuration.") + { + CHECK_EQ(config.topology(), topology_type::SPHERICAL); + CHECK_EQ(config.simplices(), 64); + CHECK_EQ(config.timeslices(), 3); + CHECK_EQ(config.dimensions(), 3); + CHECK_EQ(config.initial_radius(), 1.0); + CHECK_EQ(config.foliation_spacing(), 1.0); + } + } + } + + GIVEN("Raw topology and dimensionality parameters.") + { + WHEN("No topology is selected.") + { + THEN("The options are rejected as ambiguous.") + { + CHECK_THROWS_AS( + test_make_triangulation(false, false, 64, 3, 3, 1.0, 1.0), + std::invalid_argument); + } + } + WHEN("Conflicting topologies are selected.") + { + THEN("The options are rejected as ambiguous.") + { + CHECK_THROWS_AS(test_make_triangulation(true, true, 64, 3, 3, 1.0, 1.0), + std::invalid_argument); + } + } + WHEN("An unsupported topology is selected.") + { + THEN("The options are rejected.") + { + CHECK_THROWS_AS( + test_make_triangulation(false, true, 64, 3, 3, 1.0, 1.0), + std::invalid_argument); + } + } + WHEN("An unsupported dimensionality is selected.") + { + THEN("The options are rejected.") + { + CHECK_THROWS_AS( + test_make_triangulation(true, false, 64, 3, 2, 1.0, 1.0), + std::invalid_argument); + } + } + } + + GIVEN("Raw population, radius, and spacing parameters.") + { + auto const too_large = + static_cast(std::numeric_limits::max()) + 1; + + WHEN("An integer exceeds the validated representation.") + { + THEN("Narrowing is rejected with an out-of-range error.") + { + CHECK_THROWS_AS( + test_make_triangulation(true, false, too_large, 3, 3, 1.0, 1.0), + std::out_of_range); + } + } + WHEN("The requested population cannot form the foliation.") + { + THEN("The population is rejected.") + { + CHECK_THROWS_AS(test_make_triangulation(true, false, 1, 3, 3, 1.0, 1.0), + std::invalid_argument); + CHECK_THROWS_AS(test_make_triangulation(true, false, 3, 2, 3, 1.0, 1.0), + std::invalid_argument); + } + } + WHEN("The radius or foliation spacing is nonpositive.") + { + THEN("The geometric parameters are rejected.") + { + CHECK_THROWS_AS( + test_make_triangulation(true, false, 64, 3, 3, 0.0, 1.0), + std::invalid_argument); + CHECK_THROWS_AS( + test_make_triangulation(true, false, 64, 3, 3, 1.0, 0.0), + std::invalid_argument); + } + } + WHEN("The radius or foliation spacing is nonfinite.") + { + THEN("The geometric parameters are rejected.") + { + CHECK_THROWS_AS(test_make_triangulation( + true, false, 64, 3, 3, + std::numeric_limits::infinity(), 1.0), + std::invalid_argument); + CHECK_THROWS_AS( + test_make_triangulation(true, false, 64, 3, 3, 1.0, + std::numeric_limits::quiet_NaN()), + std::invalid_argument); + } + } + } +} + +SCENARIO("Simulation options parse into a validated value" * + doctest::test_suite("runtime_config")) +{ + GIVEN("A validated triangulation and raw simulation parameters.") + { + auto const triangulation = + test_make_triangulation(true, false, 64, 3, 3, 1.0, 1.0); + + WHEN("Supported finite parameters and positive cadence are parsed.") + { + auto const config = + test_make_simulation(triangulation, 0.6L, 1.1L, 0.1L, 10, 2, false); + + THEN("The value contains the validated simulation configuration.") + { + CHECK_EQ(config.triangulation().simplices(), 64); + CHECK_EQ(config.alpha(), 0.6L); + CHECK_EQ(config.k(), 1.1L); + CHECK_EQ(config.lambda(), 0.1L); + CHECK_EQ(config.passes(), 10); + CHECK_EQ(config.checkpoint(), 2); + CHECK_FALSE(config.write_files()); + } + } + WHEN("Alpha is outside its physical domain.") + { + THEN("The parameter is rejected with a domain error.") + { + CHECK_THROWS_AS(test_make_simulation(triangulation, -0.6L, 1.1L, 0.1L, + 10, 2, false), + std::domain_error); + CHECK_THROWS_AS( + test_make_simulation(triangulation, 0.5L, 1.1L, 0.1L, 10, 2, false), + std::domain_error); + } + } + WHEN("A physical parameter is nonfinite.") + { + THEN("The parameter is rejected as invalid input.") + { + CHECK_THROWS_AS( + test_make_simulation(triangulation, + std::numeric_limits::infinity(), + 1.1L, 0.1L, 10, 2, false), + std::invalid_argument); + CHECK_THROWS_AS( + test_make_simulation(triangulation, 0.6L, + std::numeric_limits::quiet_NaN(), + 0.1L, 10, 2, false), + std::invalid_argument); + CHECK_THROWS_AS( + test_make_simulation(triangulation, 0.6L, 1.1L, + std::numeric_limits::infinity(), + 10, 2, false), + std::invalid_argument); + } + } + WHEN("A pass or checkpoint count is nonpositive.") + { + THEN("The cadence is rejected as invalid input.") + { + CHECK_THROWS_AS( + test_make_simulation(triangulation, 0.6L, 1.1L, 0.1L, 0, 2, false), + std::invalid_argument); + CHECK_THROWS_AS( + test_make_simulation(triangulation, 0.6L, 1.1L, 0.1L, 10, 0, false), + std::invalid_argument); + } + } + } +} diff --git a/tests/S3Action_test.cpp b/tests/S3Action_test.cpp index 27c57a523..b12e20b50 100644 --- a/tests/S3Action_test.cpp +++ b/tests/S3Action_test.cpp @@ -14,11 +14,58 @@ #include +#include +#include + #include "Manifold.hpp" using namespace std; using namespace manifolds; +static_assert(std::is_nothrow_destructible_v); + +SCENARIO("MPFR calculations use scope-owned values" * + doctest::test_suite("s3action")) +{ + GIVEN("MPFR operands and the process-wide default precision.") + { + auto const default_precision = mpfr_get_default_prec(); + auto const numerator = mpfr_values::from_decimal("1.5"); + auto const denominator = mpfr_values::from_integer(3); + + WHEN("The operands are divided into a new value.") + { + auto const quotient = mpfr_values::divide(numerator, denominator); + + THEN("The calculation uses the configured precision.") + { + CHECK_EQ(numerator.get_precision(), mpfr_values::precision); + CHECK(mpfr_values::to_long_double(quotient) == doctest::Approx(0.5L)); + } + AND_THEN("The process-wide default precision is unchanged.") + { CHECK_EQ(mpfr_get_default_prec(), default_precision); } + } + WHEN("An invalid decimal is parsed.") + { + THEN("The invalid input is rejected.") + { + CHECK_THROWS_AS( + static_cast(mpfr_values::from_decimal("not-a-number")), + std::invalid_argument); + } + } + WHEN("A null decimal pointer is supplied.") + { + THEN("The invalid boundary is rejected before calling MPFR.") + { + CHECK_THROWS_AS(static_cast(mpfr_values::from_decimal( + static_cast(nullptr))), + std::invalid_argument); + } + } + } +} + SCENARIO("Calculate the bulk action on S3 triangulations" * doctest::test_suite("s3action")) { @@ -101,3 +148,46 @@ SCENARIO("Calculate the bulk action on S3 triangulations" * } } } + +SCENARIO("Bulk action rejects invalid physical parameters" * + doctest::test_suite("s3action")) +{ + GIVEN("Minimal simplex counts and otherwise valid physical parameters.") + { + WHEN("Alpha is at the lower domain boundary.") + { + THEN("The generalized action rejects it with a domain error.") + { + CHECK_THROWS_AS( + static_cast(S3_bulk_action(1, 1, 1, 0.5L, 1.1L, 0.1L)), + std::domain_error); + } + } + WHEN("Alpha is not finite.") + { + THEN("The generalized action rejects it as invalid input.") + { + CHECK_THROWS_AS( + static_cast(S3_bulk_action( + 1, 1, 1, std::numeric_limits::quiet_NaN(), 1.1L, + 0.1L)), + std::invalid_argument); + } + } + WHEN("A specialized action receives an infinite coupling.") + { + THEN("The specialized action rejects it as invalid input.") + { + CHECK_THROWS_AS( + static_cast(S3_bulk_action_alpha_one( + 1, 1, 1, std::numeric_limits::infinity(), 0.1L)), + std::invalid_argument); + } + } + WHEN("The generalized action's exception specification is examined.") + { + THEN("It permits parameter validation to throw.") + { CHECK_FALSE(noexcept(S3_bulk_action(1, 1, 1, 0.6L, 1.1L, 0.1L))); } + } + } +} diff --git a/tests/Tetrahedron_test.cpp b/tests/Tetrahedron_test.cpp index b3ef12934..02725b30d 100644 --- a/tests/Tetrahedron_test.cpp +++ b/tests/Tetrahedron_test.cpp @@ -145,7 +145,8 @@ SCENARIO("Find distances between points of the tetrahedron" * std::pow(triangulation.expected_radius(vertex), 2), triangulation.expected_timevalue(vertex)); }; - ranges::for_each(triangulation.get_vertices(), print); + auto snapshot = triangulation.delaunay_snapshot(); + ranges::for_each(collect_vertices<3>(snapshot), print); } } } @@ -194,20 +195,21 @@ SCENARIO("Construct a foliated tetrahedron in a foliated triangulation" * THEN("The cell info is correct.") { - auto cell = triangulation.get_delaunay().finite_cells_begin(); + auto snapshot = triangulation.delaunay_snapshot(); + auto cell = snapshot.finite_cells_begin(); CHECK_EQ(expected_cell_type<3>(cell), Cell_type::THREE_ONE); // Human verification triangulation.print_cells(); } THEN("There is one (3,1) simplex.") - { REQUIRE_EQ(triangulation.get_three_one().size(), 1); } + { REQUIRE_EQ(triangulation.number_of_three_one_cells(), 1); } THEN("There are no (2,2) simplices.") - { REQUIRE(triangulation.get_two_two().empty()); } + { REQUIRE_EQ(triangulation.number_of_two_two_cells(), 0); } THEN("There are no (1,3) simplices.") - { REQUIRE(triangulation.get_one_three().empty()); } + { REQUIRE_EQ(triangulation.number_of_one_three_cells(), 0); } THEN("There are 3 timelike edges.") { REQUIRE_EQ(triangulation.N1_TL(), 3); } diff --git a/tests/Utilities_test.cpp b/tests/Utilities_test.cpp index a14109fc6..ed1b5fdfc 100644 --- a/tests/Utilities_test.cpp +++ b/tests/Utilities_test.cpp @@ -13,11 +13,46 @@ #include #include +#include +#include #include using namespace std; using namespace utilities; +namespace +{ + struct SerializationFailure + {}; + + auto operator<<(std::ostream& output, SerializationFailure const& /*unused*/) + -> std::ostream& + { + output.setstate(std::ios::badbit); + return output; + } + + struct ReentrantSerialization + { + std::filesystem::path filename; + }; + + auto operator<<(std::ostream& output, ReentrantSerialization const& value) + -> std::ostream& + { + write_file(value.filename, 42); + return output; + } + + struct SingleInteger + { + int value{}; + }; + + auto operator>>(std::istream& input, SingleInteger& parsed) -> std::istream& + { return input >> parsed.value; } +} // namespace + SCENARIO("Various string/stream/time utilities" * doctest::test_suite("utilities")) { @@ -128,7 +163,7 @@ SCENARIO("Reading and writing Delaunay triangulations to files" * auto const filename = std::filesystem::temp_directory_path() / "cdt-plusplus-utilities-roundtrip.off"; std::filesystem::remove(filename); - write_file(filename, manifold.get_delaunay()); + write_file(filename, manifold.delaunay_snapshot()); REQUIRE(std::filesystem::exists(filename)); auto triangulation_from_file = @@ -153,6 +188,108 @@ SCENARIO("Reading and writing Delaunay triangulations to files" * } } +SCENARIO("File serialization reports complete failures" * + doctest::test_suite("utilities")) +{ + auto const directory = std::filesystem::temp_directory_path(); + + GIVEN("A serializer that marks its output stream bad.") + { + auto const filename = directory / "cdt-plusplus-write-failure.off"; + auto temporary = filename; + temporary += ".tmp"; + std::filesystem::remove(filename); + std::filesystem::remove(temporary); + { + std::ofstream existing{filename}; + existing << "previous-checkpoint"; + } + + WHEN("Writing the value is attempted.") + { + THEN("The failure is reported without replacing the existing file.") + { + CHECK_THROWS_AS(write_file(filename, SerializationFailure{}), + std::filesystem::filesystem_error); + std::ifstream preserved{filename}; + std::string const contents{std::istreambuf_iterator{preserved}, + std::istreambuf_iterator{}}; + CHECK_EQ(contents, "previous-checkpoint"); + CHECK_FALSE(std::filesystem::exists(temporary)); + REQUIRE(std::filesystem::remove(filename)); + } + } + } + + GIVEN("A serializer that recursively starts another file write.") + { + auto const filename = directory / "cdt-plusplus-reentrant-write.off"; + auto temporary = filename; + temporary += ".tmp"; + std::filesystem::remove(filename); + std::filesystem::remove(temporary); + { + std::ofstream existing{filename}; + existing << "previous-checkpoint"; + } + + WHEN("Writing the value is attempted.") + { + THEN("Reentrancy is rejected without replacing the existing file.") + { + CHECK_THROWS_AS(write_file(filename, ReentrantSerialization{filename}), + std::logic_error); + std::ifstream preserved{filename}; + std::string const contents{std::istreambuf_iterator{preserved}, + std::istreambuf_iterator{}}; + CHECK_EQ(contents, "previous-checkpoint"); + CHECK_FALSE(std::filesystem::exists(temporary)); + REQUIRE(std::filesystem::remove(filename)); + } + } + } + + GIVEN("A serialized value followed by unexpected trailing input.") + { + auto const filename = directory / "cdt-plusplus-trailing-input.off"; + std::filesystem::remove(filename); + { + std::ofstream output{filename}; + output << "42 trailing-data"; + } + + WHEN("The file is parsed.") + { + THEN("The trailing input is reported and the fixture can be removed.") + { + CHECK_THROWS_AS(read_file(filename), + std::filesystem::filesystem_error); + REQUIRE(std::filesystem::remove(filename)); + } + } + } + + GIVEN("A file containing malformed input.") + { + auto const filename = directory / "cdt-plusplus-malformed-input.off"; + std::filesystem::remove(filename); + { + std::ofstream output{filename}; + output << "not-an-integer"; + } + + WHEN("The file is parsed.") + { + THEN("The malformed input is reported and the fixture can be removed.") + { + CHECK_THROWS_AS(read_file(filename), + std::filesystem::filesystem_error); + REQUIRE(std::filesystem::remove(filename)); + } + } + } +} + SCENARIO("Randomizing functions" * doctest::test_suite("utilities")) { spdlog::debug("Randomizing functions.\n"); diff --git a/tests/Vertex_test.cpp b/tests/Vertex_test.cpp index 99b1311ba..01d406381 100644 --- a/tests/Vertex_test.cpp +++ b/tests/Vertex_test.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include "Manifold.hpp" @@ -20,6 +21,21 @@ using namespace manifolds; static inline auto constexpr RADIUS_2 = 2.0 * std::numbers::inv_sqrt3_v; +namespace +{ + [[nodiscard]] auto snapshot_vertices_are_owned( + Manifold_3 const& manifold, std::size_t const expected_vertices) -> bool + { + auto snapshot = manifold.delaunay_snapshot(); + auto vertices = foliated_triangulations::collect_vertices<3>(snapshot); + return !vertices.empty() && vertices.size() == expected_vertices && + static_cast(manifold.N0()) == expected_vertices && + std::ranges::all_of(vertices, [&snapshot](auto const& vertex) { + return snapshot.tds().is_vertex(vertex); + }); + } +} // namespace + SCENARIO("Point operations" * doctest::test_suite("vertex")) { using Point = Point_t<3>; @@ -49,11 +65,7 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) causal_vertices.emplace_back(Point(0, 0, 0), 1); Manifold const manifold(causal_vertices, 0, 1); THEN("The vertex is in the manifold.") - { - // auto vertex = manifold.get_vertices(); - auto vertex = manifold.get_vertices_span(); - REQUIRE(manifold.is_vertex(vertex.front())); - } + { REQUIRE(snapshot_vertices_are_owned(manifold, 1)); } THEN("The Delaunay triangulation is valid.") { REQUIRE(manifold.is_valid()); } @@ -65,11 +77,21 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) THEN("A 1 vertex manifold has dimension 0.") { REQUIRE_EQ(manifold.dimensionality(), 0); } + THEN("Value copies and rebuilds preserve the lower-dimensional state.") + { + auto const copied = manifold; + auto const rebuilt = manifold.updated(); + CHECK_EQ(copied.N0(), 1); + CHECK_EQ(copied.dimensionality(), 0); + CHECK_EQ(rebuilt.N0(), 1); + CHECK_EQ(rebuilt.dimensionality(), 0); + } + THEN("The vertex is valid.") { fmt::print("When a causal vertex is inserted, the vertices are:\n"); manifold.print_vertices(); - CHECK(manifold.get_triangulation().check_all_vertices()); + CHECK(manifold.check_vertices()); } } @@ -80,11 +102,7 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) Manifold const manifold(causal_vertices, 0, 1); THEN("The vertices are in the manifold.") - { - auto vertex = manifold.get_vertices_span(); - REQUIRE(manifold.is_vertex(vertex.front())); - REQUIRE(manifold.is_vertex(vertex.back())); - } + { REQUIRE(snapshot_vertices_are_owned(manifold, 2)); } THEN("The Delaunay triangulation is valid.") { REQUIRE(manifold.is_valid()); } @@ -102,7 +120,7 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) { fmt::print("When 2 causal vertices are inserted, the vertices are:\n"); manifold.print_vertices(); - CHECK(manifold.get_triangulation().check_all_vertices()); + CHECK(manifold.check_vertices()); } } @@ -114,13 +132,7 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) Manifold manifold(causal_vertices, 0, 1); THEN("The vertices are in the manifold.") - { - auto vertices = manifold.get_vertices_span(); - auto require = [&manifold](auto& vertex) { - REQUIRE(manifold.is_vertex(vertex)); - }; - std::ranges::for_each(vertices, require); - } + { REQUIRE(snapshot_vertices_are_owned(manifold, 3)); } THEN("The Delaunay triangulation is valid.") { REQUIRE(manifold.is_valid()); } @@ -140,7 +152,7 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) { fmt::print("When 3 causal vertices are inserted, the vertices are:\n"); manifold.print_vertices(); - CHECK(manifold.get_triangulation().check_all_vertices()); + CHECK(manifold.check_vertices()); } } @@ -153,13 +165,7 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) Manifold manifold(causal_vertices, 0, 1); THEN("The vertices are in the manifold.") - { - auto vertices = manifold.get_vertices_span(); - auto require = [&manifold](auto& vertex) { - REQUIRE(manifold.is_vertex(vertex)); - }; - std::ranges::for_each(vertices, require); - } + { REQUIRE(snapshot_vertices_are_owned(manifold, 4)); } THEN("The Delaunay triangulation is valid.") { REQUIRE(manifold.is_valid()); } @@ -180,7 +186,7 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) fmt::print( "When 4 causal vertices are inserted, there is a simplex:\n"); manifold.print_cells(); - CHECK(manifold.get_triangulation().check_all_vertices()); + CHECK(manifold.check_vertices()); } } @@ -194,13 +200,7 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) Manifold manifold(causal_vertices, 0, 1); THEN("The vertices are in the manifold.") - { - auto vertices = manifold.get_vertices_span(); - auto require = [&manifold](auto& vertex_candidate) { - REQUIRE(manifold.is_vertex(vertex_candidate)); - }; - std::ranges::for_each(vertices, require); - } + { REQUIRE(snapshot_vertices_are_owned(manifold, 5)); } THEN("The Delaunay triangulation is valid.") { REQUIRE(manifold.is_valid()); } @@ -221,7 +221,7 @@ SCENARIO("Vertex operations" * doctest::test_suite("vertex")) fmt::print( "When 5 causal vertices are inserted, there are 2 simplices:\n"); manifold.print_cells(); - CHECK(manifold.get_triangulation().check_all_vertices()); + CHECK(manifold.check_vertices()); } } }