DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
DirichletBC.h
1// Copyright (C) 2007-2024 Michal Habera, Anders Logg, Garth N. Wells, Jørgen
2// 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 "Constant.h"
11#include "DofMap.h"
12#include "Function.h"
13#include "FunctionSpace.h"
14#include <algorithm>
15#include <array>
16#include <concepts>
17#include <dolfinx/common/types.h>
18#include <functional>
19#include <memory>
20#include <optional>
21#include <span>
22#include <stdexcept>
23#include <type_traits>
24#include <utility>
25#include <variant>
26#include <vector>
27
28namespace dolfinx::fem
29{
30
56std::vector<std::int32_t>
57locate_dofs_topological(const mesh::Topology& topology, const DofMap& dofmap,
58 int dim, std::span<const std::int32_t> entities,
59 bool remote = true);
60
87std::array<std::vector<std::int32_t>, 2> locate_dofs_topological(
88 const mesh::Topology& topology,
89 std::array<std::reference_wrapper<const DofMap>, 2> dofmaps, int dim,
90 std::span<const std::int32_t> entities, bool remote = true);
91
103template <std::floating_point T, typename U>
104std::vector<std::int32_t> locate_dofs_geometrical(const FunctionSpace<T>& V,
105 U marker_fn)
106{
107 // FIXME: Calling V.tabulate_dof_coordinates() is very expensive,
108 // especially when we usually want the boundary dofs only. Add
109 // interface that computes dofs coordinates only for specified cell.
110
111 for (std::size_t i = 0; i < V.mesh()->topology()->cell_types().size(); ++i)
112 {
113 assert(V.elements(i));
114 if (V.elements(i)->is_mixed())
115 {
116 throw std::invalid_argument(
117 "Cannot locate dofs geometrically for mixed space. Use subspaces.");
118 }
119 }
120
121 // Compute dof coordinates
122 const std::vector<T> dof_coordinates = V.tabulate_dof_coordinates(true);
123
124 using cmdspan3x_t
125 = md::mdspan<const T, md::extents<std::size_t, 3, md::dynamic_extent>>;
126
127 // Compute marker for each dof coordinate
128 cmdspan3x_t x(dof_coordinates.data(), 3, dof_coordinates.size() / 3);
129 const std::vector<std::int8_t> marked_dofs = marker_fn(x);
130
131 std::vector<std::int32_t> dofs;
132 dofs.reserve(std::count(marked_dofs.begin(), marked_dofs.end(), true));
133 for (std::size_t i = 0; i < marked_dofs.size(); ++i)
134 {
135 if (marked_dofs[i])
136 dofs.push_back(i);
137 }
138
139 return dofs;
140}
141
155template <std::floating_point T, typename U>
156std::array<std::vector<std::int32_t>, 2> locate_dofs_geometrical(
157 std::array<std::reference_wrapper<const FunctionSpace<T>>, 2> V,
158 U marker_fn)
159{
160 // FIXME: Calling V.tabulate_dof_coordinates() is very expensive,
161 // especially when we usually want the boundary dofs only. Add
162 // interface that computes dofs coordinates only for specified cell.
163
164 // Get function spaces
165 const FunctionSpace<T>& V0 = V.at(0).get();
166 const FunctionSpace<T>& V1 = V.at(1).get();
167
168 // Get mesh
169 auto mesh = V0.mesh();
170 assert(mesh);
171 assert(V1.mesh());
172 if (mesh != V1.mesh())
173 throw std::invalid_argument("Meshes are not the same.");
174 const int tdim = mesh->topology()->dim();
175
176 assert(V0.element());
177 assert(V1.element());
178 if (*V0.element() != *V1.element())
179 throw std::invalid_argument("Function spaces must have the same element.");
180
181 // Compute dof coordinates
182 const std::vector<T> dof_coordinates = V1.tabulate_dof_coordinates(true);
183
184 using cmdspan3x_t
185 = md::mdspan<const T, md::extents<std::size_t, 3, md::dynamic_extent>>;
186
187 // Evaluate marker for each dof coordinate
188 cmdspan3x_t x(dof_coordinates.data(), 3, dof_coordinates.size() / 3);
189 const std::vector<std::int8_t> marked_dofs = marker_fn(x);
190
191 // Get dofmaps
192 std::shared_ptr<const DofMap> dofmap0 = V0.dofmap();
193 assert(dofmap0);
194 const int bs0 = dofmap0->bs();
195 std::shared_ptr<const DofMap> dofmap1 = V1.dofmap();
196 assert(dofmap1);
197 const int bs1 = dofmap1->bs();
198
199 const int element_bs = dofmap0->element_dof_layout().block_size();
200 assert(element_bs == dofmap1->element_dof_layout().block_size());
201
202 // Iterate over cells
203 auto topology = mesh->topology();
204 assert(topology);
205 std::vector<std::array<std::int32_t, 2>> bc_dofs;
206 for (int c = 0; c < topology->connectivity(tdim, 0)->num_nodes(); ++c)
207 {
208 // Get cell dofmaps
209 auto cell_dofs0 = dofmap0->cell_dofs(c);
210 auto cell_dofs1 = dofmap1->cell_dofs(c);
211
212 // Loop over cell dofs and add to bc_dofs if marked.
213 for (std::size_t i = 0; i < cell_dofs1.size(); ++i)
214 {
215 if (marked_dofs[cell_dofs1[i]])
216 {
217 // Unroll over blocks
218 for (int k = 0; k < element_bs; ++k)
219 {
220 const int local_pos = element_bs * i + k;
221 const std::div_t pos0 = std::div(local_pos, bs0);
222 const std::div_t pos1 = std::div(local_pos, bs1);
223 const std::int32_t dof_index0
224 = bs0 * cell_dofs0[pos0.quot] + pos0.rem;
225 const std::int32_t dof_index1
226 = bs1 * cell_dofs1[pos1.quot] + pos1.rem;
227 bc_dofs.push_back({dof_index0, dof_index1});
228 }
229 }
230 }
231 }
232
233 // Remove duplicates
234 std::ranges::sort(bc_dofs);
235 auto [unique_end, range_end] = std::ranges::unique(bc_dofs);
236 bc_dofs.erase(unique_end, range_end);
237
238 // Copy to separate array
239 std::array dofs = {std::vector<std::int32_t>(bc_dofs.size()),
240 std::vector<std::int32_t>(bc_dofs.size())};
241 std::ranges::transform(bc_dofs, dofs[0].begin(),
242 [](auto dof) { return dof[0]; });
243 std::ranges::transform(bc_dofs, dofs[1].begin(),
244 [](auto dof) { return dof[1]; });
245
246 return dofs;
247}
248
257template <dolfinx::scalar T, std::floating_point U = dolfinx::scalar_value_t<T>>
259{
260private:
263 std::size_t num_owned(const DofMap& dofmap,
264 std::span<const std::int32_t> dofs)
265 {
266 int bs = dofmap.index_map_bs();
267 std::int32_t map_size = dofmap.index_map->size_local();
268 std::int32_t owned_size = bs * map_size;
269 auto it = std::ranges::lower_bound(dofs, owned_size);
270 return std::ranges::distance(dofs.begin(), it);
271 }
272
274 static std::vector<std::int32_t>
275 unroll_dofs(std::span<const std::int32_t> dofs, int bs)
276 {
277 std::vector<std::int32_t> dofs_unrolled(bs * dofs.size());
278 for (std::size_t i = 0; i < dofs.size(); ++i)
279 for (int k = 0; k < bs; ++k)
280 dofs_unrolled[bs * i + k] = bs * dofs[i] + k;
281 return dofs_unrolled;
282 }
283
284public:
302 template <typename S, typename X>
303 requires(std::is_convertible_v<S, T>
304 || std::is_convertible_v<S, std::span<const T>>)
305 && std::is_convertible_v<std::remove_cvref_t<X>,
306 std::vector<std::int32_t>>
307 DirichletBC(const S& g, X&& dofs, std::shared_ptr<const FunctionSpace<U>> V)
308 : DirichletBC(std::make_shared<Constant<T>>(g), dofs, V)
309 {
310 }
311
327 template <typename X>
328 requires std::is_convertible_v<std::remove_cvref_t<X>,
329 std::vector<std::int32_t>>
330 DirichletBC(std::shared_ptr<const Constant<T>> g, X&& dofs,
331 std::shared_ptr<const FunctionSpace<U>> V)
332 : _function_space(V), _g(g), _dofs0(std::forward<X>(dofs))
333 {
334 assert(g);
335 assert(V);
336 assert(V->elements(0));
337 if (g->shape.size() != V->elements(0)->value_shape().size())
338 {
339 throw std::invalid_argument(
340 "Rank mismatch between Constant and function space in DirichletBC");
341 }
342
343 if (g->value.size()
344 != (std::size_t)_function_space->dofmaps().front()->bs())
345 {
346 throw std::invalid_argument(
347 "Creating a DirichletBC using a Constant is not supported when the "
348 "Constant size is not equal to the block size of the constrained "
349 "(sub-)space. Use a fem::Function to create the fem::DirichletBC.");
350 }
351
352 if (!V->elements(0)->interpolation_ident())
353 {
354 throw std::invalid_argument(
355 "Constant can be used only with point-evaluation elements");
356 }
357
358 // Unroll _dofs0 if dofmap block size > 1
359 if (const int bs = V->dofmaps().front()->bs(); bs > 1)
360 _dofs0 = unroll_dofs(_dofs0, bs);
361
362 _owned_indices0 = num_owned(*_function_space->dofmaps().front(), _dofs0);
363 }
364
377 template <typename X>
378 requires std::is_convertible_v<std::remove_cvref_t<X>,
379 std::vector<std::int32_t>>
380 DirichletBC(std::shared_ptr<const Function<T, U>> g, X&& dofs)
381 : _function_space(g->function_space()), _g(g),
382 _dofs0(std::forward<X>(dofs))
383 {
384 assert(_function_space);
385
386 // Unroll _dofs0 if dofmap block size > 1
387 if (const int bs = _function_space->dofmaps().front()->bs(); bs > 1)
388 _dofs0 = unroll_dofs(_dofs0, bs);
389
390 _owned_indices0 = num_owned(*_function_space->dofmaps().front(), _dofs0);
391 }
392
414 template <typename X>
415 DirichletBC(std::shared_ptr<const Function<T, U>> g, X&& V_g_dofs,
416 std::shared_ptr<const FunctionSpace<U>> V)
417 : _function_space(V), _g(g),
418 _dofs0(std::forward<typename std::remove_reference_t<X>::value_type>(
419 V_g_dofs[0])),
420 _dofs1_g(std::forward<typename std::remove_reference_t<X>::value_type>(
421 V_g_dofs[1])),
422 _owned_indices0(num_owned(*_function_space->dofmap(), _dofs0))
423 {
424 }
425
428 DirichletBC(const DirichletBC& bc) = default;
429
432 DirichletBC(DirichletBC&& bc) = default;
433
435 ~DirichletBC() = default;
436
439 DirichletBC& operator=(const DirichletBC& bc) = default;
440
443
446 std::shared_ptr<const FunctionSpace<U>> function_space() const
447 {
448 return _function_space;
449 }
450
453 std::variant<std::shared_ptr<const Function<T, U>>,
454 std::shared_ptr<const Constant<T>>>
455 value() const
456 {
457 return _g;
458 }
459
466 std::pair<std::span<const std::int32_t>, std::int32_t> dof_indices() const
467 {
468 return {_dofs0, _owned_indices0};
469 }
470
496 void set(std::span<T> x, std::optional<std::span<const T>> x0,
497 T alpha = 1) const
498 {
499 // set_fn is a lambda which gets evaluated for every index in [0,
500 // _dofs0.size()) and its result is assigned to x[_dofs0[i]].
501 auto apply = [this, &x](std::invocable<std::int32_t> auto set_fn)
502 {
503 static_assert(
504 std::is_same_v<std::invoke_result_t<decltype(set_fn), std::int32_t>,
505 T>);
506
507 std::int32_t x_size = x.size();
508 for (std::size_t i = 0; i < _dofs0.size(); ++i)
509 {
510 if (_dofs0[i] < x_size)
511 x[_dofs0[i]] = set_fn(i);
512 }
513 };
514
515 if (alpha == T(0)) // Optimisation for when alpha == 0
516 {
517 apply([](std::int32_t) -> T { return 0; });
518 return;
519 }
520
521 if (std::holds_alternative<std::shared_ptr<const Function<T, U>>>(_g))
522 {
523 auto g = std::get<std::shared_ptr<const Function<T, U>>>(_g);
524 assert(g);
525 std::span<const T> values = g->x()->array();
526
527 // Extract degrees of freedom associated with g. If g is in a collapsed
528 // sub-space, get the dofs in this space, otherwise the degrees of g is
529 // the same as for x
530 auto dofs_g = _dofs1_g.empty() ? std::span(_dofs0) : std::span(_dofs1_g);
531
532 if (x0)
533 {
534 assert(x.size() <= x0->size());
535 apply(
536 [dofs_g, x0 = *x0, alpha, values,
537 &dofs0 = this->_dofs0](std::int32_t i) -> T
538 {
539 assert(dofs_g[i] < static_cast<std::int32_t>(values.size()));
540 return alpha * (values[dofs_g[i]] - x0[dofs0[i]]);
541 });
542 }
543 else
544 {
545 apply(
546 [dofs_g, values, alpha](std::int32_t i) -> T
547 {
548 assert(dofs_g[i] < static_cast<std::int32_t>(values.size()));
549 return alpha * values[dofs_g[i]];
550 });
551 }
552 }
553 else if (std::holds_alternative<std::shared_ptr<const Constant<T>>>(_g))
554 {
555 auto g = std::get<std::shared_ptr<const Constant<T>>>(_g);
556 const std::vector<T>& value = g->value;
557 std::int32_t bs = _function_space->dofmaps().front()->bs();
558 if (x0)
559 {
560 assert(x.size() <= x0->size());
561 apply(
562 [x0 = *x0, alpha, bs, &value, &dofs0 = _dofs0](std::int32_t i) -> T
563 {
564 auto dof = dofs0[i];
565 return alpha * (value[dof % bs] - x0[dof]);
566 });
567 }
568 else
569 {
570 apply([alpha, bs, &value, &dofs0 = _dofs0](std::int32_t i) -> T
571 { return alpha * value[dofs0[i] % bs]; });
572 }
573 }
574 else
575 {
576 // replace with std::unreachable once C++23 is supported
577 assert(false);
578 }
579 }
580
590 void mark_dofs(std::span<std::int8_t> markers) const
591 {
592#ifndef NDEBUG
593 if (!_dofs0.empty()
594 and *std::ranges::max_element(_dofs0) >= (std::int32_t)markers.size())
595 {
596 throw std::runtime_error("Marker array is too short for the boundary "
597 "condition dofs.");
598 }
599#endif
600 for (std::int32_t idx : _dofs0)
601 markers[idx] = true;
602 }
603
604private:
605 // The function space (possibly a sub function space)
606 std::shared_ptr<const FunctionSpace<U>> _function_space;
607
608 // The function
609 std::variant<std::shared_ptr<const Function<T, U>>,
610 std::shared_ptr<const Constant<T>>>
611 _g;
612
613 // Dof indices (_dofs0) in _function_space and (_dofs1_g) in the space
614 // of _g. _dofs1_g may be empty if _dofs0 can be re-used
615 std::vector<std::int32_t> _dofs0, _dofs1_g;
616
617 // The first _owned_indices in _dofs are owned by this process
618 std::int32_t _owned_indices0 = -1;
619};
620} // 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
DirichletBC(const S &g, X &&dofs, std::shared_ptr< const FunctionSpace< U > > V)
Create a representation of a Dirichlet boundary condition constrained by a scalar- or vector-valued c...
Definition DirichletBC.h:307
DirichletBC & operator=(const DirichletBC &bc)=default
DirichletBC(std::shared_ptr< const Constant< T > > g, X &&dofs, std::shared_ptr< const FunctionSpace< U > > V)
Create a representation of a Dirichlet boundary condition constrained by a fem::Constant.
Definition DirichletBC.h:330
void set(std::span< T > x, std::optional< std::span< const T > > x0, T alpha=1) const
Set entries in an array that are constrained by Dirichlet boundary conditions.
Definition DirichletBC.h:496
std::variant< std::shared_ptr< const Function< T, U > >, std::shared_ptr< const Constant< T > > > value() const
Definition DirichletBC.h:455
DirichletBC(const DirichletBC &bc)=default
DirichletBC(DirichletBC &&bc)=default
std::pair< std::span< const std::int32_t >, std::int32_t > dof_indices() const
Definition DirichletBC.h:466
std::shared_ptr< const FunctionSpace< U > > function_space() const
Definition DirichletBC.h:446
~DirichletBC()=default
Destructor.
DirichletBC(std::shared_ptr< const Function< T, U > > g, X &&dofs)
Create a representation of a Dirichlet boundary condition where the space being constrained is the sa...
Definition DirichletBC.h:380
DirichletBC & operator=(DirichletBC &&bc)=default
Move assignment operator.
void mark_dofs(std::span< std::int8_t > markers) const
Set markers[i] = true if dof i has a boundary condition applied.
Definition DirichletBC.h:590
DirichletBC(std::shared_ptr< const Function< T, U > > g, X &&V_g_dofs, std::shared_ptr< const FunctionSpace< U > > V)
Create a representation of a Dirichlet boundary condition where the space being constrained and the f...
Definition DirichletBC.h:415
Degree-of-freedom map.
Definition DofMap.h:73
std::shared_ptr< const common::IndexMap > index_map
Index map that describes the parallel distribution of the dofmap.
Definition DofMap.h:164
int index_map_bs() const
Block size associated with the index_map.
Definition DofMap.cpp:282
This class represents a finite element function space defined by a mesh, a finite element,...
Definition FunctionSpace.h:35
std::shared_ptr< const FiniteElement< geometry_type > > elements(int cell_type_idx) const
The finite elements.
Definition FunctionSpace.h:390
std::shared_ptr< const DofMap > dofmap() const
The dofmap.
Definition FunctionSpace.h:396
std::shared_ptr< const mesh::Mesh< geometry_type > > mesh() const
The mesh.
Definition FunctionSpace.h:371
std::shared_ptr< const FiniteElement< geometry_type > > element() const
The finite element.
Definition FunctionSpace.h:377
std::vector< geometry_type > tabulate_dof_coordinates(bool transpose) const
Tabulate the physical coordinates of all dofs on this process.
Definition FunctionSpace.h:230
Definition Function.h:48
Finite element method functionality.
Definition assemble_expression_impl.h:24
std::vector< std::int32_t > locate_dofs_geometrical(const FunctionSpace< T > &V, U marker_fn)
Find degrees of freedom whose geometric coordinate is true for the provided marking function.
Definition DirichletBC.h:104
std::vector< std::int32_t > locate_dofs_topological(const mesh::Topology &topology, const DofMap &dofmap, int dim, std::span< const std::int32_t > entities, bool remote=true)
Find degrees-of-freedom which belong to the provided mesh entities (topological).
Definition DirichletBC.cpp:202
Mesh data structures and algorithms on meshes.
Definition DofMap.h:32