An introductory example

This file contains an introductory example to define and traverse a simple quadrilateral mesh. The code for this example can be found in axom/src/axom/slam/examples/UserDocs.cpp.

A quad mesh with five elements

Fig. 41 An unstructured mesh with eleven vertices (red circles) and five elements (quadrilaterals bounded by black lines)

We first import the unified Slam header, which includes all necessary files for working with Slam:

#include "axom/slam.hpp"

Note

All code in slam is in the axom::slam namespace. For convenience, we add the following namespace declaration to our example to allow us to directly use the slam namespace:

namespace slam = axom::slam;

Type aliases and variables

We begin by defining some type aliases for the Sets, Relations and Maps in our mesh. These type aliases would typically be found in a configuration file or in class header files.

Each Slam type is assembled from policies that describe how it behaves, for example the cardinality and stride of a relation, or the storage backing a map.

This follows Slam’s central design philosophy: the policies name the design choices for the data structure. Spelling out every policy is always available when you need fine control, but the common configurations have named shorthands in axom/slam/Aliases.hpp (Choosing policies and aliases), and we use those aliases throughout this example.

We use the following buffer type for the mesh connectivity data. Slam objects index into their data through a buffer; axom::Array is Slam’s canonical choice, and it is the default storage for the aliases and helpers used below:

  // Slam objects index into buffers of positions.
  // We store that connectivity data in axom::Array, Slam's canonical buffer type.
  using IndexBuffer = axom::Array<PosType>;

Sets

Our mesh is defined in terms of two sets: Vertices and Elements, whose entities are referenced by integer-valued indices. Since both sets use a contiguous range of indices starting from 0, we use slam::PositionSet to represent them.

We define the following type aliases:

  using PosType = slam::DefaultPositionType;
  using ElemType = slam::DefaultElementType;
  using VertSet = slam::PositionSet<PosType, ElemType>;
  using ElemSet = slam::PositionSet<PosType, ElemType>;

and declare them as:

  VertSet verts;  // The set of vertices in the mesh
  ElemSet elems;  // The set of elements in the mesh

For other available set types, see Set.

Relations

We also have relations describing the incidences between the mesh vertices and elements.

The element-to-vertex boundary relation encodes the indices of the vertices in the boundary of each element. Since this is a quad mesh and there are always four vertices in the boundary of a quadrilateral, its cardinality is a compile-time constant. We use the slam::ConstantRelation alias, which names the common configuration of a StaticRelation with a ConstantCardinality policy, a CompileTimeStride (here, 4), and axom::Array storage:

  // Element-to-vertex boundary relation: each quad has exactly four vertices,
  // so the cardinality is a compile-time constant via ConstantRelation.
  enum
  {
    VertsPerElem = 4
  };
  using ElemToVertRelation = slam::ConstantRelation<ElemSet, VertSet, VertsPerElem>;

The vertex-to-element coboundary relation encodes the indices of all elements incident in each of the vertices. Since the cardinality of this relation changes for different vertices, we use the slam::VariableRelation alias, which names a StaticRelation with a VariableCardinality policy and axom::Array storage:

  // Vertex-to-element coboundary relation: the number of incident elements
  // varies per vertex, so we use VariableRelation.
  using VertToElemRelation = slam::VariableRelation<VertSet, ElemSet>;

Note

Each alias has a *View counterpart (ConstantRelationView, VariableRelationView) that refers to buffers managed elsewhere through an axom::ArrayView, rather than axom::Array buffers it manages. When a configuration is not covered by an alias, spell out the StaticRelation policies directly. See Choosing policies and aliases.

We declare them as:

  ElemToVertRelation bdry;    // Boundary relation from elements to vertices
  VertToElemRelation cobdry;  // Coboundary relation from vertices to elements

For other available set types, see Relation.

Maps

Finally, we have some maps that attach data to our sets.

The following defines a type alias for the positions of the mesh vertices. It is templated on a point type (Point2) that handles simple operations on 2D points.

  // A Map attaches a value to each element of a set. With no indirection policy
  // specified, a Map stores its values in an axom::Array it manages itself.
  using VertPositions = slam::Map<Point2, VertSet>;

The map’s values are stored in an axom::Array that the map allocates and frees itself. To instead point a map at a buffer whose lifetime is managed elsewhere (for instance, to view data owned by an application or to pass a map into a device kernel), give it an axom::ArrayView indirection via policies::ArrayViewIndirection.

It is declared as:

  VertPositions position;  // vertex position

Constructing the mesh

This example uses a very simple fixed mesh, which is assumed to not change after it has been initialized.

Sets

The sets are created using a constructor that takes the number of elements.

    verts = VertSet(11);  // Construct vertex set with 11 vertices
    elems = ElemSet(5);   // Construct the element set with 5 elements

The values of the vertex indices range from 0 to verts.size()-1 (and similarly for elems).

Note

All sets, relations and maps in Slam have internal validity checks using the isValid() function:

    SLIC_ASSERT_MSG(verts.isValid(), "Vertex set is not valid.");
    SLIC_ASSERT_MSG(elems.isValid(), "Elment set is not valid.");

Relations

The relations are constructed by binding their associated sets and buffers of connectivity data. We use the slam::make_*_relation helper functions, which deduce the relation type from their arguments (including the axom::Array buffers) and return a ready-to-use relation.

We construct the boundary relation from its two sets (elems as its fromSet and verts as its toSet) and the array of vertex indices:

      // construct boundary relation from elements to vertices
      bdry = slam::make_constant_relation_ct<VertsPerElem>(&elems, &verts, evInds);

