DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
pack.h
Go to the documentation of this file.
1// Copyright (C) 2013-2026 Garth N. Wells and Jørgen S. Dokken
2//
3// This file is part of DOLFINx (https://www.fenicsproject.org)
4//
5// SPDX-License-Identifier: LGPL-3.0-or-later
6
7#pragma once
8
9#include "Constant.h"
10#include "DofMap.h"
11#include "FiniteElement.h"
12#include "Form.h"
13#include "Function.h"
14#include "FunctionSpace.h"
15#include "traits.h"
16#include <algorithm>
17#include <array>
18#include <basix/mdspan.hpp>
19#include <concepts>
20#include <dolfinx/mesh/Topology.h>
21#include <format>
22#include <ranges>
23#include <span>
24#include <stdexcept>
25#include <type_traits>
26#include <vector>
27
30
31namespace dolfinx::fem
32{
33template <dolfinx::scalar T, std::floating_point U>
34class Expression;
35
36namespace impl
37{
45template <dolfinx::scalar T, std::floating_point U>
46std::span<const std::uint32_t>
47get_cell_orientation_info(const Function<T, U>& coefficient)
48{
49 std::span<const std::uint32_t> cell_info;
50 auto element = coefficient.function_space()->element();
51 assert(element);
52 if (element->needs_dof_transformations())
53 {
54 auto mesh = coefficient.function_space()->mesh();
55 mesh->topology_mutable()->create_entity_permutations();
56 cell_info = std::span(mesh->topology()->get_cell_permutation_info());
57 }
58
59 return cell_info;
60}
61
81template <dolfinx::scalar T>
82void pack_impl(std::span<T> coeffs, std::int32_t cell, auto bs,
83 std::span<const T> v, std::span<const std::uint32_t> cell_info,
84 const DofMap& dofmap, auto transform, bool transform_set)
85{
86 std::span<const std::int32_t> dofs = dofmap.cell_dofs(cell);
87 for (std::size_t i = 0; i < dofs.size(); ++i)
88 std::copy_n(v.data() + bs * dofs[i], bs, coeffs.data() + bs * i);
89
90 if (transform_set)
91 transform(coeffs, cell_info, cell, 1);
92}
93
110template <dolfinx::scalar T, std::floating_point U>
111void pack_coefficient_entity(std::span<T> c, int cstride,
112 const Function<T, U>& u,
113 std::span<const std::uint32_t> cell_info,
114 auto cells, std::int32_t offset)
115{
116 static_assert(cells.rank() == 1);
117
118 // Read data from coefficient Function u
119 std::span<const T> v = u.x()->array();
120 const DofMap& dofmap = *u.function_space()->dofmap();
121 auto element = u.function_space()->element();
122 assert(element);
123 int space_dim = element->space_dimension();
124
125 // Transformation from conforming degrees-of-freedom to reference
126 // degrees-of-freedom
127 auto transformation
128 = element->template dof_transformation_fn<T>(doftransform::transpose);
129 const int bs = dofmap.bs();
130
131 // `transformation` does not change across cells in this call, so
132 // whether it is a set (non-null) transform is loop-invariant --
133 // checked once here rather than on every cell.
134 const bool transform_set = is_transform_set(transformation);
135
136 // Passing the block size as a compile-time constant
137 // (std::integral_constant<int, N>) lets `pack_impl` unroll its inner
138 // (per-DOF) loop for the common block sizes 1, 2, and 3, rather than
139 // looping `bs` times at runtime for every cell.
140 auto pack_for_bs = [&cells, &c, &cstride, &offset, &space_dim, &v, &cell_info,
141 &dofmap, &transformation, transform_set](auto bs)
142 {
143 for (std::size_t e = 0; e < cells.extent(0); ++e)
144 {
145 if (std::int32_t cell = cells(e); cell >= 0)
146 {
147 auto cell_coeff = c.subspan(e * cstride + offset, space_dim);
148 pack_impl(cell_coeff, cell, bs, v, cell_info, dofmap, transformation,
149 transform_set);
150 }
151 }
152 };
153
154 switch (bs)
155 {
156 case 1:
157 pack_for_bs(std::integral_constant<int, 1>());
158 break;
159 case 2:
160 pack_for_bs(std::integral_constant<int, 2>());
161 break;
162 case 3:
163 pack_for_bs(std::integral_constant<int, 3>());
164 break;
165 default:
166 pack_for_bs(bs);
167 break;
168 }
169}
170} // namespace impl
171
179template <dolfinx::scalar T, std::floating_point U>
180std::pair<std::vector<T>, int>
182 int idx)
183{
184 std::size_t num_entities = 0;
185 int cstride = 0;
186 if (const std::vector<std::shared_ptr<const Function<T, U>>>& coefficients
187 = form.coefficients();
188 !coefficients.empty())
189 {
190 const std::vector<int> offsets = form.coefficient_offsets();
191 cstride = offsets.back();
192
193 // `domain()` returns entities flattened as (cell,) for cell
194 // integrals, (cell, local_entity_index) pairs for exterior_facet/
195 // vertex/ridge integrals, and (cell, local_facet, cell,
196 // local_facet) quadruples for interior_facet integrals (one '+'
197 // and one '-' side). Dividing by 2 therefore gives the number of
198 // entities for exterior_facet/vertex/ridge integrals, but *twice*
199 // the number of facets for interior_facet integrals -- which is
200 // exactly the entity count required, since interior_facet
201 // coefficient data is packed at a doubled `cstride` (one side
202 // each), see ::pack_coefficients.
203 num_entities = form.domain(integral_type, idx, 0).size();
204 if (integral_type != IntegralType::cell)
205 num_entities /= 2;
206 }
207
208 return {std::vector<T>(num_entities * cstride), cstride};
209}
210
216template <dolfinx::scalar T, std::floating_point U>
217std::map<std::pair<IntegralType, int>, std::pair<std::vector<T>, int>>
219{
220 std::map<std::pair<IntegralType, int>, std::pair<std::vector<T>, int>> coeffs;
221 for (fem::IntegralType type : form.integral_types())
222 {
223 // `num_integrals` scans all of `form`'s integrals, so it is
224 // evaluated once per `type` here rather than as the loop
225 // condition (which would re-scan on every iteration).
226 const int n = form.num_integrals(type, 0);
227 for (int idx = 0; idx < n; ++idx)
228 {
229 coeffs.emplace_hint(coeffs.end(), std::pair{type, idx},
230 allocate_coefficient_storage(form, type, idx));
231 }
232 }
233
234 return coeffs;
235}
236
258template <dolfinx::scalar T, std::floating_point U>
260 std::map<std::pair<IntegralType, int>,
261 std::pair<std::vector<T>, int>>& coeffs)
262{
263 const std::vector<std::shared_ptr<const Function<T, U>>>& coefficients
264 = form.coefficients();
265 const std::vector<int> offsets = form.coefficient_offsets();
266
267 for (auto& [integral_key, coeff_data] : coeffs)
268 {
269 auto [integral_type, idx] = integral_key;
270 std::vector<T>& c = coeff_data.first;
271 int cstride = coeff_data.second;
272 if (!coefficients.empty())
273 {
274 switch (integral_type)
275 {
277 {
278 // `form.mesh()` is fixed for the whole call, so its dimension
279 // is fetched once rather than once per active coefficient.
280 const int form_tdim = form.mesh()->topology()->dim();
281
282 // Iterate over coefficients that are active in cell integrals
283 for (int coeff : form.active_coeffs(IntegralType::cell, idx))
284 {
285 // Get coefficient mesh
286 auto mesh = coefficients[coeff]->function_space()->mesh();
287 assert(mesh);
288
289 // A cell-integral coefficient must be defined over cells (or
290 // a mesh view of them), not lower-codimension entities such
291 // as facets -- that combination doesn't make sense and is a
292 // logic error, so fail loudly rather than pack it anyway.
293 if (int codim = form_tdim - mesh->topology()->dim(); codim > 0)
294 {
295 throw std::invalid_argument(
296 "Should not be packing coefficients with "
297 "codim>0 in a cell integral");
298 }
299
300 std::span<const std::int32_t> cells_b
301 = form.domain_coeff(IntegralType::cell, idx, coeff);
302 md::mdspan cells(cells_b.data(), cells_b.size());
303 std::span<const std::uint32_t> cell_info
304 = impl::get_cell_orientation_info(*coefficients[coeff]);
305 impl::pack_coefficient_entity(std::span(c), cstride,
306 *coefficients[coeff], cell_info, cells,
307 offsets[coeff]);
308 }
309 break;
310 }
312 {
313 // Iterate over coefficients that are active in interior
314 // facet integrals
315 for (int coeff : form.active_coeffs(IntegralType::interior_facet, idx))
316 {
317 auto mesh = coefficients[coeff]->function_space()->mesh();
318 std::span<const std::int32_t> facets_b
319 = form.domain_coeff(IntegralType::interior_facet, idx, coeff);
320 md::mdspan<const std::int32_t,
321 md::extents<std::size_t, md::dynamic_extent, 4>>
322 facets(facets_b.data(), facets_b.size() / 4, 4);
323
324 std::span<const std::uint32_t> cell_info
325 = impl::get_cell_orientation_info(*coefficients[coeff]);
326
327 // Data for the '+' and '-' sides of coefficient `coeff` are
328 // interleaved per-coefficient (not stored as two contiguous
329 // blocks), i.e. layout is [coeff0 '+', coeff0 '-', coeff1
330 // '+', coeff1 '-', ...]. `2 * offsets[coeff]` is therefore
331 // the start of coefficient `coeff`'s '+' data, immediately
332 // followed by its '-' data at `offsets[coeff] +
333 // offsets[coeff + 1]`.
334
335 // Pack coefficient ['+']
336 auto cells0 = md::submdspan(facets, md::full_extent, 0);
337 impl::pack_coefficient_entity(std::span(c), 2 * cstride,
338 *coefficients[coeff], cell_info, cells0,
339 2 * offsets[coeff]);
340
341 // Pack coefficient ['-']
342 auto cells1 = md::submdspan(facets, md::full_extent, 2);
343 impl::pack_coefficient_entity(std::span(c), 2 * cstride,
344 *coefficients[coeff], cell_info, cells1,
345 offsets[coeff] + offsets[coeff + 1]);
346 }
347 break;
348 }
352 {
353 // Iterate over coefficients that are active in exterior_facet,
354 // vertex, and ridge integrals (all use the same (cell,
355 // local_entity_index) entity layout)
356 for (int coeff : form.active_coeffs(integral_type, idx))
357 {
358 // Get coefficient mesh
359 auto mesh = coefficients[coeff]->function_space()->mesh();
360 assert(mesh);
361
362 std::span<const std::int32_t> entities_b
363 = form.domain_coeff(integral_type, idx, coeff);
364 md::mdspan<const std::int32_t,
365 md::extents<std::size_t, md::dynamic_extent, 2>>
366 entities(entities_b.data(), entities_b.size() / 2, 2);
367 std::span<const std::uint32_t> cell_info
368 = impl::get_cell_orientation_info(*coefficients[coeff]);
369 impl::pack_coefficient_entity(
370 std::span(c), cstride, *coefficients[coeff], cell_info,
371 md::submdspan(entities, md::full_extent, 0), offsets[coeff]);
372 }
373 break;
374 }
375 default:
376 throw std::invalid_argument(
377 "Could not pack coefficient. Integral type not supported.");
378 }
379 }
380 }
381}
382
396template <dolfinx::scalar T, std::floating_point U>
398 const fem::Function<T, U>& coeff, const mesh::Mesh<U>& mesh,
399 fem::MDSpan2 auto entities,
400 std::optional<std::reference_wrapper<const dolfinx::mesh::EntityMap>>
401 entity_map)
402{
403 auto mesh_c = coeff.function_space()->mesh();
404 assert(mesh_c);
405
406 auto span_to_vector = [](auto entities)
407 {
408 assert(entities.rank() == 1);
409
410 std::vector<std::int32_t> vec;
411 vec.reserve(entities.extent(0));
412 for (std::size_t i = 0; i < entities.extent(0); ++i)
413 vec.push_back(entities[i]);
414 return vec;
415 };
416
417 if (mesh_c->topology() == mesh.topology())
418 {
419 // If same mesh no mapping is needed
420 if constexpr (entities.rank() == 1)
421 return span_to_vector(entities);
422
423 else
424 // If (cell, local_index) pairs are given, extract the cells
425 return span_to_vector(md::submdspan(entities, md::full_extent, 0));
426 }
427 else
428 {
429 assert(entity_map.has_value());
430 const mesh::Topology& topology = *mesh.topology();
431 int tdim = topology.dim();
432 int codim = tdim - mesh_c->topology()->dim();
433 const dolfinx::mesh::EntityMap& emap = entity_map.value().get();
434 bool inverse = emap.sub_topology() == mesh_c->topology();
435 // If cells are supplied on the parent mesh, we can directly map them to
436 // cells on the coefficient mesh.
437 if constexpr (entities.rank() == 1)
438 {
439 assert(codim == 0);
440
441 return emap.sub_topology_to_topology(span_to_vector(entities), inverse);
442 }
443 else if constexpr (entities.rank() == 2)
444 {
445 if (codim == 0)
446 {
447 // If codim is zero we extract the cells and map them
448 auto cells = md::submdspan(entities, md::full_extent, 0);
449 return emap.sub_topology_to_topology(span_to_vector(cells), inverse);
450 }
451 else
452 {
453 // Any other codim needs to map (cell, local index) to facets and then
454 // to cells of the submesh
455 if (!inverse)
456 {
457 throw std::invalid_argument(
458 "Unsupported mapping. Can only map from submesh to parent mesh.");
459 }
460 assert(codim > 0);
461 auto c_to_e = topology.connectivity(tdim, tdim - codim);
462 if (!c_to_e)
463 {
464 throw std::runtime_error(std::format(
465 "Topology connectivity from codim {} to {} not found.", tdim,
466 tdim - codim));
467 }
468 // Map parent (cell, local_index) to parent facet
469 std::vector<std::int32_t> contiguous_cells;
470 contiguous_cells.reserve(entities.extent(0));
471 for (std::size_t e = 0; e < entities.extent(0); ++e)
472 {
473 contiguous_cells.push_back(
474 c_to_e->links(entities(e, 0))[entities(e, 1)]);
475 }
476 // Map parent facet to submesh cell
477 return emap.sub_topology_to_topology(contiguous_cells, inverse);
478 }
479 }
480 }
481}
482
498template <dolfinx::scalar T, std::floating_point U>
500 const std::vector<std::reference_wrapper<const Function<T, U>>>& coeffs,
501 const mesh::Mesh<U>& mesh, fem::MDSpan2 auto entities,
502 const std::vector<std::reference_wrapper<const dolfinx::mesh::EntityMap>>&
503 entity_maps,
504 std::span<const int> offsets, std::span<T> c)
505{
506
507 assert(!offsets.empty());
508 const int cstride = offsets.back();
509
510 if (c.size() < entities.extent(0) * offsets.back())
511 throw std::runtime_error("Coefficient packing span is too small.");
512
513 // Helper function to get correct entity map. Note: `mesh` is
514 // captured by reference -- capturing it by value would copy the
515 // whole Mesh (including its Geometry's coordinate array) on every
516 // call.
517 auto get_entity_map
518 = [&mesh, &entity_maps](auto& mesh0) -> const mesh::EntityMap&
519 {
520 auto it = std::ranges::find_if(
521 entity_maps,
522 [&mesh, mesh0](const mesh::EntityMap& em)
523 {
524 return (em.topology() == mesh0->topology()
525 and em.sub_topology() == mesh.topology())
526 or (em.sub_topology() == mesh0->topology()
527 and em.topology() == mesh.topology());
528 });
529
530 if (it == entity_maps.end())
531 {
532 throw std::invalid_argument(
533 "Incompatible mesh. argument entity_maps must be provided.");
534 }
535 return *it;
536 };
537
538 // Iterate over coefficients
539 for (std::size_t coeff = 0; coeff < coeffs.size(); ++coeff)
540 {
541 // Get mesh of coefficient and check if entity map is required
542 auto mesh_c = coeffs[coeff].get().function_space()->mesh();
543 std::vector<std::int32_t> coefficient_cells;
544 if (mesh_c->topology() == mesh.topology())
545 {
546 coefficient_cells = extract_coefficient_cells_from_entities(
547 coeffs[coeff].get(), mesh, entities, std::nullopt);
548 }
549 else
550 {
551 // Find correct entity map and determine direction of the map
552 const mesh::EntityMap& emap = get_entity_map(mesh_c);
553 coefficient_cells = extract_coefficient_cells_from_entities(
554 coeffs[coeff].get(), mesh, entities,
555 std::reference_wrapper<const mesh::EntityMap>(emap));
556 }
557
558 std::span<const std::uint32_t> cell_info
559 = impl::get_cell_orientation_info(coeffs[coeff].get());
560 md::mdspan cells(coefficient_cells.data(), coefficient_cells.size());
561 impl::pack_coefficient_entity(std::span(c), cstride, coeffs[coeff].get(),
562 cell_info, cells, offsets[coeff]);
563 }
564}
565
572template <typename T>
573std::vector<T> pack_constants(
574 const std::vector<std::reference_wrapper<const fem::Constant<T>>>& c)
575{
576 // Calculate size of array needed to store packed constants
577 std::int32_t size = std::accumulate(
578 c.cbegin(), c.cend(), 0, [](std::int32_t sum, auto& constant)
579 { return sum + constant.get().value.size(); });
580
581 // Pack constants
582 std::vector<T> constant_values(size);
583 std::int32_t offset = 0;
584 for (auto& constant : c)
585 {
586 std::ranges::copy(constant.get().value,
587 std::next(constant_values.begin(), offset));
588 offset += constant.get().value.size();
589 }
590
591 return constant_values;
592}
593
598template <typename U>
599 requires std::convertible_to<
601 typename std::decay_t<U>::geometry_type>>
602 or std::convertible_to<
604 typename std::decay_t<U>::geometry_type>>
605std::vector<typename U::scalar_type> pack_constants(const U& u)
606{
607 using T = typename std::decay_t<U>::scalar_type;
608 std::vector<std::reference_wrapper<const Constant<T>>> c;
609 c.reserve(u.constants().size());
610 std::ranges::transform(u.constants(), std::back_inserter(c),
611 [](auto& c) -> const Constant<T>& { return *c; });
612 return fem::pack_constants(c);
613}
614
615} // namespace dolfinx::fem
Degree-of-freedom map representations and tools.
Constant (in space) value which can be attached to a Form.
Definition Constant.h:22
Degree-of-freedom map.
Definition DofMap.h:73
std::span< const std::int32_t > cell_dofs(std::int32_t c) const
Local-to-global mapping of dofs on a cell.
Definition DofMap.h:127
int bs() const noexcept
Return the block size for the dofmap.
Definition DofMap.cpp:165
An Expression represents a mathematical expression evaluated at a pre-defined points on a reference c...
Definition Expression.h:43
A representation of finite element variational forms.
Definition Form.h:118
int num_integrals(IntegralType type, int kernel_idx) const
Get number of integrals (kernels) for a given integral type and kernel index.
Definition Form.h:450
const std::vector< std::shared_ptr< const Function< scalar_type, geometry_type > > > & coefficients() const
Access coefficients.
Definition Form.h:577
std::vector< int > coefficient_offsets() const
Offset for each coefficient expansion array on a cell.
Definition Form.h:593
std::span< const std::int32_t > domain_coeff(IntegralType type, int idx, int c) const
Coefficient function mesh integration entity indices.
Definition Form.h:563
std::shared_ptr< const mesh::Mesh< geometry_type > > mesh() const
Common mesh for the form (the 'integration domain').
Definition Form.h:367
std::vector< int > active_coeffs(IntegralType type, int idx) const
Indices of coefficients that are active for a given integral (kernel).
Definition Form.h:421
std::set< IntegralType > integral_types() const
Get types of integrals in the form.
Definition Form.h:400
std::span< const std::int32_t > domain(IntegralType type, int idx, int kernel_idx) const
Mesh entity indices to integrate over for a given integral (kernel).
Definition Form.h:494
Definition Function.h:48
std::shared_ptr< const FunctionSpace< geometry_type > > function_space() const
Access the function space.
Definition Function.h:149
std::shared_ptr< const la::Vector< value_type > > x() const
Underlying vector (const version).
Definition Function.h:155
A bidirectional map relating entities in one topology to another.
Definition EntityMap.h:22
std::vector< std::int32_t > sub_topology_to_topology(CellRange auto &&entities, bool inverse) const
Map entities between the sub-topology and the parent topology.
Definition EntityMap.h:104
std::shared_ptr< const Topology > sub_topology() const
Get the sub-topology.
Definition EntityMap.cpp:23
std::shared_ptr< const Topology > topology() const
Get the (parent) topology.
Definition EntityMap.cpp:18
A Mesh consists of a set of connected and numbered mesh topological entities, and geometry data.
Definition Mesh.h:23
Topology stores the topology of a mesh, consisting of mesh entities and connectivity (incidence relat...
Definition Topology.h:49
std::shared_ptr< const graph::AdjacencyList< std::int32_t > > connectivity(std::array< int, 2 > d0, std::array< int, 2 > d1) const
Get the connectivity from entities of topological dimension d0 to dimension d1.
Definition Topology.cpp:950
int dim() const noexcept
Topological dimension of the mesh.
Definition Topology.cpp:888
Concept for mdspan of rank 1 or 2.
Definition traits.h:52
Finite element method functionality.
Definition assemble_expression_impl.h:24
@ transpose
Transpose.
Definition FiniteElement.h:30
@ inverse
Inverse.
Definition FiniteElement.h:31
void pack_coefficients(const Form< T, U > &form, std::map< std::pair< IntegralType, int >, std::pair< std::vector< T >, int > > &coeffs)
Pack coefficients of a Form.
Definition pack.h:259
std::pair< std::vector< T >, int > allocate_coefficient_storage(const Form< T, U > &form, IntegralType integral_type, int idx)
Allocate storage for coefficients of a pair (integral_type, idx) from a Form.
Definition pack.h:181
std::vector< std::int32_t > extract_coefficient_cells_from_entities(const fem::Function< T, U > &coeff, const mesh::Mesh< U > &mesh, fem::MDSpan2 auto entities, std::optional< std::reference_wrapper< const dolfinx::mesh::EntityMap > > entity_map)
Given a Function and a related mesh and its integration entities, extract the cell indices of the coe...
Definition pack.h:397
IntegralType
Type of integral.
Definition Form.h:41
@ vertex
Vertex.
Definition Form.h:45
@ interior_facet
Interior facet.
Definition Form.h:44
@ ridge
Ridge.
Definition Form.h:46
@ cell
Cell.
Definition Form.h:42
@ exterior_facet
Exterior facet.
Definition Form.h:43
constexpr bool is_transform_set(const F &fn)
Whether a DofTransformKernel fn should be invoked.
Definition traits.h:33
std::vector< T > pack_constants(const std::vector< std::reference_wrapper< const fem::Constant< T > > > &c)
Pack constants of an Expression or Form into a single array ready for assembly.
Definition pack.h:573
Mesh data structures and algorithms on meshes.
Definition DofMap.h:32
void pack_impl(std::span< T > coeffs, std::int32_t cell, auto bs, std::span< const T > v, std::span< const std::uint32_t > cell_info, const DofMap &dofmap, auto transform, bool transform_set)
Gather a single coefficient's degrees-of-freedom for a single cell and apply its DOF transformation.
Definition pack.h:82
void pack_coefficient_entity(std::span< T > c, int cstride, const Function< T, U > &u, std::span< const std::uint32_t > cell_info, auto cells, std::int32_t offset)
Pack a single coefficient for a set of active entities.
Definition pack.h:111