DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
interpolate.h
1// Copyright (C) 2020-2026 Garth N. Wells, Igor A. Baratta, Massimiliano Leoni,
2// Jørgen S.Dokken and Paul T. Kühner
3//
4// This file is part of DOLFINx (https://www.fenicsproject.org)
5//
6// SPDX-License-Identifier: LGPL-3.0-or-later
7
8#pragma once
9
10#include "CoordinateElement.h"
11#include "DofMap.h"
12#include "FiniteElement.h"
13#include "FunctionSpace.h"
14#include <algorithm>
15#include <basix/mdspan.hpp>
16#include <concepts>
17#include <dolfinx/common/IndexMap.h>
18#include <dolfinx/common/log.h>
19#include <dolfinx/common/types.h>
20#include <dolfinx/geometry/utils.h>
21#include <dolfinx/mesh/Mesh.h>
22#include <functional>
23#include <numeric>
24#include <ranges>
25#include <span>
26#include <stdexcept>
27#include <utility>
28#include <vector>
29
30namespace dolfinx::fem
31{
32template <dolfinx::scalar T, std::floating_point U>
33class Function;
34
45template <std::floating_point T>
46std::vector<T> interpolation_coords(const fem::FiniteElement<T>& element,
48 mesh::CellRange auto&& cells)
49{
50 // Find CoordinateElement appropriate to element
51 auto cmap_index = [&geometry](mesh::CellType cell_type)
52 {
53 for (std::size_t i = 0; i < geometry.cmaps().size(); ++i)
54 {
55 if (geometry.cmaps().at(i).cell_shape() == cell_type)
56 return i;
57 }
58 throw std::runtime_error("Cannot find CoordinateElement for FiniteElement");
59 };
60 int index = cmap_index(element.cell_type());
61
62 // Get geometry data and the element coordinate map
63 const std::size_t gdim = geometry.dim();
64 auto x_dofmap = geometry.dofmaps().at(index);
65 std::span<const T> x_g = geometry.x();
66
67 const CoordinateElement<T>& cmap = geometry.cmaps().at(index);
68 const std::size_t num_dofs_g = cmap.dim();
69
70 // Get the interpolation points on the reference cells
71 const auto [X, Xshape] = element.interpolation_points();
72
73 // Evaluate coordinate element basis at reference points
74 std::array<std::size_t, 4> phi_shape = cmap.tabulate_shape(0, Xshape[0]);
75 std::vector<T> phi_b(
76 std::reduce(phi_shape.begin(), phi_shape.end(), 1, std::multiplies{}));
77 md::mdspan<const T, md::extents<std::size_t, 1, md::dynamic_extent,
78 md::dynamic_extent, 1>>
79 phi_full(phi_b.data(), phi_shape);
80 cmap.tabulate(0, X, Xshape, phi_b);
81 auto phi = md::submdspan(phi_full, 0, md::full_extent, md::full_extent, 0);
82
83 // Push reference coordinates (X) forward to the physical coordinates
84 // (x) for each cell
85 std::vector<T> coordinate_dofs(num_dofs_g * gdim, 0);
86 std::vector<T> x(3 * (cells.size() * Xshape[0]), 0);
87 for (auto cell_it = cells.begin(); cell_it != cells.end(); ++cell_it)
88 {
89 // Get geometry data for current cell
90 auto x_dofs = md::submdspan(x_dofmap, *cell_it, md::full_extent);
91 for (std::size_t i = 0; i < x_dofs.size(); ++i)
92 {
93 std::copy_n(std::next(x_g.begin(), 3 * x_dofs[i]), gdim,
94 std::next(coordinate_dofs.begin(), i * gdim));
95 }
96
97 // Push forward coordinates (X -> x)
98 std::size_t offset = std::ranges::distance(cells.begin(), cell_it);
99 for (std::size_t p = 0; p < Xshape[0]; ++p)
100 {
101 for (std::size_t j = 0; j < gdim; ++j)
102 {
103 T acc = 0;
104 for (std::size_t k = 0; k < num_dofs_g; ++k)
105 acc += phi(p, k) * coordinate_dofs[k * gdim + j];
106 x[j * (cells.size() * Xshape[0]) + offset * Xshape[0] + p] = acc;
107 }
108 }
109 }
110
111 return x;
112}
113
139template <dolfinx::scalar T, std::floating_point U>
140void interpolate(Function<T, U>& u, std::span<const T> f,
141 std::array<std::size_t, 2> fshape,
142 mesh::CellRange auto&& cells);
143
144namespace impl
145{
147template <typename T, std::size_t D>
148using mdspan_t = md::mdspan<T, md::dextents<std::size_t, D>>;
149
169template <dolfinx::scalar T>
170void scatter_values(MPI_Comm comm, std::span<const std::int32_t> src_ranks,
171 std::span<const std::int32_t> dest_ranks,
172 mdspan_t<const T, 2> send_values, std::span<T> recv_values)
173{
174 const std::size_t block_size = send_values.extent(1);
175 assert(src_ranks.size() * block_size == send_values.size());
176 assert(recv_values.size() == dest_ranks.size() * block_size);
177
178 // Build unique set of the sorted src_ranks
179 std::vector<std::int32_t> out_ranks(src_ranks.size());
180 out_ranks.assign(src_ranks.begin(), src_ranks.end());
181 out_ranks.erase(std::ranges::unique(out_ranks).begin(), out_ranks.end());
182 out_ranks.reserve(out_ranks.size() + 1);
183
184 // Remove negative entries from dest_ranks
185 std::vector<std::int32_t> in_ranks;
186 in_ranks.reserve(dest_ranks.size());
187 std::copy_if(dest_ranks.begin(), dest_ranks.end(),
188 std::back_inserter(in_ranks),
189 [](auto rank) { return rank >= 0; });
190
191 // Create unique set of sorted in-ranks
192 std::ranges::sort(in_ranks);
193 in_ranks.erase(std::ranges::unique(in_ranks).begin(), in_ranks.end());
194 in_ranks.reserve(in_ranks.size() + 1);
195
196 // Create neighborhood communicator
197 MPI_Comm reverse_comm;
198 MPI_Dist_graph_create_adjacent(
199 comm, in_ranks.size(), in_ranks.data(), MPI_UNWEIGHTED, out_ranks.size(),
200 out_ranks.data(), MPI_UNWEIGHTED, MPI_INFO_NULL, false, &reverse_comm);
201
202 std::vector<std::int32_t> comm_to_output;
203 std::vector<std::int32_t> recv_sizes(in_ranks.size());
204 recv_sizes.reserve(1);
205 std::vector<std::int32_t> recv_offsets(in_ranks.size() + 1, 0);
206 {
207 // Build map from parent to neighborhood communicator ranks
208 std::vector<std::pair<std::int32_t, std::int32_t>> rank_to_neighbor;
209 rank_to_neighbor.reserve(in_ranks.size());
210 for (std::size_t i = 0; i < in_ranks.size(); i++)
211 rank_to_neighbor.push_back({in_ranks[i], i});
212 std::ranges::sort(rank_to_neighbor);
213
214 // Compute receive sizes
215 std::ranges::for_each(
216 dest_ranks,
217 [&rank_to_neighbor, &recv_sizes, block_size](auto rank)
218 {
219 if (rank >= 0)
220 {
221 auto it = std::ranges::lower_bound(rank_to_neighbor, rank,
222 std::ranges::less(),
223 [](auto e) { return e.first; });
224 assert(it != rank_to_neighbor.end() and it->first == rank);
225 recv_sizes[it->second] += block_size;
226 }
227 });
228
229 // Compute receiving offsets
230 std::partial_sum(recv_sizes.begin(), recv_sizes.end(),
231 std::next(recv_offsets.begin(), 1));
232
233 // Compute map from receiving values to position in recv_values
234 comm_to_output.resize(recv_offsets.back() / block_size);
235 std::vector<std::int32_t> recv_counter(recv_sizes.size(), 0);
236 for (std::size_t i = 0; i < dest_ranks.size(); ++i)
237 {
238 if (const std::int32_t rank = dest_ranks[i]; rank >= 0)
239 {
240 auto it = std::ranges::lower_bound(rank_to_neighbor, rank,
241 std::ranges::less(),
242 [](auto e) { return e.first; });
243 assert(it != rank_to_neighbor.end() and it->first == rank);
244 int insert_pos = recv_offsets[it->second] + recv_counter[it->second];
245 comm_to_output[insert_pos / block_size] = i * block_size;
246 recv_counter[it->second] += block_size;
247 }
248 }
249 }
250
251 std::vector<std::int32_t> send_sizes(out_ranks.size());
252 send_sizes.reserve(1);
253 {
254 // Compute map from parent MPI rank to neighbor rank for outgoing
255 // data. `out_ranks` is sorted, so rank_to_neighbor will be sorted
256 // too.
257 std::vector<std::pair<std::int32_t, std::int32_t>> rank_to_neighbor;
258 rank_to_neighbor.reserve(out_ranks.size());
259 for (std::size_t i = 0; i < out_ranks.size(); i++)
260 rank_to_neighbor.push_back({out_ranks[i], i});
261
262 // Compute send sizes. As `src_ranks` is sorted, we can move 'start'
263 // in search forward.
264 auto start = rank_to_neighbor.begin();
265 std::ranges::for_each(
266 src_ranks,
267 [&rank_to_neighbor, &send_sizes, block_size, &start](auto rank)
268 {
269 auto it = std::ranges::lower_bound(start, rank_to_neighbor.end(),
270 rank, std::ranges::less(),
271 [](auto e) { return e.first; });
272 assert(it != rank_to_neighbor.end() and it->first == rank);
273 send_sizes[it->second] += block_size;
274 start = it;
275 });
276 }
277
278 // Compute sending offsets
279 std::vector<std::int32_t> send_offsets(send_sizes.size() + 1, 0);
280 std::partial_sum(send_sizes.begin(), send_sizes.end(),
281 std::next(send_offsets.begin(), 1));
282
283 // Send values to dest ranks
284 std::vector<T> values(recv_offsets.back());
285 values.reserve(1);
286 MPI_Neighbor_alltoallv(send_values.data_handle(), send_sizes.data(),
287 send_offsets.data(), dolfinx::MPI::mpi_t<T>,
288 values.data(), recv_sizes.data(), recv_offsets.data(),
289 dolfinx::MPI::mpi_t<T>, reverse_comm);
290 MPI_Comm_free(&reverse_comm);
291
292 // Insert values received from neighborhood communicator in output
293 // span
294 std::ranges::fill(recv_values, T{0});
295 for (std::size_t i = 0; i < comm_to_output.size(); i++)
296 {
297 auto vals = std::next(recv_values.begin(), comm_to_output[i]);
298 auto vals_from = std::next(values.begin(), i * block_size);
299 std::copy_n(vals_from, block_size, vals);
300 }
301};
302
311template <dolfinx::MDSpanRank2 U, dolfinx::MDSpanRank2 V, dolfinx::scalar T>
312void interpolation_apply(U&& Pi, V&& data, std::span<T> coeffs, int bs)
313{
314 // Geometry (real) scalar type, taken from the interpolation operator Pi
315 // rather than scalar_value_t<T> so it is independent of the value scalar T.
316 using X = typename std::remove_cvref_t<U>::value_type;
317
318 // Compute coefficients = Pi * x (matrix-vector multiply)
319 if (bs == 1)
320 {
321 assert(data.extent(0) * data.extent(1) == Pi.extent(1));
322 for (std::size_t i = 0; i < Pi.extent(0); ++i)
323 {
324 coeffs[i] = 0.0;
325 for (std::size_t k = 0; k < data.extent(1); ++k)
326 for (std::size_t j = 0; j < data.extent(0); ++j)
327 {
328 coeffs[i]
329 += static_cast<X>(Pi(i, k * data.extent(0) + j)) * data(j, k);
330 }
331 }
332 }
333 else
334 {
335 assert(data.extent(0) == Pi.extent(1));
336 assert(static_cast<int>(data.extent(1)) == bs);
337 std::size_t cols = Pi.extent(1);
338 for (int k = 0; k < bs; ++k)
339 {
340 for (std::size_t i = 0; i < Pi.extent(0); ++i)
341 {
342 T acc = 0;
343 for (std::size_t j = 0; j < cols; ++j)
344 acc += static_cast<X>(Pi(i, j)) * data(j, k);
345 coeffs[bs * i + k] = acc;
346 }
347 }
348 }
349}
350
370template <dolfinx::scalar T, std::floating_point U>
371void interpolate_same_map(Function<T, U>& u1, mesh::CellRange auto&& cells1,
372 const Function<T, U>& u0,
373 mesh::CellRange auto&& cells0)
374{
375 auto V0 = u0.function_space();
376 assert(V0);
377 auto V1 = u1.function_space();
378 assert(V1);
379 auto mesh0 = V0->mesh();
380 assert(mesh0);
381
382 auto mesh1 = V1->mesh();
383 assert(mesh1);
384
385 auto element0 = V0->element();
386 assert(element0);
387 auto element1 = V1->element();
388 assert(element1);
389
390 assert(mesh0->topology()->dim());
391 const int tdim = mesh0->topology()->dim();
392 auto map = mesh0->topology()->index_map(tdim);
393 assert(map);
394 std::span<T> u1_array = u1.x()->array();
395 std::span<const T> u0_array = u0.x()->array();
396
397 std::span<const std::uint32_t> cell_info0;
398 std::span<const std::uint32_t> cell_info1;
399 if (element1->needs_dof_transformations()
400 or element0->needs_dof_transformations())
401 {
402 mesh0->topology_mutable()->create_cell_permutations();
403 cell_info0 = std::span(mesh0->topology()->get_cell_permutation_info());
404 mesh1->topology_mutable()->create_cell_permutations();
405 cell_info1 = std::span(mesh1->topology()->get_cell_permutation_info());
406 }
407
408 // Get dofmaps
409 auto dofmap1 = V1->dofmap();
410 auto dofmap0 = V0->dofmap();
411
412 // Get block sizes and dof transformation operators
413 const int bs1 = dofmap1->bs();
414 const int bs0 = dofmap0->bs();
415 auto apply_dof_transformation = element0->template dof_transformation_fn<T>(
417 auto apply_inverse_dof_transform
418 = element1->template dof_transformation_fn<T>(
420
421 // Create working array
422 std::vector<T> local0(element0->space_dimension());
423 std::vector<T> local1(element1->space_dimension());
424
425 // Create interpolation operator
426 auto [i_m, im_shape] = element1->create_interpolation_operator(*element0);
427
428 // Iterate over mesh and interpolate on each cell
429 using X = U; // geometry (real) type, independent of the value scalar T
430 if (cells0.size() != cells1.size())
431 throw std::invalid_argument("Length of cells0 and cells1 must match.");
432 for (auto cell0_it = cells0.begin(), cell1_it = cells1.begin();
433 cell0_it != cells0.end() and cell1_it != cells1.end();
434 ++cell0_it, ++cell1_it)
435 {
436 // Pack and transform cell dofs to reference ordering
437 std::span<const std::int32_t> dofs0 = dofmap0->cell_dofs(*cell0_it);
438 for (std::size_t i = 0; i < dofs0.size(); ++i)
439 for (int k = 0; k < bs0; ++k)
440 local0[bs0 * i + k] = u0_array[bs0 * dofs0[i] + k];
441
442 if (apply_dof_transformation)
443 apply_dof_transformation(local0, cell_info0, *cell0_it, 1);
444
445 // FIXME: Get compile-time ranges from Basix
446 // Apply interpolation operator
447 std::ranges::fill(local1, 0);
448 for (std::size_t i = 0; i < im_shape[0]; ++i)
449 for (std::size_t j = 0; j < im_shape[1]; ++j)
450 local1[i] += static_cast<X>(i_m[im_shape[1] * i + j]) * local0[j];
451
452 if (apply_inverse_dof_transform)
453 apply_inverse_dof_transform(local1, cell_info1, *cell1_it, 1);
454 std::span<const std::int32_t> dofs1 = dofmap1->cell_dofs(*cell1_it);
455 for (std::size_t i = 0; i < dofs1.size(); ++i)
456 for (int k = 0; k < bs1; ++k)
457 u1_array[bs1 * dofs1[i] + k] = local1[bs1 * i + k];
458 }
459}
460
474template <dolfinx::scalar T, std::floating_point U>
475void interpolate_nonmatching_maps(Function<T, U>& u1,
476 mesh::CellRange auto&& cells1,
477 const Function<T, U>& u0,
478 mesh::CellRange auto&& cells0)
479{
480 // Get mesh
481 auto V0 = u0.function_space();
482 assert(V0);
483 auto mesh0 = V0->mesh();
484 assert(mesh0);
485
486 // Mesh dims
487 const int tdim = mesh0->topology()->dim();
488 const int gdim = mesh0->geometry().dim();
489
490 // Get elements
491 auto V1 = u1.function_space();
492 assert(V1);
493 auto mesh1 = V1->mesh();
494 assert(mesh1);
495 auto element0 = V0->element();
496 assert(element0);
497 auto element1 = V1->element();
498 assert(element1);
499
500 std::span<const std::uint32_t> cell_info0;
501 std::span<const std::uint32_t> cell_info1;
502 if (element1->needs_dof_transformations()
503 or element0->needs_dof_transformations())
504 {
505 mesh0->topology_mutable()->create_cell_permutations();
506 cell_info0 = std::span(mesh0->topology()->get_cell_permutation_info());
507 mesh1->topology_mutable()->create_cell_permutations();
508 cell_info1 = std::span(mesh1->topology()->get_cell_permutation_info());
509 }
510
511 // Get symmetry
512 const bool symmetric0 = V0->symmetric();
513 const bool symmetric1 = V1->symmetric();
514
515 // Get dofmaps
516 auto dofmap0 = V0->dofmap();
517 auto dofmap1 = V1->dofmap();
518
519 const auto [X, Xshape] = element1->interpolation_points();
520
521 // Get block sizes and dof transformation operators
522 const int bs0 = element0->block_size();
523 const int bs1 = element1->block_size();
524 auto apply_dof_transformation0 = element0->template dof_transformation_fn<U>(
526 auto apply_inv_dof_transform1 = element1->template dof_transformation_fn<T>(
528
529 // Get sizes of elements
530 const std::size_t dim0 = element0->space_dimension() / bs0;
531 const std::size_t value_size_ref0 = element0->reference_value_size();
532 // basis0 holds values pushed forward to the physical cell, one block
533 // at a time, so it is sized with the physical (base) value size.
534 const std::size_t value_size0 = V0->element()->physical_base_value_size();
535
536 const CoordinateElement<U>& cmap = mesh0->geometry().cmaps().front();
537 auto x_dofmap = mesh0->geometry().dofmaps().front();
538 std::span<const U> x_g = mesh0->geometry().x();
539
540 // (0) is derivative index, (1) is the point index, (2) is the basis
541 // function index and (3) is the basis function component.
542
543 // Evaluate coordinate map basis at reference interpolation points
544 const std::array<std::size_t, 4> phi_shape
545 = cmap.tabulate_shape(1, Xshape[0]);
546 std::vector<U> phi_b(
547 std::reduce(phi_shape.begin(), phi_shape.end(), 1, std::multiplies{}));
548 md::mdspan<const U, md::extents<std::size_t, md::dynamic_extent,
549 md::dynamic_extent, md::dynamic_extent, 1>>
550 phi(phi_b.data(), phi_shape);
551 cmap.tabulate(1, X, Xshape, phi_b);
552
553 // Evaluate v basis functions at reference interpolation points
554 const auto [_basis_derivatives_reference0, b0shape]
555 = element0->tabulate(X, Xshape, 0);
556 md::mdspan<const U, std::extents<std::size_t, 1, md::dynamic_extent,
557 md::dynamic_extent, md::dynamic_extent>>
558 basis_derivatives_reference0(_basis_derivatives_reference0.data(),
559 b0shape);
560
561 // Create working arrays
562 std::vector<T> local1(element1->space_dimension());
563 std::vector<T> coeffs0(element0->space_dimension());
564
565 std::vector<U> basis0_b(Xshape[0] * dim0 * value_size0);
566 md::mdspan<U, std::dextents<std::size_t, 3>> basis0(
567 basis0_b.data(), Xshape[0], dim0, value_size0);
568
569 std::vector<U> basis_reference0_b(Xshape[0] * dim0 * value_size_ref0);
570 md::mdspan<U, std::dextents<std::size_t, 3>> basis_reference0(
571 basis_reference0_b.data(), Xshape[0], dim0, value_size_ref0);
572
573 // Size of (rank-2) tensor for symmetric elements
574 std::size_t matrix_size = 0;
575 if (symmetric0 or symmetric1)
576 {
577 assert(element0->value_shape().size() == 2);
578 assert(!symmetric0 or element0->physical_base_value_size() == 1);
579 assert(!symmetric1 or element1->physical_base_value_size() == 1);
580 matrix_size = element1->value_shape().front();
581 }
582
583 // values0 holds physical values in the block layout of element 1;
584 // mapped_values0 holds them pulled back to the reference
585 // cell of element 1, where each of its bs1 blocks has
586 // reference_value_size components.
587 const std::size_t value_size1
588 = element1->physical_base_value_size() * static_cast<std::size_t>(bs1);
589 const std::size_t value_size_ref1
590 = element1->reference_value_size() * static_cast<std::size_t>(bs1);
591 std::vector<T> values0_b(Xshape[0] * 1 * value_size1);
592 md::mdspan<
593 T, md::extents<std::size_t, md::dynamic_extent, 1, md::dynamic_extent>>
594 values0(values0_b.data(), Xshape[0], 1, value_size1);
595
596 std::vector<T> mapped_values_b(Xshape[0] * 1 * value_size_ref1);
597 md::mdspan<
598 T, md::extents<std::size_t, md::dynamic_extent, 1, md::dynamic_extent>>
599 mapped_values0(mapped_values_b.data(), Xshape[0], 1, value_size_ref1);
600
601 const std::size_t num_dofs_g = cmap.dim();
602 std::vector<U> coord_dofs_b(num_dofs_g * gdim);
603 md::mdspan<U, std::dextents<std::size_t, 2>> coord_dofs(coord_dofs_b.data(),
604 num_dofs_g, gdim);
605
606 std::vector<U> J_b(Xshape[0] * gdim * tdim);
607 md::mdspan<U, std::dextents<std::size_t, 3>> J(J_b.data(), Xshape[0], gdim,
608 tdim);
609 std::vector<U> K_b(Xshape[0] * tdim * gdim);
610 md::mdspan<U, std::dextents<std::size_t, 3>> K(K_b.data(), Xshape[0], tdim,
611 gdim);
612 std::vector<U> detJ(Xshape[0]);
613 std::vector<U> det_scratch(2 * gdim * tdim);
614
615 // Get interpolation operator
616 const auto [_Pi_1, pi_shape] = element1->interpolation_operator();
617 impl::mdspan_t<const U, 2> Pi_1(_Pi_1.data(), pi_shape);
618
619 using u_t = md::mdspan<U, std::dextents<std::size_t, 2>>;
620 using U_t = md::mdspan<const U, std::dextents<std::size_t, 2>>;
621 using J_t = md::mdspan<const U, std::dextents<std::size_t, 2>>;
622 using K_t = md::mdspan<const U, std::dextents<std::size_t, 2>>;
623 auto push_forward_fn0
624 = element0->basix_element().template map_fn<u_t, U_t, J_t, K_t>();
625
626 using v_t = md::mdspan<const T, std::dextents<std::size_t, 2>>;
627 using V_t = decltype(md::submdspan(mapped_values0, 0, md::full_extent,
628 md::full_extent));
629 auto pull_back_fn1
630 = element1->basix_element().template map_fn<V_t, v_t, K_t, J_t>();
631
632 // Iterate over mesh and interpolate on each cell
633 std::span<const T> array0 = u0.x()->array();
634 std::span<T> array1 = u1.x()->array();
635 if (cells0.size() != cells1.size())
636 throw std::invalid_argument("Length of cells0 and cells1 must match.");
637 for (auto cell0_it = cells0.begin(), cell1_it = cells1.begin();
638 cell0_it != cells0.end() and cell1_it != cells1.end();
639 ++cell0_it, ++cell1_it)
640 {
641 // Get cell geometry (coordinate dofs)
642 auto x_dofs = md::submdspan(x_dofmap, *cell0_it, md::full_extent);
643 for (std::size_t i = 0; i < num_dofs_g; ++i)
644 {
645 const int pos = 3 * x_dofs[i];
646 for (int j = 0; j < gdim; ++j)
647 coord_dofs(i, j) = x_g[pos + j];
648 }
649
650 // Compute Jacobians and reference points for current cell
651 std::ranges::fill(J_b, 0);
652 for (std::size_t p = 0; p < Xshape[0]; ++p)
653 {
654 auto dphi
655 = md::submdspan(phi, std::pair(1, tdim + 1), p, md::full_extent, 0);
656 auto _J = md::submdspan(J, p, md::full_extent, md::full_extent);
657 cmap.compute_jacobian(dphi, coord_dofs, _J);
658 auto _K = md::submdspan(K, p, md::full_extent, md::full_extent);
659 cmap.compute_jacobian_inverse(_J, _K);
660 detJ[p] = cmap.compute_jacobian_determinant(_J, det_scratch);
661 }
662
663 // Copy evaluated basis on reference, apply DOF transformations, and
664 // push forward to physical element
665 for (std::size_t k0 = 0; k0 < basis_reference0.extent(0); ++k0)
666 for (std::size_t k1 = 0; k1 < basis_reference0.extent(1); ++k1)
667 for (std::size_t k2 = 0; k2 < basis_reference0.extent(2); ++k2)
668 {
669 basis_reference0(k0, k1, k2)
670 = basis_derivatives_reference0(0, k0, k1, k2);
671 }
672
673 if (apply_dof_transformation0)
674 {
675 for (std::size_t p = 0; p < Xshape[0]; ++p)
676 {
677 apply_dof_transformation0(
678 std::span(basis_reference0_b.data() + p * dim0 * value_size_ref0,
679 dim0 * value_size_ref0),
680 cell_info0, *cell0_it, value_size_ref0);
681 }
682 }
683
684 for (std::size_t i = 0; i < basis0.extent(0); ++i)
685 {
686 auto _u = md::submdspan(basis0, i, md::full_extent, md::full_extent);
687 auto _U = md::submdspan(basis_reference0, i, md::full_extent,
688 md::full_extent);
689 auto _K = md::submdspan(K, i, md::full_extent, md::full_extent);
690 auto _J = md::submdspan(J, i, md::full_extent, md::full_extent);
691 push_forward_fn0(_u, _U, _J, detJ[i], _K);
692 }
693
694 // Copy expansion coefficients for v into local array
695 const int dof_bs0 = dofmap0->bs();
696 std::span<const std::int32_t> dofs0 = dofmap0->cell_dofs(*cell0_it);
697 for (std::size_t i = 0; i < dofs0.size(); ++i)
698 for (int k = 0; k < dof_bs0; ++k)
699 coeffs0[dof_bs0 * i + k] = array0[dof_bs0 * dofs0[i] + k];
700
701 // Evaluate v at the interpolation points (physical space values).
702 if (symmetric0 == symmetric1)
703 {
704 // Same block layout: both or neither symmetric
705 for (std::size_t p = 0; p < Xshape[0]; ++p)
706 {
707 for (int k = 0; k < bs0; ++k)
708 {
709 for (std::size_t j = 0; j < value_size0; ++j)
710 {
711 T acc = 0;
712 for (std::size_t i = 0; i < dim0; ++i)
713 acc += coeffs0[bs0 * i + k] * static_cast<T>(basis0(p, i, j));
714 values0(p, 0, j * bs0 + k) = acc;
715 }
716 }
717 }
718 }
719 else if (symmetric0 and !symmetric1)
720 {
721 // Expand the stored components of v to the full matrix
722 for (std::size_t p = 0; p < Xshape[0]; ++p)
723 {
724 int row = 0;
725 int rowstart = 0;
726 for (int k = 0; k < bs0; ++k)
727 {
728 if (k - rowstart > row)
729 {
730 ++row;
731 rowstart = k;
732 }
733 T acc = 0;
734 for (std::size_t i = 0; i < dim0; ++i)
735 acc += coeffs0[bs0 * i + k] * static_cast<T>(basis0(p, i, 0));
736 values0(p, 0, row * matrix_size + k - rowstart) = acc;
737 values0(p, 0, row + matrix_size * (k - rowstart)) = acc;
738 }
739 }
740 }
741 else // if (!symmetric0 and symmetric1)
742 {
743 // Evaluate only the components of v stored by u1. Physical
744 // component c of v is value component c / bs0 of block c % bs0.
745 for (std::size_t p = 0; p < Xshape[0]; ++p)
746 {
747 int row = 0;
748 int rowstart = 0;
749 for (int k = 0; k < bs1; ++k)
750 {
751 if (k - rowstart > row)
752 {
753 ++row;
754 rowstart = k;
755 }
756 const int c = row * matrix_size + k - rowstart;
757 T acc = 0;
758 for (std::size_t i = 0; i < dim0; ++i)
759 {
760 acc += coeffs0[bs0 * i + c % bs0]
761 * static_cast<T>(basis0(p, i, c / bs0));
762 }
763 values0(p, 0, k) = acc;
764 }
765 }
766 }
767
768 // Pull back the physical values to the u reference
769 for (std::size_t i = 0; i < values0.extent(0); ++i)
770 {
771 auto _u = md::submdspan(values0, i, md::full_extent, md::full_extent);
772 auto _U
773 = md::submdspan(mapped_values0, i, md::full_extent, md::full_extent);
774 auto _K = md::submdspan(K, i, md::full_extent, md::full_extent);
775 auto _J = md::submdspan(J, i, md::full_extent, md::full_extent);
776 pull_back_fn1(_U, _u, _K, 1.0 / detJ[i], _J);
777 }
778
779 auto values
780 = md::submdspan(mapped_values0, md::full_extent, 0, md::full_extent);
781 interpolation_apply(Pi_1, values, std::span(local1), bs1);
782 if (apply_inv_dof_transform1)
783 apply_inv_dof_transform1(local1, cell_info1, *cell1_it, 1);
784
785 // Copy local coefficients to the correct position in u dof array
786 const int dof_bs1 = dofmap1->bs();
787 std::span<const std::int32_t> dofs1 = dofmap1->cell_dofs(*cell1_it);
788 for (std::size_t i = 0; i < dofs1.size(); ++i)
789 for (int k = 0; k < dof_bs1; ++k)
790 array1[dof_bs1 * dofs1[i] + k] = local1[dof_bs1 * i + k];
791 }
792}
793
805template <dolfinx::scalar T, std::floating_point U>
806void point_evaluation(const FiniteElement<U>& element, bool symmetric,
807 const DofMap& dofmap, mesh::CellRange auto&& cells,
808 std::span<const std::uint32_t> cell_info,
809 std::span<const T> f, std::array<std::size_t, 2> fshape,
810 std::span<T> coeffs)
811{
812 // Point evaluation element *and* the geometric map is the identity,
813 // e.g. not Piola mapped
814
815 const int element_bs = element.block_size();
816 const int num_scalar_dofs = element.space_dimension() / element_bs;
817 const int dofmap_bs = dofmap.bs();
818
819 auto apply_inv_transpose_dof_transformation
820 = element.template dof_transformation_fn<T>(
822 std::vector<T> coeffs_b(num_scalar_dofs);
823
824 // Skip the div/mod below when block sizes match (the common case)
825 const bool same_bs = (dofmap_bs == element_bs);
826
827 if (symmetric)
828 {
829 // f holds all d * d components of the (d, d) tensor, or only the
830 // d * (d + 1) / 2 the element stores, in the order below
831 const bool stored_only = fshape[0] == static_cast<std::size_t>(element_bs);
832 std::size_t matrix_size = 0;
833 while (matrix_size * (matrix_size + 1) / 2
834 < static_cast<std::size_t>(element_bs))
835 {
836 ++matrix_size;
837 }
838 assert(stored_only or matrix_size * matrix_size == fshape[0]);
839
840 // Loop over cells
841 for (auto cell_it = cells.begin(); cell_it != cells.end(); ++cell_it)
842 {
843 // The entries of a symmetric matrix are numbered (for an
844 // example 4x4 element):
845 // 0 * * *
846 // 1 2 * *
847 // 3 4 5 *
848 // 6 7 8 9
849 // The loop extracts these elements. In this loop, row is the
850 // row of this matrix, and (k - rowstart) is the column
851 std::size_t row = 0;
852 std::size_t rowstart = 0;
853 std::span<const std::int32_t> dofs = dofmap.cell_dofs(*cell_it);
854 std::size_t offset = std::ranges::distance(cells.begin(), cell_it);
855 for (int k = 0; k < element_bs; ++k)
856 {
857 if (k - rowstart > row)
858 {
859 ++row;
860 rowstart = k;
861 }
862
863 // Row of f holding entry (row, k - rowstart)
864 const std::size_t f_row = stored_only
865 ? static_cast<std::size_t>(k)
866 : row * matrix_size + k - rowstart;
867
868 // num_scalar_dofs is the number of interpolation points per
869 // cell in this case (interpolation matrix is identity)
870 std::copy_n(
871 std::next(f.begin(), f_row * fshape[1] + offset * num_scalar_dofs),
872 num_scalar_dofs, coeffs_b.data());
873 if (apply_inv_transpose_dof_transformation)
874 {
875 apply_inv_transpose_dof_transformation(coeffs_b, cell_info, *cell_it,
876 1);
877 }
878 if (same_bs)
879 {
880 for (int i = 0; i < num_scalar_dofs; ++i)
881 coeffs[dofmap_bs * dofs[i] + k] = coeffs_b[i];
882 }
883 else
884 {
885 for (int i = 0; i < num_scalar_dofs; ++i)
886 {
887 std::div_t pos = std::div(i * element_bs + k, dofmap_bs);
888 coeffs[dofmap_bs * dofs[pos.quot] + pos.rem] = coeffs_b[i];
889 }
890 }
891 }
892 }
893 }
894 else
895 {
896 // Loop over cells
897 for (auto cell_it = cells.begin(); cell_it != cells.end(); ++cell_it)
898 {
899 std::size_t offset = std::ranges::distance(cells.begin(), cell_it);
900 std::span<const std::int32_t> dofs = dofmap.cell_dofs(*cell_it);
901 for (int k = 0; k < element_bs; ++k)
902 {
903 // num_scalar_dofs is the number of interpolation points per
904 // cell in this case (interpolation matrix is identity)
905 std::copy_n(
906 std::next(f.begin(), k * fshape[1] + offset * num_scalar_dofs),
907 num_scalar_dofs, coeffs_b.data());
908 if (apply_inv_transpose_dof_transformation)
909 {
910 apply_inv_transpose_dof_transformation(coeffs_b, cell_info, *cell_it,
911 1);
912 }
913 if (same_bs)
914 {
915 for (int i = 0; i < num_scalar_dofs; ++i)
916 coeffs[dofmap_bs * dofs[i] + k] = coeffs_b[i];
917 }
918 else
919 {
920 for (int i = 0; i < num_scalar_dofs; ++i)
921 {
922 std::div_t pos = std::div(i * element_bs + k, dofmap_bs);
923 coeffs[dofmap_bs * dofs[pos.quot] + pos.rem] = coeffs_b[i];
924 }
925 }
926 }
927 }
928 }
929}
930
942template <dolfinx::scalar T, std::floating_point U>
943void identity_mapped_evaluation(const FiniteElement<U>& element, bool symmetric,
944 const DofMap& dofmap,
945 mesh::CellRange auto&& cells,
946 std::span<const std::uint32_t> cell_info,
947 std::span<const T> f,
948 std::array<std::size_t, 2> fshape,
949 std::span<T> coeffs)
950{
951 // Not a point evaluation, but the geometric map is the identity,
952 // e.g. not Piola mapped
953
954 if (symmetric)
955 {
956 throw std::invalid_argument(
957 "Interpolation into this element not supported.");
958 }
959
960 const int element_bs = element.block_size();
961 const int num_scalar_dofs = element.space_dimension() / element_bs;
962 const int dofmap_bs = dofmap.bs();
963
964 // Identity map, so the physical and reference value sizes coincide.
965 const int element_vs = element.reference_value_size();
966 assert(element_vs == element.physical_base_value_size());
967 if (element_vs > 1 and element_bs > 1)
968 throw std::runtime_error("Interpolation into this element not supported.");
969
970 // Get interpolation operator
971 const auto [_Pi, pi_shape] = element.interpolation_operator();
972 md::mdspan<const U, std::dextents<std::size_t, 2>> Pi(_Pi.data(), pi_shape);
973 const std::size_t num_interp_points = Pi.extent(1);
974 assert(static_cast<int>(Pi.extent(0)) == num_scalar_dofs);
975
976 auto apply_inv_transpose_dof_transformation
977 = element.template dof_transformation_fn<T>(
979
980 // Skip the div/mod below when block sizes match (the common case)
981 const bool same_bs = (dofmap_bs == element_bs);
982
983 // Loop over cells
984 std::vector<T> ref_data_b(num_interp_points);
985 md::mdspan<T, md::extents<std::size_t, md::dynamic_extent, 1>> ref_data(
986 ref_data_b.data(), num_interp_points, 1);
987 std::vector<T> coeffs_b(num_scalar_dofs);
988 for (auto cell_it = cells.begin(); cell_it != cells.end(); ++cell_it)
989 {
990 std::size_t offset = std::ranges::distance(cells.begin(), cell_it);
991 std::span<const std::int32_t> dofs = dofmap.cell_dofs(*cell_it);
992 for (int k = 0; k < element_bs; ++k)
993 {
994 for (int i = 0; i < element_vs; ++i)
995 {
996 std::copy_n(
997 std::next(f.begin(), (i + k) * fshape[1]
998 + offset * num_interp_points / element_vs),
999 num_interp_points / element_vs,
1000 std::next(ref_data_b.begin(), i * num_interp_points / element_vs));
1001 }
1002
1003 impl::interpolation_apply(Pi, ref_data, std::span(coeffs_b), 1);
1004 if (apply_inv_transpose_dof_transformation)
1005 {
1006 apply_inv_transpose_dof_transformation(coeffs_b, cell_info, *cell_it,
1007 1);
1008 }
1009 if (same_bs)
1010 {
1011 for (int i = 0; i < num_scalar_dofs; ++i)
1012 coeffs[dofmap_bs * dofs[i] + k] = coeffs_b[i];
1013 }
1014 else
1015 {
1016 for (int i = 0; i < num_scalar_dofs; ++i)
1017 {
1018 std::div_t pos = std::div(i * element_bs + k, dofmap_bs);
1019 coeffs[dofmap_bs * dofs[pos.quot] + pos.rem] = coeffs_b[i];
1020 }
1021 }
1022 }
1023 }
1024}
1025
1038template <dolfinx::scalar T, std::floating_point U>
1039void piola_mapped_evaluation(const FiniteElement<U>& element, bool symmetric,
1040 const DofMap& dofmap, mesh::CellRange auto&& cells,
1041 std::span<const std::uint32_t> cell_info,
1042 std::span<const T> f,
1043 std::array<std::size_t, 2> fshape,
1044 const mesh::Mesh<U>& mesh, std::span<T> coeffs)
1045{
1046 if (symmetric)
1047 {
1048 throw std::invalid_argument(
1049 "Interpolation into this element not supported.");
1050 }
1051
1052 const int gdim = mesh.geometry().dim();
1053 assert(mesh.topology());
1054 const int tdim = mesh.topology()->dim();
1055
1056 const int element_bs = element.block_size();
1057 const int num_scalar_dofs = element.space_dimension() / element_bs;
1058 // f holds physical values, one block at a time.
1059 const int value_size = element.physical_base_value_size();
1060 const int dofmap_bs = dofmap.bs();
1061
1062 // Skip the div/mod below when block sizes match (the common case)
1063 const bool same_bs = (dofmap_bs == element_bs);
1064
1065 md::mdspan<const T, md::dextents<std::size_t, 2>> _f(f.data(), fshape);
1066
1067 // Get the interpolation points on the reference cells
1068 const auto [X, Xshape] = element.interpolation_points();
1069 if (X.empty())
1070 {
1071 throw std::invalid_argument(
1072 "Interpolation into this space is not yet supported.");
1073 }
1074
1075 if (_f.extent(1) != cells.size() * Xshape[0])
1076 throw std::invalid_argument("Interpolation data has the wrong shape.");
1077
1078 // Get coordinate map
1079 const CoordinateElement<U>& cmap = mesh.geometry().cmaps().front();
1080
1081 // Get geometry data
1082 auto x_dofmap = mesh.geometry().dofmaps().front();
1083 const int num_dofs_g = cmap.dim();
1084 std::span<const U> x_g = mesh.geometry().x();
1085
1086 // Create data structures for Jacobian info
1087 std::vector<U> J_b(Xshape[0] * gdim * tdim);
1088 md::mdspan<U, std::dextents<std::size_t, 3>> J(J_b.data(), Xshape[0], gdim,
1089 tdim);
1090 std::vector<U> K_b(Xshape[0] * tdim * gdim);
1091 md::mdspan<U, std::dextents<std::size_t, 3>> K(K_b.data(), Xshape[0], tdim,
1092 gdim);
1093 std::vector<U> detJ(Xshape[0]);
1094 std::vector<U> det_scratch(2 * gdim * tdim);
1095
1096 std::vector<U> coord_dofs_b(num_dofs_g * gdim);
1097 md::mdspan<U, std::dextents<std::size_t, 2>> coord_dofs(coord_dofs_b.data(),
1098 num_dofs_g, gdim);
1099 const std::size_t value_size_ref = element.reference_value_size();
1100 std::vector<T> ref_data_b(Xshape[0] * 1 * value_size_ref);
1101 md::mdspan<
1102 T, md::extents<std::size_t, md::dynamic_extent, 1, md::dynamic_extent>>
1103 ref_data(ref_data_b.data(), Xshape[0], 1, value_size_ref);
1104
1105 std::vector<T> _vals_b(Xshape[0] * 1 * value_size);
1106 md::mdspan<
1107 T, md::extents<std::size_t, md::dynamic_extent, 1, md::dynamic_extent>>
1108 _vals(_vals_b.data(), Xshape[0], 1, value_size);
1109
1110 // Tabulate 1st derivative of shape functions at interpolation
1111 // coords
1112 std::array<std::size_t, 4> phi_shape = cmap.tabulate_shape(1, Xshape[0]);
1113 std::vector<U> phi_b(
1114 std::reduce(phi_shape.begin(), phi_shape.end(), 1, std::multiplies{}));
1115 md::mdspan<const U, md::extents<std::size_t, md::dynamic_extent,
1116 md::dynamic_extent, md::dynamic_extent, 1>>
1117 phi(phi_b.data(), phi_shape);
1118 cmap.tabulate(1, X, Xshape, phi_b);
1119 auto dphi = md::submdspan(phi, std::pair(1, tdim + 1), md::full_extent,
1120 md::full_extent, 0);
1121
1122 std::function<void(std::span<T>, std::span<const std::uint32_t>, std::int32_t,
1123 int)>
1124 apply_inv_trans_dof_transformation
1125 = element.template dof_transformation_fn<T>(
1127
1128 // Get interpolation operator
1129 const auto [_Pi, pi_shape] = element.interpolation_operator();
1130 md::mdspan<const U, std::dextents<std::size_t, 2>> Pi(_Pi.data(), pi_shape);
1131
1132 using u_t = md::mdspan<const T, md::dextents<std::size_t, 2>>;
1133 using U_t
1134 = decltype(md::submdspan(ref_data, 0, md::full_extent, md::full_extent));
1135 using J_t = md::mdspan<const U, md::dextents<std::size_t, 2>>;
1136 using K_t = md::mdspan<const U, md::dextents<std::size_t, 2>>;
1137 auto pull_back_fn
1138 = element.basix_element().template map_fn<U_t, u_t, J_t, K_t>();
1139
1140 std::vector<T> coeffs_b(num_scalar_dofs);
1141 for (auto cell_it = cells.begin(); cell_it != cells.end(); ++cell_it)
1142 {
1143 auto x_dofs = md::submdspan(x_dofmap, *cell_it, md::full_extent);
1144 for (int i = 0; i < num_dofs_g; ++i)
1145 {
1146 const int pos = 3 * x_dofs[i];
1147 for (int j = 0; j < gdim; ++j)
1148 coord_dofs(i, j) = x_g[pos + j];
1149 }
1150
1151 // Compute J, detJ and K
1152 std::ranges::fill(J_b, 0);
1153 for (std::size_t p = 0; p < Xshape[0]; ++p)
1154 {
1155 auto _dphi = md::submdspan(dphi, md::full_extent, p, md::full_extent);
1156 auto _J = md::submdspan(J, p, md::full_extent, md::full_extent);
1157 cmap.compute_jacobian(_dphi, coord_dofs, _J);
1158 auto _K = md::submdspan(K, p, md::full_extent, md::full_extent);
1159 cmap.compute_jacobian_inverse(_J, _K);
1160 detJ[p] = cmap.compute_jacobian_determinant(_J, det_scratch);
1161 }
1162
1163 const std::size_t offset = std::ranges::distance(cells.begin(), cell_it);
1164 std::span<const std::int32_t> dofs = dofmap.cell_dofs(*cell_it);
1165 for (int k = 0; k < element_bs; ++k)
1166 {
1167 // Extract computed expression values for element block k
1168 for (int m = 0; m < value_size; ++m)
1169 {
1170 for (std::size_t k0 = 0; k0 < Xshape[0]; ++k0)
1171 {
1172 _vals(k0, 0, m)
1173 = f[fshape[1] * (k * value_size + m) + offset * Xshape[0] + k0];
1174 }
1175 }
1176
1177 // Get element degrees of freedom for block
1178 for (std::size_t i = 0; i < Xshape[0]; ++i)
1179 {
1180 auto _u = md::submdspan(_vals, i, md::full_extent, md::full_extent);
1181 auto _U = md::submdspan(ref_data, i, md::full_extent, md::full_extent);
1182 auto _K = md::submdspan(K, i, md::full_extent, md::full_extent);
1183 auto _J = md::submdspan(J, i, md::full_extent, md::full_extent);
1184 pull_back_fn(_U, _u, _K, 1.0 / detJ[i], _J);
1185 }
1186
1187 auto ref = md::submdspan(ref_data, md::full_extent, 0, md::full_extent);
1188 impl::interpolation_apply(Pi, ref, std::span(coeffs_b), element_bs);
1189 if (apply_inv_trans_dof_transformation)
1190 apply_inv_trans_dof_transformation(coeffs_b, cell_info, *cell_it, 1);
1191
1192 // Copy interpolation dofs into coefficient vector
1193 assert(coeffs_b.size() == static_cast<std::size_t>(num_scalar_dofs));
1194 if (same_bs)
1195 {
1196 for (int i = 0; i < num_scalar_dofs; ++i)
1197 coeffs[dofmap_bs * dofs[i] + k] = coeffs_b[i];
1198 }
1199 else
1200 {
1201 for (int i = 0; i < num_scalar_dofs; ++i)
1202 {
1203 std::div_t pos = std::div(i * element_bs + k, dofmap_bs);
1204 coeffs[dofmap_bs * dofs[pos.quot] + pos.rem] = coeffs_b[i];
1205 }
1206 }
1207 }
1208 }
1209}
1210
1211//----------------------------------------------------------------------------
1212} // namespace impl
1213
1239template <std::floating_point T>
1241 const mesh::Geometry<T>& geometry0, const FiniteElement<T>& element0,
1242 const mesh::Mesh<T>& mesh1, mesh::CellRange auto&& cells, T padding,
1243 bool allow_extrapolation = true)
1244{
1245 // Collect all the points at which values are needed to define the
1246 // interpolating function
1247 std::vector<T> coords = interpolation_coords(element0, geometry0, cells);
1248
1249 // Transpose interpolation coords
1250 std::vector<T> x(coords.size());
1251 std::size_t num_points = coords.size() / 3;
1252 for (std::size_t i = 0; i < num_points; ++i)
1253 for (std::size_t j = 0; j < 3; ++j)
1254 x[3 * i + j] = coords[i + j * num_points];
1255
1256 // Determine ownership of each point
1257 return geometry::determine_point_ownership<T>(mesh1, x, padding, std::nullopt,
1258 allow_extrapolation);
1259}
1260
1261template <dolfinx::scalar T, std::floating_point U>
1262void interpolate(Function<T, U>& u, std::span<const T> f,
1263 std::array<std::size_t, 2> fshape,
1264 mesh::CellRange auto&& cells)
1265{
1266 // TODO: Index for mixed-topology, zero for now
1267 const int index = 0;
1268 auto element = u.function_space()->elements(index);
1269 assert(element);
1270 const int element_bs = element->block_size();
1271 if (int num_sub = element->num_sub_elements();
1272 num_sub > 0 and num_sub != element_bs)
1273 {
1274 throw std::invalid_argument("Cannot directly interpolate a mixed space. "
1275 "Interpolate into subspaces.");
1276 }
1277
1278 // Get mesh
1279 assert(u.function_space());
1280 auto mesh = u.function_space()->mesh();
1281 assert(mesh);
1282
1283 // A symmetric rank-2 tensor space also accepts only the components
1284 // it stores
1285 const bool symmetric_stored_only
1286 = u.function_space()->symmetric()
1287 and fshape[0] == static_cast<std::size_t>(element_bs);
1288 if ((fshape[0] != static_cast<std::size_t>(element->value_size())
1289 and !symmetric_stored_only)
1290 or f.size() != fshape[0] * fshape[1])
1291 {
1292 throw std::invalid_argument("Interpolation data has the wrong shape/size.");
1293 }
1294
1295 logger().debug("Check for dof transformation");
1296 std::span<const std::uint32_t> cell_info;
1297 if (element->needs_dof_transformations())
1298 {
1299 mesh->topology_mutable()->create_cell_permutations();
1300 cell_info = std::span(mesh->topology()->get_cell_permutation_info());
1301 }
1302
1303 // Get dofmap
1304 logger().debug("Interpolate: get dofmap");
1305 const auto dofmap = u.function_space()->dofmaps().at(index);
1306 assert(dofmap);
1307
1308 // Result will be stored to coeffs
1309 std::span<T> coeffs = u.x()->array();
1310
1311 if (bool symmetric = u.function_space()->symmetric();
1312 element->map_ident() and element->interpolation_ident())
1313 {
1314 // This assumes that any element with an identity interpolation
1315 // matrix is a point evaluation
1316 logger().debug("Interpolate: point evaluation");
1317 impl::point_evaluation(*element, symmetric, *dofmap, cells, cell_info, f,
1318 fshape, coeffs);
1319 }
1320 else if (element->map_ident())
1321 {
1322 logger().debug("Interpolate: identity-mapped evaluation");
1323 impl::identity_mapped_evaluation(*element, symmetric, *dofmap, cells,
1324 cell_info, f, fshape, coeffs);
1325 }
1326 else
1327 {
1328 logger().debug("Interpolate: Piola-mapped evaluation");
1329 impl::piola_mapped_evaluation(*element, symmetric, *dofmap, cells,
1330 cell_info, f, fshape, *mesh, coeffs);
1331 }
1332}
1333
1350template <dolfinx::scalar T, std::floating_point U>
1352 mesh::CellRange auto&& cells, double tol, int maxit,
1353 const geometry::PointOwnershipData<U>& interpolation_data)
1354{
1355 auto mesh1 = u1.function_space()->mesh();
1356 assert(mesh1);
1357 MPI_Comm comm = mesh1->comm();
1358 {
1359 assert(u0.function_space());
1360 auto mesh0 = u0.function_space()->mesh();
1361 assert(mesh0);
1362 int result;
1363 MPI_Comm_compare(comm, mesh0->comm(), &result);
1364 if (result == MPI_UNEQUAL)
1365 {
1366 throw std::invalid_argument("Interpolation on different meshes is only "
1367 "supported on the same communicator.");
1368 }
1369 }
1370
1371 assert(mesh1->topology());
1372 auto cell_map = mesh1->topology()->index_map(mesh1->topology()->dim());
1373 assert(cell_map);
1374 auto element1 = u1.function_space()->element();
1375 assert(element1);
1376 const std::size_t value_size = element1->value_size();
1377
1378 const std::vector<int>& dest_ranks = interpolation_data.src_owner;
1379 const std::vector<int>& src_ranks = interpolation_data.dest_owners;
1380 const std::vector<U>& recv_points = interpolation_data.dest_points;
1381 const std::vector<std::int32_t>& evaluation_cells
1382 = interpolation_data.dest_cells;
1383
1384 // Evaluate the interpolating function where possible
1385 std::vector<T> send_values(recv_points.size() / 3 * value_size);
1386 u0.eval(recv_points, {recv_points.size() / 3, (std::size_t)3},
1387 evaluation_cells, send_values, {recv_points.size() / 3, value_size},
1388 tol, maxit);
1389
1390 // Send values back to owning process
1391 std::vector<T> values_b(dest_ranks.size() * value_size);
1392 md::mdspan<const T, md::dextents<std::size_t, 2>> _send_values(
1393 send_values.data(), src_ranks.size(), value_size);
1394 impl::scatter_values(comm, src_ranks, dest_ranks, _send_values,
1395 std::span(values_b));
1396
1397 // Transpose received data
1398 md::mdspan<const T, md::dextents<std::size_t, 2>> values(
1399 values_b.data(), dest_ranks.size(), value_size);
1400 std::vector<T> valuesT_b(value_size * dest_ranks.size());
1401 md::mdspan<T, md::dextents<std::size_t, 2>> valuesT(
1402 valuesT_b.data(), value_size, dest_ranks.size());
1403 for (std::size_t i = 0; i < values.extent(0); ++i)
1404 for (std::size_t j = 0; j < values.extent(1); ++j)
1405 valuesT(j, i) = values(i, j);
1406
1407 // Call local interpolation operator
1408 fem::interpolate<T>(u1, valuesT_b, {valuesT.extent(0), valuesT.extent(1)},
1409 cells);
1410}
1411
1436template <dolfinx::scalar T, std::floating_point U>
1438 const Function<T, U>& u0, mesh::CellRange auto&& cells0)
1439{
1440 if (cells0.size() != cells1.size())
1441 throw std::invalid_argument("Length of cell lists do not match.");
1442
1443 auto V1 = u1.function_space();
1444 assert(V1);
1445 auto V0 = u0.function_space();
1446 assert(V0);
1447
1448 // Get elements and check value shape
1449 auto e0 = V0->element();
1450 assert(e0);
1451 auto e1 = V1->element();
1452 assert(e1);
1453 if (!std::ranges::equal(e0->value_shape(), e1->value_shape()))
1454 {
1455 throw std::invalid_argument(
1456 "Interpolation: elements have different value dimensions");
1457 }
1458
1459 if (e0->symmetric() != e1->symmetric())
1460 {
1461 // Convert between independent and full tensor components. This must
1462 // precede the same-map branch below, which cannot change the number
1463 // of components.
1464 impl::interpolate_nonmatching_maps(u1, cells1, u0, cells0);
1465 }
1466 else if (V1->mesh() == V0->mesh() and (e1 == e0 or *e1 == *e0))
1467 {
1468 // Same element and same mesh
1469 if (e1->block_size() != e0->block_size())
1470 throw std::invalid_argument("Mismatch in element block size.");
1471
1472 // Get dofmaps
1473 std::shared_ptr<const DofMap> dofmap0 = V0->dofmap();
1474 assert(dofmap0);
1475 std::shared_ptr<const DofMap> dofmap1 = V1->dofmap();
1476 assert(dofmap1);
1477
1478 // Iterate over mesh and interpolate on each cell
1479 const int bs0 = dofmap0->bs();
1480 const int bs1 = dofmap1->bs();
1481 std::span<T> u1_array = u1.x()->array();
1482 std::span<const T> u0_array = u0.x()->array();
1483 assert(cells0.size() == cells1.size());
1484 for (auto cell0_it = cells0.begin(), cell1_it = cells1.begin();
1485 cell0_it != cells0.end() and cell1_it != cells1.end();
1486 ++cell0_it, ++cell1_it)
1487
1488 {
1489 std::span<const std::int32_t> dofs0 = dofmap0->cell_dofs(*cell0_it);
1490 std::span<const std::int32_t> dofs1 = dofmap1->cell_dofs(*cell1_it);
1491 assert(bs0 * dofs0.size() == bs1 * dofs1.size());
1492 for (std::size_t i = 0; i < dofs0.size(); ++i)
1493 {
1494 for (int k = 0; k < bs0; ++k)
1495 {
1496 int index = bs0 * i + k;
1497 std::div_t dv1 = std::div(index, bs1);
1498 u1_array[bs1 * dofs1[dv1.quot] + dv1.rem]
1499 = u0_array[bs0 * dofs0[i] + k];
1500 }
1501 }
1502 }
1503 }
1504 else if (e1->map_type() == e0->map_type())
1505 {
1506 // Different elements, same basis function map type
1507 impl::interpolate_same_map(u1, cells1, u0, cells0);
1508 }
1509 else
1510 {
1511 // Different elements with different maps for basis functions
1512 impl::interpolate_nonmatching_maps(u1, cells1, u0, cells0);
1513 }
1514}
1515
1525template <dolfinx::scalar T, std::floating_point U>
1527 std::ranges::input_range auto&& cells)
1528{
1529 assert(u1.function_space());
1530 assert(u0.function_space());
1531 if (u1.function_space()->mesh() == u0.function_space()->mesh())
1532 interpolate<T, U>(u1, cells, u0, cells);
1533 else
1534 throw std::invalid_argument("Meshes do no match.");
1535}
1536
1546template <dolfinx::scalar T, std::floating_point U>
1548{
1549 assert(u1.function_space());
1550 assert(u0.function_space());
1551 if (auto V1 = u1.function_space(); V1 == u0.function_space())
1552 std::ranges::copy(u0.x()->array(), u1.x()->array().begin());
1553 else
1554 {
1555 auto mesh = V1->mesh();
1556 assert(mesh);
1557 assert(mesh->topology());
1558 auto map = mesh->topology()->index_map(mesh->topology()->dim());
1559 assert(map);
1560 std::int32_t num_cells = map->size_local() + map->num_ghosts();
1561 interpolate<T, U>(u1, u0, std::ranges::views::iota(0, num_cells));
1562 }
1563}
1564} // namespace dolfinx::fem
Degree-of-freedom map representations and tools.
Definition CoordinateElement.h:39
void tabulate(int nd, std::span< const T > X, std::array< std::size_t, 2 > shape, std::span< T > basis) const
Evaluate basis values and derivatives at set of points.
Definition CoordinateElement.cpp:71
std::array< std::size_t, 4 > tabulate_shape(std::size_t nd, std::size_t num_points) const
Shape of array to fill when calling tabulate.
Definition CoordinateElement.cpp:64
int dim() const
The dimension of the coordinate element space.
Definition CoordinateElement.cpp:237
Model of a finite element.
Definition FiniteElement.h:202
std::pair< std::vector< geometry_type >, std::array< std::size_t, 2 > > interpolation_points() const
Points on the reference cell at which an expression needs to be evaluated in order to interpolate the...
Definition FiniteElement.cpp:560
mesh::CellType cell_type() const noexcept
Cell shape that the element is defined on.
Definition FiniteElement.cpp:353
Definition Function.h:44
std::shared_ptr< const FunctionSpace< geometry_type > > function_space() const
Access the function space.
Definition Function.h:149
void eval(std::span< const geometry_type > x, std::array< std::size_t, 2 > xshape, mesh::CellRange auto &&cells, std::span< value_type > u, std::array< std::size_t, 2 > ushape, double tol, int maxit) const
Evaluate the Function at points.
Definition Function.h:334
std::shared_ptr< const la::Vector< value_type > > x() const
Underlying vector (const version).
Definition Function.h:155
Geometry stores the geometry imposed on a mesh.
Definition Geometry.h:39
A Mesh consists of a set of connected and numbered mesh topological entities, and geometry data.
Definition Mesh.h:25
Requirement on range of cell indices.
Definition Topology.h:35
MPI_Datatype mpi_t
Retrieves the MPI data type associated to the provided type.
Definition MPI.h:320
int rank(MPI_Comm comm)
Return process rank for the communicator.
Definition MPI.cpp:73
void cells(la::SparsityPattern &pattern, const std::pair< R0, R1 > &cells, std::array< std::reference_wrapper< const DofMap >, 2 > dofmaps)
Iterate over cells and insert entries into sparsity pattern.
Definition sparsitybuild.h:40
Finite element method functionality.
Definition assemble_expression_impl.h:28
geometry::PointOwnershipData< T > create_interpolation_data(const mesh::Geometry< T > &geometry0, const FiniteElement< T > &element0, const mesh::Mesh< T > &mesh1, mesh::CellRange auto &&cells, T padding, bool allow_extrapolation=true)
Generate data needed to interpolate finite element fem::Function's across different meshes.
Definition interpolate.h:1240
@ transpose
Transpose.
Definition FiniteElement.h:35
@ inverse_transpose
Transpose inverse.
Definition FiniteElement.h:37
@ standard
Standard.
Definition FiniteElement.h:34
std::vector< T > interpolation_coords(const fem::FiniteElement< T > &element, const mesh::Geometry< T > &geometry, mesh::CellRange auto &&cells)
Compute the evaluation points in the physical space at which an expression should be computed to inte...
Definition interpolate.h:46
void interpolate(Function< T, U > &u1, mesh::CellRange auto &&cells1, const Expression< T, U > &e0, mesh::CellRange auto &&cells0)
Interpolate an Expression into a Function over a subset of cells.
Definition expression_evaluate.h:284
Geometry data structures and algorithms.
Definition BoundingBoxTree.h:26
PointOwnershipData< T > determine_point_ownership(const mesh::Mesh< T > &mesh, std::span< const T > points, T padding, std::optional< std::span< const std::int32_t > > cells, bool find_closest_cell=true)
Determine, for a set of points, the owning process of the cell (if any) that contains each point.
Definition utils.h:820
Mesh data structures and algorithms on meshes.
Definition DofMap.h:32
CellType
Cell type identifier.
Definition cell_types.h:24
Mesh(MPI_Comm, std::shared_ptr< Topology >, V) -> Mesh< typename std::remove_cvref_t< typename V::value_type > >
Template type deduction.
auto logger() -> spdlog::logger &
Dolfinx's logger.
Definition log.cpp:24
Information on the ownership of points distributed across processes.
Definition utils.h:36
std::vector< T > dest_points
Points that are owned by current process.
Definition utils.h:41
std::vector< std::int32_t > dest_cells
Definition utils.h:43
std::vector< int > dest_owners
Ranks that sent dest_points to current process.
Definition utils.h:40
std::vector< int > src_owner
Definition utils.h:37