diff --git a/src/seissol_matrices/base.py b/src/seissol_matrices/base.py index c22c079..21c44dd 100644 --- a/src/seissol_matrices/base.py +++ b/src/seissol_matrices/base.py @@ -15,21 +15,8 @@ def material_index_last(tensor): def collocate(basis, points): - # takes a basis object, and a points array - # of the form: npoints × dim - # outputs a collocation matrix of the form - # npoints × nbasis - - # as far as the author of these lines is aware, - # this module has no broadcasing functionality yet - # for basis functions. Which is sad. - + """ + The basis functions at the points (points x dim), shape functions x points. + """ assert basis.dim() == points.shape[1] - - nbasis = basis.number_of_basis_functions() - - coll = np.empty((nbasis, points.shape[0])) - for i in range(nbasis): - for j in range(points.shape[0]): - coll[i, j] = basis.eval_basis(points[j, :], i) - return coll + return basis.eval_all(points.T).T diff --git a/src/seissol_matrices/basis_functions.py b/src/seissol_matrices/basis_functions.py index 402d3c8..df71703 100644 --- a/src/seissol_matrices/basis_functions.py +++ b/src/seissol_matrices/basis_functions.py @@ -1,3 +1,4 @@ +import math from abc import ABC import numpy as np import scipy.special as sp_special @@ -71,6 +72,27 @@ def singularity_free_jacobi_polynomial_and_derivatives(n, a, b, x, y): class BasisFunctionGenerator(ABC): + """ + The basis functions of the polynomials of degree order - 1 on the reference + element: the unit interval, the triangle (0, 0), (1, 0), (0, 1), or the + tetrahedron (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1). + + A point x is given by its coordinates x[0], ..., x[dim - 1], each a number or + an array of points; on the interval, by its coordinate itself. + + family: the name a generator of this basis is asked for (see generator) + hierarchical: whether the functions of degree at most m come first, in the + same order for every order; then a polynomial of degree m has nonzero + coefficients in the leading entries alone + orthogonal: whether the functions are orthogonal in L2 on the reference element + orthonormal: whether they are, in addition, of unit norm there + """ + + family = None + hierarchical = False + orthogonal = False + orthonormal = False + def __init__(self, order): self.order = order @@ -88,14 +110,72 @@ def number_of_basis_functions(self, o): def dim(self): pass + def degree(self): + return self.order - 1 + + def eval_all(self, x): + """All basis functions at the points x (dim x points), shape (points, functions).""" + x = _as_points(x, self.dim()) + n = self.number_of_basis_functions() + return np.stack( + [ + np.broadcast_to(self.eval_basis(_coordinates(x), i), x.shape[1:]) + for i in range(n) + ], + axis=-1, + ) + + def eval_diff_all(self, x, k): + """The derivatives d / d_x_k of all basis functions at the points x, shape + (points, functions).""" + x = _as_points(x, self.dim()) + n = self.number_of_basis_functions() + return np.stack( + [ + np.broadcast_to( + self.eval_diff_basis(_coordinates(x), i, k), x.shape[1:] + ) + for i in range(n) + ], + axis=-1, + ) + + +def _as_points(x, dim): + """Points as an array of shape (dim, points), from that shape, from the dim + coordinates of one point, or on the interval from the coordinates of the + points.""" + x = np.asarray(x, dtype=float) + if x.ndim <= 1: + return x.reshape(1, -1) if dim == 1 else x.reshape(dim, 1) + if x.ndim != 2 or x.shape[0] != dim: + raise ValueError(f"points of shape {x.shape}, not ({dim}, points)") + return x + + +def _coordinates(x): + """What eval_basis takes for points of shape (dim, points): the coordinate + itself on the interval, the rows otherwise.""" + return x[0] if x.shape[0] == 1 else x + ################################################################################ class BasisFunctionGenerator1D(BasisFunctionGenerator): + """The shifted Legendre polynomials P_i(2 x - 1) on the unit interval.""" + + family = "dubiner" + hierarchical = True + orthogonal = True + def dim(self): return 1 + def norm_squared(self, i): + """The L2 norm of the i-th function squared.""" + return 1.0 / (2 * i + 1) + def eval_basis(self, x, i): r_num = 2 * x - 1.0 r_den = 1.0 @@ -119,9 +199,20 @@ def number_of_basis_functions(self): class BasisFunctionGenerator2D(BasisFunctionGenerator): + """The Dubiner basis on the triangle, ordered by degree.""" + + family = "dubiner" + hierarchical = True + orthogonal = True + def dim(self): return 2 + def norm_squared(self, i): + """The L2 norm of the i-th function squared.""" + p, q = self.roll_index(i) + return 1.0 / (2 * (2 * p + 1) * (p + q + 1)) + def unroll_index(self, i): n = i[0] + i[1] tri = 0.5 * n * (n + 1) @@ -180,9 +271,20 @@ def number_of_basis_functions(self): class BasisFunctionGenerator3D(BasisFunctionGenerator): + """The Dubiner basis on the tetrahedron, ordered by degree.""" + + family = "dubiner" + hierarchical = True + orthogonal = True + def dim(self): return 3 + def norm_squared(self, i): + """The L2 norm of the i-th function squared.""" + p, q, r = self.roll_index(i) + return 1.0 / (2 * (2 * p + 1) * (p + q + 1) * (2 * p + 2 * q + 2 * r + 3)) + def unroll_index(self, i): n = i[0] + i[1] + i[2] tet = (n * (n + 1) * (n + 2)) / 6.0 @@ -263,3 +365,213 @@ def eval_diff_basis(self, x, i, k): def number_of_basis_functions(self): return self.order * (self.order + 1) * (self.order + 2) // 6 + + +################################################################################ + + +class _Normalized: + """The Dubiner functions divided by their L2 norm on the reference element, + so that they are orthonormal there.""" + + family = "dubiner-normalized" + orthonormal = True + + def _scale(self, i): + return 1.0 / np.sqrt(super().norm_squared(i)) + + def norm_squared(self, i): + return 1.0 + + def eval_basis(self, x, i): + return super().eval_basis(x, i) * self._scale(i) + + def eval_diff_basis(self, x, i, k): + return super().eval_diff_basis(x, i, k) * self._scale(i) + + +class NormalizedDubinerGenerator1D(_Normalized, BasisFunctionGenerator1D): + pass + + +class NormalizedDubinerGenerator2D(_Normalized, BasisFunctionGenerator2D): + pass + + +class NormalizedDubinerGenerator3D(_Normalized, BasisFunctionGenerator3D): + pass + + +################################################################################ + + +def bernstein_indices(degree, dim): + """ + The multi-indices (a_1, ..., a_dim) of the Bernstein polynomials of a degree, + in the order of the basis: a_dim varies slowest and a_1 fastest. The index of + the vertex at the origin, a_0 = degree - a_1 - ... - a_dim, is implied. + + With this order, raising one a_k by one (or lowering a_0) shifts a run of + consecutive indices by a fixed offset. + """ + + def at_most(total, count): + if count == 0: + return [()] + return [ + rest + (last,) + for last in range(total + 1) + for rest in at_most(total - last, count - 1) + ] + + return at_most(degree, dim) + + +def barycentric(x, dim): + """The barycentric coordinates (l_0, ..., l_dim) of the points x on the + reference element, l_k = x[k - 1] for k > 0.""" + if dim == 1: + coordinates = [np.asarray(x, dtype=float)] + else: + coordinates = [np.asarray(x[k], dtype=float) for k in range(dim)] + return [1.0 - sum(coordinates)] + coordinates + + +class BernsteinGenerator(BasisFunctionGenerator): + """ + The Bernstein-Bezier basis of degree order - 1 on the reference element, + + B_a(x) = m! / (a_0! ... a_dim!) l_0^a_0 ... l_dim^a_dim, + + with the barycentric coordinates l of x (see barycentric) and the multi-indices + a of degree m in the order of bernstein_indices. + """ + + family = "bernstein" + + def __init__(self, order, dim): + super().__init__(order) + self._dim = dim + self._indices = bernstein_indices(order - 1, dim) + self._positions = {a: i for i, a in enumerate(self._indices)} + self._lower = None + + def dim(self): + return self._dim + + def number_of_basis_functions(self): + return len(self._indices) + + def multi_index(self, i): + """The full multi-index (a_0, ..., a_dim) of the i-th function.""" + a = self._indices[i] + return (self.degree() - sum(a),) + a + + def index(self, a): + """The position of the function with the full multi-index a in the basis.""" + assert sum(a) == self.degree() + return self._positions[tuple(a[1:])] + + def eval_basis(self, x, i): + a = self.multi_index(i) + coefficient = math.factorial(self.degree()) + for ak in a: + coefficient //= math.factorial(ak) + value = coefficient + for lk, ak in zip(barycentric(x, self._dim), a): + value = value * lk**ak + return value + + def eval_diff_basis(self, x, i, k): + """d / d_x_k B_a = m (B_(a - e_(k+1)) - B_(a - e_0)), with the functions of + degree m - 1 and a negative index standing for zero.""" + m = self.degree() + shape = np.shape(barycentric(x, self._dim)[0]) + if m == 0: + return np.zeros(shape) + a = self.multi_index(i) + if self._lower is None: + self._lower = BernsteinGenerator(self.order - 1, self._dim) + lower = self._lower + value = np.zeros(shape) + for component, sign in ((k + 1, 1.0), (0, -1.0)): + if a[component] > 0: + b = list(a) + b[component] -= 1 + value = value + sign * m * lower.eval_basis(x, lower.index(b)) + return value + + +class BernsteinGenerator1D(BernsteinGenerator): + def __init__(self, order): + super().__init__(order, 1) + + +class BernsteinGenerator2D(BernsteinGenerator): + def __init__(self, order): + super().__init__(order, 2) + + +class BernsteinGenerator3D(BernsteinGenerator): + def __init__(self, order): + super().__init__(order, 3) + + +################################################################################ + +#: The bases a generator can be asked for. +FAMILIES = ("dubiner", "dubiner-normalized", "bernstein") + +_GENERATORS = { + ("dubiner", 1): BasisFunctionGenerator1D, + ("dubiner", 2): BasisFunctionGenerator2D, + ("dubiner", 3): BasisFunctionGenerator3D, + ("dubiner-normalized", 1): NormalizedDubinerGenerator1D, + ("dubiner-normalized", 2): NormalizedDubinerGenerator2D, + ("dubiner-normalized", 3): NormalizedDubinerGenerator3D, + ("bernstein", 1): BernsteinGenerator1D, + ("bernstein", 2): BernsteinGenerator2D, + ("bernstein", 3): BernsteinGenerator3D, +} + + +def generator(family, dim, order): + """The generator of a basis family on the reference element of a dimension, + for polynomials of degree order - 1.""" + if family not in FAMILIES: + raise ValueError(f"unknown basis {family}; known are {', '.join(FAMILIES)}") + if (family, dim) not in _GENERATORS: + raise ValueError(f"no basis on a reference element of dimension {dim}") + return _GENERATORS[(family, dim)](order) + + +def describe(family): + """ + What a consumer of the matrices of a basis may rely on, as plain data: whether + it is hierarchical, orthogonal and orthonormal, the structure of its mass + matrices (identity, diagonal or dense), and the order of its functions. + """ + basis = generator(family, 3, 2) + if basis.orthonormal: + mass = "identity" + elif basis.orthogonal: + mass = "diagonal" + else: + mass = "dense" + if family == "bernstein": + ordering = ( + "multi-indices (a_1, ..., a_dim) of the degree, a_dim slowest and a_1 " + "fastest, a_0 = degree - a_1 - ... - a_dim at the vertex at the origin" + ) + else: + ordering = ( + "by degree; within a degree as BasisFunctionGenerator2D/3D.unroll_index" + ) + return { + "family": family, + "hierarchical": basis.hierarchical, + "orthogonal": basis.orthogonal, + "orthonormal": basis.orthonormal, + "mass": mass, + "ordering": ordering, + } diff --git a/src/seissol_matrices/bernstein_matrices.py b/src/seissol_matrices/bernstein_matrices.py new file mode 100644 index 0000000..9a5de79 --- /dev/null +++ b/src/seissol_matrices/bernstein_matrices.py @@ -0,0 +1,228 @@ +""" +The operators of the Bernstein-Bezier basis (basis_functions.BernsteinGenerator) +in the sparse, exact form a kernel applies them in, instead of the dense +matrices the generic generators give. + +A polynomial of degree m has the coefficients c_a, one per multi-index a of +degree m in the order of basis_functions.bernstein_indices. All entries below are +rational and stated exactly. + +- derivative: d / d_x_k maps degree m to m - 1 with + (D c)_b = m (c_(b + e_(k+1)) - c_(b + e_0)): two entries per row. +- elevation: the same polynomial with the coefficients of degree m, + (E c)_a = sum_i a_i / m c_(a - e_i): up to dim + 1 entries per row. +- trace: the coefficients of a face are the coefficients of the volume whose + index at the opposite vertex is zero, a gather. +- face_permutation: a reparametrisation of a face permutes the coefficients. +- lift: M^-1 rT^T M_face, the map from the coefficients of a face to the cell, + factorises (Chan and Warburton, 2017) as + + L = sum_j l_j S_j (E^m_(m-j))^T L_0, + L_0 = (2m + 3) I + m^2 E^m_(m-1) (E^m_(m-1))^T, + l_j = (-1)^j binom(m, j) / (j + 1), + + with the elevations E on the face, and S_j the scatter of the face + coefficients of degree m - j to the volume coefficients whose index at the + opposite vertex is j. (E^m_(m-j))^T is the chain of single-degree steps + (E^(m-j+1)_(m-j))^T ... (E^m_(m-1))^T. +""" + +import math +from fractions import Fraction + +import numpy as np + +from seissol_matrices import basis_functions, dg_matrices + + +def count(degree, dim): + """The number of polynomials of a degree in dim variables, 0 below degree 0.""" + return math.comb(degree + dim, dim) if degree >= 0 else 0 + + +def _positions(degree, dim): + return {a: i for i, a in enumerate(basis_functions.bernstein_indices(degree, dim))} + + +def _full(tail, degree): + """(a_0, a_1, ..., a_dim) from (a_1, ..., a_dim).""" + return (degree - sum(tail),) + tuple(tail) + + +def _to_array(entries, shape): + matrix = np.zeros(shape) + for (row, column), value in entries.items(): + matrix[row, column] = float(value) + return matrix + + +def derivative_entries(degree, dim, direction): + """The entries {(row, column): value} of the derivative d / d_x_direction from + degree to degree - 1.""" + m = degree + lower = basis_functions.bernstein_indices(m - 1, dim) + upper = _positions(m, dim) + entries = {} + for row, b in enumerate(lower): + raised = list(b) + raised[direction] += 1 + entries[(row, upper[tuple(raised)])] = Fraction(m) + entries[(row, upper[tuple(b)])] = Fraction(-m) + return entries + + +def derivative(degree, dim, direction): + """The derivative d / d_x_direction as a matrix from degree to degree - 1.""" + return _to_array( + derivative_entries(degree, dim, direction), + (count(degree - 1, dim), count(degree, dim)), + ) + + +def elevation_entries(degree, dim): + """The entries of the elevation from degree - 1 to degree.""" + m = degree + lower = _positions(m - 1, dim) + entries = {} + for row, tail in enumerate(basis_functions.bernstein_indices(m, dim)): + a = _full(tail, m) + for i in range(dim + 1): + if a[i] > 0: + b = list(a) + b[i] -= 1 + entries[(row, lower[tuple(b[1:])])] = Fraction(a[i], m) + return entries + + +def elevation(degree, dim): + """The elevation from degree - 1 to degree, as a matrix.""" + return _to_array( + elevation_entries(degree, dim), (count(degree, dim), count(degree - 1, dim)) + ) + + +def _volume_index(face, face_index, degree, level=0, ranks=(0, 1, 2)): + """ + The full volume multi-index of the face multi-index (b_1, b_2) of degree + `degree`, with `level` at the opposite vertex. The face index is in the frame + in which the cell's face has the orientation `ranks` + (dg_matrices.canonical_to_face_parametrisation); (0, 1, 2) is the frame of the + cell's own parametrisation. + """ + b = _full(face_index, degree) + a = [0, 0, 0, 0] + for slot, vertex in enumerate(dg_matrices.face_vertices(face)): + a[vertex] = b[ranks[slot]] + a[dg_matrices.opposite_vertex(face)] = level + return tuple(a) + + +def trace_indices(degree, face, ranks=(0, 1, 2)): + """For every face coefficient (in face order), the volume coefficient it is: + in the cell's parametrisation of the face, or in its canonical frame for the + orientation `ranks`.""" + volume = _positions(degree, 3) + return [ + volume[_volume_index(face, b, degree, 0, ranks)[1:]] + for b in basis_functions.bernstein_indices(degree, 2) + ] + + +def trace(degree, face, ranks=(0, 1, 2)): + """The trace on a face as a matrix of zeros and ones, one per row.""" + indices = trace_indices(degree, face, ranks) + matrix = np.zeros((len(indices), count(degree, 3))) + matrix[np.arange(len(indices)), indices] = 1.0 + return matrix + + +def face_permutation_indices(degree, reparametrisation): + """ + For the face coefficients of f(y) with y = face_to_face_parametrisation(x, + reparametrisation), as a function of x: the coefficient of f each one is. + """ + corners = np.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) + mapped = dg_matrices.face_to_face_parametrisation(corners, reparametrisation) + reference = corners.T + # the corner of the face y lands on for each corner x + image = [ + int(np.argmin(np.linalg.norm(reference - mapped[:, s], axis=1))) + for s in range(3) + ] + positions = _positions(degree, 2) + indices = [] + for tail in basis_functions.bernstein_indices(degree, 2): + a = _full(tail, degree) + # the barycentric coordinate of y at corner image[s] is the one of x at s + b = [0, 0, 0] + for s in range(3): + b[image[s]] = a[s] + indices.append(positions[tuple(b[1:])]) + return indices + + +def face_permutation(degree, reparametrisation): + indices = face_permutation_indices(degree, reparametrisation) + matrix = np.zeros((len(indices), len(indices))) + matrix[np.arange(len(indices)), indices] = 1.0 + return matrix + + +def lift_coefficients(degree): + """l_j = (-1)^j binom(m, j) / (j + 1) for the levels j = 0, ..., m.""" + m = degree + return [Fraction((-1) ** j * math.comb(m, j), j + 1) for j in range(m + 1)] + + +def lift_face_entries(degree): + """The entries of L_0 = (2m + 3) I + m^2 E E^T on the face.""" + m = degree + n = count(m, 2) + entries = {(i, i): Fraction(2 * m + 3) for i in range(n)} + if m > 0: + E = elevation_entries(m, 2) + columns = {} + for (row, column), value in E.items(): + columns.setdefault(column, []).append((row, value)) + for terms in columns.values(): + for row_a, value_a in terms: + for row_b, value_b in terms: + key = (row_a, row_b) + entries[key] = entries.get(key, 0) + m * m * value_a * value_b + return entries + + +def lift_face(degree): + n = count(degree, 2) + return _to_array(lift_face_entries(degree), (n, n)) + + +def lift_scatter_indices(degree, face, level, ranks=(0, 1, 2)): + """For every face coefficient of degree m - level, the volume coefficient of + degree m with index `level` at the opposite vertex that it lands on, for face + coefficients in the frame of the orientation `ranks`.""" + m = degree + volume = _positions(m, 3) + return [ + volume[_volume_index(face, b, m - level, level, ranks)[1:]] + for b in basis_functions.bernstein_indices(m - level, 2) + ] + + +def lift(degree, face, ranks=(0, 1, 2)): + """ + The lift M^-1 rT^T M_face as a dense matrix, assembled from its factors, for + face coefficients in the frame of the orientation `ranks`. L_0 and the + elevations commute with the permutations of a face, so a frame changes the + scatters alone. + """ + m = degree + L0 = lift_face(m) + result = np.zeros((count(m, 3), count(m, 2))) + chain = L0 + for level, scale in enumerate(lift_coefficients(m)): + if level > 0: + chain = elevation(m - level + 1, 2).T @ chain + indices = lift_scatter_indices(m, face, level, ranks) + result[indices, :] += float(scale) * chain + return result diff --git a/src/seissol_matrices/dg_matrices.py b/src/seissol_matrices/dg_matrices.py index a976bdd..18c583d 100644 --- a/src/seissol_matrices/dg_matrices.py +++ b/src/seissol_matrices/dg_matrices.py @@ -1,3 +1,5 @@ +import itertools + import numpy as np import quad_rules.WitherdenVincentTri import quad_rules.WitherdenVincentTet @@ -5,26 +7,139 @@ import quad_rules.GaussJacobi import quad_rules.Quadrature -import itertools from seissol_matrices import base from seissol_matrices import basis_functions +#: An integral at most this much of the largest one of its form vanishes. The +#: quadrature leaves rounding of a few 1e-16 of the largest entry where an +#: integral is zero, while the smallest integral that is not, at order 8, is +#: about 3e-9 of it. +ZERO_TOLERANCE = 1e-12 + + +def snap_zeros(tensor, tolerance=ZERO_TOLERANCE): + """The tensor with every entry of at most `tolerance` times its largest + entry set to zero.""" + magnitude = np.abs(tensor) + largest = magnitude.max() if magnitude.size > 0 else 0.0 + return np.where(magnitude > tolerance * largest, tensor, 0.0) + + +def face_to_face_parametrisation(x, side): + # implement Dumbser & Käser, 2006 Table 2 b) + # chi = x[0,:] + # tau = x[1,:] + # y[0,:] = chi ~ + # y[1,:] = tau ~ + y = np.zeros((x.shape[0], x.shape[1])) + if side == 0: + y[0, :] = x[1, :] + y[1, :] = x[0, :] + elif side == 1: + y[0, :] = 1 - x[0, :] - x[1, :] + y[1, :] = x[1, :] + elif side == 2: + y[0, :] = x[0, :] + y[1, :] = 1 - x[0, :] - x[1, :] + return y + + +def volume_to_face_parametrisation(x, side): + # implement Dumbser & Käser, 2006 Table 2 a) + # chi = x[0,:] + # tau = x[1,:] + # y[0,:] = xi(j) + # y[1,:] = eta(j) + # y[2,:] = zeta(j) + y = np.zeros((x.shape[0] + 1, x.shape[1])) + if side == 0: + y[0, :] = x[1, :] + y[1, :] = x[0, :] + elif side == 1: + y[0, :] = x[0, :] + y[2, :] = x[1, :] + elif side == 2: + y[1, :] = x[1, :] + y[2, :] = x[0, :] + elif side == 3: + y[0, :] = 1 - x[0, :] - x[1, :] + y[1, :] = x[0, :] + y[2, :] = x[1, :] + return y + + +def face_vertices(face): + """The vertices of the tetrahedron at the points (0, 0), (1, 0), (0, 1) of a + face, as volume_to_face_parametrisation places the face.""" + corners = np.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) + points = volume_to_face_parametrisation(corners, face) + vertices = np.vstack([np.zeros(3), np.eye(3)]) + return tuple( + int(np.argmin(np.linalg.norm(vertices - points[:, s], axis=1))) + for s in range(3) + ) + + +def opposite_vertex(face): + """The vertex of the tetrahedron not on a face.""" + return ({0, 1, 2, 3} - set(face_vertices(face))).pop() + + +#: The orientations a face can have against its canonical frame, see +#: canonical_to_face_parametrisation. +FACE_ORIENTATIONS = tuple(itertools.permutations(range(3))) + + +def canonical_to_face_parametrisation(x, ranks): + """ + A point x (2 x points) of a face in its canonical frame, in the coordinates of + the face as a cell parametrises it (volume_to_face_parametrisation). + + The canonical frame of a face places the vertex with the smallest global ID at + (0, 0), the next one at (1, 0) and the largest at (0, 1), so that both cells of + the face see it alike. `ranks` is the orientation of the cell's face against + it (one of FACE_ORIENTATIONS): the rank, among the three vertices of the face + ordered by global ID, of the vertex the cell has at (0, 0), (1, 0), (0, 1). + """ + canonical = [1.0 - x[0] - x[1], x[0], x[1]] + local = [canonical[rank] for rank in ranks] + return np.stack([local[1], local[2]]) + + +def sorted_vertex_ranks(face): + """The orientation of a face of a cell whose local vertices are ordered by + their global IDs.""" + vertices = face_vertices(face) + ordered = sorted(vertices) + return tuple(ordered.index(vertex) for vertex in vertices) + + ### Generates matrices which are of general interest for DG methods: ### Mass and Stiffness matrices ### kDivM and kDivMT which are SeisSol specific class dg_generator: - def __init__(self, o, d): + """ + The matrices of the DG scheme on the reference tetrahedron (d = 3), triangle + (d = 2) or interval (d = 1), for polynomials of degree o - 1 in the basis + `family` (see basis_functions.FAMILIES). + """ + + def __init__(self, o, d, family="dubiner"): self.order = o self.dim = d + self.family = family self.M = None self.K = self.dim * [None] + self.generator_finder = lambda order: basis_functions.generator( + family, self.dim, order + ) + self.generator = self.generator_finder(self.order) if self.dim == 3: - self.generator = basis_functions.BasisFunctionGenerator3D(self.order) self.geometry = np.array( [ [0.0, 0.0, 0.0], @@ -33,27 +148,20 @@ def __init__(self, o, d): [0.0, 0.0, 1.0], ] ) - self.face_generator = dg_generator(o, 2) + self.face_generator = dg_generator(o, 2, family) self.quadrule_finder = ( quad_rules.JaskowiecSukumar.JaskowiecSukumar().find_best_rule ) - self.generator_finder = basis_functions.BasisFunctionGenerator3D elif self.dim == 2: - self.generator = basis_functions.BasisFunctionGenerator2D(self.order) self.geometry = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]) self.quadrule_finder = ( quad_rules.WitherdenVincentTri.WitherdenVincentTri().find_best_rule ) - self.generator_finder = basis_functions.BasisFunctionGenerator2D - elif self.dim == 1: - self.generator = basis_functions.BasisFunctionGenerator1D(self.order) + else: self.geometry = np.array([[0.0], [1.0]]) self.quadrule_finder = quad_rules.GaussJacobi.GaussJacobi( 0, 0 ).find_best_rule - self.generator_finder = basis_functions.BasisFunctionGenerator1D - else: - raise Execption("Can only generate 1D, 2D or 2D basis functions") self.nodes, self.weights = self.get_quadrature_rule(2 * self.order) @@ -81,10 +189,6 @@ def multilinear_form(self, face, der, order=None, dim=None, side=None): otherwise the respective face side. If an entry is None, then we assume the respective volume term. """ - # NOTE: we could extract the multiplication/quadrature part from the function selection part. - # I.e., eval_functions (or a list of basis functions here) could be given as an input parameter, - # instead of the two current ones. - # we only support a first derivative at the moment assert np.all([d in (None, *(i for i in range(self.dim))) for d in der]) @@ -100,52 +204,43 @@ def multilinear_form(self, face, der, order=None, dim=None, side=None): assert len(order) == len(der) assert len(side) == len(der) - def get_basis_function(o, d, s, r): + def values(o, d, s, r, points): + # the basis (or its derivative) of order o and dimension r at the + # points, (points, functions), through the parametrisation a side asks for if r == 3: basis = self.generator_finder(o) else: basis = self.face_generator.generator_finder(o) - basiseval_pre = ( - basis.eval_basis - if d is None - else lambda x, i: basis.eval_diff_basis(x, i, d) - ) if face: if r == 3: - basiseval = lambda x, i: basiseval_pre( - self.volume_to_face_parametrisation(x, s), i - ) - else: - if s is None: - basiseval = basiseval_pre - else: - basiseval = lambda x, i: basiseval_pre( - self.face_to_face_parametrisation(x, s), i - ) + points = self.volume_to_face_parametrisation(points, s) + elif s is not None: + points = self.face_to_face_parametrisation(points, s) else: # volume * face does not make sense when evaluating on the whole volume assert r == 3 - basiseval = basiseval_pre - return basiseval, basis.number_of_basis_functions() - - basis_functions = [ - get_basis_function(o, d, s, r) for o, d, s, r in zip(order, der, side, dim) - ] + if d is None: + return basis.eval_all(points) + return basis.eval_diff_all(points, d) if face: nodes, weights = self.face_generator.get_quadrature_rule(np.sum(order)) else: nodes, weights = self.get_quadrature_rule(np.sum(order)) + points = nodes.T - sizes = [bn for _, bn in basis_functions] - tensor = np.empty(sizes) - generic_eval_basis = lambda x, index: np.prod( - [basis_functions[k][0](x, i) for k, i in enumerate(index)], axis=0 - ) - for index in itertools.product(*[range(size) for size in sizes]): - eval_basis = lambda x: generic_eval_basis(x, index) - tensor[index] = quad_rules.Quadrature.quad(nodes, weights, eval_basis) - return tensor + factors = [ + values(o, d, s, r, points) for o, d, s, r in zip(order, der, side, dim) + ] + letters = "abcdefghijklmnop"[: len(factors)] + subscripts = "q," + ",".join(f"q{a}" for a in letters) + "->" + letters + return snap_zeros(np.einsum(subscripts, weights, *factors, optimize=True)) + + def basis_integrals(self): + """The integrals of the basis functions over the reference element. In an + orthogonal basis whose first function is constant they vanish but for the + first one; in other bases every coefficient adds to the mean of the cell.""" + return self.multilinear_form(False, [None], order=[self.order]) def mass_matrix(self): if not np.any(self.M == None): @@ -190,22 +285,7 @@ def kDivMT(self, dim, matorder=None): return base.material_index_last(np.linalg.solve(mass, sT)) def face_to_face_parametrisation(self, x, side): - # implement Dumbser & Käser, 2006 Table 2 b) - # chi = x[0,:] - # tau = x[1,:] - # y[0,:] = chi ~ - # y[1,:] = tau ~ - y = np.zeros((x.shape[0], x.shape[1])) - if side == 0: - y[0, :] = x[1, :] - y[1, :] = x[0, :] - elif side == 1: - y[0, :] = 1 - x[0, :] - x[1, :] - y[1, :] = x[1, :] - elif side == 2: - y[0, :] = x[0, :] - y[1, :] = 1 - x[0, :] - x[1, :] - return y + return face_to_face_parametrisation(x, side) def face_times_face_mass_matrix(self, side): assert self.dim == 3 @@ -215,27 +295,7 @@ def fP(self, side): return self.face_times_face_mass_matrix(side) def volume_to_face_parametrisation(self, x, side): - # implement Dumbser & Käser, 2006 Table 2 a) - # chi = x[0,:] - # tau = x[1,:] - # y[0,:] = xi(j) - # y[1,:] = eta(j) - # y[2,:] = zeta(j) - y = np.zeros((x.shape[0] + 1, x.shape[1])) - if side == 0: - y[0, :] = x[1, :] - y[1, :] = x[0, :] - elif side == 1: - y[0, :] = x[0, :] - y[2, :] = x[1, :] - elif side == 2: - y[1, :] = x[1, :] - y[2, :] = x[0, :] - elif side == 3: - y[0, :] = 1 - x[0, :] - x[1, :] - y[1, :] = x[0, :] - y[2, :] = x[1, :] - return y + return volume_to_face_parametrisation(x, side) def volume_times_face_mass_matrix(self, side): assert self.dim == 3 @@ -249,6 +309,27 @@ def rT(self, side): mass = self.face_generator.mass_matrix() return np.linalg.solve(mass, matrix) + def canonical_rT(self, face, ranks): + """ + The trace on a face in the face basis of its canonical frame: the same + coefficients from both cells of the face, whatever their numbering + (see canonical_to_face_parametrisation). A cell whose face has the + orientation `ranks` reads its trace there with this matrix. + """ + assert self.dim == 3 + nodes, weights = self.face_generator.get_quadrature_rule(2 * self.order) + x = nodes.T + local = canonical_to_face_parametrisation(x, ranks) + volume = self.generator.eval_all(volume_to_face_parametrisation(local, face)) + face_values = self.face_generator.generator.eval_all(x) + moments = (face_values * weights[:, None]).T @ volume + return np.linalg.solve(self.face_generator.mass_matrix(), moments) + + def canonical_rDivM(self, face, ranks): + """M^-1 canonical_rT^T, which takes what a flux gives in the canonical frame + of a face back into the cell, as rDivM does from the cell's own frame.""" + return np.linalg.solve(self.mass_matrix(), self.canonical_rT(face, ranks).T) + def rDivM(self, side, matorder=None): assert self.dim == 3 mass = self.mass_matrix() @@ -256,11 +337,12 @@ def rDivM(self, side, matorder=None): matrix = self.rT(side).T return np.linalg.solve(mass, matrix) + # the material is a field of the cell, read on the face like the basis prematrix = self.multilinear_form( True, [None, None, None], order=[matorder, self.order, self.order], - side=[None, None, side], + side=[side, None, side], dim=[3, 2, 3], ) facemass = self.face_generator.mass_matrix() @@ -278,6 +360,21 @@ def collocate_face(self, points, side): return base.collocate(self.generator, projected) +def basis_change(order, dim, source, target): + """ + The matrix T with c_target = T c_source for the same polynomial of degree + order - 1 on the reference element of the dimension, in the basis families + source and target: M_target^-1 int phi_target phi_source. + """ + generator = dg_generator(order, dim, target) + nodes, weights = generator.get_quadrature_rule(2 * order) + points = nodes.T + phi_target = generator.generator.eval_all(points) + phi_source = basis_functions.generator(source, dim, order).eval_all(points) + moments = (phi_target * weights[:, None]).T @ phi_source + return np.linalg.solve(generator.mass_matrix(), moments) + + if __name__ == "__main__": from seissol_matrices import json_io diff --git a/src/seissol_matrices/dr_matrices.py b/src/seissol_matrices/dr_matrices.py index bb5ac79..46e2df1 100755 --- a/src/seissol_matrices/dr_matrices.py +++ b/src/seissol_matrices/dr_matrices.py @@ -7,69 +7,70 @@ from seissol_matrices import quad_points +def fault_points(a, b, points): + """ + The points (shape points x 2) of a fault face in the coordinates of the + tetrahedron, shape 3 x points: on its side a, with the face parametrised as + the cell sees it (b = 0) or as its neighbour does with the orientation b - 1 + (see dg_matrices.dg_generator.face_to_face_parametrisation). + """ + p0 = points[:, 0] + p1 = points[:, 1] + p2 = 1.0 - p0 - p1 + zero = np.zeros_like(p0) + table = { + (0, 0): (p1, p0, zero), + (0, 1): (p0, p1, zero), + (0, 2): (p1, p2, zero), + (0, 3): (p2, p0, zero), + (1, 0): (p0, zero, p1), + (1, 1): (p1, zero, p0), + (1, 2): (p2, zero, p1), + (1, 3): (p0, zero, p2), + (2, 0): (zero, p1, p0), + (2, 1): (zero, p0, p1), + (2, 2): (zero, p1, p2), + (2, 3): (zero, p2, p0), + (3, 0): (p2, p0, p1), + (3, 1): (p2, p1, p0), + (3, 2): (p0, p2, p1), + (3, 3): (p1, p0, p2), + } + return np.stack(table[(a, b)]) + + class dr_generator: - def __init__(self, o, q): + """ + The matrices of a fault face for the quadrature rule q, in the basis `family`. + + A cell reads its field at the points of the fault either from the volume + (V3mTo2n, for its side a and the orientation b of the face) or from its trace: + with the trace in the canonical frame of the face + (dg_matrices.dg_generator.canonical_rT) and the points given in that frame, + V2mTo2Quad reads the trace at the points for both sides alike, and the fault's + flux goes back through V2QuadTo2m and the canonical lift + (canonical_rDivM M_face, or bernstein_matrices.lift). In a basis that is not + hierarchical, the time derivatives of the predictor have lower degrees and + their traces are read with V2mTo2Quad of that degree. + """ + + def __init__(self, o, q, family="dubiner"): self.order = o self.quadrule = q - self.bf3_generator = basis_functions.BasisFunctionGenerator3D(self.order) - self.bf2_generator = basis_functions.BasisFunctionGenerator2D(self.order) - self.dg3_generator = dg_matrices.dg_generator(self.order, 3) - self.dg2_generator = dg_matrices.dg_generator(self.order, 2) + self.family = family + self.bf3_generator = basis_functions.generator(family, 3, self.order) + self.bf2_generator = basis_functions.generator(family, 2, self.order) + self.dg3_generator = dg_matrices.dg_generator(self.order, 3, family) + self.dg2_generator = dg_matrices.dg_generator(self.order, 2, family) def V3mTo2n(self, a, b, matorder=None): - m = self.bf3_generator.number_of_basis_functions() - points = self.quadrule.points() - n = points.shape[0] - + points = fault_points(a, b, self.quadrule.points()) + values = self.bf3_generator.eval_all(points) if matorder is None: - evalfun = lambda q, j, k: self.bf3_generator.eval_basis(q, j) - materialdim = 1 - else: - materialbasis = basis_functions.BasisFunctionGenerator3D(matorder) - evalfun = lambda q, j, k: self.bf3_generator.eval_basis( - q, j - ) * materialbasis.eval_basis(q, k) - materialdim = materialbasis.number_of_basis_functions() - - matrix = np.zeros((materialdim, n, m)) - for i, p in enumerate(points): - for j in range(m): - for k in range(materialdim): - if a == 0 and b == 0: - matrix[k, i, j] = evalfun([p[1], p[0], 0], j, k) - if a == 0 and b == 1: - matrix[k, i, j] = evalfun([p[0], p[1], 0], j, k) - if a == 0 and b == 2: - matrix[k, i, j] = evalfun([p[1], 1 - p[0] - p[1], 0], j, k) - if a == 0 and b == 3: - matrix[k, i, j] = evalfun([1 - p[0] - p[1], p[0], 0], j, k) - if a == 1 and b == 0: - matrix[k, i, j] = evalfun([p[0], 0, p[1]], j, k) - if a == 1 and b == 1: - matrix[k, i, j] = evalfun([p[1], 0, p[0]], j, k) - if a == 1 and b == 2: - matrix[k, i, j] = evalfun([1 - p[0] - p[1], 0, p[1]], j, k) - if a == 1 and b == 3: - matrix[k, i, j] = evalfun([p[0], 0, 1 - p[0] - p[1]], j, k) - if a == 2 and b == 0: - matrix[k, i, j] = evalfun([0, p[1], p[0]], j, k) - if a == 2 and b == 1: - matrix[k, i, j] = evalfun([0, p[0], p[1]], j, k) - if a == 2 and b == 2: - matrix[k, i, j] = evalfun([0, p[1], 1 - p[0] - p[1]], j, k) - if a == 2 and b == 3: - matrix[k, i, j] = evalfun([0, 1 - p[0] - p[1], p[0]], j, k) - if a == 3 and b == 0: - matrix[k, i, j] = evalfun([1 - p[0] - p[1], p[0], p[1]], j, k) - if a == 3 and b == 1: - matrix[k, i, j] = evalfun([1 - p[0] - p[1], p[1], p[0]], j, k) - if a == 3 and b == 2: - matrix[k, i, j] = evalfun([p[0], 1 - p[0] - p[1], p[1]], j, k) - if a == 3 and b == 3: - matrix[k, i, j] = evalfun([p[1], p[0], 1 - p[0] - p[1]], j, k) - if matorder is None: - matrix = np.squeeze(matrix) - return matrix + return values + materialbasis = basis_functions.generator(self.family, 3, matorder) + material = materialbasis.eval_all(points) + return np.einsum("ij,ik->kij", values, material) def V3mTo2nTWDivM(self, a, b, matorder=None): matrix = self.V3mTo2n(a, b, matorder) @@ -95,33 +96,19 @@ def quadweights(self): return weights def V2QuadTo2m(self): - n = self.bf2_generator.number_of_basis_functions() points = self.quadrule.points() weights = self.quadrule.weights() - m = weights.shape[0] - - E = np.zeros((n, m)) - for i in range(n): - for j, p in enumerate(points): - E[i, j] = self.bf2_generator.eval_basis(p, i) * weights[j] - + E = self.bf2_generator.eval_all(points.T).T * weights[None, :] mass = self.dg2_generator.mass_matrix() - - V = np.linalg.solve(mass, E) - - return V - - def V2mTo2Quad(self): - n = self.bf2_generator.number_of_basis_functions() - points = self.quadrule.points() - m = points.shape[0] - - E = np.zeros((m, n)) - for i in range(n): - for j, p in enumerate(points): - E[j, i] = self.bf2_generator.eval_basis(p, i) - - return E + return np.linalg.solve(mass, E) + + def V2mTo2Quad(self, degree=None): + """The face basis of the scheme, or of `degree`, at the points of the fault, + shape (points, face basis functions).""" + basis = self.bf2_generator + if degree is not None: + basis = basis_functions.generator(self.family, 2, degree + 1) + return basis.eval_all(self.quadrule.points().T) def resample(self): return self.V2mTo2Quad() @ self.V2QuadTo2m() diff --git a/src/seissol_matrices/energy.py b/src/seissol_matrices/energy.py index de8e9e2..6450a74 100755 --- a/src/seissol_matrices/energy.py +++ b/src/seissol_matrices/energy.py @@ -1,24 +1,13 @@ #!/bin/env python3 -import numpy as np from seissol_matrices import basis_functions, quad_points, xml_io import json import sys -def generate_V2mTo2n(order, quadrule): - bf2_generator = basis_functions.BasisFunctionGenerator2D(order) - m = bf2_generator.number_of_basis_functions() - - points = quadrule.points() - - n = points.shape[0] - matrix = np.zeros((n, m)) - for i, p in enumerate(points): - for j in range(m): - matrix[i, j] = bf2_generator.eval_basis([p[0], p[1]], j) - - return matrix +def generate_V2mTo2n(order, quadrule, family="dubiner"): + bf2_generator = basis_functions.generator(family, 2, order) + return bf2_generator.eval_all(quadrule.points().T) def main(): diff --git a/src/seissol_matrices/face_quadrature.py b/src/seissol_matrices/face_quadrature.py index a6eb349..1959dc2 100644 --- a/src/seissol_matrices/face_quadrature.py +++ b/src/seissol_matrices/face_quadrature.py @@ -2,7 +2,6 @@ import os -import numpy as np from seissol_matrices import basis_functions, dg_matrices, json_io, quad_points @@ -19,9 +18,10 @@ class FaceQuadratureGenerator: sharing a face see the same points, only numbered differently. """ - def __init__(self, order): - self.bf2_generator = basis_functions.BasisFunctionGenerator2D(order) - self.dg3_generator = dg_matrices.dg_generator(order, d=3) + def __init__(self, order, family="dubiner"): + self.family = family + self.bf2_generator = basis_functions.generator(family, 2, order) + self.dg3_generator = dg_matrices.dg_generator(order, d=3, family=family) rule = quad_points.symmetric(2 * (order - 1)) self.points = rule.points() @@ -29,14 +29,14 @@ def __init__(self, order): self.vandermonde = self.generate_V2mToFaceQuad() self.rTs = [self.dg3_generator.rT(faceid) for faceid in range(4)] - def generate_V2mToFaceQuad(self): - """The face basis functions at the points, shape (points, face basis functions).""" - m = self.bf2_generator.number_of_basis_functions() - vandermonde = np.zeros((self.points.shape[0], m)) - for i, p in enumerate(self.points): - for j in range(m): - vandermonde[i, j] = self.bf2_generator.eval_basis([p[0], p[1]], j) - return vandermonde + def generate_V2mToFaceQuad(self, degree=None): + """The face basis functions at the points, shape (points, face basis + functions): of the scheme, or of `degree` for the trace of a time derivative + in a basis that is not hierarchical.""" + basis = self.bf2_generator + if degree is not None: + basis = basis_functions.generator(self.family, 2, degree + 1) + return basis.eval_all(self.points.T) def generate_VFaceQuadTo2m(self): """ diff --git a/src/seissol_matrices/generate.py b/src/seissol_matrices/generate.py index 596d237..e07ae3c 100644 --- a/src/seissol_matrices/generate.py +++ b/src/seissol_matrices/generate.py @@ -1,125 +1,288 @@ -import sys -from seissol_matrices import json_io -from dg_matrices import dg_generator -from dr_matrices import dr_generator -from vtk_points import vtk_lagrange_2d, vtk_lagrange_3d -from seissol_matrices import quad_points -from plasticity_matrices import PlasticityGenerator - - -def main(): - assert len(sys.argv) > 1 - if sys.argv[1] == "vtk": - import dg_matrices - - vtkpoints2 = {} - vtkpoints3 = {} +""" +Writes the matrices SeisSol reads, as JSON files. + + python generate.py [materialorder] [--basis FAMILY] [--output-dir DIR] + +The modes vtk, ader, dr and hom write the matrices of the visualisation, of the +ADER-DG kernels, of dynamic rupture and of the material projections; basis, +faces, degrees and bernstein write what a basis other than the Dubiner one needs +on top (see their functions). --basis selects the basis family (basis_functions.FAMILIES); +the files of a family other than the Dubiner basis go into a directory named after +it, unless --output-dir says otherwise. Every mode writes basis.json there, which +states what the matrices of the family may be relied on for +(basis_functions.describe). +""" + +import argparse +import json +import os + +import numpy as np + +from seissol_matrices import basis_functions, bernstein_matrices, json_io, quad_points +from seissol_matrices import face_quadrature +from seissol_matrices.dg_matrices import FACE_ORIENTATIONS, basis_change, dg_generator +from seissol_matrices.dr_matrices import dr_generator +from seissol_matrices.plasticity_matrices import PlasticityGenerator +from seissol_matrices.vtk_points import vtk_lagrange_2d, vtk_lagrange_3d + +ORDERS = range(2, 9) + + +def vtk(family, output, materialorder): + vtkpoints2 = {} + vtkpoints3 = {} + base = {} + for deg in range(0, 9): + vtkpoints2[deg] = vtk_lagrange_2d(deg) + vtkpoints3[deg] = vtk_lagrange_3d(deg) + base[f"vtk2d({deg})"] = vtkpoints2[deg].T + base[f"vtk3d({deg})"] = vtkpoints3[deg].T + json_io.write_tensors(base, output("vtkbase.json")) + for basisorder in ORDERS: + dggen = dg_generator(basisorder, 3, family) + tensors = {} for deg in range(0, 9): - vtkpoints2[deg] = vtk_lagrange_2d(deg) - vtkpoints3[deg] = vtk_lagrange_3d(deg) - json_io.write_tensor(vtkpoints2[deg].T, f"vtk2d({deg})", f"vtkbase.json") - json_io.write_tensor(vtkpoints3[deg].T, f"vtk3d({deg})", f"vtkbase.json") - for basisorder in range(2, 9): - dggen = dg_generator(basisorder, 3) - for deg in range(0, 9): - json_io.write_tensor( - dggen.collocate_volume(vtkpoints3[deg]).T, - f"collvv({basisorder},{deg})", - f"vtko{basisorder}.json", + tensors[f"collvv({basisorder},{deg})"] = dggen.collocate_volume( + vtkpoints3[deg] + ).T + tensors[ + f"collff({basisorder},{deg})" + ] = dggen.face_generator.collocate_volume(vtkpoints2[deg]).T + for f in range(4): + tensors[f"collvf({basisorder},{deg},{f})"] = dggen.collocate_face( + vtkpoints2[deg], f + ).T + json_io.write_tensors(tensors, output(f"vtko{basisorder}.json")) + + +def ader(family, output, materialorder): + for order in ORDERS: + if materialorder is None: + filename = output(f"linear-ader-{order}.json") + else: + filename = output(f"linear-ader-{order}-h{materialorder}.json") + dggen = dg_generator(order, 3, family) + tensors = {} + for dim in range(3): + tensors[f"kDivMT({dim})"] = dggen.kDivMT(dim, materialorder) + tensors[f"kDivM({dim})"] = dggen.kDivM(dim, materialorder) + for line in range(3): + tensors[f"fP({line})"] = dggen.fP(line) + for face in range(4): + tensors[f"rDivM({face})"] = dggen.rDivM(face, materialorder) + tensors[f"rT({face})"] = dggen.rT(face) + tensors[f"fMrT({face})"] = dggen.fMrT(face) + json_io.write_tensors(tensors, filename) + + +def dr(family, output, materialorder): + for order in ORDERS: + for quadname, quadrule in quad_points.dr_rules(order).items(): + if materialorder is None: + filename = output(f"dr-{quadname}-{order}.json") + else: + filename = output(f"dr-{quadname}-{order}-h{materialorder}.json") + generator = dr_generator(order, quadrule, family) + tensors = { + "quadpoints": generator.quadpoints(), + "quadweights": generator.quadweights(), + "resample": generator.resample(), + "V2QuadTo2m": generator.V2QuadTo2m(), + "V2mTo2Quad": generator.V2mTo2Quad(), + } + for a in range(0, 4): + for b in range(0, 4): + tensors[f"V3mTo2n({a},{b})"] = generator.V3mTo2n(a, b) + tensors[f"V3mTo2nTWDivM({a},{b})"] = generator.V3mTo2nTWDivM( + a, b, matorder=materialorder + ) + if not basis_functions.describe(family)["hierarchical"]: + # the traces of the time derivatives at the points of the fault + for degree in range(order - 1): + tensors[f"V2mTo2QuadDegree({degree})"] = generator.V2mTo2Quad( + degree + ) + json_io.write_tensors(tensors, filename) + + +def hom(family, output, materialorder): + if materialorder is None: + raise ValueError("hom needs the material order") + for mode in ("nb", "ip"): + generator = PlasticityGenerator(materialorder, family) + json_io.write_tensors( + { + "hompoints": generator.nodes(mode), + "homproject": generator.generate_Vandermonde_inv(mode), + "homiproject": generator.generate_Vandermonde(mode), + }, + output(f"hom-{mode}-h{materialorder}.json"), + ) + for order in ORDERS: + for quadname, quadrule in quad_points.dr_rules(order).items(): + generator = dr_generator(materialorder, quadrule, family) + json_io.write_tensors( + { + f"homV3mTo2n({a},{b})": generator.V3mTo2n(a, b) + for a in range(0, 4) + for b in range(0, 4) + }, + output(f"homdr-{mode}-{quadname}-{order}-h{materialorder}.json"), ) - json_io.write_tensor( - dggen.face_generator.collocate_volume(vtkpoints2[deg]).T, - f"collff({basisorder},{deg})", - f"vtko{basisorder}.json", + + +def basis(family, output, materialorder): + """ + basis-.json: the integrals of the basis functions (basisIntegrals, + faceBasisIntegrals), which give the mean of a cell where the first + coefficient does not, and the changes to and from the Dubiner basis + (toDubiner: c_dubiner = toDubiner c; fromDubiner; faceToDubiner, + faceFromDubiner), for checkpoints and for comparing runs. + """ + for order in ORDERS: + generator = dg_generator(order, 3, family) + json_io.write_tensors( + { + "basisIntegrals": generator.basis_integrals(), + "faceBasisIntegrals": generator.face_generator.basis_integrals(), + "toDubiner": basis_change(order, 3, family, "dubiner"), + "fromDubiner": basis_change(order, 3, "dubiner", family), + "faceToDubiner": basis_change(order, 2, family, "dubiner"), + "faceFromDubiner": basis_change(order, 2, "dubiner", family), + }, + output(f"basis-{order}.json"), + ) + + +def faces(family, output, materialorder): + """ + faces-.json: the orientations a face can have against its canonical + frame (faceOrientations, the ranks per orientation index), the canonical + traces and lifts (rTCanonical(face,orientation), rDivMCanonical(face, + orientation)), and the face basis of every degree up to the one of the scheme + at the points of the symmetric face rule of the flux + (V2mToFaceQuadDegree(degree)). + """ + for order in ORDERS: + generator = dg_generator(order, 3, family) + tensors = {"faceOrientations": np.array(FACE_ORIENTATIONS, dtype=float)} + for face in range(4): + for index, ranks in enumerate(FACE_ORIENTATIONS): + tensors[f"rTCanonical({face},{index})"] = generator.canonical_rT( + face, ranks ) - for f in range(4): - json_io.write_tensor( - dggen.collocate_face(vtkpoints2[deg], f).T, - f"collvf({basisorder},{deg},{f})", - f"vtko{basisorder}.json", - ) - elif sys.argv[1] == "ader": - materialorder = None - if len(sys.argv) > 2: - materialorder = int(sys.argv[2]) - for order in range(2, 9): - filename = f"linear-ader-{order}-h{materialorder}.json" - if materialorder is None: - filename = f"linear-ader-{order}.json" - dggen = dg_generator(order, 3) - for dim in range(3): - json_io.write_tensor( - dggen.kDivMT(dim, materialorder), - f"kDivMT({dim})", - filename, + tensors[f"rDivMCanonical({face},{index})"] = generator.canonical_rDivM( + face, ranks ) - json_io.write_tensor( - dggen.kDivM(dim, materialorder), f"kDivM({dim})", filename + quadrature = face_quadrature.FaceQuadratureGenerator(order, family) + for degree in range(order): + tensors[ + f"V2mToFaceQuadDegree({degree})" + ] = quadrature.generate_V2mToFaceQuad(degree) + json_io.write_tensors(tensors, output(f"faces-{order}.json")) + + +def degrees(family, output, materialorder): + """ + degrees--.json: the basis of every degree up to the one of the + scheme at the points of a plasticity or material point set (vDegree(degree)) + and the projection back (vInvDegree(degree)), for the time derivatives of + the predictor, which have lower degrees. The nodal points (nb) are left out: + they are unisolvent for the degree of the scheme alone. + """ + for mode in ("ip", "sq", "sq3"): + for order in ORDERS: + generator = PlasticityGenerator(order, family) + tensors = {} + for degree in range(order): + tensors[f"vDegree({degree})"] = generator.generate_Vandermonde( + mode, degree ) - for line in range(3): - json_io.write_tensor(dggen.fP(line), f"fP({line})", filename) - for face in range(4): - json_io.write_tensor( - dggen.rDivM(face, materialorder), f"rDivM({face})", filename + tensors[f"vInvDegree({degree})"] = generator.generate_Vandermonde_inv( + mode, degree ) - json_io.write_tensor(dggen.rT(face), f"rT({face})", filename) - json_io.write_tensor(dggen.fMrT(face), f"fMrT({face})", filename) - elif sys.argv[1] == "dr": - materialorder = None - if len(sys.argv) > 2: - materialorder = int(sys.argv[2]) - for order in range(2, 9): - for quadname, quadrule in quad_points.dr_rules(order).items(): - filename = f"dr-{quadname}-{order}-h{materialorder}.json" - if materialorder is None: - filename = f"dr-{quadname}-{order}.json" - generator = dr_generator(order, quadrule) - - quadpoints = generator.quadpoints() - quadweights = generator.quadweights() - resample = generator.resample() - V2QuadTo2m = generator.V2QuadTo2m() - V2mTo2Quad = generator.V2mTo2Quad() - - json_io.write_tensor(quadpoints, "quadpoints", filename) - json_io.write_tensor(quadweights, "quadweights", filename) - json_io.write_tensor(resample, "resample", filename) - json_io.write_tensor(V2QuadTo2m, "V2QuadTo2m", filename) - json_io.write_tensor(V2mTo2Quad, "V2mTo2Quad", filename) - for a in range(0, 4): - for b in range(0, 4): - V3mTo2n = generator.V3mTo2n(a, b) - V3mTo2nTWDivM = generator.V3mTo2nTWDivM( - a, b, matorder=materialorder - ) - json_io.write_tensor(V3mTo2n, f"V3mTo2n({a},{b})", filename) - json_io.write_tensor( - V3mTo2nTWDivM, f"V3mTo2nTWDivM({a},{b})", filename + json_io.write_tensors(tensors, output(f"degrees-{mode}-{order}.json")) + + +def bernstein(family, output, materialorder): + """ + bernstein-.json: the sparse operators of the Bernstein basis (see + bernstein_matrices), for the degree m = order - 1 and below: + derivative(degree,direction), elevation3(degree), elevation2(degree), + trace(face,orientation,degree) (in the canonical frame, a gather), + liftFace (L_0) and liftScatter(face,orientation,level), the scatter of the + level scaled by its coefficient l_j, so that the lift is + sum_j liftScatter(j) (E^m_(m-j))^T liftFace with the transposed face + elevations in between. + """ + if family != "bernstein": + raise ValueError("the Bernstein operators need --basis bernstein") + for order in ORDERS: + m = order - 1 + tensors = {} + for degree in range(1, m + 1): + for direction in range(3): + tensors[ + f"derivative({degree},{direction})" + ] = bernstein_matrices.derivative(degree, 3, direction) + tensors[f"elevation3({degree})"] = bernstein_matrices.elevation(degree, 3) + tensors[f"elevation2({degree})"] = bernstein_matrices.elevation(degree, 2) + for face in range(4): + for index, ranks in enumerate(FACE_ORIENTATIONS): + for degree in range(m + 1): + tensors[ + f"trace({face},{index},{degree})" + ] = bernstein_matrices.trace(degree, face, ranks) + for level, scale in enumerate(bernstein_matrices.lift_coefficients(m)): + rows = bernstein_matrices.lift_scatter_indices( + m, face, level, ranks + ) + scatter = np.zeros( + ( + bernstein_matrices.count(m, 3), + bernstein_matrices.count(m - level, 2), ) - elif sys.argv[1] == "hom": - materialorder = None - if len(sys.argv) > 2: - materialorder = int(sys.argv[2]) - for mode in ("nb", "ip"): - filename = f"hom-{mode}-h{materialorder}.json" - generator = PlasticityGenerator(materialorder) - points = generator.nodes(mode) - interpolator = generator.generate_Vandermonde_inv(mode) - deinterpolator = generator.generate_Vandermonde(mode) - - json_io.write_tensor(points, "hompoints", filename) - json_io.write_tensor(interpolator, "homproject", filename) - json_io.write_tensor(deinterpolator, "homiproject", filename) - for order in range(2, 9): - for quadname, quadrule in quad_points.dr_rules(order).items(): - filename = f"homdr-{mode}-{quadname}-{order}-h{materialorder}.json" - generator = dr_generator(materialorder, quadrule) - for a in range(0, 4): - for b in range(0, 4): - V3mTo2n = generator.V3mTo2n(a, b) - json_io.write_tensor( - V3mTo2n, f"homV3mTo2n({a},{b})", filename - ) + ) + scatter[rows, np.arange(len(rows))] = float(scale) + tensors[f"liftScatter({face},{index},{level})"] = scatter + tensors["liftFace"] = bernstein_matrices.lift_face(m) + json_io.write_tensors(tensors, output(f"bernstein-{order}.json")) + + +MODES = { + "vtk": vtk, + "ader": ader, + "dr": dr, + "hom": hom, + "basis": basis, + "faces": faces, + "degrees": degrees, + "bernstein": bernstein, +} + + +def main(arguments=None): + parser = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0]) + parser.add_argument("mode", choices=sorted(MODES)) + parser.add_argument("materialorder", nargs="?", type=int, default=None) + parser.add_argument("--basis", default="dubiner", choices=basis_functions.FAMILIES) + parser.add_argument("--output-dir", default=None) + args = parser.parse_args(arguments) + if args.mode == "hom" and args.materialorder is None: + parser.error("hom needs the material order") + if args.mode == "bernstein" and args.basis != "bernstein": + parser.error("bernstein needs --basis bernstein") + + directory = args.output_dir + if directory is None: + directory = "." if args.basis == "dubiner" else args.basis + os.makedirs(directory, exist_ok=True) + output = lambda filename: os.path.join(directory, filename) + with open(output("basis.json"), "w") as f: + json.dump(basis_functions.describe(args.basis), f, indent=2) + f.write("\n") + MODES[args.mode](args.basis, output, args.materialorder) if __name__ == "__main__": diff --git a/src/seissol_matrices/json_io.py b/src/seissol_matrices/json_io.py index d44c0c0..d27c0ad 100644 --- a/src/seissol_matrices/json_io.py +++ b/src/seissol_matrices/json_io.py @@ -23,6 +23,15 @@ def create_empty_json_file(filename): write_json([], filename) +def _entries(tensor): + """The entries above 1e-14 of a tensor, as 1-based indices and the value.""" + entries = [] + for index in itertools.product(*[range(dim) for dim in tensor.shape]): + if np.abs(tensor[tuple(index)]) > 1e-14: + entries.append([i + 1 for i in index] + [str(tensor[tuple(index)])]) + return entries + + def write_tensor(tensor, tensorname, filename): if not os.path.exists(filename): create_empty_json_file(filename) @@ -30,15 +39,24 @@ def write_tensor(tensor, tensorname, filename): tensor_list = read_json(filename) assert isinstance(tensor_list, list) - entries = [] - for index in itertools.product(*[range(dim) for dim in tensor.shape]): - if np.abs(tensor[tuple(index)]) > 1e-14: - entries.append([i + 1 for i in index] + [str(tensor[tuple(index)])]) - m = {"name": tensorname, "shape": tensor.shape, "entries": entries} + m = {"name": tensorname, "shape": tensor.shape, "entries": _entries(tensor)} tensor_list.append(m) write_json(tensor_list, filename) +def write_tensors(tensors, filename): + """Writes the tensors {name: array} into one file at once, appending them to + the tensors the file has.""" + tensor_list = read_json(filename) if os.path.exists(filename) else [] + assert isinstance(tensor_list, list) + for tensorname, tensor in tensors.items(): + tensor = np.asarray(tensor) + tensor_list.append( + {"name": tensorname, "shape": tensor.shape, "entries": _entries(tensor)} + ) + write_json(tensor_list, filename) + + def read_tensor(tensorname, filename): tensor_list = read_json(filename) for raw_tensor in tensor_list: diff --git a/src/seissol_matrices/nodal_boundary.py b/src/seissol_matrices/nodal_boundary.py index 62a23aa..4a6a0f3 100644 --- a/src/seissol_matrices/nodal_boundary.py +++ b/src/seissol_matrices/nodal_boundary.py @@ -12,10 +12,10 @@ def parse_nodes(filename): class NodalBoundaryGenerator: - def __init__(self, order): - self.bf2_generator = basis_functions.BasisFunctionGenerator2D(order) - self.dg2_generator = dg_matrices.dg_generator(order, d=2) - self.dg3_generator = dg_matrices.dg_generator(order, d=3) + def __init__(self, order, family="dubiner"): + self.bf2_generator = basis_functions.generator(family, 2, order) + self.dg2_generator = dg_matrices.dg_generator(order, d=2, family=family) + self.dg3_generator = dg_matrices.dg_generator(order, d=3, family=family) self.nodes = parse_nodes(f"{os.path.dirname(__file__)}/nodal/nodes_{order}.txt") self.vandermonde = self.generate_Vandermonde() @@ -25,15 +25,7 @@ def __init__(self, order): def generate_Vandermonde(self): m = self.bf2_generator.number_of_basis_functions() assert self.nodes.shape[0] == m - - vandermonde = np.zeros((m, m)) - - for i in range(m): - for j in range(m): - n = self.nodes[i] - vandermonde[i, j] = self.bf2_generator.eval_basis([n[0], n[1]], j) - - return vandermonde + return self.bf2_generator.eval_all(self.nodes.T) def generate_V2mTo2n(self): return self.vandermonde diff --git a/src/seissol_matrices/plasticity_matrices.py b/src/seissol_matrices/plasticity_matrices.py index 537623a..150f59e 100644 --- a/src/seissol_matrices/plasticity_matrices.py +++ b/src/seissol_matrices/plasticity_matrices.py @@ -19,9 +19,10 @@ def parse_nodes(filename): class PlasticityGenerator: - def __init__(self, order): - self.bf3_generator = basis_functions.BasisFunctionGenerator3D(order) - self.dg3_generator = dg_matrices.dg_generator(order, d=3) + def __init__(self, order, family="dubiner"): + self.family = family + self.bf3_generator = basis_functions.generator(family, 3, order) + self.dg3_generator = dg_matrices.dg_generator(order, d=3, family=family) self.order = order def quadrature_rule(self, mode): @@ -57,52 +58,41 @@ def nodes(self, mode): return nodes - def generate_Vandermonde(self, mode): - nodes = self.nodes(mode) - m = self.bf3_generator.number_of_basis_functions() - n = nodes.shape[0] + def _basis(self, degree): + if degree is None: + return self.bf3_generator + return basis_functions.generator(self.family, 3, degree + 1) - vandermonde = np.zeros((n, m)) - - for i in range(n): - for j in range(m): - node = nodes[i] - vandermonde[i, j] = self.bf3_generator.eval_basis( - [node[0], node[1], node[2]], j - ) - - return vandermonde + def generate_Vandermonde(self, mode, degree=None): + """The basis at the points, shape (points, functions): of the scheme, or of + `degree` for the time derivatives of the predictor, which a basis that is + not hierarchical represents with fewer functions of their own.""" + return self._basis(degree).eval_all(self.nodes(mode).T) def generate_VandermondeDerivative(self, mode): - nodes = self.nodes(mode) - m = self.bf3_generator.number_of_basis_functions() - n = nodes.shape[0] - - vandermonde = np.zeros((3, n, m)) - - for k in range(3): - for i in range(n): - for j in range(m): - node = nodes[i] - vandermonde[k, i, j] = self.bf3_generator.eval_diff_basis( - [node[0], node[1], node[2]], j, k - ) - - return vandermonde + nodes = self.nodes(mode).T + return np.stack([self.bf3_generator.eval_diff_all(nodes, k) for k in range(3)]) - def generate_Vandermonde_inv(self, mode): - vandermonde = self.generate_Vandermonde(mode) + def generate_Vandermonde_inv(self, mode, degree=None): + """ + The map from values at the points back to the basis (of the scheme, or of + `degree`): the inverse of the Vandermonde matrix for the nodal points (nb), + and the L2 projection with the quadrature rule otherwise, M^-1 V^T W. + """ + scheme = degree is None or degree == self.order - 1 + vandermonde = self.generate_Vandermonde(mode, degree) if mode == "nb": - vandermonde_inv = np.linalg.solve(vandermonde, np.eye(vandermonde.shape[0])) - else: + if not scheme: + raise ValueError( + "the nodal points are unisolvent for the degree of the scheme alone" + ) + return np.linalg.solve(vandermonde, np.eye(vandermonde.shape[0])) + if scheme: mass = self.dg3_generator.mass_matrix() - nodes, weights = self.quadrature_rule(mode) - vandermonde_inv = np.zeros(vandermonde.T.shape) - for l in range(vandermonde_inv.shape[0]): - for i in range(vandermonde_inv.shape[1]): - vandermonde_inv[l, i] = vandermonde[i, l] * weights[i] / mass[l, l] - - return vandermonde_inv + else: + mass = dg_matrices.dg_generator(degree + 1, 3, self.family).mass_matrix() + _, weights = self.quadrature_rule(mode) + return np.linalg.solve(mass, vandermonde.T * weights[None, :]) if __name__ == "__main__": diff --git a/tests/test_bases.py b/tests/test_bases.py new file mode 100644 index 0000000..d81662e --- /dev/null +++ b/tests/test_bases.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 + +import math +import unittest + +import numpy as np + +from seissol_matrices import basis_functions, dg_matrices, plasticity_matrices + + +def random_points(rng, dim, count): + """Points inside the reference element.""" + points = rng.random((dim, count)) + return points / (1.0 + points.sum(axis=0)) + + +def change_to_dubiner(generator, rng): + """ + The coefficients of the functions of a generator in the Dubiner basis of the + same degree, from their values at random points; the residual tells whether + the functions lie in the polynomials of that degree. + """ + dubiner = basis_functions.generator("dubiner", generator.dim(), generator.order) + points = random_points( + rng, generator.dim(), 4 * dubiner.number_of_basis_functions() + ) + D = dubiner.eval_all(points) + F = generator.eval_all(points) + T, *_ = np.linalg.lstsq(D, F, rcond=None) + return T, np.abs(D @ T - F).max(), dubiner + + +class test_bases(unittest.TestCase): + def setUp(self): + self.rng = np.random.default_rng(1) + + def test_factory(self): + for family in basis_functions.FAMILIES: + for dim in (1, 2, 3): + generator = basis_functions.generator(family, dim, 4) + self.assertEqual(generator.family, family) + self.assertEqual(generator.dim(), dim) + self.assertEqual( + generator.number_of_basis_functions(), math.comb(3 + dim, dim) + ) + with self.assertRaises(ValueError): + basis_functions.generator("lagrange", 3, 4) + with self.assertRaises(ValueError): + basis_functions.generator("bernstein", 4, 4) + + def test_same_space(self): + # every family spans the polynomials of degree order - 1, and its + # derivatives are the ones of those polynomials + for family in basis_functions.FAMILIES: + for dim in (1, 2, 3): + for order in range(1, 7): + generator = basis_functions.generator(family, dim, order) + T, residual, dubiner = change_to_dubiner(generator, self.rng) + self.assertLess(residual, 1e-11, (family, dim, order)) + self.assertEqual( + np.linalg.matrix_rank(T), T.shape[0], (family, dim, order) + ) + points = random_points(self.rng, dim, 9) + for k in range(dim): + expected = dubiner.eval_diff_all(points, k) @ T + np.testing.assert_allclose( + generator.eval_diff_all(points, k), + expected, + rtol=0, + atol=1e-9 * max(1.0, np.abs(expected).max()), + err_msg=f"{family} {dim} {order} d{k}", + ) + + def test_eval_all(self): + for family in basis_functions.FAMILIES: + for dim in (1, 2, 3): + generator = basis_functions.generator(family, dim, 4) + points = random_points(self.rng, dim, 5) + coordinates = points[0] if dim == 1 else points + values = generator.eval_all(points) + for i in range(generator.number_of_basis_functions()): + np.testing.assert_array_equal( + values[:, i], generator.eval_basis(coordinates, i) + ) + + def test_mass(self): + for dim in (1, 2, 3): + for order in range(1, 7): + dubiner = dg_matrices.dg_generator(order, dim, "dubiner") + M = dubiner.mass_matrix() + norms = [ + dubiner.generator.norm_squared(i) + for i in range(dubiner.generator.number_of_basis_functions()) + ] + np.testing.assert_allclose(M, np.diag(norms), rtol=0, atol=1e-13) + + normalized = dg_matrices.dg_generator(order, dim, "dubiner-normalized") + np.testing.assert_allclose( + normalized.mass_matrix(), np.eye(len(norms)), rtol=0, atol=1e-13 + ) + + bernstein = dg_matrices.dg_generator(order, dim, "bernstein") + MB = bernstein.mass_matrix() + np.testing.assert_allclose(MB, MB.T, rtol=0, atol=1e-16) + self.assertGreater(np.linalg.eigvalsh(MB).min(), 0.0) + + def test_bernstein(self): + for dim in (1, 2, 3): + for order in range(1, 7): + generator = basis_functions.generator("bernstein", dim, order) + degree = order - 1 + points = random_points(self.rng, dim, 11) + values = generator.eval_all(points) + # a partition of unity, nonnegative inside + np.testing.assert_allclose(values.sum(axis=1), 1.0, rtol=0, atol=1e-14) + self.assertGreaterEqual(values.min(), 0.0) + # the function of a vertex is one there and the others vanish + vertices = np.vstack([np.zeros(dim), np.eye(dim)]).T + at_vertices = generator.eval_all(vertices) + for v in range(dim + 1): + a = [0] * (dim + 1) + a[v] = degree + i = generator.index(a) + expected = np.zeros(generator.number_of_basis_functions()) + expected[i] = 1.0 + np.testing.assert_allclose(at_vertices[v], expected, atol=1e-15) + # multi-index and position agree + for i in range(generator.number_of_basis_functions()): + self.assertEqual(generator.index(generator.multi_index(i)), i) + + def test_bernstein_order(self): + # a_dim varies slowest, a_1 fastest; raising a_1 moves to the next index + self.assertEqual( + basis_functions.bernstein_indices(2, 2), + [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (0, 2)], + ) + indices = basis_functions.bernstein_indices(3, 3) + self.assertEqual(indices[:4], [(0, 0, 0), (1, 0, 0), (2, 0, 0), (3, 0, 0)]) + self.assertEqual(indices[-1], (0, 0, 3)) + positions = {a: i for i, a in enumerate(indices)} + for a in indices: + if sum(a) < 3: + self.assertEqual(positions[(a[0] + 1,) + a[1:]], positions[a] + 1) + + def test_operators(self): + # the DG matrices of every family do what they do for the Dubiner basis: + # kDivMT is the derivative, rT the trace, rDivM = M^-1 rT^T + for family in basis_functions.FAMILIES: + for order in (1, 3, 5): + generator = dg_matrices.dg_generator(order, 3, family) + basis = generator.generator + face_basis = generator.face_generator.generator + coefficients = self.rng.standard_normal( + basis.number_of_basis_functions() + ) + points = random_points(self.rng, 3, 13) + for d in range(3): + np.testing.assert_allclose( + basis.eval_all(points) @ (generator.kDivMT(d) @ coefficients), + basis.eval_diff_all(points, d) @ coefficients, + rtol=0, + atol=1e-10, + err_msg=f"{family} {order} kDivMT({d})", + ) + face_points = random_points(self.rng, 2, 7) + M = generator.mass_matrix() + for f in range(4): + volume_points = generator.volume_to_face_parametrisation( + face_points, f + ) + np.testing.assert_allclose( + face_basis.eval_all(face_points) + @ (generator.rT(f) @ coefficients), + basis.eval_all(volume_points) @ coefficients, + rtol=0, + atol=1e-11, + err_msg=f"{family} {order} rT({f})", + ) + np.testing.assert_allclose( + M @ generator.rDivM(f), + generator.rT(f).T, + rtol=0, + atol=1e-13, + err_msg=f"{family} {order} rDivM({f})", + ) + + def test_plasticity_projection(self): + # the projection from the points of a quadrature rule reproduces the basis + for family in basis_functions.FAMILIES: + for mode in ("ip", "sq", "sq3"): + generator = plasticity_matrices.PlasticityGenerator(4, family) + v = generator.generate_Vandermonde(mode) + vInv = generator.generate_Vandermonde_inv(mode) + np.testing.assert_allclose( + vInv @ v, np.eye(v.shape[1]), rtol=0, atol=1e-12 + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_basis_functions.py b/tests/test_basis_functions.py index fc1bc5d..24cb48a 100755 --- a/tests/test_basis_functions.py +++ b/tests/test_basis_functions.py @@ -132,6 +132,31 @@ def test_index(self): self.assertEqual(generator_3d.unroll_index([0, 1, 2]), 18) self.assertEqual(generator_3d.unroll_index([0, 0, 3]), 19) + def test_eval_all(self): + # all functions at once agree with one function at a time + rng = np.random.default_rng(0) + for generator in [ + basis_functions.BasisFunctionGenerator1D(5), + basis_functions.BasisFunctionGenerator2D(5), + basis_functions.BasisFunctionGenerator3D(5), + ]: + dim = generator.dim() + points = rng.random((dim, 7)) / dim + coordinates = points[0] if dim == 1 else points + values = generator.eval_all(points) + n = generator.number_of_basis_functions() + self.assertEqual(values.shape, (7, n)) + for k in range(dim): + derivatives = generator.eval_diff_all(points, k) + for i in range(n): + np.testing.assert_array_equal( + derivatives[:, i], generator.eval_diff_basis(coordinates, i, k) + ) + for i in range(n): + np.testing.assert_array_equal( + values[:, i], generator.eval_basis(coordinates, i) + ) + def numerical_derivative(self, f, x): h = 1e-11 return (f(x + h) - f(x - h)) / (2 * h) diff --git a/tests/test_bernstein_matrices.py b/tests/test_bernstein_matrices.py new file mode 100644 index 0000000..d637c66 --- /dev/null +++ b/tests/test_bernstein_matrices.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 + +import unittest +from fractions import Fraction + +import numpy as np + +from seissol_matrices import basis_functions, bernstein_matrices, dg_matrices + + +def random_points(rng, dim, count): + points = rng.random((dim, count)) + return points / (1.0 + points.sum(axis=0)) + + +def bernstein(dim, degree): + return basis_functions.generator("bernstein", dim, degree + 1) + + +class test_bernstein_matrices(unittest.TestCase): + def setUp(self): + self.rng = np.random.default_rng(2) + + def test_face_vertices(self): + self.assertEqual( + [dg_matrices.face_vertices(f) for f in range(4)], + [(0, 2, 1), (0, 1, 3), (0, 3, 2), (1, 2, 3)], + ) + self.assertEqual( + [dg_matrices.opposite_vertex(f) for f in range(4)], [3, 2, 1, 0] + ) + + def test_derivative(self): + for dim in (1, 2, 3): + for degree in range(1, 8): + upper, lower = bernstein(dim, degree), bernstein(dim, degree - 1) + points = random_points(self.rng, dim, 9) + c = self.rng.standard_normal(upper.number_of_basis_functions()) + for k in range(dim): + entries = bernstein_matrices.derivative_entries(degree, dim, k) + # two entries per row, +m and -m + self.assertEqual( + sorted(set(entries.values())), [-degree, degree], (dim, k) + ) + D = bernstein_matrices.derivative(degree, dim, k) + self.assertEqual( + len(entries), 2 * lower.number_of_basis_functions() + ) + np.testing.assert_allclose( + lower.eval_all(points) @ (D @ c), + upper.eval_diff_all(points, k) @ c, + rtol=0, + atol=1e-10, + ) + + def test_elevation(self): + for dim in (1, 2, 3): + for degree in range(1, 8): + upper, lower = bernstein(dim, degree), bernstein(dim, degree - 1) + E = bernstein_matrices.elevation(degree, dim) + np.testing.assert_allclose(E.sum(axis=1), 1.0, rtol=0, atol=1e-15) + points = random_points(self.rng, dim, 9) + c = self.rng.standard_normal(lower.number_of_basis_functions()) + np.testing.assert_allclose( + upper.eval_all(points) @ (E @ c), + lower.eval_all(points) @ c, + rtol=0, + atol=1e-12, + ) + + def test_trace(self): + for degree in range(0, 8): + generator = dg_matrices.dg_generator(degree + 1, 3, "bernstein") + for f in range(4): + G = bernstein_matrices.trace(degree, f) + self.assertTrue(np.all(G.sum(axis=1) == 1)) + np.testing.assert_allclose(G, generator.rT(f), rtol=0, atol=1e-12) + + def test_face_permutation(self): + for degree in range(0, 8): + generator = dg_matrices.dg_generator(degree + 1, 3, "bernstein") + Mf = generator.face_generator.mass_matrix() + for h in range(3): + P = bernstein_matrices.face_permutation(degree, h) + self.assertTrue(np.all(P.sum(axis=0) == 1)) + self.assertTrue(np.all(P.sum(axis=1) == 1)) + np.testing.assert_allclose( + P, np.linalg.solve(Mf, generator.fP(h)), rtol=0, atol=1e-11 + ) + + def test_lift(self): + self.assertEqual( + bernstein_matrices.lift_coefficients(3), + [Fraction(1), Fraction(-3, 2), Fraction(1), Fraction(-1, 4)], + ) + for degree in range(0, 8): + generator = dg_matrices.dg_generator(degree + 1, 3, "bernstein") + M = generator.mass_matrix() + Mf = generator.face_generator.mass_matrix() + for f in range(4): + dense = np.linalg.solve(M, generator.rT(f).T @ Mf) + np.testing.assert_allclose( + bernstein_matrices.lift(degree, f), + dense, + rtol=0, + atol=2e-11 * np.abs(dense).max(), + err_msg=f"degree {degree} face {f}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_canonical_faces.py b/tests/test_canonical_faces.py new file mode 100644 index 0000000..b958dc0 --- /dev/null +++ b/tests/test_canonical_faces.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 + +import itertools +import unittest + +import numpy as np + +from seissol_matrices import ( + basis_functions, + bernstein_matrices, + dg_matrices, + dr_matrices, + face_quadrature, + quad_points, +) + + +def project(generator, vertices, polynomial): + """The coefficients of a polynomial given in physical space on the cell with + the vertices (4 x 3), in the basis of the generator.""" + nodes, weights = generator.get_quadrature_rule(2 * generator.order) + reference = nodes.T + jacobian = (vertices[1:] - vertices[0]).T + physical = vertices[0][:, None] + jacobian @ reference + values = generator.generator.eval_all(reference) + moments = (values * weights[:, None]).T @ polynomial(physical) + return np.linalg.solve(generator.mass_matrix(), moments) + + +def face_of(cell, shared): + """The local face of a cell (local vertex -> global vertex) whose vertices are + the shared global vertices, and its orientation against the canonical frame.""" + for face in range(4): + globals_ = [cell[v] for v in dg_matrices.face_vertices(face)] + if set(globals_) == set(shared): + ordered = sorted(globals_) + return face, tuple(ordered.index(g) for g in globals_) + raise AssertionError("no shared face") + + +class test_canonical_faces(unittest.TestCase): + def setUp(self): + self.rng = np.random.default_rng(3) + + def test_sorted_numbering(self): + # a cell with its vertices ordered by global ID sees faces 1 and 3 in the + # canonical frame and faces 0 and 2 with their two last vertices swapped + self.assertEqual( + [dg_matrices.sorted_vertex_ranks(f) for f in range(4)], + [(0, 2, 1), (0, 1, 2), (0, 2, 1), (0, 1, 2)], + ) + for family in basis_functions.FAMILIES: + generator = dg_matrices.dg_generator(4, 3, family) + swap = np.linalg.solve( + generator.face_generator.mass_matrix(), generator.fP(0) + ) + for f in range(4): + expected = generator.rT(f) if f in (1, 3) else swap @ generator.rT(f) + np.testing.assert_allclose( + generator.canonical_rT(f, dg_matrices.sorted_vertex_ranks(f)), + expected, + rtol=0, + atol=1e-12, + ) + + def test_two_cells(self): + # two cells sharing a face, numbered at random, give the same canonical + # trace of a polynomial defined on both + for family in basis_functions.FAMILIES: + for order in (1, 3, 5): + generator = dg_matrices.dg_generator(order, 3, family) + degree = order - 1 + for _ in range(4): + shared = self.rng.random((3, 3)) + normal = np.cross(shared[1] - shared[0], shared[2] - shared[0]) + apexes = [ + shared.mean(axis=0) + normal, + shared.mean(axis=0) - normal, + ] + ids = self.rng.permutation(5) + exponents = [ + e for e in itertools.product(range(degree + 1), repeat=3) + ] + exponents = [e for e in exponents if sum(e) <= degree] + weights = self.rng.standard_normal(len(exponents)) + polynomial = lambda x: sum( + w * x[0] ** e[0] * x[1] ** e[1] * x[2] ** e[2] + for w, e in zip(weights, exponents) + ) + traces = [] + for side, apex in enumerate(apexes): + points = np.vstack([shared, apex]) + global_ids = [ids[0], ids[1], ids[2], ids[3 + side]] + order_of_cell = self.rng.permutation(4) + cell = [global_ids[v] for v in order_of_cell] + vertices = points[order_of_cell] + face, ranks = face_of(cell, ids[:3]) + coefficients = project(generator, vertices, polynomial) + traces.append( + generator.canonical_rT(face, ranks) @ coefficients + ) + np.testing.assert_allclose( + traces[0], + traces[1], + rtol=0, + atol=1e-9 * max(1.0, np.abs(traces[0]).max()), + err_msg=f"{family} order {order}", + ) + + def test_bernstein_canonical(self): + for degree in range(0, 7): + generator = dg_matrices.dg_generator(degree + 1, 3, "bernstein") + M = generator.mass_matrix() + Mf = generator.face_generator.mass_matrix() + for f in range(4): + for ranks in dg_matrices.FACE_ORIENTATIONS: + canonical = generator.canonical_rT(f, ranks) + np.testing.assert_allclose( + bernstein_matrices.trace(degree, f, ranks), + canonical, + rtol=0, + atol=1e-12, + ) + dense = np.linalg.solve(M, canonical.T @ Mf) + np.testing.assert_allclose( + bernstein_matrices.lift(degree, f, ranks), + dense, + rtol=0, + atol=2e-11 * np.abs(dense).max(), + ) + + def test_dr_face_route(self): + # the fault reads the volume at its points through the trace: V3mTo2n(a, b) + # is V2mTo2Quad P_b rT(a), with P_b the reparametrisation b - 1 of the face + # (none for b = 0), and V3mTo2nTWDivM(a, b) is rDivM(a) P_b^T M_face V2QuadTo2m + for family in basis_functions.FAMILIES: + for order in (3, 5): + rule = quad_points.stroud(order + 1) + dr = dr_matrices.dr_generator(order, rule, family) + generator = dr.dg3_generator + Mf = generator.face_generator.mass_matrix() + reparametrisations = [np.eye(Mf.shape[0])] + [ + np.linalg.solve(Mf, generator.fP(h)) for h in range(3) + ] + V = dr.V2mTo2Quad() + project_back = Mf @ dr.V2QuadTo2m() + for a in range(4): + for b in range(4): + P = reparametrisations[b] + np.testing.assert_allclose( + dr.V3mTo2n(a, b), + V @ P @ generator.rT(a), + rtol=0, + atol=1e-12, + ) + np.testing.assert_allclose( + dr.V3mTo2nTWDivM(a, b), + generator.rDivM(a) @ P.T @ project_back, + rtol=0, + atol=1e-10, + ) + + def test_dr_canonical_route(self): + # with the points of the fault in the canonical frame of the face, + # V2mTo2Quad reads the canonical trace of either side as the volume basis + # at the points mapped into the cell, and the flux goes back through + # V2QuadTo2m and the canonical lift as through V3mTo2nTWDivM + for family in basis_functions.FAMILIES: + for order in (3, 5): + rule = quad_points.stroud(order + 1) + dr = dr_matrices.dr_generator(order, rule, family) + generator = dr.dg3_generator + Mf = generator.face_generator.mass_matrix() + V = dr.V2mTo2Quad() + back = Mf @ dr.V2QuadTo2m() + for f in range(4): + for ranks in dg_matrices.FACE_ORIENTATIONS: + local = dg_matrices.canonical_to_face_parametrisation( + rule.points().T, ranks + ) + volume = generator.generator.eval_all( + dg_matrices.volume_to_face_parametrisation(local, f) + ) + np.testing.assert_allclose( + V @ generator.canonical_rT(f, ranks), + volume, + rtol=0, + atol=1e-11, + ) + np.testing.assert_allclose( + generator.canonical_rDivM(f, ranks) @ back, + np.linalg.solve( + generator.mass_matrix(), + volume.T * rule.weights()[None, :], + ), + rtol=0, + atol=1e-9, + ) + + def test_degrees(self): + # the face basis of a lower degree at the points: for a hierarchical basis + # the leading columns, otherwise a basis of its own + rule = quad_points.stroud(6) + for family in basis_functions.FAMILIES: + dr = dr_matrices.dr_generator(5, rule, family) + face = face_quadrature.FaceQuadratureGenerator(5, family) + for degree in range(5): + for full, lower in ( + (dr.V2mTo2Quad(), dr.V2mTo2Quad(degree)), + ( + face.generate_V2mToFaceQuad(), + face.generate_V2mToFaceQuad(degree), + ), + ): + count = (degree + 1) * (degree + 2) // 2 + self.assertEqual(lower.shape, (full.shape[0], count)) + if family != "bernstein": + np.testing.assert_array_equal(lower, full[:, :count]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_degrees_and_basis.py b/tests/test_degrees_and_basis.py new file mode 100644 index 0000000..0041971 --- /dev/null +++ b/tests/test_degrees_and_basis.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 + +import json +import math +import os +import shutil +import tempfile +import unittest + +import numpy as np + +from seissol_matrices import ( + basis_functions, + bernstein_matrices, + dg_matrices, + generate, + json_io, + plasticity_matrices, +) + + +class test_degrees_and_basis(unittest.TestCase): + def setUp(self): + self.rng = np.random.default_rng(4) + + def test_degree_projection(self): + # the projection of a degree reproduces its basis; in the hierarchical + # bases the matrices of a degree are the leading columns and rows + for family in basis_functions.FAMILIES: + for mode in ("ip", "sq", "sq3"): + generator = plasticity_matrices.PlasticityGenerator(4, family) + v = generator.generate_Vandermonde(mode) + vInv = generator.generate_Vandermonde_inv(mode) + for degree in range(4): + vd = generator.generate_Vandermonde(mode, degree) + vInvd = generator.generate_Vandermonde_inv(mode, degree) + count = math.comb(degree + 3, 3) + self.assertEqual(vd.shape, (v.shape[0], count)) + np.testing.assert_allclose( + vInvd @ vd, np.eye(count), rtol=0, atol=1e-12 + ) + if family != "bernstein": + np.testing.assert_array_equal(vd, v[:, :count]) + np.testing.assert_allclose( + vInvd, vInv[:count], rtol=0, atol=1e-13 + ) + + def test_basis_integrals(self): + for order in (1, 3, 5): + n3 = math.comb(order + 2, 3) + n2 = math.comb(order + 1, 2) + expected = { + "dubiner": (np.eye(n3)[0] / 6, np.eye(n2)[0] / 2), + "dubiner-normalized": ( + np.eye(n3)[0] * math.sqrt(1 / 6), + np.eye(n2)[0] * math.sqrt(1 / 2), + ), + "bernstein": (np.full(n3, 1 / 6 / n3), np.full(n2, 1 / 2 / n2)), + } + for family, (volume, face) in expected.items(): + generator = dg_matrices.dg_generator(order, 3, family) + np.testing.assert_allclose( + generator.basis_integrals(), volume, rtol=0, atol=1e-15 + ) + np.testing.assert_allclose( + generator.face_generator.basis_integrals(), face, rtol=0, atol=1e-15 + ) + + def test_basis_change(self): + for dim in (2, 3): + for order in (1, 4, 6): + for source in basis_functions.FAMILIES: + for target in basis_functions.FAMILIES: + T = dg_matrices.basis_change(order, dim, source, target) + back = dg_matrices.basis_change(order, dim, target, source) + np.testing.assert_allclose( + back @ T, np.eye(T.shape[0]), rtol=0, atol=1e-11 + ) + points = self.rng.random((dim, 9)) / dim + c = self.rng.standard_normal(T.shape[1]) + np.testing.assert_allclose( + basis_functions.generator(target, dim, order).eval_all( + points + ) + @ (T @ c), + basis_functions.generator(source, dim, order).eval_all( + points + ) + @ c, + rtol=0, + atol=1e-10, + ) + + def test_describe(self): + self.assertEqual(basis_functions.describe("dubiner")["mass"], "diagonal") + self.assertEqual( + basis_functions.describe("dubiner-normalized")["mass"], "identity" + ) + bernstein = basis_functions.describe("bernstein") + self.assertEqual(bernstein["mass"], "dense") + self.assertFalse(bernstein["hierarchical"]) + + def test_generate_arguments(self): + # a mode that cannot run with its arguments stops before writing anything + directory = tempfile.mkdtemp() + try: + for arguments in (["hom"], ["bernstein", "--basis", "dubiner"]): + with self.assertRaises(SystemExit): + generate.main(arguments + ["--output-dir", directory]) + self.assertEqual(os.listdir(directory), []) + finally: + shutil.rmtree(directory) + + def test_generate(self): + # the modes basis, faces, degrees and bernstein write what they say, for a + # reduced set of orders + directory = tempfile.mkdtemp() + orders = generate.ORDERS + try: + generate.ORDERS = range(2, 5) + for mode in ("basis", "faces", "degrees", "bernstein"): + generate.main([mode, "--basis", "bernstein", "--output-dir", directory]) + with open(os.path.join(directory, "basis.json")) as f: + self.assertEqual(json.load(f), basis_functions.describe("bernstein")) + order = 4 + m = order - 1 + filename = os.path.join(directory, f"bernstein-{order}.json") + face, index = 2, 3 + ranks = dg_matrices.FACE_ORIENTATIONS[index] + chain = json_io.read_tensor("liftFace", filename) + lift = np.zeros((math.comb(m + 3, 3), math.comb(m + 2, 2))) + for level in range(m + 1): + if level > 0: + chain = ( + json_io.read_tensor(f"elevation2({m - level + 1})", filename).T + @ chain + ) + lift += ( + json_io.read_tensor( + f"liftScatter({face},{index},{level})", filename + ) + @ chain + ) + np.testing.assert_allclose( + lift, bernstein_matrices.lift(m, face, ranks), rtol=0, atol=1e-12 + ) + np.testing.assert_array_equal( + json_io.read_tensor(f"trace({face},{index},{m})", filename), + bernstein_matrices.trace(m, face, ranks), + ) + faces = os.path.join(directory, f"faces-{order}.json") + np.testing.assert_array_equal( + json_io.read_tensor("faceOrientations", faces), + np.array(dg_matrices.FACE_ORIENTATIONS, dtype=float), + ) + generator = dg_matrices.dg_generator(order, 3, "bernstein") + np.testing.assert_allclose( + json_io.read_tensor(f"rTCanonical({face},{index})", faces), + generator.canonical_rT(face, ranks), + rtol=0, + atol=1e-14, + ) + for name in (f"basis-{order}.json", f"degrees-sq-{order}.json"): + self.assertTrue(os.path.exists(os.path.join(directory, name))) + finally: + generate.ORDERS = orders + shutil.rmtree(directory) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_material_order.py b/tests/test_material_order.py index 20a781c..f067266 100644 --- a/tests/test_material_order.py +++ b/tests/test_material_order.py @@ -36,6 +36,51 @@ def test_rDivM_constant_material(self): self.generator.rDivM(side, 1)[:, :, 0], self.generator.rDivM(side) ) + def test_rDivM_material_on_the_face(self): + # M^-1 (integral over the face of the cell basis times the face basis + # times the material basis) M_face^-1, by a quadrature of its own + generator = self.generator + material = dg_matrices.dg_generator(3, 3).generator + nodes, weights = generator.face_generator.get_quadrature_rule( + 2 * self.order + 4 + ) + points = nodes.T + face_basis = generator.face_generator.generator.eval_all(points) + Mf = generator.face_generator.mass_matrix() + M = generator.mass_matrix() + for side in range(4): + volume_points = generator.volume_to_face_parametrisation(points, side) + volume = generator.generator.eval_all(volume_points) + materials = material.eval_all(volume_points) + matrix = generator.rDivM(side, 3) + for m in range(materials.shape[1]): + integral = np.einsum( + "q,qk,qj->kj", weights * materials[:, m], volume, face_basis + ) + expected = np.linalg.solve(M, np.linalg.solve(Mf, integral.T).T) + self.compare(matrix[:, :, m], expected) + + def test_rDivM_material_vanishing_on_the_face(self): + # a material that vanishes on a face, the barycentric coordinate of the + # vertex opposite to it, gives nothing through that face + material = dg_matrices.dg_generator(2, 3) + nodes, weights = material.get_quadrature_rule(4) + points = nodes.T + values = material.generator.eval_all(points) + for side, vertex in enumerate((3, 2, 1, 0)): + barycentric = ( + 1.0 - points.sum(axis=0) if vertex == 0 else points[vertex - 1] + ) + coefficients = np.linalg.solve( + material.mass_matrix(), values.T @ (weights * barycentric) + ) + lift = self.generator.rDivM(side, 2) @ coefficients + np.testing.assert_allclose(lift, 0.0, rtol=0.0, atol=1e-11) + self.assertGreater( + np.abs(self.generator.rDivM((side + 1) % 4, 2) @ coefficients).max(), + 1e-3, + ) + def test_V3mTo2nTWDivM_constant_material(self): for a in range(4): for b in range(4): diff --git a/tests/test_zeros.py b/tests/test_zeros.py new file mode 100644 index 0000000..8208c3b --- /dev/null +++ b/tests/test_zeros.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 + +import unittest + +import numpy as np + +from seissol_matrices import dg_matrices + + +class test_zeros(unittest.TestCase): + def test_snap_zeros(self): + tensor = np.array([[2.0, 1e-13], [-1.5e-12, -2.5e-12]]) + np.testing.assert_array_equal( + dg_matrices.snap_zeros(tensor), [[2.0, 0.0], [0.0, -2.5e-12]] + ) + np.testing.assert_array_equal( + dg_matrices.snap_zeros(np.zeros((2, 3))), np.zeros((2, 3)) + ) + + def test_orthogonal_basis(self): + # the mass matrices of the orthogonal basis are diagonal, and what is + # computed from them has its zeros where the integrals have theirs + for order in range(2, 6): + generator = dg_matrices.dg_generator(order, 3) + for M in (generator.mass_matrix(), generator.face_generator.mass_matrix()): + self.assertTrue(np.all(M == np.diag(np.diag(M)))) + for d in range(3): + np.testing.assert_array_equal( + generator.kDivM(d) != 0, generator.stiffness_matrix(d) != 0 + ) + for side in range(4): + np.testing.assert_array_equal( + generator.rDivM(side) != 0, generator.fMrT(side).T != 0 + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/basis_benchmark/README.md b/tools/basis_benchmark/README.md new file mode 100644 index 0000000..953ab96 --- /dev/null +++ b/tools/basis_benchmark/README.md @@ -0,0 +1,62 @@ +# Basis benchmark + +Times the blocks of a time step of SeisSol's ADER-DG scheme as yateto generates +them, in the Dubiner and in the Bernstein basis of `seissol_matrices`, outside +of SeisSol. + +## Blocks + +The kernels are defined in `blocks.py`; per cell unless noted: + +| block | kernels | what it does | +|---|---|---| +| `ck` | `ck` | the time derivatives dQ(k) of the Cauchy-Kovalevskaya procedure, each of degree N - k | +| `taylor` | `taylor` | the time integral I and the value at the end of the step (strong form, no volume kernel) | +| `trace` | `trace(f, o)` | the traces of I on the four faces, in the canonical frame of each face | +| `lift` | `lift(f, o)` | per face: jump of the traces of both cells, flux, lift into Q | +| `nodal` | `nodal(f, o)` | the same with the flux at the points of a face quadrature | +| `dr-volume` | `drTaylor`, `drEval(a, b)`, `drBack(a, b)` | per fault face: dynamic rupture as SeisSol reads the fault today, per time point the Taylor expansion of both cells evaluated at the fault points (`V3mTo2n`), the flux back through `V3mTo2nTWDivM` | +| `dr-face` | `drTrace(f, o)`, `drCombine`, `drFaceBack(f, o)` | per fault face: dynamic rupture through the trace, the traces of the time derivatives evaluated at the fault points once, combined per time point, the flux back through its moments on the face and the lift | + +In the Bernstein basis the derivative is a difference stencil with entries ±1 +(the factor of the degree moves into the Taylor coefficients), sums of time +derivatives of different degrees go through the elevation (Horner's scheme), +the trace is a gather and the lift is factorised (`bernstein_matrices.lift`). + +## Variants + +- `--families`: `dubiner`, `bernstein` +- `--storages`, how the constant operators are kept: `dense` (bounding box of + the non-zeros, aligned, multiplied by PSpaMM), `csc` (non-zeros read from + memory) or `immediate` (the numbers in the generated code, so that a one is no + multiplication and a zero no instruction) +- `--simulations`: 1, or fused simulations (8), which lead the data +- `--archs`: `dhsw` (AVX2), `dskx` (AVX-512) +- `--orientations`: `sorted`, the orientation each face has when the cells order + their vertices by global ID (one per face), or `all` six +- `--orders` + +## Running + + python3 tools/basis_benchmark/benchmark.py --yateto /path/to/yateto --work /tmp/bench + +yateto has to come with its `include` directory, `pspamm-generator` has to be +on the `PATH` (or given with `--pspamm`), and the kernels are compiled with +`g++` (`--cxx`, `--cxxflags`). Builds run in parallel (`--jobs`), timings one +after another, on one core. + +Every build is first run once on known input and compared with what numpy +computes from the dense matrices of `seissol_matrices` (`check.py`); a build +that does not match is not timed. + +Each build is timed with a working set that fits the caches (`--cache-bytes`) +and with one larger than the last level cache (`--memory-bytes`); a block's +time is the best of its repetitions. + +## Output + +`results.csv` in the work directory has a row per build, working set and block +with the time per item (cell, or fault face for dynamic rupture) and the +non-zero and hardware flops per item that yateto counts. `summary.md` gives the +time per cell and simulation in ns, with the hardware flops in thousands in +parentheses. diff --git a/tools/basis_benchmark/benchmark.py b/tools/basis_benchmark/benchmark.py new file mode 100644 index 0000000..6f79f33 --- /dev/null +++ b/tools/basis_benchmark/benchmark.py @@ -0,0 +1,370 @@ +#!/usr/bin/env python3 +""" +Generates the kernels of blocks.py with yateto for the bases, storages, orders, +numbers of fused simulations and architectures asked for, checks every build +against numpy (check.py), times it with driver.cpp and writes the times per +cell (per fault face for dynamic rupture) as CSV, with a summary in Markdown. + + python3 benchmark.py [--orders 4 6 8] [--families dubiner bernstein] + [--storages dense csc immediate] [--simulations 1 8] + [--archs dhsw dskx] [--orientations sorted] [--work DIR] [--jobs 2] + +yateto must be importable (or given with --yateto) and have its headers in +include/ next to the package; the GEMMs go to pspamm-generator (--pspamm). +The working set of a run is either small enough for the caches ("cache", +--cache-bytes) or larger than the last level cache ("memory", +--memory-bytes); the time of a block is the best of its repetitions. +""" + +import argparse +import concurrent.futures +import csv +import importlib +import itertools +import os +import shutil +import subprocess +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "..", "..", "src")) +sys.path.insert(0, HERE) + +ARCH_FLAGS = { + "dhsw": ["-march=haswell"], + "dskx": ["-march=skylake-avx512", "-mprefer-vector-width=512"], +} +SOURCES = ["kernel.cpp", "init.cpp", "pool.cpp", "tensor.cpp", "subroutine.cpp"] +DT = 0.25 +BLOCKS = ("ck", "taylor", "trace", "lift", "nodal", "dr-volume", "dr-face") + + +def name(family, storage, simulations, order, arch, orientations): + return f"{family}-{storage}-s{simulations}-o{order}-{arch}-{orientations}" + + +def import_yateto(path): + if path: + sys.path.insert(0, path) + return importlib.import_module("yateto") + + +def include_directory(yateto): + return os.path.join(os.path.dirname(os.path.dirname(yateto.__file__)), "include") + + +def layout(tensor): + """The memory layout of a tensor as the driver's setup::Layout.""" + memory = tensor.memoryLayout() + shape = list(tensor.shape()) + start = [r.start for r in memory.bbox()] + stop = [r.stop for r in memory.bbox()] + stride = list(memory.stride()) + pad = lambda v: ", ".join(str(int(x)) for x in v + [0] * (3 - len(v))) + return f"{{{len(shape)}, {{{pad(shape)}}}, {{{pad(start)}}}, {{{pad(stop)}}}, {{{pad(stride)}}}}}" + + +def setup_header(kernels, orientations): + """setup.h for the driver: configuration, coefficients and layouts.""" + from seissol_matrices import dg_matrices + + ops = kernels.ops + N = ops.degree + c = ops.taylor_coefficients(DT, scaled=True) + numbers = lambda values: ", ".join(repr(float(v)) for v in values) + runtime = kernels.runtime + sorted_orientations = [ + dg_matrices.FACE_ORIENTATIONS.index(dg_matrices.sorted_vertex_ranks(f)) + for f in range(4) + ] + lines = [ + "// written by benchmark.py", + "#pragma once", + "namespace setup {", + "struct Layout {", + " int rank;", + " unsigned shape[3];", + " unsigned start[3];", + " unsigned stop[3];", + " long stride[3];", + "};", + f'constexpr const char* Family = "{ops.family}";', + f'constexpr const char* Storage = "{kernels.storage}";', + f"constexpr int Order = {ops.order};", + f"constexpr int Degree = {N};", + f"constexpr int Simulations = {kernels.simulations};", + f"constexpr int TimePoints = {len(c['points'])};", + f"constexpr bool AllOrientations = {'true' if orientations == 'all' else 'false'};", + "constexpr unsigned SortedOrientation[4] = {" + + ", ".join(str(sorted_orientations[f]) for f in range(4)) + + "};", + f"constexpr int NumberOfCombinations = {len(ops.combos)};", + "constexpr unsigned Combinations[][2] = {" + + ", ".join(f"{{{f}, {o}}}" for f, o in ops.combos) + + "};", + f"constexpr double IntegralCoefficients[] = {{{numbers(c['integral'])}}};", + f"constexpr double EndCoefficients[] = {{{numbers(c['end'])}}};", + "constexpr double PointCoefficients[][Degree + 1] = {" + + ", ".join(f"{{{numbers(row)}}}" for row in c["points"]) + + "};", + ] + for tensor in ("Q", "I", "AminusT", "T", "Tn", "q", "qp", "F"): + lines.append(f"constexpr Layout layout_{tensor} = {layout(runtime[tensor])};") + lines.append(f"constexpr Layout layout_star = {layout(runtime['star(0)'])};") + dQ = [layout(runtime["Q"])] + [layout(runtime[f"dQ({k})"]) for k in range(1, N + 1)] + lines.append(f"constexpr Layout layout_dQ[] = {{{', '.join(dQ)}}};") + lines.append("} // namespace setup") + return "\n".join(lines) + "\n" + + +def build(args, config): + """Generates and compiles one configuration in its directory under the work + directory; returns the directory.""" + family, storage, simulations, order, arch, orientations = config + yateto = import_yateto(args.yateto) + from yateto import Generator, useArchitectureIdentifiedBy + from yateto.gemm_configuration import GeneratorCollection, PSpaMM + import blocks + + directory = os.path.join(args.work, name(*config)) + shutil.rmtree(directory, ignore_errors=True) + os.makedirs(directory) + architecture = useArchitectureIdentifiedBy(arch) + generator = Generator(architecture) + ops = blocks.Operators(order, family, orientations) + kernels = blocks.Kernels(ops, storage, simulations) + kernels.add_to(generator) + with open(os.path.join(directory, "build.log"), "w") as log: + stdout = sys.stdout + sys.stdout = log + try: + generator.generate( + directory, + gemm_cfg=GeneratorCollection([PSpaMM(architecture, cmd=args.pspamm)]), + ) + finally: + sys.stdout = stdout + with open(os.path.join(directory, "setup.h"), "w") as f: + f.write(setup_header(kernels, orientations)) + command = ( + [args.cxx, "-O3", "-std=c++17", "-fopenmp-simd", "-DNDEBUG"] + + ARCH_FLAGS[arch] + + args.cxxflags.split() + + ["-I", directory, "-I", include_directory(yateto)] + + [os.path.join(HERE, "driver.cpp")] + + [os.path.join(directory, source) for source in SOURCES] + + ["-o", os.path.join(directory, "driver")] + ) + subprocess.run(command, check=True, stdout=log, stderr=subprocess.STDOUT) + return directory + + +def check(config, directory, operators): + """Runs the driver's check and compares with numpy; returns the failures and + the largest relative error.""" + family, storage, simulations, order, arch, orientations = config + import blocks + from check import Reference, compare, read + + key = (order, family, orientations) + if key not in operators: + operators[key] = blocks.Operators(order, family, orientations) + ops = operators[key] + path = os.path.join(directory, "check.bin") + subprocess.run([os.path.join(directory, "driver"), "--check", path], check=True) + records = read(path) + reference = Reference(ops, simulations, ops.taylor_coefficients(DT, scaled=False)) + return compare(records, reference.expected(records)) + + +def run(directory, regime, size, repetitions): + """The driver's results for a working set of `size` bytes.""" + result = subprocess.run( + [ + os.path.join(directory, "driver"), + "--bytes", + str(size), + "--repetitions", + str(repetitions), + ], + check=True, + capture_output=True, + text=True, + ) + with open(os.path.join(directory, f"run-{regime}.txt"), "w") as f: + f.write(result.stdout) + lines = [line for line in result.stdout.splitlines() if not line.startswith("#")] + return list(csv.DictReader(lines)), result.stdout.splitlines()[0] + + +def summary(rows, args): + """Markdown tables of ns per cell and simulation (per fault face and + simulation for dynamic rupture), one table per architecture, number of + simulations and working set, a column per basis and storage.""" + variants = [f"{f} {s}" for f, s in itertools.product(args.families, args.storages)] + out = [] + for arch, simulations, regime in itertools.product( + args.archs, args.simulations, ("cache", "memory") + ): + selected = [ + r + for r in rows + if r["arch"] == arch + and int(r["simulations"]) == simulations + and r["regime"] == regime + ] + if not selected: + continue + out.append( + f"### {arch}, {simulations} simulation{'s' if simulations > 1 else ''}, " + f"working set: {regime}\n" + ) + out.append("| order | block | " + " | ".join(variants) + " |") + out.append("|---|---|" + "---:|" * len(variants)) + for order in args.orders: + for block in BLOCKS: + cells = [] + for variant in variants: + family, storage = variant.split() + match = [ + r + for r in selected + if r["family"] == family + and r["storage"] == storage + and int(r["order"]) == order + and r["block"] == block + ] + if match: + r = match[0] + ns = float(r["ns_per_item"]) / simulations + hardware = float(r["hardware_flops"]) / simulations + cells.append(f"{ns:.0f} ({hardware / 1e3:.1f}k)") + else: + cells.append("") + out.append(f"| {order} | {block} | " + " | ".join(cells) + " |") + out.append("") + return "\n".join(out) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--orders", type=int, nargs="+", default=[4, 6, 8]) + parser.add_argument("--families", nargs="+", default=["dubiner", "bernstein"]) + parser.add_argument("--storages", nargs="+", default=["dense", "csc", "immediate"]) + parser.add_argument("--simulations", type=int, nargs="+", default=[1, 8]) + parser.add_argument("--archs", nargs="+", default=["dhsw", "dskx"]) + parser.add_argument("--orientations", default="sorted", choices=["sorted", "all"]) + parser.add_argument("--work", default="basis_benchmark_work") + parser.add_argument("--jobs", type=int, default=2) + parser.add_argument("--yateto", default=None) + parser.add_argument("--pspamm", default="pspamm-generator") + parser.add_argument("--cxx", default="g++") + parser.add_argument("--cxxflags", default="") + parser.add_argument("--cache-bytes", type=int, default=1 << 20) + parser.add_argument("--memory-bytes", type=int, default=512 << 20) + parser.add_argument("--cache-repetitions", type=int, default=200) + parser.add_argument("--memory-repetitions", type=int, default=5) + parser.add_argument("--skip-build", action="store_true") + parser.add_argument("--skip-run", action="store_true") + parser.add_argument("--build-one", nargs=6, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + args.work = os.path.abspath(args.work) + import_yateto(args.yateto) + + if args.build_one: + family, storage, simulations, order, arch, orientations = args.build_one + build(args, (family, storage, int(simulations), int(order), arch, orientations)) + return + + configs = list( + itertools.product( + args.families, + args.storages, + args.simulations, + args.orders, + args.archs, + [args.orientations], + ) + ) + os.makedirs(args.work, exist_ok=True) + + if not args.skip_build: + + def build_in_process(config): + command = [sys.executable, os.path.abspath(__file__), "--work", args.work] + command += ["--pspamm", args.pspamm, "--cxx", args.cxx] + command += ["--cxxflags=" + args.cxxflags] + if args.yateto: + command += ["--yateto", args.yateto] + command += ["--build-one"] + [str(c) for c in config] + start = time.time() + result = subprocess.run(command, capture_output=True, text=True) + return config, result, time.time() - start + + with concurrent.futures.ThreadPoolExecutor(args.jobs) as pool: + for config, result, seconds in pool.map(build_in_process, configs): + status = "built" if result.returncode == 0 else "FAILED" + print(f"{status} {name(*config)} in {seconds:.0f} s", flush=True) + if result.returncode != 0: + print(result.stdout[-2000:], result.stderr[-4000:]) + + operators = {} + rows = [] + for config in configs: + directory = os.path.join(args.work, name(*config)) + if not os.path.exists(os.path.join(directory, "driver")): + continue + failures, worst = check(config, directory, operators) + state = "ok" if not failures else f"{len(failures)} FAILED" + print(f"check {name(*config)}: {state} (largest error {worst:.1e})", flush=True) + for failure in failures[:10]: + print(" ", *failure) + if failures or args.skip_run: + continue + family, storage, simulations, order, arch, orientations = config + for regime, size, repetitions in ( + ("cache", args.cache_bytes, args.cache_repetitions), + ("memory", args.memory_bytes, args.memory_repetitions), + ): + results, header = run(directory, regime, size, repetitions) + print(" ", regime, header[2:], flush=True) + for r in results: + r.update( + family=family, + storage=storage, + simulations=simulations, + order=order, + arch=arch, + orientations=orientations, + regime=regime, + ) + rows.append(r) + + if rows: + fields = [ + "family", + "storage", + "simulations", + "order", + "arch", + "orientations", + "regime", + "block", + "items", + "ns_per_item", + "nonzero_flops", + "hardware_flops", + "hardware_gflops", + ] + with open(os.path.join(args.work, "results.csv"), "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=fields) + writer.writeheader() + writer.writerows(rows) + with open(os.path.join(args.work, "summary.md"), "w") as f: + f.write(summary(rows, args)) + print(f"results in {args.work}/results.csv and summary.md") + + +if __name__ == "__main__": + main() diff --git a/tools/basis_benchmark/blocks.py b/tools/basis_benchmark/blocks.py new file mode 100644 index 0000000..e934d6e --- /dev/null +++ b/tools/basis_benchmark/blocks.py @@ -0,0 +1,636 @@ +""" +The blocks of a time step of SeisSol's ADER-DG scheme as yateto kernels, for one +basis of seissol_matrices (the Dubiner or the Bernstein basis) and one way to +keep the operators of the basis: + +- dense: each operator on the bounding box of its non-zeros, aligned, for a + GEMM generator; +- csc: the non-zeros in compressed columns, read from memory; +- immediate: the numbers written into the generated code + (yateto.type.AddressingMode.IMMEDIATE), so that a one is no multiplication, + a minus one a sign and a zero nothing at all. + +The matrices that evaluate at points or integrate over them are dense in every +basis and stay dense. + +With one simulation the basis functions lead the data and an operator is +applied from the left; fused simulations lead with the simulation, and the +operator, stored transposed, is applied from the right. + +The kernels, for the degree N = order - 1, the degrees of freedom Q and the +time-integrated degrees of freedom I: + +ck the time derivatives dQ(k), k = 1 ... N, of degree N - k: the sum + over the directions of a derivative times dQ(k - 1) times the + star matrix of the direction (dQ(0) = Q); +taylor I, and the value at the end of the step, which replaces Q (the + strong form needs no volume kernel); +trace(f, o) the trace of I on the face f in the canonical frame of the face, + for the orientation o of the cell's face against it + (dg_matrices.FACE_ORIENTATIONS); +lift(f, o) the jump of the traces of both cells of a face, the flux of the + face, and its lift into Q; +nodal(f, o) the same with the flux at the points of a face quadrature + (face_quadrature) and its moments; +drTaylor dynamic rupture as SeisSol reads the fault: the Taylor +drEval(a, b) expansion of the cell at a time point, evaluated at the points +drBack(a, b) of the fault seen from side a with orientation b (V3mTo2n); the + flux of the fault goes back through V3mTo2nTWDivM; +drTrace(f, o) dynamic rupture through the trace: the traces of the time +drCombine derivatives in the canonical frame, evaluated at the fault's +drFaceBack points once per face and combined per time point; the flux goes +(f, o) back through its moments on the face and the lift. + +In the Dubiner basis every operator is a matrix. The Bernstein basis applies +the factors of bernstein_matrices: the derivative as a difference stencil +(its factor, the degree, moves into the Taylor coefficients, see +Operators.derivative_scale), sums of time derivatives of different degree by +Horner's scheme with the elevation, the trace as a gather and the lift +factorised. +""" + +import math + +import numpy as np +from yateto import Scalar, Tensor +from yateto.memory import CSCMemoryLayout, DenseMemoryLayout +from yateto.type import AddressingMode + +from seissol_matrices import ( + bernstein_matrices, + dg_matrices, + dr_matrices, + face_quadrature, + quad_points, +) + +QUANTITIES = 9 +FAMILIES = ("dubiner", "bernstein") +STORAGES = ("dense", "csc", "immediate") +ORIENTATIONS = ("sorted", "all") + + +def dim3(degree): + return bernstein_matrices.count(degree, 3) + + +def dim2(degree): + return bernstein_matrices.count(degree, 2) + + +class WholeLayout: + """ + The layout of an operator written into the code: dense over its whole + shape, whatever its non-zeros. A GEMM widens its rows to the vector + boundary as soon as the layout of an operand has an aligned stride, which a + bounding box that starts at an unaligned row can have as well; over the + whole shape, the widened rows lie inside the layout. + """ + + @staticmethod + def fromSpp(spp, alignStride=False, alignOffset=0, alignmentArch=None): + return DenseMemoryLayout( + tuple(spp.shape), alignStride=alignStride, alignmentArch=alignmentArch + ) + + +def embed(block, shape): + """The block in the leading rows and columns of a zero matrix.""" + matrix = np.zeros(shape) + matrix[: block.shape[0], : block.shape[1]] = block + return matrix + + +class Operators: + """ + The constant operators of the blocks as numpy arrays, at the shape of the + scheme's degree: an operator of a lower degree sits in the leading rows and + columns, which is where the degrees of freedom of that degree are kept. + + `orientations` selects the orientations of the faces against their + canonical frame that the kernels cover: "sorted", the one each face has + when a cell orders its vertices by their global IDs, or "all" six. + """ + + def __init__(self, order, family, orientations="sorted"): + if family not in FAMILIES: + raise ValueError(f"unknown family {family}") + if orientations not in ORIENTATIONS: + raise ValueError(f"unknown orientations {orientations}") + self.order = order + self.family = family + self.degree = order - 1 + self.n3 = dim3(self.degree) + self.n2 = dim2(self.degree) + self.dg = dg_matrices.dg_generator(order, 3, family) + if orientations == "sorted": + self.combos = [ + ( + f, + dg_matrices.FACE_ORIENTATIONS.index( + dg_matrices.sorted_vertex_ranks(f) + ), + ) + for f in range(4) + ] + else: + self.combos = [ + (f, o) + for f in range(4) + for o in range(len(dg_matrices.FACE_ORIENTATIONS)) + ] + self.dr_combos = [(a, b) for a in range(4) for b in range(4)] + self.face_rule = face_quadrature.FaceQuadratureGenerator(order, family) + self.dr = dr_matrices.dr_generator(order, quad_points.stroud(order + 1), family) + self._derivatives = {} + self._canonical = {} + + @property + def bernstein(self): + return self.family == "bernstein" + + def derivative(self, k, direction): + """The map from dQ(k - 1), of degree N - k + 1, to the part of dQ(k) of + the direction.""" + m = self.degree - k + 1 + if self.bernstein: + block = bernstein_matrices.derivative(m, 3, direction) / m + else: + if direction not in self._derivatives: + self._derivatives[direction] = self.dg.kDivMT(direction) + block = self._derivatives[direction][: dim3(m - 1), : dim3(m)] + return embed(block, (self.n3, self.n3)) + + def derivative_scale(self, k): + """dQ(k) over what ck computes for it: the product of the degrees that the + difference stencils of the Bernstein basis leave out.""" + if not self.bernstein: + return 1.0 + return float(math.perm(self.degree, k)) + + def elevation(self, m): + """The elevation from degree m - 1 to m in the cell (Bernstein basis).""" + return embed(bernstein_matrices.elevation(m, 3), (self.n3, self.n3)) + + def canonical_rT(self, face, orientation): + key = (face, orientation) + if key not in self._canonical: + ranks = dg_matrices.FACE_ORIENTATIONS[orientation] + self._canonical[key] = self.dg.canonical_rT(face, ranks) + return self._canonical[key] + + def trace(self, face, orientation, degree=None): + """The trace of a polynomial of the degree (by default N) in the canonical + frame of the face.""" + degree = self.degree if degree is None else degree + if self.bernstein: + ranks = dg_matrices.FACE_ORIENTATIONS[orientation] + block = bernstein_matrices.trace(degree, face, ranks) + else: + block = self.canonical_rT(face, orientation)[: dim2(degree), : dim3(degree)] + return embed(block, (self.n2, self.n3)) + + def face_mass(self): + return self.dg.face_generator.mass_matrix() + + def lift(self, face, orientation, moments=False): + """M^-1 rT^T M_face in the canonical frame (Dubiner basis): face + coefficients into the cell; with `moments`, M^-1 rT^T for the integrals + of a flux against the face basis instead.""" + rDivM = np.linalg.solve( + self.dg.mass_matrix(), self.canonical_rT(face, orientation).T + ) + return rDivM if moments else rDivM @ self.face_mass() + + def lift_face(self): + """L_0 of the factorised lift (Bernstein basis).""" + return bernstein_matrices.lift_face(self.degree) + + def lift_elevation(self, level): + """(E^(N - level + 1)_(N - level))^T: one level of the lift further.""" + m = self.degree - level + 1 + return embed(bernstein_matrices.elevation(m, 2).T, (self.n2, self.n2)) + + def lift_scatter(self, face, orientation, level): + """l_level S_level: a level of the lift into the cell.""" + ranks = dg_matrices.FACE_ORIENTATIONS[orientation] + scale = float(bernstein_matrices.lift_coefficients(self.degree)[level]) + indices = bernstein_matrices.lift_scatter_indices( + self.degree, face, level, ranks + ) + matrix = np.zeros((self.n3, self.n2)) + matrix[indices, np.arange(len(indices))] = scale + return matrix + + def from_moments(self, moments): + """The input of the factorised lift, L_0 M_face^-1, ahead of a matrix of + moments (Bernstein basis).""" + return self.lift_face() @ np.linalg.solve(self.face_mass(), moments) + + def nodal_values(self): + """The face basis at the points of the face quadrature (points x n2).""" + return self.face_rule.generate_V2mToFaceQuad() + + def nodal_moments(self): + """The integrals against the face basis from the points (n2 x points).""" + return self.face_rule.generate_VFaceQuadTo2m() + + def dr_points(self): + return self.dr.quadpoints().shape[0] + + def dr_volume(self, side, orientation): + return self.dr.V3mTo2n(side, orientation) + + def dr_volume_back(self, side, orientation): + return self.dr.V3mTo2nTWDivM(side, orientation) + + def dr_face_values(self, degree): + """The face basis of a degree at the fault's points, which are given in the + canonical frame of the face.""" + return embed(self.dr.V2mTo2Quad(degree), (self.dr_points(), self.n2)) + + def dr_moments(self): + weights = self.dr.quadweights() + return self.dr.V2mTo2Quad().T * weights[None, :] + + def time_nodes(self): + """The time points of the fault in a step of length one: Gauss-Legendre, + as many as the order.""" + nodes, _ = np.polynomial.legendre.leggauss(self.order) + return 0.5 * (nodes + 1.0) + + def taylor_coefficients(self, dt, scaled): + """ + The coefficients of dQ(k), k = 0 ... N, in the time integral over a step + dt ("integral"), the value at its end ("end") and the values at the time + points of the fault ("points", one row per point). `scaled` gives them + for the derivatives as ck computes them, see derivative_scale. + """ + N = self.degree + scale = np.array( + [self.derivative_scale(k) if scaled else 1.0 for k in range(N + 1)] + ) + k = np.arange(N + 1) + factorial = np.array([math.factorial(i) for i in k], dtype=float) + times = dt * self.time_nodes() + return { + "integral": scale * dt ** (k + 1) / (factorial * (k + 1)), + "end": scale * dt**k / factorial, + "points": scale[None, :] * times[:, None] ** k[None, :] / factorial, + } + + +class Kernels: + """The yateto kernels of the blocks for the operators of a basis, the storage + of the operators and the number of fused simulations.""" + + def __init__(self, operators, storage, simulations=1): + if storage not in STORAGES: + raise ValueError(f"unknown storage {storage}") + self.ops = operators + self.storage = storage + self.simulations = simulations + self.runtime = {} + self.operators = {} + self.costs = {} + self.temporaries = {} + N = operators.degree + n3, n2 = operators.n3, operators.n2 + P = operators.dr_points() + + self.Q = self._data("Q", n3) + self.I = self._data("I", n3) + self.dQ = {k: self._data(f"dQ({k})", n3, dim3(N - k)) for k in range(1, N + 1)} + self.star = { + d: self._runtime(Tensor(f"star({d})", (QUANTITIES, QUANTITIES))) + for d in range(3) + } + self.AminusT = self._runtime(Tensor("AminusT", (QUANTITIES, QUANTITIES))) + self.T = self._data("T", n2) + self.Tn = self._data("Tn", n2) + self.q = self._data("q", n3) + self.qp = self._data("qp", P) + self.F = self._data("F", P) + self.Pk = {k: self._data(f"Pk({k})", P) for k in range(N + 1)} + self.cI = {k: Scalar(f"cI({k})") for k in range(N + 1)} + self.cQ = {k: Scalar(f"cQ({k})") for k in range(N + 1)} + self.cT = {k: Scalar(f"cT({k})") for k in range(N + 1)} + + # tensors + + def _runtime(self, tensor): + self.runtime[tensor.name()] = tensor + return tensor + + def _data(self, name, rows, valid=None, temporary=False): + """Data of `rows` basis functions (or points) by the quantities, of which + the leading `valid` rows are used.""" + if self.simulations == 1: + shape = (rows, QUANTITIES) + else: + shape = (self.simulations, rows, QUANTITIES) + if temporary and name in self.temporaries: + return self.temporaries[name] + spp = None + if valid is not None and valid < rows: + spp = np.zeros(shape, dtype=bool) + spp[..., :valid, :] = True + tensor = Tensor(name, shape, spp=spp, alignStride=True, temporary=temporary) + if temporary: + self.temporaries[name] = tensor + return tensor + return self._runtime(tensor) + + def _operator(self, name, matrix, storage=None): + """A constant operator, created once per name, kept as `storage` (by + default the storage under test) says; transposed for fused simulations. + What is left of a zero after computing the matrix in floating point is + dropped.""" + if name in self.operators: + return self.operators[name] + storage = self.storage if storage is None else storage + stored = matrix if self.simulations == 1 else matrix.T + largest = np.abs(stored).max() + stored = np.where(np.abs(stored) > 1e-13 * largest, stored, 0.0) + spp = { + tuple(int(i) for i in entry): repr(float(stored[tuple(entry)])) + for entry in np.argwhere(stored != 0.0) + } + if storage == "dense": + tensor = Tensor(name, stored.shape, spp=spp, alignStride=True) + elif storage == "csc": + tensor = Tensor( + name, stored.shape, spp=spp, memoryLayoutClass=CSCMemoryLayout + ) + else: + tensor = Tensor( + name, + stored.shape, + spp=spp, + memoryLayoutClass=WholeLayout, + addressing=AddressingMode.IMMEDIATE, + ) + # entries a product with the operator goes through + self.costs[name] = len(spp) if storage != "dense" else self._box(stored) + self.operators[name] = tensor + return tensor + + @staticmethod + def _box(matrix): + rows, columns = np.nonzero(matrix) + return int((rows.max() - rows.min() + 1) * (columns.max() - columns.min() + 1)) + + def _ix(self, row, column="p"): + return row + column if self.simulations == 1 else "s" + row + column + + def _apply(self, operator, data, out, inner, column="p"): + """The operator times the data; `out` indexes the rows of the operator, + `inner` its columns and the rows of the data.""" + if self.simulations == 1: + return operator[out + inner] * data[inner + column] + return data["s" + inner + column] * operator[inner + out] + + # building blocks of the kernels + + def _sum(self, coefficients, first, k_range): + """first + the sum over k of coefficients[k] dQ(k), for a hierarchical + basis, in which dQ(k) is the leading part of degree N.""" + ix = self._ix("a") + expression = first + for k in k_range: + expression = expression + coefficients[k] * self.dQ[k][ix] + return expression + + def _horner(self, name, coefficients): + """J(1) = sum over k >= 1 of coefficients[k] (dQ(k) elevated to degree + N - 1), from J(N) = coefficients[N] dQ(N) by + J(k) = coefficients[k] dQ(k) + E(N - k) J(k + 1). Returns the statements + and J(1).""" + N = self.ops.degree + ix = self._ix("a") + statements = [] + previous = None + for k in range(N, 0, -1): + J = self._data(f"{name}{k}", self.ops.n3, dim3(N - k), temporary=True) + expression = coefficients[k] * self.dQ[k][ix] + if previous is not None: + expression = expression + self._apply( + self._elevation(N - k), previous, "a", "b" + ) + statements.append(J[ix] <= expression) + previous = J + return statements, previous + + def _elevation(self, m): + return self._operator(f"E({m})", self.ops.elevation(m)) + + def _taylor_into(self, target, coefficients, name, accumulate): + """target = coefficients[0] Q + sum over k >= 1 of coefficients[k] dQ(k), + or target += the sum over k >= 1 (`accumulate`).""" + N = self.ops.degree + ix = self._ix("a") + first = self.Q[ix] if accumulate else coefficients[0] * self.Q[ix] + if not self.ops.bernstein: + return [target[ix] <= self._sum(coefficients, first, range(1, N + 1))] + statements, J1 = self._horner(name, coefficients) + statements.append( + target[ix] <= first + self._apply(self._elevation(N), J1, "a", "b") + ) + return statements + + def _chain(self, face, orientation, X0, tag): + """Q += sum over the levels j of l_j S_j (E^N_(N-j))^T X0 (Bernstein).""" + N = self.ops.degree + ix, ik = self._ix("a"), self._ix("k") + statements = [] + current = X0 + for level in range(N + 1): + if level > 0: + X = self._data( + f"{tag}X{level}", self.ops.n2, dim2(N - level), temporary=True + ) + elevation = self._operator( + f"LE({level})", self.ops.lift_elevation(level) + ) + statements.append(X[ix] <= self._apply(elevation, current, "a", "b")) + current = X + scatter = self._operator( + f"S({face},{orientation},{level})", + self.ops.lift_scatter(face, orientation, level), + ) + statements.append( + self.Q[ik] <= self.Q[ik] + self._apply(scatter, current, "k", "a") + ) + return statements + + def _lift(self, face, orientation, F, tag): + """Q += the lift of F, given by its face coefficients.""" + ix, ik = self._ix("a"), self._ix("k") + if not self.ops.bernstein: + lift = self._operator( + f"L({face},{orientation})", self.ops.lift(face, orientation) + ) + return [self.Q[ik] <= self.Q[ik] + self._apply(lift, F, "k", "a")] + X0 = self._data(f"{tag}X0", self.ops.n2, temporary=True) + L0 = self._operator("L0", self.ops.lift_face()) + return [X0[ix] <= self._apply(L0, F, "a", "b")] + self._chain( + face, orientation, X0, tag + ) + + def _lift_points(self, face, orientation, Fp, moments, tag): + """Q += the lift of a flux given at points, from its moments + (moments: face basis by points). The Dubiner basis takes the moments and + the lift as one matrix if that is cheaper.""" + ix, ik = self._ix("a"), self._ix("k") + if self.ops.bernstein: + X0 = self._data(f"{tag}X0", self.ops.n2, temporary=True) + W = self._operator(f"{tag}W", self.ops.from_moments(moments), "dense") + return [X0[ix] <= self._apply(W, Fp, "a", "i")] + self._chain( + face, orientation, X0, tag + ) + lift = self.ops.lift(face, orientation, moments=True) + W = self._operator(f"{tag}W", moments, "dense") + separate = self._operator(f"{tag}L({face},{orientation})", lift) + folded = self._operator( + f"{tag}LW({face},{orientation})", lift @ moments, "dense" + ) + cost = lambda tensor: self.costs[tensor.name()] + if cost(folded) <= cost(W) + cost(separate): + return [self.Q[ik] <= self.Q[ik] + self._apply(folded, Fp, "k", "i")] + X = self._data(f"{tag}X", self.ops.n2, temporary=True) + return [ + X[ix] <= self._apply(W, Fp, "a", "i"), + self.Q[ik] <= self.Q[ik] + self._apply(separate, X, "k", "a"), + ] + + # kernels + + def add_to(self, generator): + self._add_predictor(generator) + self._add_faces(generator) + self._add_dr_volume(generator) + self._add_dr_face(generator) + + def _add_predictor(self, generator): + N = self.ops.degree + ix = self._ix("a") + statements = [] + previous = self.Q + for k in range(1, N + 1): + terms = [ + self._apply( + self._operator(f"kD({k},{d})", self.ops.derivative(k, d)), + previous, + "a", + "b", + "q", + ) + * self.star[d]["qp"] + for d in range(3) + ] + statements.append(self.dQ[k][ix] <= terms[0] + terms[1] + terms[2]) + previous = self.dQ[k] + generator.add("ck", statements) + generator.add( + "taylor", + self._taylor_into(self.I, self.cI, "tI", accumulate=False) + + self._taylor_into(self.Q, self.cQ, "tQ", accumulate=True), + ) + + def _add_faces(self, generator): + ops = self.ops + ix, ii = self._ix("a"), self._ix("i") + traces = { + (f, o): self._operator(f"tr({f},{o},0)", ops.trace(f, o)) + for f, o in ops.combos + } + generator.addFamily( + "trace", + ops.combos, + lambda f, o: self.T[ix] <= self._apply(traces[(f, o)], self.I, "a", "l"), + ) + + J = self._data("fJ", ops.n2, temporary=True) + F = self._data("fF", ops.n2, temporary=True) + jump = [ + J[ix] <= self.Tn[ix] - self.T[ix], + F[ix] <= J[self._ix("a", "q")] * self.AminusT["qp"], + ] + generator.addFamily( + "lift", ops.combos, lambda f, o: jump + self._lift(f, o, F, "f") + ) + + points = ops.nodal_values().shape[0] + V = self._operator("nV", ops.nodal_values(), "dense") + Jp = self._data("nJ", points, temporary=True) + Fp = self._data("nF", points, temporary=True) + nodal_jump = [ + J[ix] <= self.Tn[ix] - self.T[ix], + Jp[ii] <= self._apply(V, J, "i", "a"), + Fp[ii] <= Jp[self._ix("i", "q")] * self.AminusT["qp"], + ] + moments = ops.nodal_moments() + generator.addFamily( + "nodal", + ops.combos, + lambda f, o: nodal_jump + self._lift_points(f, o, Fp, moments, "n"), + ) + + def _add_dr_volume(self, generator): + ops = self.ops + ii, ik = self._ix("i"), self._ix("k") + generator.add( + "drTaylor", self._taylor_into(self.q, self.cT, "tT", accumulate=False) + ) + volume = { + (a, b): self._operator(f"V3({a},{b})", ops.dr_volume(a, b), "dense") + for a, b in ops.dr_combos + } + generator.addFamily( + "drEval", + ops.dr_combos, + lambda a, b: self.qp[ii] <= self._apply(volume[(a, b)], self.q, "i", "a"), + ) + back = { + (a, b): self._operator(f"V3TW({a},{b})", ops.dr_volume_back(a, b), "dense") + for a, b in ops.dr_combos + } + generator.addFamily( + "drBack", + ops.dr_combos, + lambda a, b: self.Q[ik] + <= self.Q[ik] + self._apply(back[(a, b)], self.F, "k", "i"), + ) + + def _add_dr_face(self, generator): + ops = self.ops + N = ops.degree + ix, ii = self._ix("a"), self._ix("i") + values = { + k: self._operator(f"V2({k})", ops.dr_face_values(N - k), "dense") + for k in range(N + 1) + } + + def traces(f, o): + statements = [] + for k in range(N + 1): + source = self.Q if k == 0 else self.dQ[k] + trace = self._operator(f"tr({f},{o},{k})", ops.trace(f, o, N - k)) + Tk = self._data(f"dT{k}", ops.n2, dim2(N - k), temporary=True) + statements.append(Tk[ix] <= self._apply(trace, source, "a", "l")) + statements.append( + self.Pk[k][ii] <= self._apply(values[k], Tk, "i", "a") + ) + return statements + + generator.addFamily("drTrace", ops.combos, traces) + combination = self.cT[0] * self.Pk[0][ii] + for k in range(1, N + 1): + combination = combination + self.cT[k] * self.Pk[k][ii] + generator.add("drCombine", self.qp[ii] <= combination) + moments = ops.dr_moments() + generator.addFamily( + "drFaceBack", + ops.combos, + lambda f, o: self._lift_points(f, o, self.F, moments, "d"), + ) diff --git a/tools/basis_benchmark/check.py b/tools/basis_benchmark/check.py new file mode 100644 index 0000000..24d8133 --- /dev/null +++ b/tools/basis_benchmark/check.py @@ -0,0 +1,170 @@ +""" +What the kernels of blocks.py have to compute on the input of `driver --check`, +from the dense operators of seissol_matrices, and the comparison with what they +wrote. +""" + +import numpy as np + +from seissol_matrices import basis_functions, bernstein_matrices, dg_matrices + +from blocks import QUANTITIES, dim3 + + +def value(h, shape): + """The input the driver writes for the number h: one sine per entry + (simulation, row, column).""" + s, i, j = np.meshgrid(*[np.arange(n) for n in shape], indexing="ij") + return np.sin(0.1 + 0.37 * h + 0.417 * s + 0.731 * i + 1.913 * j) + + +def read(path): + """The records of a --check file: name -> array (simulations, rows, columns).""" + records = {} + with open(path, "rb") as f: + while True: + header = f.readline() + if not header: + break + name, *shape = header.decode().split() + shape = tuple(int(n) for n in shape) + data = np.frombuffer(f.read(8 * int(np.prod(shape))), dtype=np.float64) + records[name] = data.reshape(shape) + return records + + +class Reference: + """The expected results for the operators of a basis, `simulations` fused, + and the Taylor coefficients the driver used (unscaled).""" + + def __init__(self, ops, simulations, coefficients): + self.ops = ops + self.S = simulations + self.c = coefficients + self.dg = ops.dg + N = ops.degree + self.Q1 = value(1, (self.S, ops.n3, QUANTITIES)) + self.Q2 = value(2, (self.S, ops.n3, QUANTITIES)) + self.star = [value(10 + d, (1, QUANTITIES, QUANTITIES))[0] for d in range(3)] + self.A = value(20, (1, QUANTITIES, QUANTITIES))[0] + self.T = value(30, (self.S, ops.n2, QUANTITIES)) + self.Tn = value(31, (self.S, ops.n2, QUANTITIES)) + self.F = value(40, (self.S, ops.dr_points(), QUANTITIES)) + + # the time derivatives, of degree N - k in the leading rows + self.dQ = [self.Q1] + for k in range(1, N + 1): + m = N - k + 1 + previous = self.dQ[-1][:, : dim3(m)] + current = np.zeros_like(self.Q1) + for d in range(3): + if ops.bernstein: + D = bernstein_matrices.derivative(m, 3, d) + else: + D = self.dg.kDivMT(d)[: dim3(m - 1), : dim3(m)] + current[:, : dim3(m - 1)] += np.einsum( + "ab,sbq,qp->sap", D, previous, self.star[d] + ) + self.dQ.append(current) + + def elevated(self, k): + """dQ(k) as a polynomial of degree N.""" + N = self.ops.degree + if not self.ops.bernstein: + return self.dQ[k] + E = np.eye(dim3(N - k)) + for m in range(N - k + 1, N + 1): + E = bernstein_matrices.elevation(m, 3) @ E + return np.einsum("ab,sbp->sap", E, self.dQ[k][:, : dim3(N - k)]) + + def taylor(self, coefficients): + return sum(c * self.elevated(k) for k, c in enumerate(coefficients)) + + def ranks(self, orientation): + return dg_matrices.FACE_ORIENTATIONS[orientation] + + def lift(self, face, orientation): + """M^-1 rT^T for the moments of a flux on a face in its canonical frame.""" + return np.linalg.solve( + self.dg.mass_matrix(), + self.dg.canonical_rT(face, self.ranks(orientation)).T, + ) + + def expected(self, records): + """name -> expected array, for every record of a --check file.""" + ops = self.ops + N = ops.degree + Mf = ops.face_mass() + result = {} + for k in range(1, N + 1): + result[f"dQ({k})"] = self.dQ[k] / ops.derivative_scale(k) + result["I"] = self.taylor(self.c["integral"]) + result["Qend"] = self.taylor(self.c["end"]) + V = ops.nodal_values() + W = ops.nodal_moments() + jump = self.Tn - self.T + for f, o in ops.combos: + rT = self.dg.canonical_rT(f, self.ranks(o)) + result[f"trace({f},{o})"] = np.einsum("al,slp->sap", rT, records["I"]) + lift = self.lift(f, o) + flux = np.einsum("saq,qp->sap", jump, self.A) + result[f"lift({f},{o})"] = self.Q2 + np.einsum( + "ka,ab,sbp->skp", lift, Mf, flux + ) + points = np.einsum("ia,saq,qp->sip", V, jump, self.A) + result[f"nodal({f},{o})"] = self.Q2 + np.einsum( + "ka,ai,sip->skp", lift, W, points + ) + + result["q"] = self.taylor(self.c["points"][0]) + for a, b in ops.dr_combos: + result[f"drEval({a},{b})"] = np.einsum( + "ia,sap->sip", ops.dr_volume(a, b), records["q"] + ) + result[f"drBack({a},{b})"] = self.Q2 + np.einsum( + "ki,sip->skp", ops.dr_volume_back(a, b), self.F + ) + rule = ops.dr.quadrule + weights = rule.weights() + values = ops.dr.V2mTo2Quad() + for f, o in ops.combos: + local = dg_matrices.canonical_to_face_parametrisation( + rule.points().T, self.ranks(o) + ) + points = dg_matrices.volume_to_face_parametrisation(local, f) + fault = 0 + for k, c in enumerate(self.c["points"][0]): + basis = basis_functions.generator(ops.family, 3, N - k + 1) + fault = fault + c * np.einsum( + "ia,sap->sip", + basis.eval_all(points), + self.dQ[k][:, : dim3(N - k)], + ) + result[f"drFace({f},{o})"] = fault + result[f"drFaceBack({f},{o})"] = self.Q2 + np.einsum( + "ka,ia,i,sip->skp", self.lift(f, o), values, weights, self.F + ) + return result + + +def compare(records, expected, tolerance=1e-9): + """The records that differ from what is expected by more than the tolerance, + relative to the largest expected entry where that exceeds one, and the + largest such difference.""" + failures = [] + worst = 0.0 + missing = sorted(set(expected) - set(records)) + for name, data in records.items(): + if name not in expected: + failures.append((name, "unexpected")) + continue + target = expected[name] + if target.shape != data.shape: + failures.append((name, f"shape {data.shape} instead of {target.shape}")) + continue + error = np.abs(data - target).max() / max(1.0, np.abs(target).max()) + worst = max(worst, error) + if not error <= tolerance: + failures.append((name, f"relative error {error:.2e}")) + failures += [(name, "missing") for name in missing] + return failures, worst diff --git a/tools/basis_benchmark/driver.cpp b/tools/basis_benchmark/driver.cpp new file mode 100644 index 0000000..eca6c39 --- /dev/null +++ b/tools/basis_benchmark/driver.cpp @@ -0,0 +1,569 @@ +// Times the blocks of blocks.py as yateto generated them into the build +// directory, per cell (per fault face for dynamic rupture), or with --check +// runs each kernel once on known input and writes what it computed, for +// benchmark.py to compare with numpy. +// +// setup.h, written by benchmark.py next to the generated code, holds the +// configuration, the Taylor coefficients and the memory layouts of the data. + +#include "init.h" +#include "kernel.h" +#include "setup.h" +#include "tensor.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using real = double; +namespace yk = yateto::kernel; +namespace yt = yateto::tensor; + +constexpr int N = setup::Degree; +constexpr int Faces = 4; + +real* allocate(std::size_t count) { + std::size_t bytes = ((count * sizeof(real) + 63) / 64) * 64; + auto* data = static_cast(std::aligned_alloc(64, bytes == 0 ? 64 : bytes)); + if (data == nullptr) { + std::fprintf(stderr, "out of memory\n"); + std::exit(1); + } + std::memset(data, 0, bytes == 0 ? 64 : bytes); + return data; +} + +// `count` items of `size` reals each, every item on a cache line of its own +struct Store { + real* data = nullptr; + std::size_t stride = 0; + std::size_t count = 0; + void init(std::size_t size, std::size_t items) { + stride = ((size + 7) / 8) * 8; + count = items; + data = allocate(stride * items); + } + real* operator[](std::size_t i) const { return data + stride * i; } + std::size_t bytes() const { return stride * count * sizeof(real); } +}; + +// the logical entry (s, row, column) of a tensor in its memory layout, or -1 +// where the layout keeps nothing (which reads as zero) +long address(const setup::Layout& layout, unsigned s, unsigned row, unsigned column) { + unsigned entry[3]; + if (layout.rank == 2) { + entry[0] = row; + entry[1] = column; + } else { + entry[0] = s; + entry[1] = row; + entry[2] = column; + } + long result = 0; + for (int d = 0; d < layout.rank; ++d) { + if (entry[d] < layout.start[d] || entry[d] >= layout.stop[d]) { + return -1; + } + result += static_cast(entry[d] - layout.start[d]) * layout.stride[d]; + } + return result; +} + +unsigned sims(const setup::Layout& layout) { return layout.rank == 2 ? 1 : layout.shape[0]; } +unsigned rows(const setup::Layout& layout) { return layout.shape[layout.rank - 2]; } +unsigned columns(const setup::Layout& layout) { return layout.shape[layout.rank - 1]; } + +// the input benchmark.py expects: sin(0.1 + 0.37 h + 0.417 s + 0.731 i + 1.913 j) +real value(int h, unsigned s, unsigned i, unsigned j) { + return std::sin(0.1 + 0.37 * h + 0.417 * s + 0.731 * i + 1.913 * j); +} + +void fill(const setup::Layout& layout, real* data, int h, unsigned validRows = ~0u) { + for (unsigned s = 0; s < sims(layout); ++s) { + for (unsigned i = 0; i < rows(layout) && i < validRows; ++i) { + for (unsigned j = 0; j < columns(layout); ++j) { + long a = address(layout, s, i, j); + if (a >= 0) { + data[a] = value(h, s, i, j); + } + } + } + } +} + +void dump(std::FILE* file, const std::string& name, const setup::Layout& layout, const real* data) { + std::fprintf(file, "%s %u %u %u\n", name.c_str(), sims(layout), rows(layout), columns(layout)); + std::vector values; + for (unsigned s = 0; s < sims(layout); ++s) { + for (unsigned i = 0; i < rows(layout); ++i) { + for (unsigned j = 0; j < columns(layout); ++j) { + long a = address(layout, s, i, j); + values.push_back(a >= 0 ? data[a] : 0.0); + } + } + } + std::fwrite(values.data(), sizeof(real), values.size(), file); +} + +template +double bestTime(Body&& body, int repetitions) { + body(); + double best = 1e300; + for (int r = 0; r < repetitions; ++r) { + auto start = std::chrono::steady_clock::now(); + body(); + auto stop = std::chrono::steady_clock::now(); + best = std::min(best, std::chrono::duration(stop - start).count()); + } + return best; +} + +struct Fault { + std::size_t cell[2]; + unsigned face[2]; + unsigned orientation[2]; // against the canonical frame of the face + unsigned side[2]; // b of V3mTo2n(a, b): 0 on the first side +}; + +struct Run { + std::size_t cells = 0; + std::size_t faults = 0; + Store Q, I, dQ[N + 1], star[3], AminusT, traces; + Store qp, F, q, Pk[N + 1]; + std::vector neighbour; + std::vector neighbourFace, orientation; + std::vector fault; + + yk::ck ck; + yk::taylor taylor; + yk::trace trace; + yk::lift lift; + yk::nodal nodal; + yk::drTaylor drTaylor; + yk::drEval drEval; + yk::drBack drBack; + yk::drTrace drTrace; + yk::drCombine drCombine; + yk::drFaceBack drFaceBack; + + void allocate(std::size_t numberOfCells, std::size_t numberOfFaults, unsigned seed) { + cells = numberOfCells; + faults = numberOfFaults; + Q.init(yt::Q::size(), cells); + I.init(yt::I::size(), cells); + for (int k = 1; k <= N; ++k) { + dQ[k].init(yt::dQ::size(k), cells); + } + for (int d = 0; d < 3; ++d) { + star[d].init(yt::star::size(d), cells); + } + AminusT.init(yt::AminusT::size(), Faces * cells); + static_assert(yt::T::Size == yt::Tn::Size, "both traces share a buffer"); + traces.init(yt::T::size(), Faces * cells); + qp.init(yt::qp::size(), 2 * setup::TimePoints * faults); + F.init(yt::F::size(), 2 * faults); + q.init(yt::q::size(), 1); + for (int k = 0; k <= N; ++k) { + Pk[k].init(yt::Pk::size(k), 1); + } + + std::mt19937 random(seed); + // neighbours mostly close by, as in a mesh ordered along a curve + const std::size_t offsets[Faces] = {1, 3, cells / 7 + 1, cells - 1}; + neighbour.resize(Faces * cells); + neighbourFace.resize(Faces * cells); + orientation.resize(Faces * cells); + for (std::size_t c = 0; c < cells; ++c) { + for (unsigned f = 0; f < Faces; ++f) { + neighbour[Faces * c + f] = (c + offsets[f]) % cells; + neighbourFace[Faces * c + f] = random() % Faces; + orientation[Faces * c + f] = pickOrientation(f, random); + } + } + fault.resize(faults); + for (std::size_t i = 0; i < faults; ++i) { + for (int s = 0; s < 2; ++s) { + fault[i].cell[s] = random() % cells; + fault[i].face[s] = random() % Faces; + fault[i].orientation[s] = pickOrientation(fault[i].face[s], random); + fault[i].side[s] = s == 0 ? 0 : 1 + random() % 3; + } + } + + // values of order one everywhere, so that no block meets denormals + for (std::size_t c = 0; c < cells; ++c) { + fill(setup::layout_Q, Q[c], 1 + c % 5); + fill(setup::layout_I, I[c], 2 + c % 5); + for (int k = 1; k <= N; ++k) { + fill(setup::layout_dQ[k], dQ[k][c], 3 + k + c % 5); + } + for (int d = 0; d < 3; ++d) { + fill(setup::layout_star, star[d][c], 20 + d + c % 3); + } + for (unsigned f = 0; f < Faces; ++f) { + fill(setup::layout_AminusT, AminusT[Faces * c + f], 30 + f + c % 3); + fill(setup::layout_T, traces[Faces * c + f], 40 + f + c % 3); + } + } + for (std::size_t i = 0; i < 2 * faults; ++i) { + fill(setup::layout_F, F[i], 50 + i % 7); + } + + const auto& pool = yateto::Pool::host(); + ck.bindGlobals(pool); + taylor.bindGlobals(pool); + trace.bindGlobals(pool); + lift.bindGlobals(pool); + nodal.bindGlobals(pool); + drTaylor.bindGlobals(pool); + drEval.bindGlobals(pool); + drBack.bindGlobals(pool); + drTrace.bindGlobals(pool); + drCombine.bindGlobals(pool); + drFaceBack.bindGlobals(pool); + for (int k = 0; k <= N; ++k) { + taylor.cI(k) = setup::IntegralCoefficients[k]; + taylor.cQ(k) = setup::EndCoefficients[k]; + } + } + + static unsigned pickOrientation(unsigned face, std::mt19937& random) { + if (setup::AllOrientations) { + return random() % 6; + } + return setup::SortedOrientation[face]; + } + + std::size_t bytesPerCell() const { + std::size_t bytes = Q.stride + I.stride + 3 * star[0].stride + + Faces * (AminusT.stride + traces.stride); + for (int k = 1; k <= N; ++k) { + bytes += dQ[k].stride; + } + return bytes * sizeof(real); + } + + // the blocks, for one cell or fault face + + void runCk(std::size_t c) { + ck.Q = Q[c]; + for (int k = 1; k <= N; ++k) { + ck.dQ(k) = dQ[k][c]; + } + for (int d = 0; d < 3; ++d) { + ck.star(d) = star[d][c]; + } + ck.execute(); + } + + void runTaylor(std::size_t c) { + taylor.Q = Q[c]; + taylor.I = I[c]; + for (int k = 1; k <= N; ++k) { + taylor.dQ(k) = dQ[k][c]; + } + taylor.execute(); + } + + void runTrace(std::size_t c) { + trace.I = I[c]; + for (unsigned f = 0; f < Faces; ++f) { + trace.T = traces[Faces * c + f]; + trace.execute(f, orientation[Faces * c + f]); + } + } + + template + void runFlux(Kernel& kernel, std::size_t c) { + kernel.Q = Q[c]; + for (unsigned f = 0; f < Faces; ++f) { + std::size_t i = Faces * c + f; + kernel.T = traces[i]; + kernel.Tn = traces[Faces * neighbour[i] + neighbourFace[i]]; + kernel.AminusT = AminusT[i]; + kernel.execute(f, orientation[i]); + } + } + + void setDerivatives(std::size_t c) { + drTaylor.Q = Q[c]; + drTrace.Q = Q[c]; + for (int k = 1; k <= N; ++k) { + drTaylor.dQ(k) = dQ[k][c]; + drTrace.dQ(k) = dQ[k][c]; + } + } + + void runDrVolume(std::size_t i) { + for (int s = 0; s < 2; ++s) { + const Fault& face = fault[i]; + setDerivatives(face.cell[s]); + drTaylor.q = q[0]; + drEval.q = q[0]; + for (int t = 0; t < setup::TimePoints; ++t) { + for (int k = 0; k <= N; ++k) { + drTaylor.cT(k) = setup::PointCoefficients[t][k]; + } + drTaylor.execute(); + drEval.qp = qp[(2 * i + s) * setup::TimePoints + t]; + drEval.execute(face.face[s], face.side[s]); + } + drBack.Q = Q[face.cell[s]]; + drBack.F = F[2 * i + s]; + drBack.execute(face.face[s], face.side[s]); + } + } + + void runDrFace(std::size_t i) { + for (int s = 0; s < 2; ++s) { + const Fault& face = fault[i]; + setDerivatives(face.cell[s]); + for (int k = 0; k <= N; ++k) { + drTrace.Pk(k) = Pk[k][0]; + drCombine.Pk(k) = Pk[k][0]; + } + drTrace.execute(face.face[s], face.orientation[s]); + for (int t = 0; t < setup::TimePoints; ++t) { + for (int k = 0; k <= N; ++k) { + drCombine.cT(k) = setup::PointCoefficients[t][k]; + } + drCombine.qp = qp[(2 * i + s) * setup::TimePoints + t]; + drCombine.execute(); + } + drFaceBack.Q = Q[face.cell[s]]; + drFaceBack.F = F[2 * i + s]; + drFaceBack.execute(face.face[s], face.orientation[s]); + } + } +}; + +struct Result { + const char* block; + std::size_t items; + double seconds; + double nonZeroFlops; + double hardwareFlops; +}; + +void benchmark(std::size_t bytes, int repetitions, unsigned seed) { + Run run; + // a first allocation of a few cells tells the size of a cell + { + Run probe; + probe.allocate(16, 1, seed); + std::size_t cells = std::max(16, bytes / probe.bytesPerCell()); + run.allocate(cells, std::max(4, cells / 4), seed); + } + + double traceFlops[2] = {0, 0}, liftFlops[2] = {0, 0}, nodalFlops[2] = {0, 0}; + for (std::size_t i = 0; i < Faces * run.cells; ++i) { + unsigned f = i % Faces, o = run.orientation[i]; + traceFlops[0] += yk::trace::nonZeroFlops(f, o); + traceFlops[1] += yk::trace::hardwareFlops(f, o); + liftFlops[0] += yk::lift::nonZeroFlops(f, o); + liftFlops[1] += yk::lift::hardwareFlops(f, o); + nodalFlops[0] += yk::nodal::nonZeroFlops(f, o); + nodalFlops[1] += yk::nodal::hardwareFlops(f, o); + } + double volumeFlops[2] = {0, 0}, faceFlops[2] = {0, 0}; + for (const Fault& face : run.fault) { + for (int s = 0; s < 2; ++s) { + volumeFlops[0] += setup::TimePoints * (yk::drTaylor::NonZeroFlops + + yk::drEval::nonZeroFlops(face.face[s], face.side[s])) + + yk::drBack::nonZeroFlops(face.face[s], face.side[s]); + volumeFlops[1] += setup::TimePoints * (yk::drTaylor::HardwareFlops + + yk::drEval::hardwareFlops(face.face[s], face.side[s])) + + yk::drBack::hardwareFlops(face.face[s], face.side[s]); + faceFlops[0] += yk::drTrace::nonZeroFlops(face.face[s], face.orientation[s]) + + setup::TimePoints * yk::drCombine::NonZeroFlops + + yk::drFaceBack::nonZeroFlops(face.face[s], face.orientation[s]); + faceFlops[1] += yk::drTrace::hardwareFlops(face.face[s], face.orientation[s]) + + setup::TimePoints * yk::drCombine::HardwareFlops + + yk::drFaceBack::hardwareFlops(face.face[s], face.orientation[s]); + } + } + const double cells = run.cells, faults = run.faults; + + std::vector results; + auto overCells = [&](auto&& body) { + return bestTime( + [&] { + for (std::size_t c = 0; c < run.cells; ++c) { + body(c); + } + }, + repetitions); + }; + results.push_back({"ck", run.cells, overCells([&](std::size_t c) { run.runCk(c); }), + double(yk::ck::NonZeroFlops), double(yk::ck::HardwareFlops)}); + results.push_back({"taylor", run.cells, overCells([&](std::size_t c) { run.runTaylor(c); }), + double(yk::taylor::NonZeroFlops), double(yk::taylor::HardwareFlops)}); + results.push_back({"trace", run.cells, overCells([&](std::size_t c) { run.runTrace(c); }), + traceFlops[0] / cells, traceFlops[1] / cells}); + results.push_back({"lift", run.cells, + overCells([&](std::size_t c) { run.runFlux(run.lift, c); }), + liftFlops[0] / cells, liftFlops[1] / cells}); + results.push_back({"nodal", run.cells, + overCells([&](std::size_t c) { run.runFlux(run.nodal, c); }), + nodalFlops[0] / cells, nodalFlops[1] / cells}); + auto overFaults = [&](auto&& body) { + return bestTime( + [&] { + for (std::size_t i = 0; i < run.faults; ++i) { + body(i); + } + }, + repetitions); + }; + results.push_back({"dr-volume", run.faults, + overFaults([&](std::size_t i) { run.runDrVolume(i); }), + volumeFlops[0] / faults, volumeFlops[1] / faults}); + results.push_back({"dr-face", run.faults, overFaults([&](std::size_t i) { run.runDrFace(i); }), + faceFlops[0] / faults, faceFlops[1] / faults}); + + std::printf("# %s %s order %d simulations %d %s orientations, %zu cells (%.1f MB), " + "%zu fault faces\n", + setup::Family, setup::Storage, setup::Order, setup::Simulations, + setup::AllOrientations ? "all" : "sorted", run.cells, + run.cells * run.bytesPerCell() / 1e6, run.faults); + std::printf("block,items,ns_per_item,nonzero_flops,hardware_flops,hardware_gflops\n"); + for (const Result& r : results) { + double ns = 1e9 * r.seconds / r.items; + std::printf("%s,%zu,%.2f,%.0f,%.0f,%.2f\n", r.block, r.items, ns, r.nonZeroFlops, + r.hardwareFlops, r.hardwareFlops / ns); + } +} + +void check(const char* path) { + Run run; + run.allocate(2, 1, 1); + std::FILE* file = std::fopen(path, "wb"); + if (file == nullptr) { + std::fprintf(stderr, "cannot write %s\n", path); + std::exit(1); + } + auto name = [](const char* base, int a, int b = -1) { + std::string result = std::string(base) + "(" + std::to_string(a); + if (b >= 0) { + result += "," + std::to_string(b); + } + return result + ")"; + }; + + fill(setup::layout_Q, run.Q[0], 1); + for (int d = 0; d < 3; ++d) { + fill(setup::layout_star, run.star[d][0], 10 + d); + } + run.runCk(0); + for (int k = 1; k <= N; ++k) { + dump(file, name("dQ", k), setup::layout_dQ[k], run.dQ[k][0]); + } + run.runTaylor(0); + dump(file, "I", setup::layout_I, run.I[0]); + dump(file, "Qend", setup::layout_Q, run.Q[0]); + + for (int c = 0; c < setup::NumberOfCombinations; ++c) { + unsigned f = setup::Combinations[c][0], o = setup::Combinations[c][1]; + run.trace.I = run.I[0]; + run.trace.T = run.traces[0]; + run.trace.execute(f, o); + dump(file, name("trace", f, o), setup::layout_T, run.traces[0]); + } + + fill(setup::layout_AminusT, run.AminusT[0], 20); + auto flux = [&](auto& kernel, const char* base, unsigned f, unsigned o) { + fill(setup::layout_T, run.traces[0], 30); + fill(setup::layout_Tn, run.traces[1], 31); + fill(setup::layout_Q, run.Q[0], 2); + kernel.Q = run.Q[0]; + kernel.T = run.traces[0]; + kernel.Tn = run.traces[1]; + kernel.AminusT = run.AminusT[0]; + kernel.execute(f, o); + dump(file, name(base, f, o), setup::layout_Q, run.Q[0]); + }; + for (int c = 0; c < setup::NumberOfCombinations; ++c) { + unsigned f = setup::Combinations[c][0], o = setup::Combinations[c][1]; + flux(run.lift, "lift", f, o); + flux(run.nodal, "nodal", f, o); + } + + // dynamic rupture at the first time point, with the derivatives of the cell + // as ck computed them from Q(1) + fill(setup::layout_Q, run.Q[0], 1); + run.setDerivatives(0); + for (int k = 0; k <= N; ++k) { + run.drTaylor.cT(k) = setup::PointCoefficients[0][k]; + run.drCombine.cT(k) = setup::PointCoefficients[0][k]; + run.drTrace.Pk(k) = run.Pk[k][0]; + run.drCombine.Pk(k) = run.Pk[k][0]; + } + run.drTaylor.q = run.q[0]; + run.drTaylor.execute(); + dump(file, "q", setup::layout_q, run.q[0]); + fill(setup::layout_F, run.F[0], 40); + for (unsigned a = 0; a < 4; ++a) { + for (unsigned b = 0; b < 4; ++b) { + run.drEval.q = run.q[0]; + run.drEval.qp = run.qp[0]; + run.drEval.execute(a, b); + dump(file, name("drEval", a, b), setup::layout_qp, run.qp[0]); + fill(setup::layout_Q, run.Q[1], 2); + run.drBack.Q = run.Q[1]; + run.drBack.F = run.F[0]; + run.drBack.execute(a, b); + dump(file, name("drBack", a, b), setup::layout_Q, run.Q[1]); + } + } + for (int c = 0; c < setup::NumberOfCombinations; ++c) { + unsigned f = setup::Combinations[c][0], o = setup::Combinations[c][1]; + run.drTrace.execute(f, o); + run.drCombine.qp = run.qp[0]; + run.drCombine.execute(); + dump(file, name("drFace", f, o), setup::layout_qp, run.qp[0]); + fill(setup::layout_Q, run.Q[1], 2); + run.drFaceBack.Q = run.Q[1]; + run.drFaceBack.F = run.F[0]; + run.drFaceBack.execute(f, o); + dump(file, name("drFaceBack", f, o), setup::layout_Q, run.Q[1]); + } + std::fclose(file); +} + +} // namespace + +int main(int argc, char** argv) { + std::size_t bytes = 256ul << 20; + int repetitions = 5; + unsigned seed = 1; + for (int i = 1; i < argc; ++i) { + std::string argument = argv[i]; + if (argument == "--check" && i + 1 < argc) { + check(argv[++i]); + return 0; + } + if (argument == "--bytes" && i + 1 < argc) { + bytes = std::strtoull(argv[++i], nullptr, 10); + } else if (argument == "--repetitions" && i + 1 < argc) { + repetitions = std::atoi(argv[++i]); + } else if (argument == "--seed" && i + 1 < argc) { + seed = std::atoi(argv[++i]); + } else { + std::fprintf(stderr, + "usage: %s [--bytes B] [--repetitions R] [--seed S] | --check FILE\n", + argv[0]); + return 1; + } + } + benchmark(bytes, repetitions, seed); + return 0; +}