The coboundary relation requires an additional array of offsets (begins) to indicate the starting index in the relation for each vertex:

      // construct coboundary relation from vertices to elements
      cobdry = slam::make_variable_relation(&verts, &elems, veBegins, veInds);

Since these are static relations, they refer to data that was constructed elsewhere (the axom::Array buffers, which must outlive the relations). The relations are lightweight views over that data, and no data is copied. To iteratively build relations instead, we would use the DynamicConstantRelation and DynamicVariableRelation classes.

The make_* helpers wrap Slam’s lower-level Builder classes; see Simplifying mesh setup for more details about constructing sets, relations and maps directly.

Maps

We define the positions of the mesh vertices as a Map on the verts set. For this example, we set the first vertex to lie at the origin, and the remaining vertices line within an annulus around the unit circle.

    // construct the position map on the vertices
    position = VertPositions(&verts);

    // first vertex is at origin
    position[0] = Point2(0., 0.);

    // remaining vertices lie within annulus around unit disk
    // in cw order, starting at angleOffset
    constexpr double rInner = 0.8;
    constexpr double rOuter = 1.2;
    constexpr double angleOffset = 0.75;
    const double N = verts.size() - 1;

    for(int i = 1; i < verts.size(); ++i)
    {
      const double angle = -(i - 1) / N * 2 * M_PI + angleOffset;
      const double mag = axom::utilities::random_real(rInner, rOuter);

      position[i] = Point2(mag * std::cos(angle), mag * std::sin(angle));
    }

Traversing the mesh

Now that we’ve constructed the mesh, we can start traversing the mesh connectivity and attaching more fields.

Computing a derived field

Our first traversal loops through the vertices and computes a derived field on the position map. For each vertex, we compute its distance to the origin.

    // Create a Map of scalars over the vertices. As with the position map,
    // this owns its values in an axom::Array (the default indirection).
    slam::Map<double, VertSet> distances(&verts);

    for(int i = 0; i < distances.size(); ++i)  // <-- Map::size()
    {
      auto vID = verts[i];               // <-- Set::operator[]
      const Point2& pt = position[vID];  // <-- Map::operator[]

      distances[i] = std::sqrt(pt[0] * pt[0]  // <-- Map::operator[]
                               + pt[1] * pt[1]);
    }

Computing element centroids

Our next example uses element-to-vertex boundary relation to compute the centroids of each element as the average of its vertex positions.

    // Create a Map of Point2 over the mesh elements
    slam::Map<Point2, ElemSet> centroid(&elems);

    // for each element...
    for(int eID = 0; eID < elems.size(); ++eID)  // <-- Set::size()
    {
      Point2 ctr;

      auto elVerts = bdry[eID];  // <-- Relation::operator[]

      // find average position of incident vertices
      for(int i = 0; i < elVerts.size(); ++i)  // <-- Set::size()
      {
        auto vID = elVerts[i];  // <-- Set::operator[]
        ctr += position[vID];   // <-- Map::operator[]
      }
      ctr /= elVerts.size();  // <-- Set::size())
      centroid[eID] = ctr;    // <-- Map::operator[]
    }

Perhaps the most interesting line here is when we call the relation’s subscript operator (bdry[eID]). This function takes an element index (eID) and returns the set of vertices that are incident in this element. As such, we can use all functions in the Set API on this return type, e.g. size() and the subscript operator.

Outputting mesh to disk

As a final example, we highlight several different ways to iterate through the mesh’s Sets, Relations and Maps as we output the mesh to disk (in the vtk format).

This is a longer example, but the callouts (left-aligned comments of the form // <-- message ) point to different iteration patterns.

    std::ofstream meshfile {"quadMesh.vtk"};

    // write header
    axom::fmt::print(meshfile,
                     "# vtk DataFile Version 3.0\n"
                     "vtk output\n"
                     "ASCII\n"
                     "DATASET UNSTRUCTURED_GRID\n\n"
                     "POINTS {} double\n",
                     verts.size());

    // write positions
    for(auto pos : position)  // <-- Uses range-based for on position map
    {
      axom::fmt::print(meshfile, "{} {} 0\n", pos[0], pos[1]);
    }

    // write elem-to-vert boundary relation
    axom::fmt::print(meshfile, "\nCELLS {} {}", elems.size(), 5 * elems.size());
    for(auto e : elems)  // <-- uses range-based for on element set
    {
      axom::fmt::print(meshfile, "\n4 ");
      for(auto v : bdry[e])  // <-- uses relation's per-element set
      {
        axom::fmt::print(meshfile, "{} ", v);
      }
    }

    // write element types ( 9 == VKT_QUAD )
    axom::fmt::print(meshfile, "\n\nCELL_TYPES {}\n", elems.size());
    for(int i = 0; i < elems.size(); ++i)
    {
      axom::fmt::print(meshfile, "9 ");
    }

    // write element ids
    axom::fmt::print(meshfile,
                     "\n\nCELL_DATA {}\n"
                     "SCALARS cellIds int 1\n"
                     "LOOKUP_TABLE default \n",
                     elems.size());
    for(int i = 0; i < elems.size(); ++i)
    {
      axom::fmt::print(meshfile, "{} ", elems[i]);  // <-- uses size() and operator[] on set
    }

    // write vertex ids
    axom::fmt::print(meshfile,
                     "\n\nPOINT_DATA {}\n"
                     "SCALARS vertIds int 1\n"
                     "LOOKUP_TABLE default \n",
                     verts.size());
    for(int i = 0; i < verts.size(); ++i)
    {
      axom::fmt::print(meshfile, "{} ", verts[i]);
    }
    axom::fmt::print(meshfile, "\n");