diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 30014e719f..f32aef7791 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -220,6 +220,7 @@ target_sources( T8 PRIVATE t8_forest/t8_forest_ghost/t8_forest_ghost_definition_helpers.cxx t8_forest/t8_forest_ghost/t8_forest_ghost_implementations/t8_forest_ghost_definition_face.cxx t8_forest/t8_forest_ghost/t8_forest_ghost_implementations/t8_forest_ghost_definition_w_search.cxx + t8_forest/t8_forest_mesh_quality/t8_forest_aspect_ratio.cxx t8_forest/t8_forest_iterate.cxx t8_forest/t8_forest_balance.cxx t8_forest/t8_forest_subelement.cxx diff --git a/src/t8_forest/t8_forest_mesh_quality/README.md b/src/t8_forest/t8_forest_mesh_quality/README.md new file mode 100644 index 0000000000..6a961d844f --- /dev/null +++ b/src/t8_forest/t8_forest_mesh_quality/README.md @@ -0,0 +1,88 @@ +# src/t8_forest/t8_forest_mesh_quality + +This folder contains functions that measure the quality of the elements of a forest. +The shape of the elements affects how accurate a numerical simulation is and how well the resulting linear systems are conditioned. +It is therefore useful to check a mesh before you use it, for example after it was created by a generator, deformed or adapted. +At the moment, the folder provides the aspect ratio. It works for all element shapes of the default scheme (triangles, quads, tets, hexes, prisms and pyramids), +including hybrid meshes. +The functions are C++ only. The functions that compute global statistics are collective for multiple processes. + +## The aspect ratio + +The aspect ratio (AR) measure how much an element differs from the ideal, regular element of its shape: + +``` +AR = L_max * |∂E| / (d * |E|) / c_E +``` + +Here, `L_max` is the longest edge of the element `E`, `|∂E|` is its perimeter (2D) or surface area (3D), `|E|` is its area (2D) or volume (3D), and `d` is the dimension. For triangles, squares, tetrahedra and cubes, `d * |E| / |∂E|` can also be called the "inradius", so the AR is the longest edge divided by the inradius. +The constant `c_E` is a scalar constant, that differs for each shape. It ensures, that the ideal element has an AR of 1: + +| Shape | Ideal element (AR = 1) | `c_E` | +|----------|--------------------------------------------------|------------------| +| triangle | equilateral triangle | 2√3 | +| quad | square | 2 | +| tet | regular tetrahedron | 2√6 | +| hex | cube | 2 | +| prism | equilateral triangle × interval, all edges equal | 2/3 + 4/√3 | +| pyramid | square base, all edges equal | √2 (1 + √3) | + +The more an element is stretched, flattened or sheared, the larger is its AR. A degenerate element (zero volume) has AR = infinity. +AR >= 1 holds for all shapes except pyramids: a pyramid slightly taller than the ideal pyramid can reach an AR of about 0.9966. +For triangles, flat quads and tetrahedra, the definition is the same as the "aspect ratio" of the Verdict library, which ParaView's "Mesh Quality" filter uses, +so you can compare the values there. +Some tools (e.g. gmsh) report a quality in [0, 1] instead; here this is 1/AR, which the histogram uses. + +A large aspect ratio is not always a mistake. Anisotropic meshes, e.g. boundary layers in flow simulations, contain stretched elements on purpose. If interested, you can look up the paper of Shewchuk below under Literature, as he explains exactly which shapes harm the interpolation error and which harm the conditioning, and how the two differ for anisotropic elements. + +The AR is computed from the corner coordinates of an element. Curved geometries are therefore treated as if the element had straight edges. A warped (non-flat) quad face is approximated by the average of its two splits into triangles. + +### Literature + +- C. J. Stimpson, C. D. Ernst, P. Knupp, P. P. Pébay, D. Thompson: + *The Verdict Geometric Quality Library*, Sandia Report SAND2007-1751, 2007. + [OSTI 901967](https://www.osti.gov/biblio/901967). + Defines the aspect ratio of triangles, quads and tetrahedra that we follow (and many other quality measures). +- P. P. Pébay, T. J. Baker: *Analysis of triangle quality measures*, Mathematics of Computation 72 (2003), + 1817–1839. [doi:10.1090/S0025-5718-03-01485-6](https://doi.org/10.1090/S0025-5718-03-01485-6). + Compares common triangle quality measures and proves their extremal and asymptotic properties. +- J. R. Shewchuk: *What Is a Good Linear Finite Element? Interpolation, Conditioning, Anisotropy, and Quality + Measures*, 2002. [Preprint (PDF)](https://people.eecs.berkeley.edu/~jrs/papers/elemj.pdf). + Explains why element shape matters for finite elements and surveys quality measures. + +## Files + +#### [t8_forest_aspect_ratio.hxx](t8_forest_aspect_ratio.hxx), [t8_forest_aspect_ratio.cxx](t8_forest_aspect_ratio.cxx) + +| Function | Purpose | +|----------|---------| +| `t8_forest_element_aspect_ratio` | AR of a single element. | +| `t8_forest_compute_element_aspect_ratios` | AR of every local leaf element as per element data (one entry per element, in forest order). | +| `t8_forest_compute_aspect_ratio_stats` | Global minimum, maximum, average and a histogram of 1/AR in 10 bins (collective). Optionally from already computed per element data. | +| `t8_forest_average_aspect_ratio`, `t8_forest_max_aspect_ratio` | Shortcuts for the average AR and the AR of the worst element (collective). | +| `t8_forest_print_aspect_ratio` | Prints best, worst and average AR and a gmsh-style histogram on rank 0. | +| `t8_forest_write_vtk_aspect_ratio` | Writes the forest to vtu files with the cell data `aspect_ratio` and `aspect_ratio_quality` (= 1/AR), e.g. for ParaView (collective). | + +The forest does not store the aspect ratios. If you need them several times, compute them once with `t8_forest_compute_element_aspect_ratios` and pass the vector to the statistics and output functions: + +```cpp +#include + +/* Quick overview. */ +t8_forest_print_aspect_ratio (forest); + +/* Compute the aspect ratios once and reuse them. */ +const std::vector aspect_ratios = t8_forest_compute_element_aspect_ratios (forest); +const t8_forest_aspect_ratio_stats stats = t8_forest_compute_aspect_ratio_stats (forest, aspect_ratios); +t8_forest_print_aspect_ratio (stats); +t8_forest_write_vtk_aspect_ratio (forest, "my_forest", aspect_ratios); +``` + +## See also + +- [example/forest/t8_example_aspect_ratio.cxx](../../../example/forest/t8_example_aspect_ratio.cxx): creates meshes with + particularly good and bad elements and writes them to vtu files, to compare with ParaView. +- [test/t8_forest/t8_gtest_aspect_ratio.cxx](../../../test/t8_forest/t8_gtest_aspect_ratio.cxx): tests with + analytically known aspect ratios. +- [mesh_handle/competences/aspect_ratio_competences.hxx](../../../mesh_handle/competences/aspect_ratio_competences.hxx): + the same functionality for the mesh handle. \ No newline at end of file diff --git a/src/t8_forest/t8_forest_mesh_quality/t8_forest_aspect_ratio.cxx b/src/t8_forest/t8_forest_mesh_quality/t8_forest_aspect_ratio.cxx new file mode 100644 index 0000000000..be5b9505f2 --- /dev/null +++ b/src/t8_forest/t8_forest_mesh_quality/t8_forest_aspect_ratio.cxx @@ -0,0 +1,402 @@ +/* + This file is part of t8code. + t8code is a C library to manage a collection (a forest) of multiple + connected adaptive space-trees of general element classes in parallel. + + Copyright (C) 2026 the developers + + t8code is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + t8code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with t8code; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +/** \file t8_forest_aspect_ratio.cxx + * Implementation of the aspect ratio functions declared in \ref t8_forest_aspect_ratio.hxx. + */ + +#include +#include +#include +#include "t8_forest_aspect_ratio.hxx" +#include +#include /* For t8_forest_element_coordinate. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** Compute L_max * |boundary(E)| / (d * |E|) for the ideal element E of a given shape, + * with L_max the longest edge of the ideal element, |boundary(E)| the measure of the element boundary, + * d the spatial dimension, and |E| the measure of the element volume. + * We divide by this value so that the ideal element has an aspect ratio of 1. + * \param [in] shape The shape of the element. Mus be 2D or 3D. + * \return The value for the ideal element of \a shape. + */ +static double +t8_forest_aspect_ratio_ideal_value (const t8_element_shape_t shape) +{ + switch (shape) { + case T8_ECLASS_TRIANGLE: + /* Equilateral triangle with edge length 1: perimeter 3, area sqrt(3)/4. */ + return 2.0 * std::sqrt (3.0); + case T8_ECLASS_QUAD: + /* Unit square: perimeter 4, area 1. */ + return 2.0; + case T8_ECLASS_TET: + /* Regular tetrahedron with edge length 1: surface area sqrt (3), volume 1/(6*sqrt(2)). */ + return 2.0 * std::sqrt (6.0); + case T8_ECLASS_HEX: + /* Unit cube: surface area 6, volume 1. */ + return 2.0; + case T8_ECLASS_PRISM: + /* Prism with all edges of length 1: surface 3 + sqrt(3)/2, volume sqrt(3)/4. */ + return 2.0 / 3.0 + 4.0 / std::sqrt (3.0); + case T8_ECLASS_PYRAMID: + /* Square pyramid with all edges of length 1: surface 1 + sqrt(3), volume 1/(3*sqrt(2)). */ + return std::sqrt (2.0) * (1.0 + std::sqrt (3.0)); + default: + SC_ABORT_NOT_REACHED (); + } + return 0.0; +} + +/** Compute the area of a triangle. + * \param [in] a, b, c The corners of the triangle. + * \return The area of the triangle. + */ +static double +t8_forest_aspect_ratio_triangle_area (const t8_3D_vec &a, const t8_3D_vec &b, const t8_3D_vec &c) +{ + t8_3D_vec ab, ac, cross; + t8_diff (b, a, ab); + t8_diff (c, a, ac); + t8_cross_3D (ab, ac, cross); + return 0.5 * t8_norm (cross); +} + +/** Compute the volume of a tetrahedron. + * \param [in] a, b, c, d The corners of the tetrahedron. + * \return The volume of the tetrahedron. + */ +static double +t8_forest_aspect_ratio_tet_volume (const t8_3D_vec &a, const t8_3D_vec &b, const t8_3D_vec &c, const t8_3D_vec &d) +{ + t8_3D_vec ab, ac, ad, cross; + t8_diff (b, a, ab); + t8_diff (c, a, ac); + t8_diff (d, a, ad); + t8_cross_3D (ab, ac, cross); + return std::fabs (t8_dot (cross, ad)) / 6.0; +} + +/** Compute the histogram bin of an aspect ratio, see \ref t8_forest_aspect_ratio_stats::histogram. + * \param [in] aspect_ratio The aspect ratio. + * \return The bin in [0, T8_FOREST_ASPECT_RATIO_NUM_BINS - 1] that \a aspect_ratio belongs to. + */ +static int +t8_forest_aspect_ratio_bin (const double aspect_ratio) +{ + T8_ASSERT (!std::isnan (aspect_ratio)); + constexpr int num_bins = T8_FOREST_ASPECT_RATIO_NUM_BINS; + /* The quality 1/AR lies in [0, 1] (0 for degenerate elements with AR = infinity). + * It can be slightly above 1 because of rounding errors, or for pyramids (see t8_forest_aspect_ratio.hxx). + * We clamp before casting to int, so that these elements end up in the last bin. + */ + const double scaled_quality = std::clamp (num_bins / aspect_ratio, 0.0, num_bins - 1.0); + return static_cast (scaled_quality); +} + +double +t8_forest_element_aspect_ratio (t8_forest_t forest, t8_locidx_t ltreeid, const t8_element_t *element) +{ + T8_ASSERT (t8_forest_is_committed (forest)); + const t8_eclass_t tree_class = t8_forest_get_tree_class (forest, ltreeid); + const t8_scheme *scheme = t8_forest_get_scheme (forest); + T8_ASSERT (scheme->element_is_valid (tree_class, element)); + + /* The shape of an element can differ from the class of its tree (a pyramid tree also contains tets), so we ask the scheme. */ + const t8_element_shape_t shape = scheme->element_get_shape (tree_class, element); + const int dim = t8_eclass_to_dimension[shape]; + if (dim < 2) { + /* Vertices and lines cannot be distorted. */ + return 1.0; + } + + /* Compute the corner coordinates and the center (mean of the corners) of the element. */ + const int num_corners = scheme->element_get_num_corners (tree_class, element); + T8_ASSERT (0 < num_corners && num_corners <= T8_ECLASS_MAX_CORNERS); + std::array corners; + t8_3D_vec center = { 0.0, 0.0, 0.0 }; + for (int icorner = 0; icorner < num_corners; ++icorner) { + t8_forest_element_coordinate (forest, ltreeid, element, icorner, corners[icorner].data ()); + t8_axpy (corners[icorner], center, 1.0); + } + t8_ax (center, 1.0 / num_corners); + + /* We loop over the faces of the element (the edges in 2D) to compute + * - the length of the longest edge. Every edge of the element lies on a face. + * In 3D each edge lies on two faces and is visited twice, which does not change the maximum. + * - the measure of the boundary (perimeter in 2D, surface area in 3D). + * - the measure of the element (area in 2D, volume in 3D). We decompose the element into + * one triangle (2D) or tetrahedron (3D) per face (quad faces: two tetrahedra) with the center as apex. + * This is exact for convex elements with flat faces. + * We ask the scheme for the corners of each face, since the face numbering can depend on the element type. */ + double longest_edge = 0.0; + double boundary = 0.0; + double measure = 0.0; + const int num_faces = scheme->element_get_num_faces (tree_class, element); + for (int iface = 0; iface < num_faces; ++iface) { + const t8_element_shape_t face_shape = scheme->element_get_face_shape (tree_class, element, iface); + const int num_face_corners = t8_eclass_num_vertices[face_shape]; + T8_ASSERT (num_face_corners <= T8_ECLASS_MAX_CORNERS_2D); + std::array face_corners; + for (int iface_corner = 0; iface_corner < num_face_corners; ++iface_corner) { + face_corners[iface_corner] = scheme->element_get_face_corner (tree_class, element, iface, iface_corner); + T8_ASSERT (0 <= face_corners[iface_corner] && face_corners[iface_corner] < num_corners); + } + + switch (face_shape) { + case T8_ECLASS_LINE: { + /* The faces of a 2D element are its edges. */ + const t8_3D_vec &a = corners[face_corners[0]]; + const t8_3D_vec &b = corners[face_corners[1]]; + const double length = t8_dist (a, b); + longest_edge = std::max (longest_edge, length); + boundary += length; + measure += t8_forest_aspect_ratio_triangle_area (center, a, b); + break; + } + case T8_ECLASS_TRIANGLE: { + const t8_3D_vec &a = corners[face_corners[0]]; + const t8_3D_vec &b = corners[face_corners[1]]; + const t8_3D_vec &c = corners[face_corners[2]]; + longest_edge = std::max ({ longest_edge, t8_dist (a, b), t8_dist (b, c), t8_dist (c, a) }); + boundary += t8_forest_aspect_ratio_triangle_area (a, b, c); + measure += t8_forest_aspect_ratio_tet_volume (center, a, b, c); + break; + } + case T8_ECLASS_QUAD: { + const t8_3D_vec &a = corners[face_corners[0]]; + const t8_3D_vec &b = corners[face_corners[1]]; + const t8_3D_vec &c = corners[face_corners[2]]; + const t8_3D_vec &d = corners[face_corners[3]]; + longest_edge = std::max ({ longest_edge, t8_dist (a, b), t8_dist (b, d), t8_dist (d, c), t8_dist (c, a) }); + const double area_split_ad + = t8_forest_aspect_ratio_triangle_area (a, b, d) + t8_forest_aspect_ratio_triangle_area (a, d, c); + const double area_split_bc + = t8_forest_aspect_ratio_triangle_area (a, b, c) + t8_forest_aspect_ratio_triangle_area (b, d, c); + boundary += 0.5 * (area_split_ad + area_split_bc); + const double volume_split_ad + = t8_forest_aspect_ratio_tet_volume (center, a, b, d) + t8_forest_aspect_ratio_tet_volume (center, a, d, c); + const double volume_split_bc + = t8_forest_aspect_ratio_tet_volume (center, a, b, c) + t8_forest_aspect_ratio_tet_volume (center, b, d, c); + measure += 0.5 * (volume_split_ad + volume_split_bc); + break; + } + default: + SC_ABORT_NOT_REACHED (); + } + } + + if (!(measure > 0.0)) { + /* The element is degenerate (zero area or volume). */ + return std::numeric_limits::infinity (); + } + return longest_edge * boundary / (dim * measure * t8_forest_aspect_ratio_ideal_value (shape)); +} + +std::vector +t8_forest_compute_element_aspect_ratios (t8_forest_t forest) +{ + T8_ASSERT (t8_forest_is_committed (forest)); + std::vector element_aspect_ratios; + element_aspect_ratios.reserve (t8_forest_get_local_num_leaf_elements (forest)); + + /* Loop over the local leaf elements in the order in which they are stored in the forest. */ + const t8_locidx_t num_local_trees = t8_forest_get_num_local_trees (forest); + for (t8_locidx_t itree = 0; itree < num_local_trees; ++itree) { + const t8_locidx_t num_elements_in_tree = t8_forest_get_tree_num_leaf_elements (forest, itree); + for (t8_locidx_t ielement = 0; ielement < num_elements_in_tree; ++ielement) { + const t8_element_t *element = t8_forest_get_leaf_element_in_tree (forest, itree, ielement); + element_aspect_ratios.push_back (t8_forest_element_aspect_ratio (forest, itree, element)); + } + } + T8_ASSERT (element_aspect_ratios.size () == static_cast (t8_forest_get_local_num_leaf_elements (forest))); + return element_aspect_ratios; +} + +t8_forest_aspect_ratio_stats +t8_forest_compute_aspect_ratio_stats (t8_forest_t forest) +{ + return t8_forest_compute_aspect_ratio_stats (forest, t8_forest_compute_element_aspect_ratios (forest)); +} + +t8_forest_aspect_ratio_stats +t8_forest_compute_aspect_ratio_stats (t8_forest_t forest, const std::vector &element_aspect_ratios) +{ + T8_ASSERT (t8_forest_is_committed (forest)); + /* The vector may also contain the values of the ghost elements after the local ones. We ignore them. */ + const size_t num_local_elements = t8_forest_get_local_num_leaf_elements (forest); + SC_CHECK_ABORT (element_aspect_ratios.size () >= num_local_elements, + "There must be one aspect ratio for each local leaf element."); + + /* Compute the statistics of the process local elements. */ + double local_sum = 0.0; + double local_min = std::numeric_limits::infinity (); + double local_max = -std::numeric_limits::infinity (); + std::array local_histogram {}; + for (size_t ielement = 0; ielement < num_local_elements; ++ielement) { + const double aspect_ratio = element_aspect_ratios[ielement]; + local_sum += aspect_ratio; + local_min = std::min (local_min, aspect_ratio); + local_max = std::max (local_max, aspect_ratio); + ++local_histogram[t8_forest_aspect_ratio_bin (aspect_ratio)]; + } + + /* Combine the results of all processes. */ + const sc_MPI_Comm comm = t8_forest_get_mpicomm (forest); + t8_forest_aspect_ratio_stats stats; + double global_sum; + int mpiret = sc_MPI_Allreduce (&local_sum, &global_sum, 1, sc_MPI_DOUBLE, sc_MPI_SUM, comm); + SC_CHECK_MPI (mpiret); + mpiret = sc_MPI_Allreduce (&local_min, &stats.min, 1, sc_MPI_DOUBLE, sc_MPI_MIN, comm); + SC_CHECK_MPI (mpiret); + mpiret = sc_MPI_Allreduce (&local_max, &stats.max, 1, sc_MPI_DOUBLE, sc_MPI_MAX, comm); + SC_CHECK_MPI (mpiret); + mpiret = sc_MPI_Allreduce (local_histogram.data (), stats.histogram.data (), T8_FOREST_ASPECT_RATIO_NUM_BINS, + T8_MPI_GLOIDX, sc_MPI_SUM, comm); + SC_CHECK_MPI (mpiret); + + stats.num_elements = 0; + for (const t8_gloidx_t count : stats.histogram) { + stats.num_elements += count; + } + T8_ASSERT (stats.num_elements == t8_forest_get_global_num_leaf_elements (forest)); + + if (stats.num_elements > 0) { + stats.average = global_sum / stats.num_elements; + } + else { + stats.min = 0.0; + stats.max = 0.0; + stats.average = 0.0; + } + return stats; +} + +double +t8_forest_average_aspect_ratio (t8_forest_t forest) +{ + return t8_forest_compute_aspect_ratio_stats (forest).average; +} + +double +t8_forest_max_aspect_ratio (t8_forest_t forest) +{ + return t8_forest_compute_aspect_ratio_stats (forest).max; +} + +void +t8_forest_print_aspect_ratio (t8_forest_t forest) +{ + t8_forest_print_aspect_ratio (t8_forest_compute_aspect_ratio_stats (forest)); +} + +void +t8_forest_print_aspect_ratio (const t8_forest_aspect_ratio_stats &stats) +{ + constexpr int num_bins = T8_FOREST_ASPECT_RATIO_NUM_BINS; + + t8_global_productionf ("Aspect ratio (AR) of the %" T8_GLOIDX_FORMAT + " leaf elements of the forest (AR = 1 is ideal, larger is worse):\n", + stats.num_elements); + if (stats.num_elements == 0) { + return; + } + t8_global_productionf (" best AR: %.4f\n", stats.min); + t8_global_productionf (" worst AR: %.4f\n", stats.max); + t8_global_productionf (" average AR: %.4f\n", stats.average); + t8_global_productionf (" Distribution of the element quality 1/AR (1 = ideal, 0 = degenerate):\n"); + for (int ibin = 0; ibin < num_bins; ++ibin) { + const double lower = static_cast (ibin) / num_bins; + const double upper = static_cast (ibin + 1) / num_bins; + const char *upper_relation = (ibin == num_bins - 1) ? "<=" : "<"; + + char ar_range[64]; + if (ibin == 0) { + snprintf (ar_range, sizeof (ar_range), "AR > %.2f", 1.0 / upper); + } + else if (ibin == num_bins - 1) { + snprintf (ar_range, sizeof (ar_range), "AR <= %.2f", 1.0 / lower); + } + else { + snprintf (ar_range, sizeof (ar_range), "%.2f < AR <= %.2f", 1.0 / upper, 1.0 / lower); + } + + const double percentage = 100.0 * stats.histogram[ibin] / stats.num_elements; + t8_global_productionf (" %.2f <= 1/AR %s %.2f (%-18s): %10" T8_GLOIDX_FORMAT " elements (%6.2f %%)\n", lower, + upper_relation, upper, ar_range, stats.histogram[ibin], percentage); + } +} + +int +t8_forest_write_vtk_aspect_ratio (t8_forest_t forest, const char *fileprefix) +{ + return t8_forest_write_vtk_aspect_ratio (forest, fileprefix, t8_forest_compute_element_aspect_ratios (forest)); +} + +int +t8_forest_write_vtk_aspect_ratio (t8_forest_t forest, const char *fileprefix, + const std::vector &element_aspect_ratios) +{ + T8_ASSERT (t8_forest_is_committed (forest)); + /* The vector may also contain the values of the ghost elements after the local ones. We ignore them. */ + const size_t num_local_elements = t8_forest_get_local_num_leaf_elements (forest); + SC_CHECK_ABORT (element_aspect_ratios.size () >= num_local_elements, + "There must be one aspect ratio for each local leaf element."); + + /* vtu files cannot store infinity. Like the Verdict library, we write 1e30 for degenerate elements instead. */ + constexpr double max_aspect_ratio = 1e30; + std::vector aspect_ratios (num_local_elements); + std::vector qualities (num_local_elements); + for (size_t ielement = 0; ielement < num_local_elements; ++ielement) { + aspect_ratios[ielement] = std::min (element_aspect_ratios[ielement], max_aspect_ratio); + qualities[ielement] = 1.0 / element_aspect_ratios[ielement]; + } + + /* One scalar per element for each data field. */ + std::array data_fields; + data_fields[0].type = T8_VTK_SCALAR; + snprintf (data_fields[0].description, T8_VTK_MAX_STRING_LENGTH, "aspect_ratio"); + data_fields[0].data = aspect_ratios.data (); + data_fields[1].type = T8_VTK_SCALAR; + snprintf (data_fields[1].description, T8_VTK_MAX_STRING_LENGTH, "aspect_ratio_quality"); + data_fields[1].data = qualities.data (); + + /* Write the same data as t8_forest_write_vtk, plus the two data fields. */ + const int write_treeid = 1; + const int write_mpirank = 1; + const int write_level = 1; + const int write_element_id = 1; + const int write_ghosts = 0; + const int write_curved = 0; + const int do_not_use_API = 0; + return t8_forest_write_vtk_ext (forest, fileprefix, write_treeid, write_mpirank, write_level, write_element_id, + write_ghosts, write_curved, do_not_use_API, static_cast (data_fields.size ()), + data_fields.data ()); +} diff --git a/src/t8_forest/t8_forest_mesh_quality/t8_forest_aspect_ratio.hxx b/src/t8_forest/t8_forest_mesh_quality/t8_forest_aspect_ratio.hxx new file mode 100644 index 0000000000..34421a3e9c --- /dev/null +++ b/src/t8_forest/t8_forest_mesh_quality/t8_forest_aspect_ratio.hxx @@ -0,0 +1,200 @@ +/* + This file is part of t8code. + t8code is a C library to manage a collection (a forest) of multiple + connected adaptive space-trees of general element classes in parallel. + + Copyright (C) 2026 the developers + + t8code is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + t8code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with t8code; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +/** \file t8_forest_aspect_ratio.hxx + * MEasure the aspect ratio of the elements of a forest. + * + * The aspect ratio (AR) measures how much an element differs from the ideal (regular) element shape. + * + * AR = L_ax * |boundary(E)| / (d * |E|) / c_shape, + * + * where L_max is the longest edge of the element E, |boundary(E)| the perimeter (2D) or the surface area (3D), |E| it area (2D) or volume(3D), + * and d the dimension. + * The constant c_shape is chosen so that the ideal element has AR = 1. + * d * |E| / |boundary(E)| is the inradius of triangles, squares, tetrahedra and cubes, so AR is the longest edge divided by the inradius, + * normalized to 1. + * + * Ideal elements (AR = 1): + * - triangle: equilateral triangle, + * - quad: square, + * - tet: regular tetrahedron, + * - hex: cube. + * - prism: right prism over an equilateral triangle whose edges all have the same length, + * - pyramid: square pyramid whose edges all have the same length. + * + * The more distorted (stretched, sheared or flattened) an element is, the larger its AR. + * A degenerate element (zero area/volume) has AR = infinity. + * AR >= 1 holds for triangles, quads, tets, hexes and prisms. Pyramids are an exception: a pyramid that is taller than the ideal one can have AR < 1. + * For straight-sided triangles, flat quads and tetrahedra this is the same definition as the "aspect ratio" of the Verdict library, + * which ParaView's "Mesh Quality" filter uses. Values can therefore be cross-checked there. + * + * Some other tools report a quality only with [0, 1] instead, where 1 is ideal and 0 is degenerate. In this file that is 1/AR, which is what the histogram + * of \ref t8_forest_compute_aspect_ratio_stats and \ref t8_forest_print_aspect_ratio uses. + * + * The aspect ratio is computed from the corner coordinates of the element. + * Curved geometries are therefore treated as if the element had straight edges between the corner points. + * Faces that are not flat (warped quad faces) are approximated by the average of their two possible splits into two triangles. + * + * The forest itself does not store the aspect ratios. \ref t8_forest_compute_element_aspect_ratios + * returns them as per element data: a vector with one entry per process-local leaf element. + * You can pass this vector to the statistics and output functions below to avoid computing the aspect ratios again. + * \ref t8_forest_write_vtk_aspect_ratio writes the forest to vtu files with the aspect ratio as cell data, for visualization in ParaView. + * + * In the hxx, we always declare the functions and implement them in the cxx. + * In some files we also provide a c_interface or .c files. We do not provide them here as we only want + * to ensure that this code is callable from C++ and not also for C. + */ + +#pragma once + +#include +#include +#include +#include + +/** Number of bins of the aspect ratio histogram in \ref t8_forest_aspect_ratio_stats + * The bins divide the quality 1/AR in [0, 1] into equally sized intervals, + * as in gmsh's quality output: 0.0 <= 1/AR <0.1, 0.1 <= 1/AR <0.2, and so on. + */ +inline constexpr int T8_FOREST_ASPECT_RATIO_NUM_BINS = 10; + +/** Statistics of the aspect ratios of all leaf elements of a forest. + * See \ref t8_forest_compute_aspect_ratio_stats. + */ +struct t8_forest_aspect_ratio_stats +{ + t8_gloidx_t num_elements; /**< Global number of leaf elements in the forest. */ + double min; /**< Smallest aspect ratio, i.e. the AR of best element (0 if forest is empty) */ + double max; /**< Largest aspect ratio, i.e. the AR of worst element (0 if forest is empty) */ + double average; /**< Arithmetic mean of the aspect ratios (0 if the forest is empty) */ + /** histogram[i] is the global number of elements whose quality 1/AR lies in + * [i / N, (i + 1) / N)], with N = \ref T8_FOREST_ASPECT_RATIO_NUM_BINS. + * The last bin also contains the elements with 1/AR >= 1 (ideal elements, and pyramids with AR slightly below 1). + * The sum of all bins is \a num_elements. + */ + std::array histogram; +}; + +/** Compute the aspect ratio of a single element. + * See the file description for a definition. Vertices and lines cannot be distorted, so their aspect ratio is 1. + * \param [in] forest The forest. Must be committed. + * \param [in] ltreeid The forest local id of the tree in which the element is. + * \param [in] element The element. + * \return The aspect ratio of \a element. It is 1 for an ideal element an >= 1 for all shapes except pyramids (see the file description). + * Larger values mean a more distorted element. It is infinity for a degenerate element. + */ +double +t8_forest_element_aspect_ratio (t8_forest_t forest, t8_locidx_t ltreeid, const t8_element_t *element); + +/** Compute the aspect ratio of every process-local leaf element of a forest, as per element data. + * Entry i of the result belongs to the i-th local leaf element. The element with index \a ielement in local tree + * \a ltreeid therefore has the index t8_forest_get_tree_element_offset (forest, ltreeid) + ielement. + * This function is not collective. Ghost elements are not included. + * \param [in] forest The forest. Must be committed. + * \return The aspect ratios of the local leaf elements, with t8_forest_get_local_num_leaf_elements (forest) entries. + */ +std::vector +t8_forest_compute_element_aspect_ratios (t8_forest_t forest); + +/** Compute statistics (minimum, maximum, average and a histogram) of the aspect ratios of all leaf elements of a forest. + * This function is collective: it must be called on all processes of the forest's communicator, and every process receives the global result. + * \param [in] forest The forest. Must be committed. + * \return The global aspect ratio statistics of \a forest. + */ +t8_forest_aspect_ratio_stats +t8_forest_compute_aspect_ratio_stats (t8_forest_t forest); + +/** Compute statistics of the aspect ratios of all leaf elements of a forest from already computed per element data. + * Use this instead of the version of \ref t8_forest_compute_aspect_ratio_stats without \a element_aspect_ratios + * if you already computed the aspect ratios with \ref t8_forest_compute_element_aspect_ratios. + * This function is collective. + * \param [in] forest The forest. Must be committed. + * \param [in] element_aspect_ratios The aspect ratios of the local leaf elements of \a forest + * \return The global aspect ratios statistics of \a forest. + */ +t8_forest_aspect_ratio_stats +t8_forest_compute_aspect_ratio_stats (t8_forest_t forest, const std::vector &element_aspect_ratios); + +/** Compute the average aspect ratio of all leaf elements of a forest. + * This function is collective + * \param [in] forest The forest. Must be committed. + * \return The arithmetic mean of the aspect ratios of all leaf elements of \a forest, or 0 if the forest has no elements. + */ +double +t8_forest_average_aspect_ratio (t8_forest_t forest); + +/** Compute the largest aspect ratio of all leaf elements of a forest, i.e. the aspect ratio of the worst element of the mesh. + * This function is collective. + * \param [in] forest The forest. Must be committed. + * \return The maximum aspect ratio of all leaf elements of \a forest, or 0 if the forest has no elements. + */ +double +t8_forest_max_aspect_ratio (t8_forest_t forest); + +/** Print an overview of the aspect ratios of all leaf elements of a forest: + * the best, worst and average aspect ratio, and a gmsh-style histogram that shows + * how many elements (and which percentage) lie in each quality range 1/AR. + * This function is collective. The output is only printed on rank 0. + * \param [in] forest The forest. Must be committed. + */ +void +t8_forest_print_aspect_ratio (t8_forest_t forest); + +/** Print an overview of already computed aspect ratio statistics, like the version of + * \ref t8_forest_print_aspect_ratio that takes a forest. + * The output is only printed on rank 0. This function is not collective, but \a stats is usually the result + * of the collective function \ref t8_forest_compute_aspect_ratio_stats. + * \param [in] stats The statistics to print. + */ +void +t8_forest_print_aspect_ratio (const t8_forest_aspect_ratio_stats &stats); + +/** Write a forest in parallel vtu format, with the aspect ratio of each element as cell data. + * Besides the data that \ref t8_forest_write_vtk writes (tree id, level, MPI rank and element id), + * two cell data fields are written: + * - "aspect_ratio": The aspect ratio AR of the element (1 = ideal, larger is worse). + * - "aspect_ratio_quality": The quality 1/AR (1 = ideal, 0 = degenerate), as in the histogram. + * A degenerate element (AR = infinity) is written with AR = 1e30, as the Verdict library + * (used by ParaView's "Mesh Quality" filter) does, since vtu files cannot store infinity. + * This function is collective. + * \param [in] forest The forest. Must be committed. + * \param [in] fileprefix The prefix of the files. The master file is fileprefix.pvtu, and the process + * with rank r writes the file fileprefix_r.vtu. + * \return True if successful, false if not (process local). + */ +int +t8_forest_write_vtk_aspect_ratio (t8_forest_t forest, const char *fileprefix); + +/** Write a forest in parallel vtu format with already computed aspect ratios as cell data. + * Use this instead of the version of \ref t8_forest_write_vtk_aspect_ratio without + * \a element_aspect_ratios if you already computed the aspect ratios with \ref t8_forest_compute_element_aspect_ratios. + * This function is collective. + * \param [in] forest The forest. Must be committed. + * \param [in] fileprefix The prefix of the files, see \ref t8_forest_write_vtk_aspect_ratio. + * \param [in] element_aspect_ratios The aspect ratios of the local leaf elements of \a forest, + * as returned by \ref t8_forest_compute_element_aspect_ratios. + * Values of ghost elements after the local ones are ignored. + * \return True if successful, false if not (process local). + */ +int +t8_forest_write_vtk_aspect_ratio (t8_forest_t forest, const char *fileprefix, + const std::vector &element_aspect_ratios); diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 540ba9cbba..e79a96a3dc 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -167,6 +167,7 @@ add_t8_cpp_test( NAME t8_gtest_weighted_partitioning_parallel SOURCES t8_for add_t8_cpp_test( NAME t8_gtest_element_is_boundary_parallel SOURCES t8_forest/t8_gtest_element_is_boundary.cxx t8_gtest_adapt_callbacks.cxx ) add_t8_cpp_test( NAME t8_gtest_subelement_parallel SOURCES t8_forest/t8_gtest_subelement.cxx t8_gtest_adapt_callbacks.cxx ) add_t8_cpp_test( NAME t8_gtest_neighbors_of_ghosts_parallel SOURCES t8_forest/t8_gtest_neighbors_of_ghosts.cxx t8_gtest_adapt_callbacks.cxx ) +add_t8_cpp_test( NAME t8_gtest_aspect_ratio_serial SOURCES t8_forest/t8_gtest_aspect_ratio.cxx ) add_t8_cpp_test( NAME t8_gtest_element_is_leaf_parallel SOURCES t8_forest/t8_gtest_element_is_leaf.cxx t8_gtest_adapt_callbacks.cxx ) add_t8_cpp_test( NAME t8_gtest_permute_hole_serial SOURCES t8_forest_incomplete/t8_gtest_permute_hole.cxx ) diff --git a/test/t8_forest/t8_gtest_aspect_ratio.cxx b/test/t8_forest/t8_gtest_aspect_ratio.cxx new file mode 100644 index 0000000000..2841a10d6c --- /dev/null +++ b/test/t8_forest/t8_gtest_aspect_ratio.cxx @@ -0,0 +1,349 @@ +/* + This file is part of t8code. + t8code is a C library to manage a collection (a forest) of multiple + connected adaptive space-trees of general element classes in parallel. + + Copyright (C) 2026 the developers + + t8code is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + t8code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with t8code; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +/** + * \file t8_gtest_aspect_ratio.cxx + * Tests for the mesh quality functions in \ref t8_forest_aspect_ratio.hxx. + * + * Every test builds a forest whose elements have an aspect ratio (AR) that we know analytically, + * and compares the computed aspect ratios and statistics with it. + * The expected values are derived by hand from the definition + * AR = L_max * |boundary(E)| / (d * |E|) / c_shape + * (see \ref t8_forest_aspect_ratio.hxx), not by calling the tested functions. + * + * The tests are: + * - ideal_elements: One tree that is the ideal element of its class. Its aspect ratio must be 1. + * - reference_elements: One tree that is the reference element of its class, uniformly refined. + * Uniform refinement of a reference element only creates scaled copies of it, so all elements of one shape have the same AR. + * - distorted_quads: Rectangles and a parallelogram with known aspect ratios, a rotated square in 3D, + * and the statistics and print function of a forest with difference aspect ratios. + * - stretched_hex: A 4 x 2 x 1 box. + * This is a serial test. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +/** Build a uniformly refined forest with the default scheme and linear geometry. + * \param [in] eclass The class of all trees. + * \param [in] trees_vertices For each tree, the coordinates of its vertices (3 doubles per vertex). + * \param [in] level The uniform refinement level of the forest. + * \return The committed forest. Must be destroyed with \ref t8_forest_unref. + */ +static t8_forest_t +t8_test_forest_from_vertices (const t8_eclass_t eclass, const std::vector> &trees_vertices, + const int level) +{ + const int num_vertices = t8_eclass_num_vertices[eclass]; + t8_cmesh_t cmesh; + t8_cmesh_init (&cmesh); + t8_cmesh_register_geometry (cmesh); + for (size_t itree = 0; itree < trees_vertices.size (); ++itree) { + T8_ASSERT (trees_vertices[itree].size () == static_cast (num_vertices * 3)); + const t8_gloidx_t gtree_id = static_cast (itree); + t8_cmesh_set_tree_class (cmesh, gtree_id, eclass); + t8_cmesh_set_tree_vertices (cmesh, gtree_id, trees_vertices[itree].data (), num_vertices); + } + t8_cmesh_commit (cmesh, sc_MPI_COMM_WORLD); + return t8_forest_new_uniform (cmesh, t8_scheme_new_default (), level, 0, sc_MPI_COMM_WORLD); +} + +/** Compute the histogram bin that an aspect ratio belongs to, as documented for + * \ref t8_forest_aspect_ratio_stats::histogram: bin i holds 1/AR in [i/N, (i+1)/N). + * \param [in] aspect_ratio An aspect ratio >= 1. Should not be close to a bin boundary. + * \return The bin of \a aspect_ratio. + */ +static int +t8_test_histogram_bin (const double aspect_ratio) +{ + const int bin = static_cast (T8_FOREST_ASPECT_RATIO_NUM_BINS / aspect_ratio); + return std::min (bin, T8_FOREST_ASPECT_RATIO_NUM_BINS - 1); +} + +/** Check the aspect ratio of every element of a serial forest and the statistics of the forest. + * \param [in] forest A committed forest whose elements are all on this process. + * \param [in] expected_ar Function (ltreeid, elements_shape) -> expected aspect ratio of an element. + */ +template +static void +t8_test_check_forest (t8_forest_t forest, TExpectedAspectRatio expected_ar) +{ + const t8_scheme *scheme = t8_forest_get_scheme (forest); + double expected_sum = 0.0; + double expected_min = std::numeric_limits::infinity (); + double expected_max = -std::numeric_limits::infinity (); + std::array expected_histogram {}; + + /* Check every element and compute the expected statistics from the expected values. */ + const t8_locidx_t num_local_trees = t8_forest_get_num_local_trees (forest); + for (t8_locidx_t itree = 0; itree < num_local_trees; ++itree) { + const t8_eclass_t tree_class = t8_forest_get_tree_class (forest, itree); + const t8_locidx_t num_elements_in_tree = t8_forest_get_tree_num_leaf_elements (forest, itree); + for (t8_locidx_t ielem = 0; ielem < num_elements_in_tree; ++ielem) { + const t8_element_t *element = t8_forest_get_leaf_element_in_tree (forest, itree, ielem); + const t8_element_shape_t shape = scheme->element_get_shape (tree_class, element); + const double expected = expected_ar (itree, shape); + EXPECT_NEAR (t8_forest_element_aspect_ratio (forest, itree, element), expected, T8_PRECISION_SQRT_EPS) + << "Tree " << itree << ", element " << ielem << ", shape " << t8_eclass_to_string[shape]; + expected_sum += expected; + expected_min = std::min (expected_min, expected); + expected_max = std::max (expected_max, expected); + ++expected_histogram[t8_test_histogram_bin (expected)]; + } + } + + /* Serial test: the local elements are all elements. */ + const t8_gloidx_t num_elements = t8_forest_get_global_num_leaf_elements (forest); + ASSERT_EQ (num_elements, t8_forest_get_local_num_leaf_elements (forest)); + ASSERT_GT (num_elements, 0); + const double expected_average = expected_sum / num_elements; + + const t8_forest_aspect_ratio_stats stats = t8_forest_compute_aspect_ratio_stats (forest); + EXPECT_EQ (stats.num_elements, num_elements); + EXPECT_NEAR (stats.average, expected_average, T8_PRECISION_SQRT_EPS); + EXPECT_NEAR (stats.min, expected_min, T8_PRECISION_SQRT_EPS); + EXPECT_NEAR (stats.max, expected_max, T8_PRECISION_SQRT_EPS); + for (int ibin = 0; ibin < T8_FOREST_ASPECT_RATIO_NUM_BINS; ++ibin) { + EXPECT_EQ (stats.histogram[ibin], expected_histogram[ibin]) << "Histogram bin " << ibin; + } + + EXPECT_NEAR (t8_forest_average_aspect_ratio (forest), expected_average, T8_PRECISION_SQRT_EPS); + EXPECT_NEAR (t8_forest_max_aspect_ratio (forest), expected_max, T8_PRECISION_SQRT_EPS); +} + +/** The vertices of the ideal element of a class, with the same orientation as the reference element. * + * \param [in] eclass An element class. + * \return The coordinates of the vertices (3 doubles per vertex). + */ +static std::vector +t8_test_ideal_vertices (const t8_eclass_t eclass) +{ + const double sqrt3 = std::sqrt (3.0); + switch (eclass) { + case T8_ECLASS_VERTEX: + return { 0.0, 0.0, 0.0 }; + case T8_ECLASS_LINE: + return { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }; + case T8_ECLASS_QUAD: + return { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0 }; + case T8_ECLASS_TRIANGLE: + return { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5, sqrt3 / 2.0, 0.0 }; + case T8_ECLASS_HEX: + return { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, + 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; + case T8_ECLASS_TET: + return { 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; + case T8_ECLASS_PRISM: + return { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5, sqrt3 / 2.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.5, sqrt3 / 2.0, 1.0 }; + case T8_ECLASS_PYRAMID: + return { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.5, 0.5, 1.0 / std::sqrt (2.0) }; + default: + SC_ABORT_NOT_REACHED (); + } + return {}; +} + +struct t8_gtest_aspect_ratio_ideal: public testing::TestWithParam +{ + protected: + void + SetUp () override + { + eclass = GetParam (); + forest = t8_test_forest_from_vertices (eclass, { t8_test_ideal_vertices (eclass) }, 0); + } + void + TearDown () override + { + t8_forest_unref (&forest); + } + t8_eclass_t eclass; + t8_forest_t forest; +}; + +TEST_P (t8_gtest_aspect_ratio_ideal, ideal_elements) +{ + ASSERT_EQ (t8_forest_get_global_num_leaf_elements (forest), 1); + t8_test_check_forest (forest, [] (t8_locidx_t, t8_element_shape_t) { return 1.0; }); +} + +INSTANTIATE_TEST_SUITE_P (t8_gtest_mesh_quality, t8_gtest_aspect_ratio_ideal, AllEclasses, print_eclass); + +/** The aspect ratio of everyelement of a give shape in a uniformly refined reference element. + * \param [in] shape An element shape. + * \return The aspect ratio, computed by hand. + */ +static double +t8_test_reference_aspect_ratio (const t8_element_shape_t shape) +{ + const double sqrt2 = std::sqrt (2.0); + const double sqrt3 = std::sqrt (3.0); + const double sqrt6 = std::sqrt (6.0); + switch (shape) { + case T8_ECLASS_VERTEX: + case T8_ECLASS_LINE: + return 1.0; // Vertices and lines cannot be distorted + case T8_ECLASS_QUAD: + case T8_ECLASS_HEX: + return 1.0; // Squares and cubes cannot be distorted + case T8_ECLASS_TRIANGLE: + return sqrt2 * (2 + sqrt2) / (2 * 0.5) / (2 * sqrt3); + case T8_ECLASS_TET: + return sqrt3 * (1 + sqrt2) / (3 * (1.0 / 6.0)) / (2 * sqrt6); + case T8_ECLASS_PRISM: + return sqrt2 * (3 + sqrt2) / (3 * 0.5) / (2.0 / 3.0 + 4.0 / sqrt3); + case T8_ECLASS_PYRAMID: + return sqrt3 * (2 + sqrt2) / (3 * (1.0 / 3.0)) / (sqrt2 * (1 + sqrt3)); + default: + SC_ABORT_NOT_REACHED (); + } + return 0.0; +} + +struct t8_gtest_aspect_ratio_reference: public testing::TestWithParam> +{ + protected: + void + SetUp () override + { + eclass = std::get<0> (GetParam ()); + level = std::get<1> (GetParam ()); + const int num_vertices = t8_eclass_num_vertices[eclass]; + const std::vector vertices (&t8_element_corner_ref_coords[eclass][0][0], + &t8_element_corner_ref_coords[eclass][0][0] + 3 * num_vertices); + forest = t8_test_forest_from_vertices (eclass, { vertices }, level); + } + void + TearDown () override + { + t8_forest_unref (&forest); + } + t8_eclass_t eclass; + int level; + t8_forest_t forest; +}; + +/** Lambda to print the eclass and the level of a test case. */ +static auto print_eclass_and_level = [] (const testing::TestParamInfo> &info) { + return std::string (t8_eclass_to_string[std::get<0> (info.param)]) + "_level_" + + std::to_string (std::get<1> (info.param)); +}; + +TEST_P (t8_gtest_aspect_ratio_reference, reference_elements) +{ + t8_test_check_forest (forest, + [] (t8_locidx_t, t8_element_shape_t shape) { return t8_test_reference_aspect_ratio (shape); }); +} + +INSTANTIATE_TEST_SUITE_P (t8_gtest_mesh_quality, t8_gtest_aspect_ratio_reference, + testing::Combine (AllEclasses, testing::Range (0, 3)), print_eclass_and_level); + +/** Vertices of a parallelogram in Z-order: origin, origin + a, origin + b, origin + a + b. + * \param [in] origin, a, b The origin and the two edge vectors. + * \return The coordinates of the 4 vertices. + */ +static std::vector +t8_test_parallelogram (const std::array &origin, const std::array &a, + const std::array &b) +{ + std::vector vertices; + for (const double factor_b : { 0.0, 1.0 }) { + for (const double factor_a : { 0.0, 1.0 }) { + for (int dim = 0; dim < 3; ++dim) { + vertices.push_back (origin[dim] + factor_a * a[dim] + factor_b * b[dim]); + } + } + } + return vertices; +} + +TEST (t8_gtest_mesh_quality, distorted_quads) +{ + const double sqrt2 = std::sqrt (2.0); + const double sqrt6 = std::sqrt (6.0); + /* A square with edge length 3 in the plane spanned by the orthonormal vectors + * u = (1, 1, 0) / sqrt(2) and v = (-1, 1, 2) / sqrt(6), i.e. rotated in 3D, scaled and translated. */ + const std::array u = { 3 / sqrt2, 3 / sqrt2, 0 }; + const std::array v = { -3 / sqrt6, 3 / sqrt6, 6 / sqrt6 }; + + /* For a parallelogram with edges a >= b and angle alpha: + * AR = L_max * perimeter / (2 * area) / 2 = a * 2 (a + b) / (4 a b sin (alpha)) = (a + b) / (2 b sin (alpha)). */ + const std::vector> trees_vertices = { + t8_test_parallelogram ({ 1, 2, 3 }, u, v), /* rotated square: AR = 1 */ + t8_test_parallelogram ({ 0, 0, 0 }, { 1, 0, 0 }, { 1 / sqrt2, 1 / sqrt2, 0 }), /* rhombus, 45 deg: AR = sqrt(2) */ + t8_test_parallelogram ({ 0, 0, 0 }, { 2, 0, 0 }, { 0, 1, 0 }), /* 2 x 1 rectangle: AR = 3/2 */ + t8_test_parallelogram ({ 0, 0, 0 }, { 10, 0, 0 }, { 0, 1, 0 }), /* 10 x 1 rectangle: AR = 11/2 */ + }; + const std::array expected_per_tree = { 1.0, sqrt2, 1.5, 5.5 }; + + /* Uniform refinement of a parallelogram creates parallelograms that are similar to it. */ + const int level = 2; + t8_forest_t forest = t8_test_forest_from_vertices (T8_ECLASS_QUAD, trees_vertices, level); + ASSERT_EQ (t8_forest_get_num_local_trees (forest), static_cast (expected_per_tree.size ())); + + t8_test_check_forest (forest, [&] (t8_locidx_t itree, t8_element_shape_t) { return expected_per_tree[itree]; }); + + const t8_forest_aspect_ratio_stats stats = t8_forest_compute_aspect_ratio_stats (forest); + EXPECT_EQ (stats.num_elements, 4 * (1 << (2 * level))); + EXPECT_NEAR (stats.min, 1.0, T8_PRECISION_SQRT_EPS); + EXPECT_NEAR (stats.max, 5.5, T8_PRECISION_SQRT_EPS); + EXPECT_NEAR (stats.average, (1.0 + sqrt2 + 1.5 + 5.5) / 4, T8_PRECISION_SQRT_EPS); + + /* The bins of 1/AR = 1, 0.71, 0.67 and 0.18 are 9, 7, 6 and 1. */ + for (int ibin = 0; ibin < T8_FOREST_ASPECT_RATIO_NUM_BINS; ++ibin) { + const bool is_filled = ibin == 9 || ibin == 7 || ibin == 6 || ibin == 1; + EXPECT_EQ (stats.histogram[ibin], is_filled ? (1 << (2 * level)) : 0) << "Histogram bin " << ibin; + } + + /* Output cannot be checked, but the function should run without errors. */ + t8_forest_print_aspect_ratio (forest); + + t8_forest_unref (&forest); +} + +TEST (t8_gtest_mesh_quality, stretched_hex) +{ + const std::vector> trees_vertices + = { { 0, 0, 0, 4, 0, 0, 0, 2, 0, 4, 2, 0, 0, 0, 1, 4, 0, 1, 0, 2, 1, 4, 2, 1 } }; + t8_forest_t forest = t8_test_forest_from_vertices (T8_ECLASS_HEX, trees_vertices, 1); + t8_test_check_forest (forest, [] (t8_locidx_t, t8_element_shape_t) { return 7.0 / 3.0; }); + t8_forest_unref (&forest); +}