libMesh
Loading...
Searching...
No Matches
dof_map_constraints.C
Go to the documentation of this file.
1// The libMesh Finite Element Library.
2// Copyright (C) 2002-2026 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
3
4// This library is free software; you can redistribute it and/or
5// modify it under the terms of the GNU Lesser General Public
6// License as published by the Free Software Foundation; either
7// version 2.1 of the License, or (at your option) any later version.
8
9// This library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12// Lesser General Public License for more details.
13
14// You should have received a copy of the GNU Lesser General Public
15// License along with this library; if not, write to the Free Software
16// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
18// Local includes
19#include "libmesh/dof_map.h"
20
21// libMesh includes
22#include "libmesh/boundary_info.h" // needed for dirichlet constraints
23#include "libmesh/dense_matrix.h"
24#include "libmesh/dense_vector.h"
25#include "libmesh/dirichlet_boundaries.h"
26#include "libmesh/elem.h"
27#include "libmesh/elem_range.h"
28#include "libmesh/fe_base.h"
29#include "libmesh/fe_interface.h"
30#include "libmesh/fe_type.h"
31#include "libmesh/function_base.h"
32#include "libmesh/int_range.h"
33#include "libmesh/libmesh_logging.h"
34#include "libmesh/linear_solver.h" // for spline Dirichlet projection solves
35#include "libmesh/mesh_base.h"
36#include "libmesh/null_output_iterator.h"
37#include "libmesh/mesh_tools.h" // for libmesh_assert_valid_boundary_ids()
38#include "libmesh/nonlinear_implicit_system.h"
39#include "libmesh/numeric_vector.h" // for enforce_constraints_exactly()
40#include "libmesh/parallel_algebra.h"
41#include "libmesh/parallel_elem.h"
42#include "libmesh/parallel_node.h"
43#include "libmesh/periodic_boundaries.h"
44#include "libmesh/periodic_boundary.h"
45#include "libmesh/periodic_boundary_base.h"
46#include "libmesh/point_locator_base.h"
47#include "libmesh/quadrature.h" // for dirichlet constraints
48#include "libmesh/raw_accessor.h"
49#include "libmesh/sparse_matrix.h" // needed to constrain adjoint rhs
50#include "libmesh/static_condensation_dof_map.h"
51#include "libmesh/system.h" // needed by enforce_constraints_exactly()
52#include "libmesh/tensor_tools.h"
53#include "libmesh/threads.h"
54#include "libmesh/enum_to_string.h"
55#include "libmesh/coupling_matrix.h"
56
57// TIMPI includes
59#include "timpi/parallel_sync.h"
60
61// C++ Includes
62#include <set>
63#include <algorithm> // for std::count, std::fill
64#include <sstream>
65#include <cstdlib> // *must* precede <cmath> for proper std:abs() on PGI, Sun Studio CC
66#include <cmath>
67#include <memory>
68#include <numeric>
69#include <unordered_set>
70
71// Anonymous namespace to hold helper classes
72namespace {
73
74using namespace libMesh;
75
76class ComputeConstraints
77{
78public:
79 ComputeConstraints (DofConstraints & constraints,
80 DofMap & dof_map,
81#ifdef LIBMESH_ENABLE_PERIODIC
82 PeriodicBoundaries & periodic_boundaries,
83#endif
84 const MeshBase & mesh,
85 const unsigned int variable_number) :
86 _constraints(constraints),
87 _dof_map(dof_map),
88#ifdef LIBMESH_ENABLE_PERIODIC
89 _periodic_boundaries(periodic_boundaries),
90#endif
91 _mesh(mesh),
92 _variable_number(variable_number)
93 {}
94
95 void operator()(const ConstElemRange & range) const
96 {
97 const Variable & var_description = _dof_map.variable(_variable_number);
98
99#ifdef LIBMESH_ENABLE_PERIODIC
100 std::unique_ptr<PointLocatorBase> point_locator;
101 const bool have_periodic_boundaries =
102 !_periodic_boundaries.empty();
103 if (have_periodic_boundaries && !range.empty())
104 point_locator = _mesh.sub_point_locator();
105#endif
106
107 for (const auto & elem : range)
108 if (var_description.active_on_subdomain(elem->subdomain_id()))
109 {
110#ifdef LIBMESH_ENABLE_AMR
112 _dof_map,
113 _variable_number,
114 elem);
115#endif
116#ifdef LIBMESH_ENABLE_PERIODIC
117 // FIXME: periodic constraints won't work on a non-serial
118 // mesh unless it's kept ghost elements from opposing
119 // boundaries!
120 if (have_periodic_boundaries)
122 _dof_map,
123 _periodic_boundaries,
124 _mesh,
125 point_locator.get(),
126 _variable_number,
127 elem);
128#endif
129 }
130 }
131
132private:
133 DofConstraints & _constraints;
134 DofMap & _dof_map;
135#ifdef LIBMESH_ENABLE_PERIODIC
136 PeriodicBoundaries & _periodic_boundaries;
137#endif
138 const MeshBase & _mesh;
139 const unsigned int _variable_number;
140};
141
142
143
144#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
145class ComputeNodeConstraints
146{
147public:
148 ComputeNodeConstraints (NodeConstraints & node_constraints,
149#ifdef LIBMESH_ENABLE_PERIODIC
150 PeriodicBoundaries & periodic_boundaries,
151#endif
152 const MeshBase & mesh) :
153 _node_constraints(node_constraints),
154#ifdef LIBMESH_ENABLE_PERIODIC
155 _periodic_boundaries(periodic_boundaries),
156#endif
157 _mesh(mesh)
158 {}
159
160 void operator()(const ConstElemRange & range) const
161 {
162#ifdef LIBMESH_ENABLE_PERIODIC
163 std::unique_ptr<PointLocatorBase> point_locator;
164 bool have_periodic_boundaries = !_periodic_boundaries.empty();
165 if (have_periodic_boundaries && !range.empty())
166 point_locator = _mesh.sub_point_locator();
167#endif
168
169 for (const auto & elem : range)
170 {
171#ifdef LIBMESH_ENABLE_AMR
172 FEBase::compute_node_constraints (_node_constraints, elem);
173#endif
174#ifdef LIBMESH_ENABLE_PERIODIC
175 // FIXME: periodic constraints won't work on a non-serial
176 // mesh unless it's kept ghost elements from opposing
177 // boundaries!
178 if (have_periodic_boundaries)
180 _periodic_boundaries,
181 _mesh,
182 point_locator.get(),
183 elem);
184#endif
185 }
186 }
187
188private:
189 NodeConstraints & _node_constraints;
190#ifdef LIBMESH_ENABLE_PERIODIC
191 PeriodicBoundaries & _periodic_boundaries;
192#endif
193 const MeshBase & _mesh;
194};
195#endif // LIBMESH_ENABLE_NODE_CONSTRAINTS
196
197
198#ifdef LIBMESH_ENABLE_DIRICHLET
199
203class AddConstraint
204{
205protected:
206 DofMap & dof_map;
207
208public:
209 AddConstraint(DofMap & dof_map_in) : dof_map(dof_map_in) {}
210
211 virtual void operator()(dof_id_type dof_number,
212 const DofConstraintRow & constraint_row,
213 const Number constraint_rhs) const = 0;
214};
215
216class AddPrimalConstraint : public AddConstraint
217{
218public:
219 AddPrimalConstraint(DofMap & dof_map_in) : AddConstraint(dof_map_in) {}
220
221 virtual void operator()(dof_id_type dof_number,
222 const DofConstraintRow & constraint_row,
223 const Number constraint_rhs) const
224 {
225 if (!dof_map.is_constrained_dof(dof_number))
226 dof_map.add_constraint_row (dof_number, constraint_row,
227 constraint_rhs, true);
228 }
229};
230
231class AddAdjointConstraint : public AddConstraint
232{
233private:
234 const unsigned int qoi_index;
235
236public:
237 AddAdjointConstraint(DofMap & dof_map_in, unsigned int qoi_index_in)
238 : AddConstraint(dof_map_in), qoi_index(qoi_index_in) {}
239
240 virtual void operator()(dof_id_type dof_number,
241 const DofConstraintRow & constraint_row,
242 const Number constraint_rhs) const
243 {
244 dof_map.add_adjoint_constraint_row
245 (qoi_index, dof_number, constraint_row, constraint_rhs,
246 true);
247 }
248};
249
250
251
257class ConstrainDirichlet
258{
259private:
260 DofMap & dof_map;
261 const MeshBase & mesh;
262 const Real time;
263 const DirichletBoundaries & dirichlets;
264
265 const AddConstraint & add_fn;
266
267 static Number f_component (FunctionBase<Number> * f,
269 const FEMContext * c,
270 unsigned int i,
271 const Point & p,
272 Real time)
273 {
274 if (f_fem)
275 {
276 if (c)
277 return f_fem->component(*c, i, p, time);
278 else
279 return std::numeric_limits<Real>::quiet_NaN();
280 }
281 return f->component(i, p, time);
282 }
283
284 static Gradient g_component (FunctionBase<Gradient> * g,
286 const FEMContext * c,
287 unsigned int i,
288 const Point & p,
289 Real time)
290 {
291 if (g_fem)
292 {
293 if (c)
294 return g_fem->component(*c, i, p, time);
295 else
296 return std::numeric_limits<Number>::quiet_NaN();
297 }
298 return g->component(i, p, time);
299 }
300
301
302
309 struct SingleElemBoundaryInfo
310 {
311 SingleElemBoundaryInfo(const BoundaryInfo & bi,
312 const std::map<boundary_id_type, std::set<std::pair<unsigned int, DirichletBoundary *>>> & ordered_map_in) :
313 boundary_info(bi),
314 boundary_id_to_ordered_dirichlet_boundaries(ordered_map_in),
315 elem(nullptr),
316 n_sides(0),
317 n_edges(0),
318 n_nodes(0)
319 {}
320
321 const BoundaryInfo & boundary_info;
322 const std::map<boundary_id_type, std::set<std::pair<unsigned int, DirichletBoundary *>>> & boundary_id_to_ordered_dirichlet_boundaries;
323 const Elem * elem;
324
325 unsigned short n_sides;
326 unsigned short n_edges;
327 unsigned short n_nodes;
328
329 // Mapping from DirichletBoundary objects which are active on this
330 // element to sides/nodes/edges/shellfaces of this element which
331 // they are active on.
332 std::map<const DirichletBoundary *, std::vector<bool>> is_boundary_node_map;
333 std::map<const DirichletBoundary *, std::vector<bool>> is_boundary_side_map;
334 std::map<const DirichletBoundary *, std::vector<bool>> is_boundary_edge_map;
335 std::map<const DirichletBoundary *, std::vector<bool>> is_boundary_shellface_map;
336
337 std::map<const DirichletBoundary *, std::vector<bool>> is_boundary_nodeset_map;
338
339 // The set of (dirichlet_id, DirichletBoundary) pairs which have at least one boundary
340 // id related to this Elem.
341 std::set<std::pair<unsigned int, DirichletBoundary *>> ordered_dbs;
342
350 bool reinit(const Elem * elem_in)
351 {
352 elem = elem_in;
353
354 n_sides = elem->n_sides();
355 n_edges = elem->n_edges();
356 n_nodes = elem->n_nodes();
357
358 // objects and node/side/edge/shellface ids.
359 is_boundary_node_map.clear();
360 is_boundary_side_map.clear();
361 is_boundary_edge_map.clear();
362 is_boundary_shellface_map.clear();
363 is_boundary_nodeset_map.clear();
364
365 // Clear any DirichletBoundaries from the previous Elem
366 ordered_dbs.clear();
367
368 // Update has_dirichlet_constraint below, and if it remains false then
369 // we can skip this element since there are not constraints to impose.
370 bool has_dirichlet_constraint = false;
371
372 // Container to catch boundary ids handed back for sides,
373 // nodes, and edges in the loops below.
374 std::vector<boundary_id_type> ids_vec;
375
376 for (unsigned char s = 0; s != n_sides; ++s)
377 {
378 // First see if this side has been requested
379 boundary_info.boundary_ids (elem, s, ids_vec);
380
381 bool do_this_side = false;
382 for (const auto & bc_id : ids_vec)
383 {
384 if (auto it = boundary_id_to_ordered_dirichlet_boundaries.find(bc_id);
385 it != boundary_id_to_ordered_dirichlet_boundaries.end())
386 {
387 do_this_side = true;
388
389 // Associate every DirichletBoundary object that has this bc_id with the current Elem
390 ordered_dbs.insert(it->second.begin(), it->second.end());
391
392 // Turn on the flag for the current side for each DirichletBoundary
393 for (const auto & db_pair : it->second)
394 {
395 // Attempt to emplace an empty vector. If there
396 // is already an entry, the insertion will fail
397 // and we'll get an iterator back to the
398 // existing entry. Either way, we'll then set
399 // index s of that vector to "true".
400 auto pr = is_boundary_side_map.emplace(db_pair.second, std::vector<bool>(n_sides, false));
401 pr.first->second[s] = true;
402 }
403 }
404 }
405
406 if (!do_this_side)
407 continue;
408
409 has_dirichlet_constraint = true;
410
411 // Then determine what nodes are on this side
412 for (unsigned int n = 0; n != n_nodes; ++n)
413 if (elem->is_node_on_side(n,s))
414 {
415 // Attempt to emplace an empty vector. If there is
416 // already an entry, the insertion will fail and we'll
417 // get an iterator back to the existing entry. Either
418 // way, we'll then set index n of that vector to
419 // "true".
420 for (const auto & db_pair : ordered_dbs)
421 {
422 // Only add this as a boundary node for this db if
423 // it is also a boundary side for this db.
424 if (auto side_it = is_boundary_side_map.find(db_pair.second);
425 side_it != is_boundary_side_map.end() && side_it->second[s])
426 {
427 auto pr = is_boundary_node_map.emplace(db_pair.second, std::vector<bool>(n_nodes, false));
428 pr.first->second[n] = true;
429 }
430 }
431 }
432
433 // Finally determine what edges are on this side
434 for (unsigned int e = 0; e != n_edges; ++e)
435 if (elem->is_edge_on_side(e,s))
436 {
437 // Attempt to emplace an empty vector. If there is
438 // already an entry, the insertion will fail and we'll
439 // get an iterator back to the existing entry. Either
440 // way, we'll then set index e of that vector to
441 // "true".
442 for (const auto & db_pair : ordered_dbs)
443 {
444 // Only add this as a boundary edge for this db if
445 // it is also a boundary side for this db.
446 if (auto side_it = is_boundary_side_map.find(db_pair.second);
447 side_it != is_boundary_side_map.end() && side_it->second[s])
448 {
449 auto pr = is_boundary_edge_map.emplace(db_pair.second, std::vector<bool>(n_edges, false));
450 pr.first->second[e] = true;
451 }
452 }
453 }
454 } // for (s = 0..n_sides)
455
456 // We can also impose Dirichlet boundary conditions on nodes, so we should
457 // also independently check whether the nodes have been requested
458 for (unsigned int n=0; n != n_nodes; ++n)
459 {
460 boundary_info.boundary_ids (elem->node_ptr(n), ids_vec);
461
462 for (const auto & bc_id : ids_vec)
463 {
464 if (auto it = boundary_id_to_ordered_dirichlet_boundaries.find(bc_id);
465 it != boundary_id_to_ordered_dirichlet_boundaries.end())
466 {
467 // Associate every DirichletBoundary object that has this bc_id with the current Elem
468 ordered_dbs.insert(it->second.begin(), it->second.end());
469
470 // Turn on the flag for the current node for each DirichletBoundary
471 for (const auto & db_pair : it->second)
472 {
473 auto pr = is_boundary_node_map.emplace(db_pair.second, std::vector<bool>(n_nodes, false));
474 pr.first->second[n] = true;
475
476 auto pr2 = is_boundary_nodeset_map.emplace(db_pair.second, std::vector<bool>(n_nodes, false));
477 pr2.first->second[n] = true;
478 }
479
480 has_dirichlet_constraint = true;
481 }
482 }
483 } // for (n = 0..n_nodes)
484
485 // We can also impose Dirichlet boundary conditions on edges, so we should
486 // also independently check whether the edges have been requested
487 for (unsigned short e=0; e != n_edges; ++e)
488 {
489 boundary_info.edge_boundary_ids (elem, e, ids_vec);
490
491 bool do_this_side = false;
492 for (const auto & bc_id : ids_vec)
493 {
494 if (auto it = boundary_id_to_ordered_dirichlet_boundaries.find(bc_id);
495 it != boundary_id_to_ordered_dirichlet_boundaries.end())
496 {
497 do_this_side = true;
498
499 // We need to loop over all DirichletBoundary objects associated with bc_id
500 ordered_dbs.insert(it->second.begin(), it->second.end());
501
502 // Turn on the flag for the current edge for each DirichletBoundary
503 for (const auto & db_pair : it->second)
504 {
505 auto pr = is_boundary_edge_map.emplace(db_pair.second, std::vector<bool>(n_edges, false));
506 pr.first->second[e] = true;
507 }
508 }
509 }
510
511 if (!do_this_side)
512 continue;
513
514 has_dirichlet_constraint = true;
515
516 // Then determine what nodes are on this edge
517 for (unsigned int n = 0; n != n_nodes; ++n)
518 if (elem->is_node_on_edge(n,e))
519 {
520 // Attempt to emplace an empty vector. If there is
521 // already an entry, the insertion will fail and we'll
522 // get an iterator back to the existing entry. Either
523 // way, we'll then set index n of that vector to
524 // "true".
525 for (const auto & db_pair : ordered_dbs)
526 {
527 // Only add this as a boundary node for this db if
528 // it is also a boundary edge for this db.
529 if (auto edge_it = is_boundary_edge_map.find(db_pair.second);
530 edge_it != is_boundary_edge_map.end() && edge_it->second[e])
531 {
532 auto pr = is_boundary_node_map.emplace(db_pair.second, std::vector<bool>(n_nodes, false));
533 pr.first->second[n] = true;
534 }
535 }
536 }
537 }
538
539 // We can also impose Dirichlet boundary conditions on shellfaces, so we should
540 // also independently check whether the shellfaces have been requested
541 for (unsigned short shellface=0; shellface != 2; ++shellface)
542 {
543 boundary_info.shellface_boundary_ids (elem, shellface, ids_vec);
544 bool do_this_shellface = false;
545
546 for (const auto & bc_id : ids_vec)
547 {
548 if (auto it = boundary_id_to_ordered_dirichlet_boundaries.find(bc_id);
549 it != boundary_id_to_ordered_dirichlet_boundaries.end())
550 {
551 has_dirichlet_constraint = true;
552 do_this_shellface = true;
553
554 // We need to loop over all DirichletBoundary objects associated with bc_id
555 ordered_dbs.insert(it->second.begin(), it->second.end());
556
557 // Turn on the flag for the current shellface for each DirichletBoundary
558 for (const auto & db_pair : it->second)
559 {
560 auto pr = is_boundary_shellface_map.emplace(db_pair.second, std::vector<bool>(/*n_shellfaces=*/2, false));
561 pr.first->second[shellface] = true;
562 }
563 }
564 }
565
566 if (do_this_shellface)
567 {
568 // Shellface BCs induce BCs on all the nodes of a shell Elem
569 for (unsigned int n = 0; n != n_nodes; ++n)
570 for (const auto & db_pair : ordered_dbs)
571 {
572 // Only add this as a boundary node for this db if
573 // it is also a boundary shellface for this db.
574 if (auto side_it = is_boundary_shellface_map.find(db_pair.second);
575 side_it != is_boundary_shellface_map.end() && side_it->second[shellface])
576 {
577 auto pr = is_boundary_node_map.emplace(db_pair.second, std::vector<bool>(n_nodes, false));
578 pr.first->second[n] = true;
579 }
580 }
581 }
582 } // for (shellface = 0..2)
583
584 return has_dirichlet_constraint;
585 } // SingleElemBoundaryInfo::reinit()
586
587 }; // struct SingleElemBoundaryInfo
588
589
590
591 template<typename OutputType>
592 void apply_lagrange_dirichlet_impl(const SingleElemBoundaryInfo & sebi,
593 const Variable & variable,
594 const DirichletBoundary & dirichlet,
595 FEMContext & fem_context) const
596 {
597 // Get pointer to the Elem we are currently working on
598 const Elem * elem = sebi.elem;
599
600 // Per-subdomain variables don't need to be projected on
601 // elements where they're not active
602 if (!variable.active_on_subdomain(elem->subdomain_id()))
603 return;
604
605 FunctionBase<Number> * f = dirichlet.f.get();
606 FEMFunctionBase<Number> * f_fem = dirichlet.f_fem.get();
607
608 const System * f_system = dirichlet.f_system;
609
610 // We need data to project
611 libmesh_assert(f || f_fem);
612 libmesh_assert(!(f && f_fem));
613
614 // Iff our data depends on a system, we should have it.
615 libmesh_assert(!(f && f_system));
616 libmesh_assert(!(f_fem && !f_system));
617
618 // The new element coefficients. For Lagrange FEs, these are the
619 // nodal values.
621
622 // Get a reference to the fe_type associated with this variable
623 const FEType & fe_type = variable.type();
624
625 // Dimension of the vector-valued FE (1 for scalar-valued FEs)
626 unsigned int n_vec_dim = FEInterface::n_vec_dim(mesh, fe_type);
627
628 const unsigned int var_component =
629 variable.first_scalar_number();
630
631 // Get this Variable's number, as determined by the System.
632 const unsigned int var = variable.number();
633
634 // If our supplied functions require a FEMContext, and if we have
635 // an initialized solution to use with that FEMContext, then
636 // create one. We're not going to use elem_jacobian or
637 // subjacobians here so don't allocate them.
638 std::unique_ptr<FEMContext> context;
639 if (f_fem)
640 {
641 libmesh_assert(f_system);
642 if (f_system->current_local_solution->initialized())
643 {
644 context = std::make_unique<FEMContext>
645 (*f_system, nullptr,
646 /* allocate local_matrices = */ false);
647 f_fem->init_context(*context);
648 }
649 }
650
651 if (f_system && context.get())
652 context->pre_fe_reinit(*f_system, elem);
653
654 // Also pre-init the fem_context() we were passed on the current Elem.
655 fem_context.pre_fe_reinit(fem_context.get_system(), elem);
656
657 // Get a reference to the DOF indices for the current element
658 const std::vector<dof_id_type> & dof_indices =
659 fem_context.get_dof_indices(var);
660
661 // The number of DOFs on the element
662 const unsigned int n_dofs =
663 cast_int<unsigned int>(dof_indices.size());
664
665 // Fixed vs. free DoFs on edge/face projections
666 std::vector<char> dof_is_fixed(n_dofs, false); // bools
667
668 // Zero the interpolated values
669 Ue.resize (n_dofs); Ue.zero();
670
671 // For Lagrange elements, side, edge, and shellface BCs all
672 // "induce" boundary conditions on the nodes of those entities.
673 // In SingleElemBoundaryInfo::reinit(), we therefore set entries
674 // in the "is_boundary_node_map" container based on side and
675 // shellface BCs, Then, when we actually apply constraints, we
676 // only have to check whether any Nodes are in this container, and
677 // compute values as necessary.
678 unsigned int current_dof = 0;
679 for (unsigned int n=0; n!= sebi.n_nodes; ++n)
680 {
681 // For Lagrange this can return 0 (in case of a lower-order FE
682 // on a higher-order Elem) or 1. This function accounts for the
683 // Elem::p_level() internally.
684 const unsigned int nc =
685 FEInterface::n_dofs_at_node (fe_type, elem, n);
686
687 // If there are no DOFs at this node, then it doesn't matter
688 // if it's technically a boundary node or not, there's nothing
689 // to constrain.
690 if (!nc)
691 continue;
692
693 // Check whether the current node is a boundary node
694 auto is_boundary_node_it = sebi.is_boundary_node_map.find(&dirichlet);
695 const bool is_boundary_node =
696 (is_boundary_node_it != sebi.is_boundary_node_map.end() &&
697 is_boundary_node_it->second[n]);
698
699 // Check whether the current node is in a boundary nodeset
700 auto is_boundary_nodeset_it = sebi.is_boundary_nodeset_map.find(&dirichlet);
701 const bool is_boundary_nodeset =
702 (is_boundary_nodeset_it != sebi.is_boundary_nodeset_map.end() &&
703 is_boundary_nodeset_it->second[n]);
704
705 // If node is neither a boundary node or from a boundary nodeset, go to the next one.
706 if ( !(is_boundary_node || is_boundary_nodeset) )
707 {
708 current_dof += nc;
709 continue;
710 }
711
712 // Compute function values, storing them in Ue
713 libmesh_assert_equal_to (nc, n_vec_dim);
714 for (unsigned int c = 0; c < n_vec_dim; c++)
715 {
716 Ue(current_dof+c) =
717 f_component(f, f_fem, context.get(), var_component+c,
718 elem->point(n), time);
719 dof_is_fixed[current_dof+c] = true;
720 }
721 current_dof += n_vec_dim;
722 } // end for (n=0..n_nodes)
723
724 // Lock the DofConstraints since it is shared among threads.
725 {
726 Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
727
728 for (unsigned int i = 0; i < n_dofs; i++)
729 {
730 DofConstraintRow empty_row;
731 if (dof_is_fixed[i] && !libmesh_isnan(Ue(i)))
732 add_fn (dof_indices[i], empty_row, Ue(i));
733 }
734 }
735
736 } // apply_lagrange_dirichlet_impl
737
738
739
740 template<typename OutputType>
741 void apply_dirichlet_impl(const SingleElemBoundaryInfo & sebi,
742 const Variable & variable,
743 const DirichletBoundary & dirichlet,
744 FEMContext & fem_context) const
745 {
746 // Get pointer to the Elem we are currently working on
747 const Elem * elem = sebi.elem;
748
749 // Per-subdomain variables don't need to be projected on
750 // elements where they're not active
751 if (!variable.active_on_subdomain(elem->subdomain_id()))
752 return;
753
754 typedef OutputType OutputShape;
755 typedef typename TensorTools::IncrementRank<OutputShape>::type OutputGradient;
756 //typedef typename TensorTools::IncrementRank<OutputGradient>::type OutputTensor;
757 typedef typename TensorTools::MakeNumber<OutputShape>::type OutputNumber;
758 typedef typename TensorTools::IncrementRank<OutputNumber>::type OutputNumberGradient;
759 //typedef typename TensorTools::IncrementRank<OutputNumberGradient>::type OutputNumberTensor;
760
761 FunctionBase<Number> * f = dirichlet.f.get();
762 FunctionBase<Gradient> * g = dirichlet.g.get();
763
764 FEMFunctionBase<Number> * f_fem = dirichlet.f_fem.get();
765 FEMFunctionBase<Gradient> * g_fem = dirichlet.g_fem.get();
766
767 const System * f_system = dirichlet.f_system;
768
769 // We need data to project
770 libmesh_assert(f || f_fem);
771 libmesh_assert(!(f && f_fem));
772
773 // Iff our data depends on a system, we should have it.
774 libmesh_assert(!(f && f_system));
775 libmesh_assert(!(f_fem && !f_system));
776
777 // The element matrix and RHS for projections.
778 // Note that Ke is always real-valued, whereas
779 // Fe may be complex valued if complex number
780 // support is enabled
783 // The new element coefficients
785
786 // The dimensionality of the current mesh
787 const unsigned int dim = mesh.mesh_dimension();
788
789 // Get a reference to the fe_type associated with this variable
790 const FEType & fe_type = variable.type();
791
792 // Dimension of the vector-valued FE (1 for scalar-valued FEs)
793 unsigned int n_vec_dim = FEInterface::n_vec_dim(mesh, fe_type);
794
795 const unsigned int var_component =
796 variable.first_scalar_number();
797
798 // Get this Variable's number, as determined by the System.
799 const unsigned int var = variable.number();
800
801 // The type of projections done depend on the FE's continuity.
803
804 // Make sure we have the right data available for C1 projections
805 if ((cont == C_ONE) && (fe_type.family != SUBDIVISION))
806 {
807 // We'll need gradient data for a C1 projection
808 libmesh_assert(g || g_fem);
809
810 // We currently demand that either neither nor both function
811 // object depend on current FEM data.
812 libmesh_assert(!(g && g_fem));
813 libmesh_assert(!(f && g_fem));
814 libmesh_assert(!(f_fem && g));
815 }
816
817 // If our supplied functions require a FEMContext, and if we have
818 // an initialized solution to use with that FEMContext, then
819 // create one. We're not going to use elem_jacobian or
820 // subjacobians here so don't allocate them.
821 std::unique_ptr<FEMContext> context;
822 if (f_fem)
823 {
824 libmesh_assert(f_system);
825 if (f_system->current_local_solution->initialized())
826 {
827 context = std::make_unique<FEMContext>
828 (*f_system, nullptr,
829 /* allocate local_matrices = */ false);
830 f_fem->init_context(*context);
831 if (g_fem)
832 g_fem->init_context(*context);
833 }
834 }
835
836 // There's a chicken-and-egg problem with FEMFunction-based
837 // Dirichlet constraints: we can't evaluate the FEMFunction
838 // until we have an initialized local solution vector, we
839 // can't initialize local solution vectors until we have a
840 // send list, and we can't generate a send list until we know
841 // all our constraints
842 //
843 // We don't generate constraints on uninitialized systems;
844 // currently user code will have to reinit() before any
845 // FEMFunction-based constraints will be correct. This should
846 // be fine, since user code would want to reinit() after
847 // setting initial conditions anyway.
848 if (f_system && context.get())
849 context->pre_fe_reinit(*f_system, elem);
850
851 // Also pre-init the fem_context() we were passed on the current Elem.
852 fem_context.pre_fe_reinit(fem_context.get_system(), elem);
853
854 // Get a reference to the DOF indices for the current element
855 const std::vector<dof_id_type> & dof_indices =
856 fem_context.get_dof_indices(var);
857
858 // The number of DOFs on the element
859 const unsigned int n_dofs =
860 cast_int<unsigned int>(dof_indices.size());
861
862 // Fixed vs. free DoFs on edge/face projections
863 std::vector<char> dof_is_fixed(n_dofs, false); // bools
864 std::vector<int> free_dof(n_dofs, 0);
865
866 // Zero the interpolated values
867 Ue.resize (n_dofs); Ue.zero();
868
869 // In general, we need a series of
870 // projections to ensure a unique and continuous
871 // solution. We start by interpolating boundary nodes, then
872 // hold those fixed and project boundary edges, then hold
873 // those fixed and project boundary faces,
874
875 // Interpolate node values first.
876 //
877 // If we have non-vertex nodes that have a boundary nodeset, we
878 // need to interpolate them directly, but that had better be
879 // happening in the apply_lagrange_dirichlet_impl code path,
880 // because you *can't* interpolate to evaluate non-nodal FE
881 // coefficients.
882 unsigned int current_dof = 0;
883 for (unsigned int n=0; n!= sebi.n_nodes; ++n)
884 {
885 // FIXME: this should go through the DofMap,
886 // not duplicate dof_indices code badly!
887
888 // Get the number of DOFs at this node, accounting for
889 // Elem::p_level() internally.
890 const unsigned int nc =
891 FEInterface::n_dofs_at_node (fe_type, elem, n);
892
893 // Get a reference to the "is_boundary_node" flags for the
894 // current DirichletBoundary object. In case the map does not
895 // contain an entry for this DirichletBoundary object, it
896 // means there are no boundary nodes active.
897 auto is_boundary_node_it = sebi.is_boundary_node_map.find(&dirichlet);
898
899 // The current n is not a boundary node if either there is no
900 // boundary_node_map for this DirichletBoundary object, or if
901 // there is but the entry in the corresponding vector is
902 // false.
903 const bool not_boundary_node =
904 (is_boundary_node_it == sebi.is_boundary_node_map.end() ||
905 !is_boundary_node_it->second[n]);
906
907 if (!elem->is_vertex(n) || not_boundary_node)
908 {
909 current_dof += nc;
910 continue;
911 }
912 if (cont == DISCONTINUOUS)
913 {
914 libmesh_assert_equal_to (nc, 0);
915 }
916 // Assume that C_ZERO elements have a single nodal
917 // value shape function
918 else if ((cont == C_ZERO) || (fe_type.family == SUBDIVISION))
919 {
920 libmesh_assert_equal_to (nc, n_vec_dim);
921 for (unsigned int c = 0; c < n_vec_dim; c++)
922 {
923 Ue(current_dof+c) =
924 f_component(f, f_fem, context.get(), var_component+c,
925 elem->point(n), time);
926 dof_is_fixed[current_dof+c] = true;
927 }
928 current_dof += n_vec_dim;
929 }
930 // The hermite element vertex shape functions are weird
931 else if (fe_type.family == HERMITE)
932 {
933 Ue(current_dof) =
934 f_component(f, f_fem, context.get(), var_component,
935 elem->point(n), time);
936 dof_is_fixed[current_dof] = true;
937 current_dof++;
938 Gradient grad =
939 g_component(g, g_fem, context.get(), var_component,
940 elem->point(n), time);
941 // x derivative
942 Ue(current_dof) = grad(0);
943 dof_is_fixed[current_dof] = true;
944 current_dof++;
945 if (dim > 1)
946 {
947 // We'll finite difference mixed derivatives
948 Point nxminus = elem->point(n),
949 nxplus = elem->point(n);
950 nxminus(0) -= TOLERANCE;
951 nxplus(0) += TOLERANCE;
952 Gradient gxminus =
953 g_component(g, g_fem, context.get(), var_component,
954 nxminus, time);
955 Gradient gxplus =
956 g_component(g, g_fem, context.get(), var_component,
957 nxplus, time);
958 // y derivative
959 Ue(current_dof) = grad(1);
960 dof_is_fixed[current_dof] = true;
961 current_dof++;
962 // xy derivative
963 Ue(current_dof) = (gxplus(1) - gxminus(1))
964 / 2. / TOLERANCE;
965 dof_is_fixed[current_dof] = true;
966 current_dof++;
967
968 if (dim > 2)
969 {
970 // z derivative
971 Ue(current_dof) = grad(2);
972 dof_is_fixed[current_dof] = true;
973 current_dof++;
974 // xz derivative
975 Ue(current_dof) = (gxplus(2) - gxminus(2))
976 / 2. / TOLERANCE;
977 dof_is_fixed[current_dof] = true;
978 current_dof++;
979 // We need new points for yz
980 Point nyminus = elem->point(n),
981 nyplus = elem->point(n);
982 nyminus(1) -= TOLERANCE;
983 nyplus(1) += TOLERANCE;
984 Gradient gyminus =
985 g_component(g, g_fem, context.get(), var_component,
986 nyminus, time);
987 Gradient gyplus =
988 g_component(g, g_fem, context.get(), var_component,
989 nyplus, time);
990 // xz derivative
991 Ue(current_dof) = (gyplus(2) - gyminus(2))
992 / 2. / TOLERANCE;
993 dof_is_fixed[current_dof] = true;
994 current_dof++;
995 // Getting a 2nd order xyz is more tedious
996 Point nxmym = elem->point(n),
997 nxmyp = elem->point(n),
998 nxpym = elem->point(n),
999 nxpyp = elem->point(n);
1000 nxmym(0) -= TOLERANCE;
1001 nxmym(1) -= TOLERANCE;
1002 nxmyp(0) -= TOLERANCE;
1003 nxmyp(1) += TOLERANCE;
1004 nxpym(0) += TOLERANCE;
1005 nxpym(1) -= TOLERANCE;
1006 nxpyp(0) += TOLERANCE;
1007 nxpyp(1) += TOLERANCE;
1008 Gradient gxmym =
1009 g_component(g, g_fem, context.get(), var_component,
1010 nxmym, time);
1011 Gradient gxmyp =
1012 g_component(g, g_fem, context.get(), var_component,
1013 nxmyp, time);
1014 Gradient gxpym =
1015 g_component(g, g_fem, context.get(), var_component,
1016 nxpym, time);
1017 Gradient gxpyp =
1018 g_component(g, g_fem, context.get(), var_component,
1019 nxpyp, time);
1020 Number gxzplus = (gxpyp(2) - gxmyp(2))
1021 / 2. / TOLERANCE;
1022 Number gxzminus = (gxpym(2) - gxmym(2))
1023 / 2. / TOLERANCE;
1024 // xyz derivative
1025 Ue(current_dof) = (gxzplus - gxzminus)
1026 / 2. / TOLERANCE;
1027 dof_is_fixed[current_dof] = true;
1028 current_dof++;
1029 }
1030 }
1031 }
1032 // Assume that other C_ONE elements have a single nodal
1033 // value shape function and nodal gradient component
1034 // shape functions
1035 else if (cont == C_ONE)
1036 {
1037 libmesh_assert_equal_to (nc, 1 + dim);
1038 Ue(current_dof) =
1039 f_component(f, f_fem, context.get(), var_component,
1040 elem->point(n), time);
1041 dof_is_fixed[current_dof] = true;
1042 current_dof++;
1043 Gradient grad =
1044 g_component(g, g_fem, context.get(), var_component,
1045 elem->point(n), time);
1046 for (unsigned int i=0; i!= dim; ++i)
1047 {
1048 Ue(current_dof) = grad(i);
1049 dof_is_fixed[current_dof] = true;
1050 current_dof++;
1051 }
1052 }
1053 else
1054 libmesh_error_msg("Unknown continuity cont = " << cont);
1055 } // end for (n=0..n_nodes)
1056
1057 // In 3D, project any edge values next
1058 if (dim > 2 && cont != DISCONTINUOUS)
1059 {
1060 // Get a pointer to the 1 dimensional (edge) FE for the current
1061 // var which is stored in the fem_context. This will only be
1062 // different from side_fe in 3D.
1063 FEGenericBase<OutputType> * edge_fe = nullptr;
1064 fem_context.get_edge_fe(var, edge_fe);
1065
1066 // Set tolerance on underlying FEMap object. This will allow us to
1067 // avoid spurious negative Jacobian errors while imposing BCs by
1068 // simply ignoring them. This should only be required in certain
1069 // special cases, see the DirichletBoundaries comments on this
1070 // parameter for more information.
1072
1073 // Pre-request FE data
1074 const std::vector<std::vector<OutputShape>> & phi = edge_fe->get_phi();
1075 const std::vector<Point> & xyz_values = edge_fe->get_xyz();
1076 const std::vector<Real> & JxW = edge_fe->get_JxW();
1077
1078 // Only pre-request gradients for C1 projections
1079 const std::vector<std::vector<OutputGradient>> * dphi = nullptr;
1080 if ((cont == C_ONE) && (fe_type.family != SUBDIVISION))
1081 {
1082 const std::vector<std::vector<OutputGradient>> & ref_dphi = edge_fe->get_dphi();
1083 dphi = &ref_dphi;
1084 }
1085
1086 // Vector to hold edge local DOF indices
1087 std::vector<unsigned int> edge_dofs;
1088
1089 // Get a reference to the "is_boundary_edge" flags for the
1090 // current DirichletBoundary object. In case the map does not
1091 // contain an entry for this DirichletBoundary object, it
1092 // means there are no boundary edges active.
1093 if (const auto is_boundary_edge_it = sebi.is_boundary_edge_map.find(&dirichlet);
1094 is_boundary_edge_it != sebi.is_boundary_edge_map.end())
1095 {
1096 for (unsigned int e=0; e != sebi.n_edges; ++e)
1097 {
1098 if (!is_boundary_edge_it->second[e])
1099 continue;
1100
1101 FEInterface::dofs_on_edge(elem, dim, fe_type, e,
1102 edge_dofs);
1103
1104 const unsigned int n_edge_dofs =
1105 cast_int<unsigned int>(edge_dofs.size());
1106
1107 // Some edge dofs are on nodes and already
1108 // fixed, others are free to calculate
1109 unsigned int free_dofs = 0;
1110 for (unsigned int i=0; i != n_edge_dofs; ++i)
1111 if (!dof_is_fixed[edge_dofs[i]])
1112 free_dof[free_dofs++] = i;
1113
1114 // There may be nothing to project
1115 if (!free_dofs)
1116 continue;
1117
1118 Ke.resize (free_dofs, free_dofs); Ke.zero();
1119 Fe.resize (free_dofs); Fe.zero();
1120 // The new edge coefficients
1121 DenseVector<Number> Uedge(free_dofs);
1122
1123 // Initialize FE data on the edge
1124 edge_fe->edge_reinit(elem, e);
1125 const unsigned int n_qp = fem_context.get_edge_qrule().n_points();
1126
1127 // Loop over the quadrature points
1128 for (unsigned int qp=0; qp<n_qp; qp++)
1129 {
1130 // solution at the quadrature point
1131 OutputNumber fineval(0);
1132 libMesh::RawAccessor<OutputNumber> f_accessor( fineval, dim );
1133
1134 for (unsigned int c = 0; c < n_vec_dim; c++)
1135 f_accessor(c) =
1136 f_component(f, f_fem, context.get(), var_component+c,
1137 xyz_values[qp], time);
1138
1139 // solution grad at the quadrature point
1140 OutputNumberGradient finegrad;
1141 libMesh::RawAccessor<OutputNumberGradient> g_accessor( finegrad, dim );
1142
1143 unsigned int g_rank;
1144 switch( FEInterface::field_type( fe_type ) )
1145 {
1146 case TYPE_SCALAR:
1147 {
1148 g_rank = 1;
1149 break;
1150 }
1151 case TYPE_VECTOR:
1152 {
1153 g_rank = 2;
1154 break;
1155 }
1156 default:
1157 libmesh_error_msg("Unknown field type!");
1158 }
1159
1160 if (cont == C_ONE)
1161 for (unsigned int c = 0; c < n_vec_dim; c++)
1162 for (unsigned int d = 0; d < g_rank; d++)
1163 g_accessor(c + d*dim ) =
1164 g_component(g, g_fem, context.get(), var_component,
1165 xyz_values[qp], time)(c);
1166
1167 // Form edge projection matrix
1168 for (unsigned int sidei=0, freei=0; sidei != n_edge_dofs; ++sidei)
1169 {
1170 unsigned int i = edge_dofs[sidei];
1171 // fixed DoFs aren't test functions
1172 if (dof_is_fixed[i])
1173 continue;
1174 for (unsigned int sidej=0, freej=0; sidej != n_edge_dofs; ++sidej)
1175 {
1176 unsigned int j = edge_dofs[sidej];
1177 if (dof_is_fixed[j])
1178 Fe(freei) -= phi[i][qp] * phi[j][qp] *
1179 JxW[qp] * Ue(j);
1180 else
1181 Ke(freei,freej) += phi[i][qp] *
1182 phi[j][qp] * JxW[qp];
1183 if (cont == C_ONE)
1184 {
1185 if (dof_is_fixed[j])
1186 Fe(freei) -= ((*dphi)[i][qp].contract((*dphi)[j][qp]) ) *
1187 JxW[qp] * Ue(j);
1188 else
1189 Ke(freei,freej) += ((*dphi)[i][qp].contract((*dphi)[j][qp]))
1190 * JxW[qp];
1191 }
1192 if (!dof_is_fixed[j])
1193 freej++;
1194 }
1195 Fe(freei) += phi[i][qp] * fineval * JxW[qp];
1196 if (cont == C_ONE)
1197 Fe(freei) += (finegrad.contract( (*dphi)[i][qp]) ) *
1198 JxW[qp];
1199 freei++;
1200 }
1201 }
1202
1203 Ke.cholesky_solve(Fe, Uedge);
1204
1205 // Transfer new edge solutions to element
1206 for (unsigned int i=0; i != free_dofs; ++i)
1207 {
1208 Number & ui = Ue(edge_dofs[free_dof[i]]);
1209 libmesh_assert(std::abs(ui) < TOLERANCE ||
1210 std::abs(ui - Uedge(i)) < TOLERANCE);
1211 ui = Uedge(i);
1212 dof_is_fixed[edge_dofs[free_dof[i]]] = true;
1213 }
1214 } // end for (e = 0..n_edges)
1215 } // end if (is_boundary_edge_it != sebi.is_boundary_edge_map.end())
1216 } // end if (dim > 2 && cont != DISCONTINUOUS)
1217
1218 // Project any side values (edges in 2D, faces in 3D)
1219 if (dim > 1 && cont != DISCONTINUOUS)
1220 {
1221 FEGenericBase<OutputType> * side_fe = nullptr;
1222 fem_context.get_side_fe(var, side_fe);
1223
1224 // Set tolerance on underlying FEMap object. This will allow us to
1225 // avoid spurious negative Jacobian errors while imposing BCs by
1226 // simply ignoring them. This should only be required in certain
1227 // special cases, see the DirichletBoundaries comments on this
1228 // parameter for more information.
1230
1231 // Pre-request FE data
1232 const std::vector<std::vector<OutputShape>> & phi = side_fe->get_phi();
1233 const std::vector<Point> & xyz_values = side_fe->get_xyz();
1234 const std::vector<Real> & JxW = side_fe->get_JxW();
1235
1236 // Only pre-request gradients for C1 projections
1237 const std::vector<std::vector<OutputGradient>> * dphi = nullptr;
1238 if ((cont == C_ONE) && (fe_type.family != SUBDIVISION))
1239 {
1240 const std::vector<std::vector<OutputGradient>> & ref_dphi = side_fe->get_dphi();
1241 dphi = &ref_dphi;
1242 }
1243
1244 // Vector to hold side local DOF indices
1245 std::vector<unsigned int> side_dofs;
1246
1247 // Get a reference to the "is_boundary_side" flags for the
1248 // current DirichletBoundary object. In case the map does not
1249 // contain an entry for this DirichletBoundary object, it
1250 // means there are no boundary sides active.
1251 if (const auto is_boundary_side_it = sebi.is_boundary_side_map.find(&dirichlet);
1252 is_boundary_side_it != sebi.is_boundary_side_map.end())
1253 {
1254 for (unsigned int s=0; s != sebi.n_sides; ++s)
1255 {
1256 if (!is_boundary_side_it->second[s])
1257 continue;
1258
1259 FEInterface::dofs_on_side(elem, dim, fe_type, s,
1260 side_dofs);
1261
1262 const unsigned int n_side_dofs =
1263 cast_int<unsigned int>(side_dofs.size());
1264
1265 // Some side dofs are on nodes/edges and already
1266 // fixed, others are free to calculate
1267 unsigned int free_dofs = 0;
1268 for (unsigned int i=0; i != n_side_dofs; ++i)
1269 if (!dof_is_fixed[side_dofs[i]])
1270 free_dof[free_dofs++] = i;
1271
1272 // There may be nothing to project
1273 if (!free_dofs)
1274 continue;
1275
1276 Ke.resize (free_dofs, free_dofs); Ke.zero();
1277 Fe.resize (free_dofs); Fe.zero();
1278 // The new side coefficients
1279 DenseVector<Number> Uside(free_dofs);
1280
1281 // Initialize FE data on the side
1282 side_fe->reinit(elem, s);
1283 const unsigned int n_qp = fem_context.get_side_qrule().n_points();
1284
1285 // Loop over the quadrature points
1286 for (unsigned int qp=0; qp<n_qp; qp++)
1287 {
1288 // solution at the quadrature point
1289 OutputNumber fineval(0);
1290 libMesh::RawAccessor<OutputNumber> f_accessor( fineval, dim );
1291
1292 for (unsigned int c = 0; c < n_vec_dim; c++)
1293 f_accessor(c) =
1294 f_component(f, f_fem, context.get(), var_component+c,
1295 xyz_values[qp], time);
1296
1297 // solution grad at the quadrature point
1298 OutputNumberGradient finegrad;
1299 libMesh::RawAccessor<OutputNumberGradient> g_accessor( finegrad, dim );
1300
1301 unsigned int g_rank;
1302 switch( FEInterface::field_type( fe_type ) )
1303 {
1304 case TYPE_SCALAR:
1305 {
1306 g_rank = 1;
1307 break;
1308 }
1309 case TYPE_VECTOR:
1310 {
1311 g_rank = 2;
1312 break;
1313 }
1314 default:
1315 libmesh_error_msg("Unknown field type!");
1316 }
1317
1318 if (cont == C_ONE)
1319 for (unsigned int c = 0; c < n_vec_dim; c++)
1320 for (unsigned int d = 0; d < g_rank; d++)
1321 g_accessor(c + d*dim ) =
1322 g_component(g, g_fem, context.get(), var_component,
1323 xyz_values[qp], time)(c);
1324
1325 // Form side projection matrix
1326 for (unsigned int sidei=0, freei=0; sidei != n_side_dofs; ++sidei)
1327 {
1328 unsigned int i = side_dofs[sidei];
1329 // fixed DoFs aren't test functions
1330 if (dof_is_fixed[i])
1331 continue;
1332 for (unsigned int sidej=0, freej=0; sidej != n_side_dofs; ++sidej)
1333 {
1334 unsigned int j = side_dofs[sidej];
1335 if (dof_is_fixed[j])
1336 Fe(freei) -= phi[i][qp] * phi[j][qp] *
1337 JxW[qp] * Ue(j);
1338 else
1339 Ke(freei,freej) += phi[i][qp] *
1340 phi[j][qp] * JxW[qp];
1341 if (cont == C_ONE)
1342 {
1343 if (dof_is_fixed[j])
1344 Fe(freei) -= ((*dphi)[i][qp].contract((*dphi)[j][qp])) *
1345 JxW[qp] * Ue(j);
1346 else
1347 Ke(freei,freej) += ((*dphi)[i][qp].contract((*dphi)[j][qp]))
1348 * JxW[qp];
1349 }
1350 if (!dof_is_fixed[j])
1351 freej++;
1352 }
1353 Fe(freei) += (fineval * phi[i][qp]) * JxW[qp];
1354 if (cont == C_ONE)
1355 Fe(freei) += (finegrad.contract((*dphi)[i][qp])) *
1356 JxW[qp];
1357 freei++;
1358 }
1359 }
1360
1361 Ke.cholesky_solve(Fe, Uside);
1362
1363 // Transfer new side solutions to element
1364 for (unsigned int i=0; i != free_dofs; ++i)
1365 {
1366 Number & ui = Ue(side_dofs[free_dof[i]]);
1367
1368 libmesh_assert(std::abs(ui) < TOLERANCE ||
1369 std::abs(ui - Uside(i)) < TOLERANCE);
1370 ui = Uside(i);
1371
1372 dof_is_fixed[side_dofs[free_dof[i]]] = true;
1373 }
1374 } // end for (s = 0..n_sides)
1375 } // end if (is_boundary_side_it != sebi.is_boundary_side_map.end())
1376 } // end if (dim > 1 && cont != DISCONTINUOUS)
1377
1378 // Project any shellface values
1379 if (dim == 2 && cont != DISCONTINUOUS)
1380 {
1381 FEGenericBase<OutputType> * fe = nullptr;
1382 fem_context.get_element_fe(var, fe, dim);
1383
1384 // Set tolerance on underlying FEMap object. This will allow us to
1385 // avoid spurious negative Jacobian errors while imposing BCs by
1386 // simply ignoring them. This should only be required in certain
1387 // special cases, see the DirichletBoundaries comments on this
1388 // parameter for more information.
1390
1391 // Pre-request FE data
1392 const std::vector<std::vector<OutputShape>> & phi = fe->get_phi();
1393 const std::vector<Point> & xyz_values = fe->get_xyz();
1394 const std::vector<Real> & JxW = fe->get_JxW();
1395
1396 // Only pre-request gradients for C1 projections
1397 const std::vector<std::vector<OutputGradient>> * dphi = nullptr;
1398 if ((cont == C_ONE) && (fe_type.family != SUBDIVISION))
1399 {
1400 const std::vector<std::vector<OutputGradient>> & ref_dphi = fe->get_dphi();
1401 dphi = &ref_dphi;
1402 }
1403
1404 // Get a reference to the "is_boundary_shellface" flags for the
1405 // current DirichletBoundary object. In case the map does not
1406 // contain an entry for this DirichletBoundary object, it
1407 // means there are no boundary shellfaces active.
1408 if (const auto is_boundary_shellface_it = sebi.is_boundary_shellface_map.find(&dirichlet);
1409 is_boundary_shellface_it != sebi.is_boundary_shellface_map.end())
1410 {
1411 for (unsigned int shellface=0; shellface != 2; ++shellface)
1412 {
1413 if (!is_boundary_shellface_it->second[shellface])
1414 continue;
1415
1416 // A shellface has the same dof indices as the element itself
1417 std::vector<unsigned int> shellface_dofs(n_dofs);
1418 std::iota(shellface_dofs.begin(), shellface_dofs.end(), 0);
1419
1420 // Some shellface dofs are on nodes/edges and already
1421 // fixed, others are free to calculate
1422 unsigned int free_dofs = 0;
1423 for (unsigned int i=0; i != n_dofs; ++i)
1424 if (!dof_is_fixed[shellface_dofs[i]])
1425 free_dof[free_dofs++] = i;
1426
1427 // There may be nothing to project
1428 if (!free_dofs)
1429 continue;
1430
1431 Ke.resize (free_dofs, free_dofs); Ke.zero();
1432 Fe.resize (free_dofs); Fe.zero();
1433 // The new shellface coefficients
1434 DenseVector<Number> Ushellface(free_dofs);
1435
1436 // Initialize FE data on the element
1437 fe->reinit (elem);
1438 const unsigned int n_qp = fem_context.get_element_qrule().n_points();
1439
1440 // Loop over the quadrature points
1441 for (unsigned int qp=0; qp<n_qp; qp++)
1442 {
1443 // solution at the quadrature point
1444 OutputNumber fineval(0);
1445 libMesh::RawAccessor<OutputNumber> f_accessor( fineval, dim );
1446
1447 for (unsigned int c = 0; c < n_vec_dim; c++)
1448 f_accessor(c) =
1449 f_component(f, f_fem, context.get(), var_component+c,
1450 xyz_values[qp], time);
1451
1452 // solution grad at the quadrature point
1453 OutputNumberGradient finegrad;
1454 libMesh::RawAccessor<OutputNumberGradient> g_accessor( finegrad, dim );
1455
1456 unsigned int g_rank;
1457 switch( FEInterface::field_type( fe_type ) )
1458 {
1459 case TYPE_SCALAR:
1460 {
1461 g_rank = 1;
1462 break;
1463 }
1464 case TYPE_VECTOR:
1465 {
1466 g_rank = 2;
1467 break;
1468 }
1469 default:
1470 libmesh_error_msg("Unknown field type!");
1471 }
1472
1473 if (cont == C_ONE)
1474 for (unsigned int c = 0; c < n_vec_dim; c++)
1475 for (unsigned int d = 0; d < g_rank; d++)
1476 g_accessor(c + d*dim ) =
1477 g_component(g, g_fem, context.get(), var_component,
1478 xyz_values[qp], time)(c);
1479
1480 // Form shellface projection matrix
1481 for (unsigned int shellfacei=0, freei=0;
1482 shellfacei != n_dofs; ++shellfacei)
1483 {
1484 unsigned int i = shellface_dofs[shellfacei];
1485 // fixed DoFs aren't test functions
1486 if (dof_is_fixed[i])
1487 continue;
1488 for (unsigned int shellfacej=0, freej=0;
1489 shellfacej != n_dofs; ++shellfacej)
1490 {
1491 unsigned int j = shellface_dofs[shellfacej];
1492 if (dof_is_fixed[j])
1493 Fe(freei) -= phi[i][qp] * phi[j][qp] *
1494 JxW[qp] * Ue(j);
1495 else
1496 Ke(freei,freej) += phi[i][qp] *
1497 phi[j][qp] * JxW[qp];
1498 if (cont == C_ONE)
1499 {
1500 if (dof_is_fixed[j])
1501 Fe(freei) -= ((*dphi)[i][qp].contract((*dphi)[j][qp])) *
1502 JxW[qp] * Ue(j);
1503 else
1504 Ke(freei,freej) += ((*dphi)[i][qp].contract((*dphi)[j][qp]))
1505 * JxW[qp];
1506 }
1507 if (!dof_is_fixed[j])
1508 freej++;
1509 }
1510 Fe(freei) += (fineval * phi[i][qp]) * JxW[qp];
1511 if (cont == C_ONE)
1512 Fe(freei) += (finegrad.contract((*dphi)[i][qp])) *
1513 JxW[qp];
1514 freei++;
1515 }
1516 }
1517
1518 Ke.cholesky_solve(Fe, Ushellface);
1519
1520 // Transfer new shellface solutions to element
1521 for (unsigned int i=0; i != free_dofs; ++i)
1522 {
1523 Number & ui = Ue(shellface_dofs[free_dof[i]]);
1524 libmesh_assert(std::abs(ui) < TOLERANCE ||
1525 std::abs(ui - Ushellface(i)) < TOLERANCE);
1526 ui = Ushellface(i);
1527 dof_is_fixed[shellface_dofs[free_dof[i]]] = true;
1528 }
1529 } // end for (shellface = 0..2)
1530 } // end if (is_boundary_shellface_it != sebi.is_boundary_shellface_map.end())
1531 } // end if (dim == 2 && cont != DISCONTINUOUS)
1532
1533 // Lock the DofConstraints since it is shared among threads.
1534 {
1535 Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
1536
1537 for (unsigned int i = 0; i < n_dofs; i++)
1538 {
1539 DofConstraintRow empty_row;
1540 if (dof_is_fixed[i] && !libmesh_isnan(Ue(i)))
1541 add_fn (dof_indices[i], empty_row, Ue(i));
1542 }
1543 }
1544 } // apply_dirichlet_impl
1545
1546public:
1547 ConstrainDirichlet (DofMap & dof_map_in,
1548 const MeshBase & mesh_in,
1549 const Real time_in,
1550 const DirichletBoundaries & dirichlets_in,
1551 const AddConstraint & add_in) :
1552 dof_map(dof_map_in),
1553 mesh(mesh_in),
1554 time(time_in),
1555 dirichlets(dirichlets_in),
1556 add_fn(add_in) { }
1557
1558 // This class can be default copy/move constructed.
1559 ConstrainDirichlet (ConstrainDirichlet &&) = default;
1560 ConstrainDirichlet (const ConstrainDirichlet &) = default;
1561
1562 // This class cannot be default copy/move assigned because it
1563 // contains reference members.
1564 ConstrainDirichlet & operator= (const ConstrainDirichlet &) = delete;
1565 ConstrainDirichlet & operator= (ConstrainDirichlet &&) = delete;
1566
1567 void operator()(const ConstElemRange & range) const
1568 {
1575 // Figure out which System the DirichletBoundary objects are
1576 // defined for. We break out of the loop as soon as we encounter a
1577 // valid System pointer, the assumption is thus that all Variables
1578 // are defined on the same System.
1579 System * system = nullptr;
1580
1581 // Map from boundary_id -> set<pair<id,DirichletBoundary*>> objects which
1582 // are active on that boundary_id. Later we will use this to determine
1583 // which DirichletBoundary objects to loop over for each Elem.
1584 std::map<boundary_id_type, std::set<std::pair<unsigned int, DirichletBoundary *>>>
1585 boundary_id_to_ordered_dirichlet_boundaries;
1586
1587 for (auto dirichlet_id : index_range(dirichlets))
1588 {
1589 // Pointer to the current DirichletBoundary object
1590 const auto & dirichlet = dirichlets[dirichlet_id];
1591
1592 // Construct mapping from boundary_id -> (dirichlet_id, DirichletBoundary)
1593 for (const auto & b_id : dirichlet->b)
1594 boundary_id_to_ordered_dirichlet_boundaries[b_id].emplace(dirichlet_id, dirichlet.get());
1595
1596 for (const auto & var : dirichlet->variables)
1597 {
1598 const Variable & variable = dof_map.variable(var);
1599 auto current_system = variable.system();
1600
1601 if (!system)
1602 system = current_system;
1603 else
1604 libmesh_error_msg_if(current_system != system,
1605 "All variables should be defined on the same System");
1606 }
1607 }
1608
1609 // If we found no System, it could be because none of the
1610 // Variables have one defined, or because there are
1611 // DirichletBoundary objects with no Variables defined on
1612 // them. These situations both indicate a likely error in the
1613 // setup of a problem, so let's throw an error in this case.
1614 libmesh_error_msg_if(!system, "Valid System not found for any Variables.");
1615
1616 // Construct a FEMContext object for the System on which the
1617 // Variables in our DirichletBoundary objects are defined. This
1618 // will be used in the apply_dirichlet_impl() function.
1619 // We're not going to use elem_jacobian or subjacobians here so
1620 // don't allocate them.
1621 auto fem_context = std::make_unique<FEMContext>
1622 (*system, nullptr, /* allocate local_matrices = */ false);
1623
1624 // At the time we are using this FEMContext, the current_local_solution
1625 // vector is not initialized, but also we don't need it, so set
1626 // the algebraic_type flag to DOFS_ONLY.
1628
1629 // Boundary info for the current mesh
1630 const BoundaryInfo & boundary_info = mesh.get_boundary_info();
1631
1632 // This object keeps track of the BoundaryInfo for a single Elem
1633 SingleElemBoundaryInfo sebi(boundary_info, boundary_id_to_ordered_dirichlet_boundaries);
1634
1635 // Iterate over all the elements in the range
1636 for (const auto & elem : range)
1637 {
1638 // We only calculate Dirichlet constraints on active
1639 // elements
1640 if (!elem->active())
1641 continue;
1642
1643 // Reinitialize BoundaryInfo data structures for the current elem
1644 bool has_dirichlet_constraint = sebi.reinit(elem);
1645
1646 // If this Elem has no boundary ids, go to the next one.
1647 if (!has_dirichlet_constraint)
1648 continue;
1649
1650 for (const auto & db_pair : sebi.ordered_dbs)
1651 {
1652 // Get pointer to the DirichletBoundary object
1653 const auto & dirichlet = db_pair.second;
1654
1655 // Loop over all the variables which this DirichletBoundary object is responsible for
1656 for (const auto & var : dirichlet->variables)
1657 {
1658 const Variable & variable = dof_map.variable(var);
1659
1660 // Make sure that the Variable and the DofMap agree on
1661 // what number this variable is.
1662 libmesh_assert_equal_to(variable.number(), var);
1663
1664 const FEType & fe_type = variable.type();
1665
1666 if (fe_type.family == SCALAR)
1667 continue;
1668
1669 switch( FEInterface::field_type( fe_type ) )
1670 {
1671 case TYPE_SCALAR:
1672 {
1673 // For Lagrange FEs we don't need to do a full
1674 // blown projection, we can just interpolate
1675 // values directly.
1676 if (fe_type.family == LAGRANGE)
1677 this->apply_lagrange_dirichlet_impl<Real>( sebi, variable, *dirichlet, *fem_context );
1678 else
1679 this->apply_dirichlet_impl<Real>( sebi, variable, *dirichlet, *fem_context );
1680 break;
1681 }
1682 case TYPE_VECTOR:
1683 {
1684 this->apply_dirichlet_impl<RealGradient>( sebi, variable, *dirichlet, *fem_context );
1685 break;
1686 }
1687 default:
1688 libmesh_error_msg("Unknown field type!");
1689 }
1690 } // for (var : variables)
1691 } // for (db_pair : ordered_dbs)
1692 } // for (elem : range)
1693 } // operator()
1694
1695}; // class ConstrainDirichlet
1696
1697
1698#endif // LIBMESH_ENABLE_DIRICHLET
1699
1700
1701} // anonymous namespace
1702
1703
1704
1705namespace libMesh
1706{
1707
1708// ------------------------------------------------------------
1709// DofMap member functions
1710
1711#ifdef LIBMESH_ENABLE_CONSTRAINTS
1712
1713
1715{
1716 parallel_object_only();
1717
1718 dof_id_type nc_dofs = this->n_local_constrained_dofs();
1719 this->comm().sum(nc_dofs);
1720 return nc_dofs;
1721}
1722
1723
1725{
1726 const DofConstraints::const_iterator lower =
1727 _dof_constraints.lower_bound(this->first_dof()),
1728 upper =
1729 _dof_constraints.lower_bound(this->end_dof());
1730
1731 return cast_int<dof_id_type>(std::distance(lower, upper));
1732}
1733
1734
1735
1737{
1738 parallel_object_only();
1739
1740 LOG_SCOPE("create_dof_constraints()", "DofMap");
1741
1743
1744 // The user might have set boundary conditions after the mesh was
1745 // prepared; we should double-check that those boundary conditions
1746 // are still consistent.
1747#ifdef DEBUG
1749#endif
1750
1751 // We might get constraint equations from AMR hanging nodes in
1752 // 2D/3D, or from spline constraint rows or boundary conditions in
1753 // any dimension
1754 const bool possible_local_constraints = false
1755 || !mesh.n_elem()
1757#ifdef LIBMESH_ENABLE_AMR
1758 || mesh.mesh_dimension() > 1
1759#endif
1760#ifdef LIBMESH_ENABLE_PERIODIC
1761 || !_periodic_boundaries->empty()
1762#endif
1763#ifdef LIBMESH_ENABLE_DIRICHLET
1764 || !_dirichlet_boundaries->empty()
1765#endif
1766 ;
1767
1768 // Even if we don't have constraints, another processor might.
1769 bool possible_global_constraints = possible_local_constraints;
1770#if defined(LIBMESH_ENABLE_PERIODIC) || defined(LIBMESH_ENABLE_DIRICHLET) || defined(LIBMESH_ENABLE_AMR)
1771 libmesh_assert(this->comm().verify(mesh.is_serial()));
1772
1773 this->comm().max(possible_global_constraints);
1774#endif
1775
1776 // Recalculate dof constraints from scratch. (Or just clear them,
1777 // if the user has just deleted their last dirichlet/periodic/user
1778 // constraint)
1779 // Note: any _stashed_dof_constraints are not cleared as it
1780 // may be the user's intention to restore them later.
1781#ifdef LIBMESH_ENABLE_CONSTRAINTS
1782 _dof_constraints.clear();
1785#endif
1786#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
1787 _node_constraints.clear();
1788#endif
1789
1790 if (!possible_global_constraints)
1791 return;
1792
1793 // Here we build the hanging node constraints. This is done
1794 // by enforcing the condition u_a = u_b along hanging sides.
1795 // u_a = u_b is collocated at the nodes of side a, which gives
1796 // one row of the constraint matrix.
1797
1798 // Processors only compute their local constraints
1799 ConstElemRange range (mesh.local_elements_begin(),
1800 mesh.local_elements_end());
1801
1802 // Global computation fails if we're using a FEMFunctionBase BC on a
1803 // ReplicatedMesh in parallel
1804 // ConstElemRange range (mesh.elements_begin(),
1805 // mesh.elements_end());
1806
1807 // compute_periodic_constraints requires a point_locator() from our
1808 // Mesh, but point_locator() construction is parallel and threaded.
1809 // Rather than nest threads within threads we'll make sure it's
1810 // preconstructed.
1811#ifdef LIBMESH_ENABLE_PERIODIC
1812 bool need_point_locator = !_periodic_boundaries->empty() && !range.empty();
1813
1814 this->comm().max(need_point_locator);
1815
1816 if (need_point_locator)
1818#endif
1819
1820#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
1821 Threads::parallel_for (range,
1822 ComputeNodeConstraints (_node_constraints,
1823#ifdef LIBMESH_ENABLE_PERIODIC
1825#endif
1826 mesh));
1827#endif // LIBMESH_ENABLE_NODE_CONSTRAINTS
1828
1829
1830 // Look at all the variables in the system. Reset the element
1831 // range at each iteration -- there is no need to reconstruct it.
1832 const auto n_vars = this->n_variables();
1833 for (unsigned int variable_number=0; variable_number<n_vars;
1834 ++variable_number, range.reset())
1835 Threads::parallel_for (range,
1836 ComputeConstraints (_dof_constraints,
1837 *this,
1838#ifdef LIBMESH_ENABLE_PERIODIC
1840#endif
1841 mesh,
1843
1844#ifdef LIBMESH_ENABLE_DIRICHLET
1845
1846 if (!_dirichlet_boundaries->empty())
1847 {
1848 // Sanity check that the boundary ids associated with the
1849 // DirichletBoundary objects are actually present in the
1850 // mesh. We do this check by default, but in cases where you
1851 // intentionally add "inconsistent but valid" DirichletBoundary
1852 // objects in parallel, this check can deadlock since it does a
1853 // collective communication internally. In that case it is
1854 // possible to disable this check by setting the flag to false.
1856 for (const auto & dirichlet : *_dirichlet_boundaries)
1857 this->check_dirichlet_bcid_consistency(mesh, *dirichlet);
1858
1859 // Threaded loop over local over elems applying all Dirichlet BCs
1861 (range,
1862 ConstrainDirichlet(*this, mesh, time, *_dirichlet_boundaries,
1863 AddPrimalConstraint(*this)));
1864
1865 // Threaded loop over local over elems per QOI applying all adjoint
1866 // Dirichlet BCs. Note that the ConstElemRange is reset before each
1867 // execution of Threads::parallel_for().
1868
1869 for (auto qoi_index : index_range(_adjoint_dirichlet_boundaries))
1870 {
1871 const DirichletBoundaries & adb_q =
1872 *(_adjoint_dirichlet_boundaries[qoi_index]);
1873
1874 if (!adb_q.empty())
1876 (range.reset(),
1877 ConstrainDirichlet(*this, mesh, time, adb_q,
1878 AddAdjointConstraint(*this, qoi_index)));
1879 }
1880 }
1881
1882#endif // LIBMESH_ENABLE_DIRICHLET
1883
1884 // Handle spline node constraints last, so we can try to move
1885 // existing constraints onto the spline basis if necessary.
1886 this->process_mesh_constraint_rows(mesh);
1887}
1888
1889
1890
1892{
1893 // If we already have simple Dirichlet constraints (with right hand
1894 // sides but with no coupling between DoFs) on spline-constrained FE
1895 // nodes, then we'll need a solve to compute the corresponding
1896 // constraints on the relevant spline nodes. (If we already have
1897 // constraints with coupling between DoFs on spline-constrained FE
1898 // nodes, then we'll need to go sit down and cry until we figure out
1899 // how to handle that.)
1900
1901 const auto & constraint_rows = mesh.get_constraint_rows();
1902
1903 // This routine is too expensive to use unless we really might
1904 // need it
1905#ifdef DEBUG
1906 bool constraint_rows_empty = constraint_rows.empty();
1907 this->comm().min(constraint_rows_empty);
1908 libmesh_assert_equal_to(constraint_rows_empty, !mesh.n_constraint_rows());
1909#endif
1910
1911 if (!mesh.n_constraint_rows())
1912 return;
1913
1914 // We can't handle periodic boundary conditions on spline meshes
1915 // yet.
1916#ifdef LIBMESH_ENABLE_PERIODIC
1917 libmesh_error_msg_if (!_periodic_boundaries->empty(),
1918 "Periodic boundary conditions are not yet implemented for spline meshes");
1919#endif
1920
1921 // We can handle existing Dirichlet constraints, but we'll need
1922 // to do solves to project them down onto the spline basis.
1923 std::unique_ptr<SparsityPattern::Build> sp;
1924 std::unique_ptr<SparseMatrix<Number>> mat;
1925
1926 const unsigned int n_adjoint_rhs =
1928
1929 // [0] for primal rhs, [q+1] for adjoint qoi q
1930 std::vector<std::unique_ptr<NumericVector<Number>>>
1931 solve_rhs(n_adjoint_rhs+1);
1932
1933 // Keep track of which spline DoFs will be Dirichlet.
1934 // We use a set here to make it easier to find what processors
1935 // to send the DoFs to later.
1936 std::set<dof_id_type> my_dirichlet_spline_dofs;
1937
1938 // And keep track of which non-spline Dofs were Dirichlet
1939 std::unordered_set<dof_id_type> was_previously_constrained;
1940
1941 const unsigned int sys_num = this->sys_number();
1942 for (auto & node_row : constraint_rows)
1943 {
1944 const Node * node = node_row.first;
1945 libmesh_assert(node == mesh.node_ptr(node->id()));
1946
1947 // Each processor only computes its own (and in distributed
1948 // cases, is only guaranteed to have the dependency data to
1949 // compute its own) constraints here.
1950 if (node->processor_id() != mesh.processor_id())
1951 continue;
1952
1953 for (auto var_num : IntRange<unsigned int>(0, this->n_variables()))
1954 {
1955 const FEFamily & fe_family = this->variable_type(var_num).family;
1956
1957 // constraint_rows only applies to nodal variables
1958 if (fe_family != LAGRANGE &&
1959 fe_family != RATIONAL_BERNSTEIN)
1960 continue;
1961
1962 DofConstraintRow dc_row;
1963
1964 const dof_id_type constrained_id =
1965 node->dof_number(sys_num, var_num, 0);
1966 for (const auto & [pr, val] : node_row.second)
1967 {
1968 const Elem * spline_elem = pr.first;
1969 libmesh_assert(spline_elem == mesh.elem_ptr(spline_elem->id()));
1970
1971 const Node & spline_node =
1972 spline_elem->node_ref(pr.second);
1973
1974 const dof_id_type spline_dof_id =
1975 spline_node.dof_number(sys_num, var_num, 0);
1976 dc_row[spline_dof_id] = val;
1977 }
1978
1979 // See if we already have a constraint here.
1980 if (this->is_constrained_dof(constrained_id))
1981 {
1982 was_previously_constrained.insert(constrained_id);
1983
1984 // Keep track of which spline DoFs will be
1985 // inheriting this non-spline DoF's constraints
1986 for (auto & row_entry : dc_row)
1987 my_dirichlet_spline_dofs.insert(row_entry.first);
1988
1989 // If it wasn't a simple Dirichlet-type constraint
1990 // then I don't know what to do with it. We'll make
1991 // this an assertion only because this should only
1992 // crop up with periodic boundary conditions, which
1993 // we've already made sure we don't have.
1994 libmesh_assert(_dof_constraints[constrained_id].empty());
1995 }
1996
1997 // Add the constraint, replacing any previous, so we can
1998 // use the new constraint in setting up the solve below
1999 this->add_constraint_row(constrained_id, dc_row, false);
2000 }
2001 }
2002
2003 // my_dirichlet_spline_dofs may now include DoFs whose owners
2004 // don't know they need to become spline DoFs! We need to push
2005 // this data to them.
2006 if (this->comm().size() > 1)
2007 {
2008 std::unordered_map
2009 <processor_id_type, std::vector<dof_id_type>>
2010 their_dirichlet_spline_dofs;
2011
2012 // If we ever change the underlying container here then we'd
2013 // better do some kind of sort before using it; we'll rely
2014 // on sorting to make the processor id lookup efficient.
2015 libmesh_assert(std::is_sorted(my_dirichlet_spline_dofs.begin(),
2016 my_dirichlet_spline_dofs.end()));
2017 processor_id_type destination_pid = 0;
2018 for (auto d : my_dirichlet_spline_dofs)
2019 {
2020 libmesh_assert_less(d, this->end_dof(this->comm().size()-1));
2021 while (d >= this->end_dof(destination_pid))
2022 destination_pid++;
2023
2024 if (destination_pid != this->processor_id())
2025 their_dirichlet_spline_dofs[destination_pid].push_back(d);
2026 }
2027
2028 auto receive_dof_functor =
2029 [& my_dirichlet_spline_dofs]
2031 const std::vector<dof_id_type> & dofs)
2032 {
2033 my_dirichlet_spline_dofs.insert(dofs.begin(), dofs.end());
2034 };
2035
2037 (this->comm(), their_dirichlet_spline_dofs, receive_dof_functor);
2038 }
2039
2040
2041 // If anyone had any prior constraints in effect, then we need
2042 // to convert them to constraints on the spline nodes.
2043 //
2044 // NOT simply testing prior_constraints here; maybe it turned
2045 // out that all our constraints were on non-spline-constrained
2046 // parts of a hybrid mesh?
2047 bool important_prior_constraints =
2048 !was_previously_constrained.empty();
2049 this->comm().max(important_prior_constraints);
2050
2051 if (important_prior_constraints)
2052 {
2053 // Now that we have the spline constraints added, we can
2054 // finally construct a sparsity pattern that correctly
2055 // accounts for those constraints!
2056 mat = SparseMatrix<Number>::build(this->comm());
2057 for (auto q : IntRange<unsigned int>(0, n_adjoint_rhs+1))
2058 {
2059 solve_rhs[q] = NumericVector<Number>::build(this->comm());
2060 solve_rhs[q]->init(this->n_dofs(), this->n_local_dofs(),
2061 false, PARALLEL);
2062 }
2063
2064 // We need to compute our own sparsity pattern, to take into
2065 // account the particularly non-sparse rows that can be
2066 // created by the spline constraints we just added.
2067 mat->attach_dof_map(*this);
2068 sp = this->build_sparsity(mesh);
2069 mat->attach_sparsity_pattern(*sp);
2070 mat->init();
2071
2072 for (auto & node_row : constraint_rows)
2073 {
2074 const Node * node = node_row.first;
2075 libmesh_assert(node == mesh.node_ptr(node->id()));
2076
2077 for (auto var_num : IntRange<unsigned int>(0, this->n_variables()))
2078 {
2079 const FEFamily & fe_family = this->variable_type(var_num).family;
2080
2081 // constraint_rows only applies to nodal variables
2082 if (fe_family != LAGRANGE &&
2083 fe_family != RATIONAL_BERNSTEIN)
2084 continue;
2085
2086 const dof_id_type constrained_id =
2087 node->dof_number(sys_num, var_num, 0);
2088
2089 if (was_previously_constrained.count(constrained_id))
2090 {
2091 for (auto q : IntRange<int>(0, n_adjoint_rhs+1))
2092 {
2093 DenseMatrix<Number> K(1,1);
2095 std::vector<dof_id_type> dof_indices(1, constrained_id);
2096
2097 K(0,0) = 1;
2098
2099 DofConstraintValueMap & vals = q ?
2102
2103 DofConstraintValueMap::const_iterator rhsit =
2104 vals.find(constrained_id);
2105 F(0) = (rhsit == vals.end()) ? 0 : rhsit->second;
2106
2107 // We no longer need any rhs values here directly.
2108 if (rhsit != vals.end())
2109 vals.erase(rhsit);
2110
2112 (K, F, dof_indices, false, q ? (q-1) : -1);
2113 if (!q)
2114 mat->add_matrix(K, dof_indices);
2115 solve_rhs[q]->add_vector(F, dof_indices);
2116 }
2117 }
2118 }
2119 }
2120
2121 // Any DoFs that aren't part of any constraint, directly or
2122 // indirectly, need a diagonal term to make the matrix
2123 // here invertible.
2125 this->end_dof()))
2126 if (!was_previously_constrained.count(d) &&
2127 !my_dirichlet_spline_dofs.count(d))
2128 mat->add(d,d,1);
2129
2130 // At this point, we're finally ready to solve for Dirichlet
2131 // constraint values on spline nodes.
2132 std::unique_ptr<LinearSolver<Number>> linear_solver =
2134
2135 std::unique_ptr<NumericVector<Number>> projected_vals =
2137
2138 projected_vals->init(this->n_dofs(), this->n_local_dofs(),
2139 false, PARALLEL);
2140
2141 DofConstraintRow empty_row;
2142 for (auto sd : my_dirichlet_spline_dofs)
2143 if (this->local_index(sd))
2144 this->add_constraint_row(sd, empty_row);
2145
2146 for (auto q : IntRange<unsigned int>(0, n_adjoint_rhs+1))
2147 {
2148 // FIXME: we don't have an EquationSystems here, but I'd
2149 // rather not hardcode these...
2150 const double tol = double(TOLERANCE * TOLERANCE);
2151 const unsigned int max_its = 5000;
2152
2153 linear_solver->solve(*mat, *projected_vals,
2154 *(solve_rhs[q]), tol, max_its);
2155
2156 DofConstraintValueMap & vals = q ?
2159
2160 for (auto sd : my_dirichlet_spline_dofs)
2161 if (this->local_index(sd))
2162 {
2163 Number constraint_rhs = (*projected_vals)(sd);
2164
2165 std::pair<DofConstraintValueMap::iterator, bool> rhs_it =
2166 vals.emplace(sd, constraint_rhs);
2167 if (!rhs_it.second)
2168 rhs_it.first->second = constraint_rhs;
2169 }
2170 }
2171 }
2172}
2173
2174
2175
2177 const DofConstraintRow & constraint_row,
2178 const Number constraint_rhs,
2179 const bool forbid_constraint_overwrite)
2180{
2181 // Optionally allow the user to overwrite constraints. Defaults to false.
2182 libmesh_error_msg_if(forbid_constraint_overwrite && this->is_constrained_dof(dof_number),
2183 "ERROR: DOF " << dof_number << " was already constrained!");
2184
2185 libmesh_assert_less(dof_number, this->n_dofs());
2186
2187 // There is an implied "1" on the diagonal of the constraint row, and the user
2188 // should not try to manually set _any_ value on the diagonal.
2189 libmesh_assert_msg(!constraint_row.count(dof_number),
2190 "Error: constraint_row for dof " << dof_number <<
2191 " should not contain an entry for dof " << dof_number);
2192
2193#ifndef NDEBUG
2194 for (const auto & pr : constraint_row)
2195 libmesh_assert_less(pr.first, this->n_dofs());
2196#endif
2197
2198 // Store the constraint_row in the map
2199 _dof_constraints.insert_or_assign(dof_number, constraint_row);
2200
2201 std::pair<DofConstraintValueMap::iterator, bool> rhs_it =
2202 _primal_constraint_values.emplace(dof_number, constraint_rhs);
2203 if (!rhs_it.second)
2204 rhs_it.first->second = constraint_rhs;
2205}
2206
2207
2208void DofMap::add_adjoint_constraint_row (const unsigned int qoi_index,
2209 const dof_id_type dof_number,
2210 const DofConstraintRow & /*constraint_row*/,
2211 const Number constraint_rhs,
2212 const bool forbid_constraint_overwrite)
2213{
2214 // Optionally allow the user to overwrite constraints. Defaults to false.
2215 if (forbid_constraint_overwrite)
2216 {
2217 libmesh_error_msg_if(!this->is_constrained_dof(dof_number),
2218 "ERROR: DOF " << dof_number << " has no corresponding primal constraint!");
2219#ifndef NDEBUG
2220 // No way to do this without a non-normalized tolerance?
2221
2222 // // If the user passed in more than just the rhs, let's check the
2223 // // coefficients for consistency
2224 // if (!constraint_row.empty())
2225 // {
2226 // DofConstraintRow row = _dof_constraints[dof_number];
2227 // for (const auto & [dof, val] : row)
2228 // libmesh_assert(constraint_row.find(dof)->second == val);
2229 // }
2230 //
2231 // if (_adjoint_constraint_values[qoi_index].find(dof_number) !=
2232 // _adjoint_constraint_values[qoi_index].end())
2233 // libmesh_assert_equal_to(_adjoint_constraint_values[qoi_index][dof_number],
2234 // constraint_rhs);
2235
2236#endif
2237 }
2238
2239 // Creates the map of rhs values if it doesn't already exist; then
2240 // adds the current value to that map
2241
2242 // Store the rhs value in the map
2243 _adjoint_constraint_values[qoi_index].insert_or_assign(dof_number, constraint_rhs);
2244}
2245
2246
2247
2248
2249void DofMap::print_dof_constraints(std::ostream & os,
2250 bool print_nonlocal) const
2251{
2252 parallel_object_only();
2253
2254 std::string local_constraints =
2255 this->get_local_constraints(print_nonlocal);
2256
2257 if (this->processor_id())
2258 {
2259 this->comm().send(0, local_constraints);
2260 }
2261 else
2262 {
2263 os << "Processor 0:\n";
2264 os << local_constraints;
2265
2266 for (auto p : IntRange<processor_id_type>(1, this->n_processors()))
2267 {
2268 this->comm().receive(p, local_constraints);
2269 os << "Processor " << p << ":\n";
2270 os << local_constraints;
2271 }
2272 }
2273}
2274
2275std::string DofMap::get_local_constraints(bool print_nonlocal) const
2276{
2277 std::ostringstream os;
2278#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
2279 if (print_nonlocal)
2280 os << "All ";
2281 else
2282 os << "Local ";
2283
2284 os << "Node Constraints:"
2285 << std::endl;
2286
2287 for (const auto & [node, pr] : _node_constraints)
2288 {
2289 // Skip non-local nodes if requested
2290 if (!print_nonlocal &&
2291 node->processor_id() != this->processor_id())
2292 continue;
2293
2294 const NodeConstraintRow & row = pr.first;
2295 const Point & offset = pr.second;
2296
2297 os << "Constraints for Node id " << node->id()
2298 << ": \t";
2299
2300 for (const auto & [cnode, val] : row)
2301 os << " (" << cnode->id() << "," << val << ")\t";
2302
2303 os << "rhs: " << offset;
2304
2305 os << std::endl;
2306 }
2307#endif // LIBMESH_ENABLE_NODE_CONSTRAINTS
2308
2309 if (print_nonlocal)
2310 os << "All ";
2311 else
2312 os << "Local ";
2313
2314 os << "DoF Constraints:"
2315 << std::endl;
2316
2317 for (const auto & [i, row] : _dof_constraints)
2318 {
2319 // Skip non-local dofs if requested
2320 if (!print_nonlocal && !this->local_index(i))
2321 continue;
2322
2323 DofConstraintValueMap::const_iterator rhsit =
2325 const Number rhs = (rhsit == _primal_constraint_values.end()) ?
2326 0 : rhsit->second;
2327
2328 os << "Constraints for DoF " << i
2329 << ": \t";
2330
2331 for (const auto & item : row)
2332 os << " (" << item.first << "," << item.second << ")\t";
2333
2334 os << "rhs: " << rhs;
2335 os << std::endl;
2336 }
2337
2338 for (unsigned int qoi_index = 0,
2339 n_qois = cast_int<unsigned int>(_adjoint_dirichlet_boundaries.size());
2340 qoi_index != n_qois; ++qoi_index)
2341 {
2342 os << "Adjoint " << qoi_index << " DoF rhs values:"
2343 << std::endl;
2344
2345 if (auto adjoint_map_it = _adjoint_constraint_values.find(qoi_index);
2346 adjoint_map_it != _adjoint_constraint_values.end())
2347 for (const auto & [i, rhs] : adjoint_map_it->second)
2348 {
2349 // Skip non-local dofs if requested
2350 if (!print_nonlocal && !this->local_index(i))
2351 continue;
2352
2353 os << "RHS for DoF " << i
2354 << ": " << rhs;
2355
2356 os << std::endl;
2357 }
2358 }
2359
2360 return os.str();
2361}
2362
2363
2364
2366 std::vector<dof_id_type> & elem_dofs,
2367 bool asymmetric_constraint_rows) const
2368{
2369 libmesh_assert_equal_to (elem_dofs.size(), matrix.m());
2370 libmesh_assert_equal_to (elem_dofs.size(), matrix.n());
2371
2372 // check for easy return
2373 if (this->_dof_constraints.empty())
2374 return;
2375
2376 // The constrained matrix is built up as C^T K C.
2378
2379
2380 this->build_constraint_matrix (C, elem_dofs);
2381
2382 LOG_SCOPE("constrain_elem_matrix()", "DofMap");
2383
2384 // It is possible that the matrix is not constrained at all.
2385 if ((C.m() == matrix.m()) &&
2386 (C.n() == elem_dofs.size())) // It the matrix is constrained
2387 {
2388 // Compute the matrix-matrix-matrix product C^T K C
2389 matrix.left_multiply_transpose (C);
2390 matrix.right_multiply (C);
2391
2392
2393 libmesh_assert_equal_to (matrix.m(), matrix.n());
2394 libmesh_assert_equal_to (matrix.m(), elem_dofs.size());
2395 libmesh_assert_equal_to (matrix.n(), elem_dofs.size());
2396
2397
2398 for (unsigned int i=0,
2399 n_elem_dofs = cast_int<unsigned int>(elem_dofs.size());
2400 i != n_elem_dofs; i++)
2401 // If the DOF is constrained
2402 if (this->is_constrained_dof(elem_dofs[i]))
2403 {
2404 for (auto j : make_range(matrix.n()))
2405 matrix(i,j) = 0.;
2406
2407 matrix(i,i) = 1.;
2408
2409 if (asymmetric_constraint_rows)
2410 {
2411 DofConstraints::const_iterator
2412 pos = _dof_constraints.find(elem_dofs[i]);
2413
2414 libmesh_assert (pos != _dof_constraints.end());
2415
2416 const DofConstraintRow & constraint_row = pos->second;
2417
2418 // This is an overzealous assertion in the presence of
2419 // heterogeneous constraints: we now can constrain "u_i = c"
2420 // with no other u_j terms involved.
2421 //
2422 // libmesh_assert (!constraint_row.empty());
2423
2424 for (const auto & item : constraint_row)
2425 for (unsigned int j=0; j != n_elem_dofs; j++)
2426 if (elem_dofs[j] == item.first)
2427 matrix(i,j) = -item.second;
2428 }
2429 }
2430 } // end if is constrained...
2431}
2432
2433
2434
2436 DenseVector<Number> & rhs,
2437 std::vector<dof_id_type> & elem_dofs,
2438 bool asymmetric_constraint_rows) const
2439{
2440 libmesh_assert_equal_to (elem_dofs.size(), matrix.m());
2441 libmesh_assert_equal_to (elem_dofs.size(), matrix.n());
2442 libmesh_assert_equal_to (elem_dofs.size(), rhs.size());
2443
2444 // check for easy return
2445 if (this->_dof_constraints.empty())
2446 return;
2447
2448 // The constrained matrix is built up as C^T K C.
2449 // The constrained RHS is built up as C^T F
2451
2452 this->build_constraint_matrix (C, elem_dofs);
2453
2454 LOG_SCOPE("cnstrn_elem_mat_vec()", "DofMap");
2455
2456 // It is possible that the matrix is not constrained at all.
2457 if ((C.m() == matrix.m()) &&
2458 (C.n() == elem_dofs.size())) // It the matrix is constrained
2459 {
2460 // Compute the matrix-matrix-matrix product C^T K C
2461 matrix.left_multiply_transpose (C);
2462 matrix.right_multiply (C);
2463
2464
2465 libmesh_assert_equal_to (matrix.m(), matrix.n());
2466 libmesh_assert_equal_to (matrix.m(), elem_dofs.size());
2467 libmesh_assert_equal_to (matrix.n(), elem_dofs.size());
2468
2469
2470 for (unsigned int i=0,
2471 n_elem_dofs = cast_int<unsigned int>(elem_dofs.size());
2472 i != n_elem_dofs; i++)
2473 if (this->is_constrained_dof(elem_dofs[i]))
2474 {
2475 for (auto j : make_range(matrix.n()))
2476 matrix(i,j) = 0.;
2477
2478 // If the DOF is constrained
2479 matrix(i,i) = 1.;
2480
2481 // This will put a nonsymmetric entry in the constraint
2482 // row to ensure that the linear system produces the
2483 // correct value for the constrained DOF.
2484 if (asymmetric_constraint_rows)
2485 {
2486 DofConstraints::const_iterator
2487 pos = _dof_constraints.find(elem_dofs[i]);
2488
2489 libmesh_assert (pos != _dof_constraints.end());
2490
2491 const DofConstraintRow & constraint_row = pos->second;
2492
2493 // p refinement creates empty constraint rows
2494 // libmesh_assert (!constraint_row.empty());
2495
2496 for (const auto & item : constraint_row)
2497 for (unsigned int j=0; j != n_elem_dofs; j++)
2498 if (elem_dofs[j] == item.first)
2499 matrix(i,j) = -item.second;
2500 }
2501 }
2502
2503
2504 // Compute the matrix-vector product C^T F
2505 DenseVector<Number> old_rhs(rhs);
2506
2507 // compute matrix/vector product
2508 C.vector_mult_transpose(rhs, old_rhs);
2509 } // end if is constrained...
2510}
2511
2512
2513
2515 DenseVector<Number> & rhs,
2516 std::vector<dof_id_type> & elem_dofs,
2517 bool asymmetric_constraint_rows,
2518 int qoi_index) const
2519{
2520 libmesh_assert_equal_to (elem_dofs.size(), matrix.m());
2521 libmesh_assert_equal_to (elem_dofs.size(), matrix.n());
2522 libmesh_assert_equal_to (elem_dofs.size(), rhs.size());
2523
2524 // check for easy return
2525 if (this->_dof_constraints.empty())
2526 return;
2527
2528 // The constrained matrix is built up as C^T K C.
2529 // The constrained RHS is built up as C^T (F - K H)
2532
2533 this->build_constraint_matrix_and_vector (C, H, elem_dofs, qoi_index);
2534
2535 LOG_SCOPE("hetero_cnstrn_elem_mat_vec()", "DofMap");
2536
2537 // It is possible that the matrix is not constrained at all.
2538 if ((C.m() == matrix.m()) &&
2539 (C.n() == elem_dofs.size())) // It the matrix is constrained
2540 {
2541 // We may have rhs values to use later
2542 const DofConstraintValueMap * rhs_values = nullptr;
2543 if (qoi_index < 0)
2544 rhs_values = &_primal_constraint_values;
2545 else if (auto it = _adjoint_constraint_values.find(qoi_index);
2546 it != _adjoint_constraint_values.end())
2547 rhs_values = &it->second;
2548
2549 // Compute matrix/vector product K H
2551 matrix.vector_mult(KH, H);
2552
2553 // Compute the matrix-vector product C^T (F - KH)
2554 DenseVector<Number> F_minus_KH(rhs);
2555 F_minus_KH -= KH;
2556 C.vector_mult_transpose(rhs, F_minus_KH);
2557
2558 // Compute the matrix-matrix-matrix product C^T K C
2559 matrix.left_multiply_transpose (C);
2560 matrix.right_multiply (C);
2561
2562 libmesh_assert_equal_to (matrix.m(), matrix.n());
2563 libmesh_assert_equal_to (matrix.m(), elem_dofs.size());
2564 libmesh_assert_equal_to (matrix.n(), elem_dofs.size());
2565
2566 for (unsigned int i=0,
2567 n_elem_dofs = cast_int<unsigned int>(elem_dofs.size());
2568 i != n_elem_dofs; i++)
2569 {
2570 const dof_id_type dof_id = elem_dofs[i];
2571
2572 if (this->is_constrained_dof(dof_id))
2573 {
2574 for (auto j : make_range(matrix.n()))
2575 matrix(i,j) = 0.;
2576
2577 // If the DOF is constrained
2578 matrix(i,i) = 1.;
2579
2580 // This will put a nonsymmetric entry in the constraint
2581 // row to ensure that the linear system produces the
2582 // correct value for the constrained DOF.
2583 if (asymmetric_constraint_rows)
2584 {
2585 DofConstraints::const_iterator
2586 pos = _dof_constraints.find(dof_id);
2587
2588 libmesh_assert (pos != _dof_constraints.end());
2589
2590 const DofConstraintRow & constraint_row = pos->second;
2591
2592 for (const auto & item : constraint_row)
2593 for (unsigned int j=0; j != n_elem_dofs; j++)
2594 if (elem_dofs[j] == item.first)
2595 matrix(i,j) = -item.second;
2596
2597 if (rhs_values)
2598 {
2599 const DofConstraintValueMap::const_iterator valpos =
2600 rhs_values->find(dof_id);
2601
2602 rhs(i) = (valpos == rhs_values->end()) ?
2603 0 : valpos->second;
2604 }
2605 }
2606 else
2607 rhs(i) = 0.;
2608 }
2609 }
2610
2611 } // end if is constrained...
2612}
2613
2614
2616 (DenseMatrix<Number> & matrix,
2617 DenseVector<Number> & rhs,
2618 std::vector<dof_id_type> & elem_dofs,
2619 NumericVector<Number> & solution_local) const
2620{
2621 libmesh_assert_equal_to (elem_dofs.size(), matrix.m());
2622 libmesh_assert_equal_to (elem_dofs.size(), matrix.n());
2623 libmesh_assert_equal_to (elem_dofs.size(), rhs.size());
2624
2625 libmesh_assert (solution_local.type() == SERIAL ||
2626 solution_local.type() == GHOSTED);
2627
2628 // check for easy return
2629 if (this->_dof_constraints.empty())
2630 return;
2631
2632 // The constrained matrix is built up as C^T K C.
2633 // The constrained RHS is built up as C^T F
2634 // Asymmetric residual terms are added if we do not have x = Cx+h
2637
2638 this->build_constraint_matrix_and_vector (C, H, elem_dofs);
2639
2640 LOG_SCOPE("hetero_cnstrn_elem_jac_res()", "DofMap");
2641
2642 // It is possible that the matrix is not constrained at all.
2643 if ((C.m() != matrix.m()) ||
2644 (C.n() != elem_dofs.size()))
2645 return;
2646
2647 // Compute the matrix-vector product C^T F
2648 DenseVector<Number> old_rhs(rhs);
2649 C.vector_mult_transpose(rhs, old_rhs);
2650
2651 // Compute the matrix-matrix-matrix product C^T K C
2652 matrix.left_multiply_transpose (C);
2653 matrix.right_multiply (C);
2654
2655 libmesh_assert_equal_to (matrix.m(), matrix.n());
2656 libmesh_assert_equal_to (matrix.m(), elem_dofs.size());
2657 libmesh_assert_equal_to (matrix.n(), elem_dofs.size());
2658
2659 for (unsigned int i=0,
2660 n_elem_dofs = cast_int<unsigned int>(elem_dofs.size());
2661 i != n_elem_dofs; i++)
2662 {
2663 const dof_id_type dof_id = elem_dofs[i];
2664
2665 if (auto pos = _dof_constraints.find(dof_id);
2666 pos != _dof_constraints.end())
2667 {
2668 for (auto j : make_range(matrix.n()))
2669 matrix(i,j) = 0.;
2670
2671 // If the DOF is constrained
2672 matrix(i,i) = 1.;
2673
2674 // This will put a nonsymmetric entry in the constraint
2675 // row to ensure that the linear system produces the
2676 // correct value for the constrained DOF.
2677 const DofConstraintRow & constraint_row = pos->second;
2678
2679 for (const auto & item : constraint_row)
2680 for (unsigned int j=0; j != n_elem_dofs; j++)
2681 if (elem_dofs[j] == item.first)
2682 matrix(i,j) = -item.second;
2683
2684 const DofConstraintValueMap::const_iterator valpos =
2685 _primal_constraint_values.find(dof_id);
2686
2687 Number & rhs_val = rhs(i);
2688 rhs_val = (valpos == _primal_constraint_values.end()) ?
2689 0 : -valpos->second;
2690 for (const auto & [constraining_dof, coef] : constraint_row)
2691 rhs_val -= coef * solution_local(constraining_dof);
2692 rhs_val += solution_local(dof_id);
2693 }
2694 }
2695}
2696
2697
2699 (DenseVector<Number> & rhs,
2700 std::vector<dof_id_type> & elem_dofs,
2701 NumericVector<Number> & solution_local) const
2702{
2703 libmesh_assert_equal_to (elem_dofs.size(), rhs.size());
2704
2705 libmesh_assert (solution_local.type() == SERIAL ||
2706 solution_local.type() == GHOSTED);
2707
2708 // check for easy return
2709 if (this->_dof_constraints.empty())
2710 return;
2711
2712 // The constrained RHS is built up as C^T F
2713 // Asymmetric residual terms are added if we do not have x = Cx+h
2716
2717 this->build_constraint_matrix_and_vector (C, H, elem_dofs);
2718
2719 LOG_SCOPE("hetero_cnstrn_elem_res()", "DofMap");
2720
2721 // It is possible that the element is not constrained at all.
2722 if ((C.m() != rhs.size()) ||
2723 (C.n() != elem_dofs.size()))
2724 return;
2725
2726 // Compute the matrix-vector product C^T F
2727 DenseVector<Number> old_rhs(rhs);
2728 C.vector_mult_transpose(rhs, old_rhs);
2729
2730 for (unsigned int i=0,
2731 n_elem_dofs = cast_int<unsigned int>(elem_dofs.size());
2732 i != n_elem_dofs; i++)
2733 {
2734 const dof_id_type dof_id = elem_dofs[i];
2735
2736 if (auto pos = _dof_constraints.find(dof_id);
2737 pos != _dof_constraints.end())
2738 {
2739 // This will put a nonsymmetric entry in the constraint
2740 // row to ensure that the linear system produces the
2741 // correct value for the constrained DOF.
2742 const DofConstraintRow & constraint_row = pos->second;
2743
2744 const DofConstraintValueMap::const_iterator valpos =
2745 _primal_constraint_values.find(dof_id);
2746
2747 Number & rhs_val = rhs(i);
2748 rhs_val = (valpos == _primal_constraint_values.end()) ?
2749 0 : -valpos->second;
2750 for (const auto & [constraining_dof, coef] : constraint_row)
2751 rhs_val -= coef * solution_local(constraining_dof);
2752 rhs_val += solution_local(dof_id);
2753 }
2754 }
2755}
2756
2757
2759 (DenseVector<Number> & rhs,
2760 std::vector<dof_id_type> & elem_dofs,
2761 NumericVector<Number> & solution_local) const
2762{
2763 libmesh_assert_equal_to (elem_dofs.size(), rhs.size());
2764
2765 libmesh_assert (solution_local.type() == SERIAL ||
2766 solution_local.type() == GHOSTED);
2767
2768 // check for easy return
2769 if (this->_dof_constraints.empty())
2770 return;
2771
2772 // The constrained RHS is built up as C^T F
2774
2775 this->build_constraint_matrix (C, elem_dofs);
2776
2777 LOG_SCOPE("cnstrn_elem_residual()", "DofMap");
2778
2779 // It is possible that the matrix is not constrained at all.
2780 if (C.n() != elem_dofs.size())
2781 return;
2782
2783 // Compute the matrix-vector product C^T F
2784 DenseVector<Number> old_rhs(rhs);
2785 C.vector_mult_transpose(rhs, old_rhs);
2786
2787 for (unsigned int i=0,
2788 n_elem_dofs = cast_int<unsigned int>(elem_dofs.size());
2789 i != n_elem_dofs; i++)
2790 {
2791 const dof_id_type dof_id = elem_dofs[i];
2792
2793 if (auto pos = _dof_constraints.find(dof_id);
2794 pos != _dof_constraints.end())
2795 {
2796 // This will put a nonsymmetric entry in the constraint
2797 // row to ensure that the linear system produces the
2798 // correct value for the constrained DOF.
2799 const DofConstraintRow & constraint_row = pos->second;
2800
2801 Number & rhs_val = rhs(i);
2802 rhs_val = 0;
2803 for (const auto & [constraining_dof, coef] : constraint_row)
2804 rhs_val -= coef * solution_local(constraining_dof);
2805 rhs_val += solution_local(dof_id);
2806 }
2807 }
2808}
2809
2810
2812 DenseVector<Number> & rhs,
2813 std::vector<dof_id_type> & elem_dofs,
2814 bool asymmetric_constraint_rows,
2815 int qoi_index) const
2816{
2817 libmesh_assert_equal_to (elem_dofs.size(), matrix.m());
2818 libmesh_assert_equal_to (elem_dofs.size(), matrix.n());
2819 libmesh_assert_equal_to (elem_dofs.size(), rhs.size());
2820
2821 // check for easy return
2822 if (this->_dof_constraints.empty())
2823 return;
2824
2825 // The constrained matrix is built up as C^T K C.
2826 // The constrained RHS is built up as C^T (F - K H)
2829
2830 this->build_constraint_matrix_and_vector (C, H, elem_dofs, qoi_index);
2831
2832 LOG_SCOPE("hetero_cnstrn_elem_vec()", "DofMap");
2833
2834 // It is possible that the matrix is not constrained at all.
2835 if ((C.m() == matrix.m()) &&
2836 (C.n() == elem_dofs.size())) // It the matrix is constrained
2837 {
2838 // We may have rhs values to use later
2839 const DofConstraintValueMap * rhs_values = nullptr;
2840 if (qoi_index < 0)
2841 rhs_values = &_primal_constraint_values;
2842 else if (auto it = _adjoint_constraint_values.find(qoi_index);
2843 it != _adjoint_constraint_values.end())
2844 rhs_values = &it->second;
2845
2846 // Compute matrix/vector product K H
2848 matrix.vector_mult(KH, H);
2849
2850 // Compute the matrix-vector product C^T (F - KH)
2851 DenseVector<Number> F_minus_KH(rhs);
2852 F_minus_KH -= KH;
2853 C.vector_mult_transpose(rhs, F_minus_KH);
2854
2855 for (unsigned int i=0,
2856 n_elem_dofs = cast_int<unsigned int>(elem_dofs.size());
2857 i != n_elem_dofs; i++)
2858 {
2859 const dof_id_type dof_id = elem_dofs[i];
2860
2861 if (this->is_constrained_dof(dof_id))
2862 {
2863 // This will put a nonsymmetric entry in the constraint
2864 // row to ensure that the linear system produces the
2865 // correct value for the constrained DOF.
2866 if (asymmetric_constraint_rows && rhs_values)
2867 {
2868 const DofConstraintValueMap::const_iterator valpos =
2869 rhs_values->find(dof_id);
2870
2871 rhs(i) = (valpos == rhs_values->end()) ?
2872 0 : valpos->second;
2873 }
2874 else
2875 rhs(i) = 0.;
2876 }
2877 }
2878
2879 } // end if is constrained...
2880}
2881
2882
2883
2884
2886 std::vector<dof_id_type> & row_dofs,
2887 std::vector<dof_id_type> & col_dofs,
2888 bool asymmetric_constraint_rows) const
2889{
2890 libmesh_assert_equal_to (row_dofs.size(), matrix.m());
2891 libmesh_assert_equal_to (col_dofs.size(), matrix.n());
2892
2893 // check for easy return
2894 if (this->_dof_constraints.empty())
2895 return;
2896
2897 // The constrained matrix is built up as R^T K C.
2900
2901 // Safeguard against the user passing us the same
2902 // object for row_dofs and col_dofs. If that is done
2903 // the calls to build_matrix would fail
2904 std::vector<dof_id_type> orig_row_dofs(row_dofs);
2905 std::vector<dof_id_type> orig_col_dofs(col_dofs);
2906
2907 this->build_constraint_matrix (R, orig_row_dofs);
2908 this->build_constraint_matrix (C, orig_col_dofs);
2909
2910 LOG_SCOPE("constrain_elem_matrix()", "DofMap");
2911
2912 row_dofs = orig_row_dofs;
2913 col_dofs = orig_col_dofs;
2914
2915 bool constraint_found = false;
2916
2917 // K_constrained = R^T K C
2918
2919 if ((R.m() == matrix.m()) &&
2920 (R.n() == row_dofs.size()))
2921 {
2922 matrix.left_multiply_transpose (R);
2923 constraint_found = true;
2924 }
2925
2926 if ((C.m() == matrix.n()) &&
2927 (C.n() == col_dofs.size()))
2928 {
2929 matrix.right_multiply (C);
2930 constraint_found = true;
2931 }
2932
2933 // It is possible that the matrix is not constrained at all.
2934 if (constraint_found)
2935 {
2936 libmesh_assert_equal_to (matrix.m(), row_dofs.size());
2937 libmesh_assert_equal_to (matrix.n(), col_dofs.size());
2938
2939
2940 for (unsigned int i=0,
2941 n_row_dofs = cast_int<unsigned int>(row_dofs.size());
2942 i != n_row_dofs; i++)
2943 if (this->is_constrained_dof(row_dofs[i]))
2944 {
2945 for (auto j : make_range(matrix.n()))
2946 {
2947 if (row_dofs[i] != col_dofs[j])
2948 matrix(i,j) = 0.;
2949 else // If the DOF is constrained
2950 matrix(i,j) = 1.;
2951 }
2952
2953 if (asymmetric_constraint_rows)
2954 {
2955 DofConstraints::const_iterator
2956 pos = _dof_constraints.find(row_dofs[i]);
2957
2958 libmesh_assert (pos != _dof_constraints.end());
2959
2960 const DofConstraintRow & constraint_row = pos->second;
2961
2962 libmesh_assert (!constraint_row.empty());
2963
2964 for (const auto & item : constraint_row)
2965 for (unsigned int j=0,
2966 n_col_dofs = cast_int<unsigned int>(col_dofs.size());
2967 j != n_col_dofs; j++)
2968 if (col_dofs[j] == item.first)
2969 matrix(i,j) = -item.second;
2970 }
2971 }
2972 } // end if is constrained...
2973}
2974
2975
2976
2978 std::vector<dof_id_type> & row_dofs,
2979 bool) const
2980{
2981 libmesh_assert_equal_to (rhs.size(), row_dofs.size());
2982
2983 // check for easy return
2984 if (this->_dof_constraints.empty())
2985 return;
2986
2987 // The constrained RHS is built up as R^T F.
2989
2990 this->build_constraint_matrix (R, row_dofs);
2991
2992 LOG_SCOPE("constrain_elem_vector()", "DofMap");
2993
2994 // It is possible that the vector is not constrained at all.
2995 if ((R.m() == rhs.size()) &&
2996 (R.n() == row_dofs.size())) // if the RHS is constrained
2997 {
2998 // Compute the matrix-vector product
2999 DenseVector<Number> old_rhs(rhs);
3000 R.vector_mult_transpose(rhs, old_rhs);
3001
3002 libmesh_assert_equal_to (row_dofs.size(), rhs.size());
3003
3004 for (unsigned int i=0,
3005 n_row_dofs = cast_int<unsigned int>(row_dofs.size());
3006 i != n_row_dofs; i++)
3007 if (this->is_constrained_dof(row_dofs[i]))
3008 {
3009 // If the DOF is constrained
3010 libmesh_assert (_dof_constraints.find(row_dofs[i]) != _dof_constraints.end());
3011
3012 rhs(i) = 0;
3013 }
3014 } // end if the RHS is constrained.
3015}
3016
3017
3018
3021 std::vector<dof_id_type> & row_dofs,
3022 bool) const
3023{
3024 libmesh_assert_equal_to (v.size(), row_dofs.size());
3025 libmesh_assert_equal_to (w.size(), row_dofs.size());
3026
3027 // check for easy return
3028 if (this->_dof_constraints.empty())
3029 return;
3030
3031 // The constrained RHS is built up as R^T F.
3033
3034 this->build_constraint_matrix (R, row_dofs);
3035
3036 LOG_SCOPE("cnstrn_elem_dyad_mat()", "DofMap");
3037
3038 // It is possible that the vector is not constrained at all.
3039 if ((R.m() == v.size()) &&
3040 (R.n() == row_dofs.size())) // if the RHS is constrained
3041 {
3042 // Compute the matrix-vector products
3043 DenseVector<Number> old_v(v);
3044 DenseVector<Number> old_w(w);
3045
3046 // compute matrix/vector product
3047 R.vector_mult_transpose(v, old_v);
3048 R.vector_mult_transpose(w, old_w);
3049
3050 libmesh_assert_equal_to (row_dofs.size(), v.size());
3051 libmesh_assert_equal_to (row_dofs.size(), w.size());
3052
3053 /* Constrain only v, not w. */
3054
3055 for (unsigned int i=0,
3056 n_row_dofs = cast_int<unsigned int>(row_dofs.size());
3057 i != n_row_dofs; i++)
3058 if (this->is_constrained_dof(row_dofs[i]))
3059 {
3060 // If the DOF is constrained
3061 libmesh_assert (_dof_constraints.find(row_dofs[i]) != _dof_constraints.end());
3062
3063 v(i) = 0;
3064 }
3065 } // end if the RHS is constrained.
3066}
3067
3068
3069
3070void DofMap::constrain_nothing (std::vector<dof_id_type> & dofs) const
3071{
3072 // check for easy return
3073 if (this->_dof_constraints.empty())
3074 return;
3075
3076 // All the work is done by \p build_constraint_matrix. We just need
3077 // a dummy matrix.
3079 this->build_constraint_matrix (R, dofs);
3080}
3081
3082
3083
3084void DofMap::enforce_constraints_exactly (const System & system,
3086 bool homogeneous) const
3087{
3088 parallel_object_only();
3089
3090 if (!this->n_constrained_dofs())
3091 return;
3092
3093 LOG_SCOPE("enforce_constraints_exactly()","DofMap");
3094
3095 if (!v)
3096 v = system.solution.get();
3097
3098 if (!v->closed())
3099 v->close();
3100
3101 NumericVector<Number> * v_local = nullptr; // will be initialized below
3102 NumericVector<Number> * v_global = nullptr; // will be initialized below
3103 std::unique_ptr<NumericVector<Number>> v_built;
3104 if (v->type() == SERIAL)
3105 {
3106 v_built = NumericVector<Number>::build(this->comm());
3107 v_built->init(this->n_dofs(), this->n_local_dofs(), true, PARALLEL);
3108 v_built->close();
3109
3110 for (dof_id_type i=v_built->first_local_index();
3111 i<v_built->last_local_index(); i++)
3112 v_built->set(i, (*v)(i));
3113 v_built->close();
3114 v_global = v_built.get();
3115
3116 v_local = v;
3117 libmesh_assert (v_local->closed());
3118 }
3119 else if (v->type() == PARALLEL)
3120 {
3121 v_built = NumericVector<Number>::build(this->comm());
3122 v_built->init (v->size(), v->local_size(),
3123 this->get_send_list(), true,
3124 GHOSTED);
3125 v->localize(*v_built, this->get_send_list());
3126 v_built->close();
3127 v_local = v_built.get();
3128
3129 v_global = v;
3130 }
3131 else if (v->type() == GHOSTED)
3132 {
3133 v_local = v;
3134 v_global = v;
3135 }
3136 else // unknown v->type()
3137 libmesh_error_msg("ERROR: Unsupported NumericVector type == " << Utility::enum_to_string(v->type()));
3138
3139 // We should never hit these asserts because we should error-out in
3140 // else clause above. Just to be sure we don't try to use v_local
3141 // and v_global uninitialized...
3142 libmesh_assert(v_local);
3143 libmesh_assert(v_global);
3144 libmesh_assert_equal_to (this, &(system.get_dof_map()));
3145
3146 for (const auto & [constrained_dof, constraint_row] : _dof_constraints)
3147 {
3148 if (!this->local_index(constrained_dof))
3149 continue;
3150
3151 Number exact_value = 0;
3152 if (!homogeneous)
3153 {
3154 if (auto rhsit = _primal_constraint_values.find(constrained_dof);
3155 rhsit != _primal_constraint_values.end())
3156 exact_value = rhsit->second;
3157 }
3158 for (const auto & [dof, val] : constraint_row)
3159 exact_value += val * (*v_local)(dof);
3160
3161 v_global->set(constrained_dof, exact_value);
3162 }
3163
3164 // If the old vector was serial, we probably need to send our values
3165 // to other processors
3166 if (v->type() == SERIAL)
3167 {
3168#ifndef NDEBUG
3169 v_global->close();
3170#endif
3171 v_global->localize (*v);
3172 }
3173 v->close();
3174}
3175
3178 NumericVector<Number> const * solution,
3179 bool homogeneous) const
3180{
3181 parallel_object_only();
3182
3183 if (!this->n_constrained_dofs())
3184 return;
3185
3186 if (!rhs)
3187 rhs = system.rhs;
3188 if (!solution)
3189 solution = system.solution.get();
3190
3191 NumericVector<Number> const * solution_local = nullptr; // will be initialized below
3192 std::unique_ptr<NumericVector<Number>> solution_built;
3193 if (solution->type() == SERIAL || solution->type() == GHOSTED)
3194 solution_local = solution;
3195 else if (solution->type() == PARALLEL)
3196 {
3197 solution_built = NumericVector<Number>::build(this->comm());
3198 solution_built->init (solution->size(), solution->local_size(),
3199 this->get_send_list(), true, GHOSTED);
3200 solution->localize(*solution_built, this->get_send_list());
3201 solution_built->close();
3202 solution_local = solution_built.get();
3203 }
3204 else // unknown solution->type()
3205 libmesh_error_msg("ERROR: Unsupported NumericVector type == " << Utility::enum_to_string(solution->type()));
3206
3207 // We should never hit these asserts because we should error-out in
3208 // else clause above. Just to be sure we don't try to use solution_local
3209 libmesh_assert(solution_local);
3210 libmesh_assert_equal_to (this, &(system.get_dof_map()));
3211
3212 for (const auto & [constrained_dof, constraint_row] : _dof_constraints)
3213 {
3214 if (!this->local_index(constrained_dof))
3215 continue;
3216
3217 Number exact_value = 0;
3218 for (const auto & [dof, val] : constraint_row)
3219 exact_value -= val * (*solution_local)(dof);
3220 exact_value += (*solution_local)(constrained_dof);
3221 if (!homogeneous)
3222 {
3223 if (auto rhsit = _primal_constraint_values.find(constrained_dof);
3224 rhsit != _primal_constraint_values.end())
3225 exact_value -= rhsit->second;
3226 }
3227
3228 rhs->set(constrained_dof, exact_value);
3229 }
3230}
3231
3233 SparseMatrix<Number> * jac) const
3234{
3235 parallel_object_only();
3236
3237 if (!this->n_constrained_dofs())
3238 return;
3239
3240 if (!jac)
3241 jac = system.matrix;
3242
3243 libmesh_assert_equal_to (this, &(system.get_dof_map()));
3244
3245 for (const auto & [constrained_dof, constraint_row] : _dof_constraints)
3246 {
3247 if (!this->local_index(constrained_dof))
3248 continue;
3249
3250 for (const auto & j : constraint_row)
3251 jac->set(constrained_dof, j.first, -j.second);
3252 jac->set(constrained_dof, constrained_dof, 1);
3253 }
3254}
3255
3256
3258 unsigned int q) const
3259{
3260 parallel_object_only();
3261
3262 if (!this->n_constrained_dofs())
3263 return;
3264
3265 LOG_SCOPE("enforce_adjoint_constraints_exactly()", "DofMap");
3266
3267 NumericVector<Number> * v_local = nullptr; // will be initialized below
3268 NumericVector<Number> * v_global = nullptr; // will be initialized below
3269 std::unique_ptr<NumericVector<Number>> v_built;
3270 if (v.type() == SERIAL)
3271 {
3272 v_built = NumericVector<Number>::build(this->comm());
3273 v_built->init(this->n_dofs(), this->n_local_dofs(), true, PARALLEL);
3274 v_built->close();
3275
3276 for (dof_id_type i=v_built->first_local_index();
3277 i<v_built->last_local_index(); i++)
3278 v_built->set(i, v(i));
3279 v_built->close();
3280 v_global = v_built.get();
3281
3282 v_local = &v;
3283 libmesh_assert (v_local->closed());
3284 }
3285 else if (v.type() == PARALLEL)
3286 {
3287 v_built = NumericVector<Number>::build(this->comm());
3288 v_built->init (v.size(), v.local_size(),
3289 this->get_send_list(), true, GHOSTED);
3290 v.localize(*v_built, this->get_send_list());
3291 v_built->close();
3292 v_local = v_built.get();
3293
3294 v_global = &v;
3295 }
3296 else if (v.type() == GHOSTED)
3297 {
3298 v_local = &v;
3299 v_global = &v;
3300 }
3301 else // unknown v.type()
3302 libmesh_error_msg("ERROR: Unknown v.type() == " << v.type());
3303
3304 // We should never hit these asserts because we should error-out in
3305 // else clause above. Just to be sure we don't try to use v_local
3306 // and v_global uninitialized...
3307 libmesh_assert(v_local);
3308 libmesh_assert(v_global);
3309
3310 // Do we have any non_homogeneous constraints?
3311 const AdjointDofConstraintValues::const_iterator
3312 adjoint_constraint_map_it = _adjoint_constraint_values.find(q);
3313 const DofConstraintValueMap * constraint_map =
3314 (adjoint_constraint_map_it == _adjoint_constraint_values.end()) ?
3315 nullptr : &adjoint_constraint_map_it->second;
3316
3317 for (const auto & [constrained_dof, constraint_row] : _dof_constraints)
3318 {
3319 if (!this->local_index(constrained_dof))
3320 continue;
3321
3322 Number exact_value = 0;
3323 if (constraint_map)
3324 {
3325 if (const auto adjoint_constraint_it = constraint_map->find(constrained_dof);
3326 adjoint_constraint_it != constraint_map->end())
3327 exact_value = adjoint_constraint_it->second;
3328 }
3329
3330 for (const auto & j : constraint_row)
3331 exact_value += j.second * (*v_local)(j.first);
3332
3333 v_global->set(constrained_dof, exact_value);
3334 }
3335
3336 // If the old vector was serial, we probably need to send our values
3337 // to other processors
3338 if (v.type() == SERIAL)
3339 {
3340#ifndef NDEBUG
3341 v_global->close();
3342#endif
3343 v_global->localize (v);
3344 }
3345 v.close();
3346}
3347
3348
3349
3350std::pair<Real, Real>
3352 NumericVector<Number> * v) const
3353{
3354 if (!v)
3355 v = system.solution.get();
3356 NumericVector<Number> & vec = *v;
3357
3358 // We'll assume the vector is closed
3359 libmesh_assert (vec.closed());
3360
3361 Real max_absolute_error = 0., max_relative_error = 0.;
3362
3363 const MeshBase & mesh = system.get_mesh();
3364
3365 libmesh_assert_equal_to (this, &(system.get_dof_map()));
3366
3367 // indices on each element
3368 std::vector<dof_id_type> local_dof_indices;
3369
3370 for (const auto & elem : mesh.active_local_element_ptr_range())
3371 {
3372 this->dof_indices(elem, local_dof_indices);
3373 std::vector<dof_id_type> raw_dof_indices = local_dof_indices;
3374
3375 // Constraint matrix for each element
3377
3378 this->build_constraint_matrix (C, local_dof_indices);
3379
3380 // Continue if the element is unconstrained
3381 if (!C.m())
3382 continue;
3383
3384 libmesh_assert_equal_to (C.m(), raw_dof_indices.size());
3385 libmesh_assert_equal_to (C.n(), local_dof_indices.size());
3386
3387 for (auto i : make_range(C.m()))
3388 {
3389 // Recalculate any constrained dof owned by this processor
3390 dof_id_type global_dof = raw_dof_indices[i];
3391 if (this->is_constrained_dof(global_dof) &&
3392 global_dof >= vec.first_local_index() &&
3393 global_dof < vec.last_local_index())
3394 {
3395#ifndef NDEBUG
3396 DofConstraints::const_iterator
3397 pos = _dof_constraints.find(global_dof);
3398
3399 libmesh_assert (pos != _dof_constraints.end());
3400#endif
3401
3402 Number exact_value = 0;
3403 DofConstraintValueMap::const_iterator rhsit =
3404 _primal_constraint_values.find(global_dof);
3405 if (rhsit != _primal_constraint_values.end())
3406 exact_value = rhsit->second;
3407
3408 for (auto j : make_range(C.n()))
3409 {
3410 if (local_dof_indices[j] != global_dof)
3411 exact_value += C(i,j) *
3412 vec(local_dof_indices[j]);
3413 }
3414
3415 max_absolute_error = std::max(max_absolute_error,
3416 std::abs(vec(global_dof) - exact_value));
3417 max_relative_error = std::max(max_relative_error,
3418 std::abs(vec(global_dof) - exact_value)
3419 / std::abs(exact_value));
3420 }
3421 }
3422 }
3423
3424 return std::pair<Real, Real>(max_absolute_error, max_relative_error);
3425}
3426
3427
3428
3430 std::vector<dof_id_type> & elem_dofs,
3431 const bool called_recursively) const
3432{
3433 LOG_SCOPE_IF("build_constraint_matrix()", "DofMap", !called_recursively);
3434
3435 // Create a set containing the DOFs we already depend on
3436 typedef std::set<dof_id_type> RCSet;
3437 RCSet dof_set;
3438
3439 bool we_have_constraints = false;
3440
3441 // Next insert any other dofs the current dofs might be constrained
3442 // in terms of. Note that in this case we may not be done: Those
3443 // may in turn depend on others. So, we need to repeat this process
3444 // in that case until the system depends only on unconstrained
3445 // degrees of freedom.
3446 for (const auto & dof : elem_dofs)
3447 if (this->is_constrained_dof(dof))
3448 {
3449 we_have_constraints = true;
3450
3451 // If the DOF is constrained
3452 DofConstraints::const_iterator
3453 pos = _dof_constraints.find(dof);
3454
3455 libmesh_assert (pos != _dof_constraints.end());
3456
3457 const DofConstraintRow & constraint_row = pos->second;
3458
3459 // Constraint rows in p refinement may be empty
3460 //libmesh_assert (!constraint_row.empty());
3461
3462 for (const auto & item : constraint_row)
3463 dof_set.insert (item.first);
3464 }
3465
3466 // May be safe to return at this point
3467 // (but remember to stop the perflog)
3468 if (!we_have_constraints)
3469 return;
3470
3471 for (const auto & dof : elem_dofs)
3472 dof_set.erase (dof);
3473
3474 // If we added any DOFS then we need to do this recursively.
3475 // It is possible that we just added a DOF that is also
3476 // constrained!
3477 //
3478 // Also, we need to handle the special case of an element having DOFs
3479 // constrained in terms of other, local DOFs
3480 if (!dof_set.empty() || // case 1: constrained in terms of other DOFs
3481 !called_recursively) // case 2: constrained in terms of our own DOFs
3482 {
3483 const unsigned int old_size =
3484 cast_int<unsigned int>(elem_dofs.size());
3485
3486 // Add new dependency dofs to the end of the current dof set
3487 elem_dofs.insert(elem_dofs.end(),
3488 dof_set.begin(), dof_set.end());
3489
3490 // Now we can build the constraint matrix.
3491 // Note that resize also zeros for a DenseMatrix<Number>.
3492 C.resize (old_size,
3493 cast_int<unsigned int>(elem_dofs.size()));
3494
3495 // Create the C constraint matrix.
3496 for (unsigned int i=0; i != old_size; i++)
3497 if (this->is_constrained_dof(elem_dofs[i]))
3498 {
3499 // If the DOF is constrained
3500 DofConstraints::const_iterator
3501 pos = _dof_constraints.find(elem_dofs[i]);
3502
3503 libmesh_assert (pos != _dof_constraints.end());
3504
3505 const DofConstraintRow & constraint_row = pos->second;
3506
3507 // p refinement creates empty constraint rows
3508 // libmesh_assert (!constraint_row.empty());
3509
3510 for (const auto & item : constraint_row)
3511 for (unsigned int j=0,
3512 n_elem_dofs = cast_int<unsigned int>(elem_dofs.size());
3513 j != n_elem_dofs; j++)
3514 if (elem_dofs[j] == item.first)
3515 C(i,j) = item.second;
3516 }
3517 else
3518 {
3519 C(i,i) = 1.;
3520 }
3521
3522 // May need to do this recursively. It is possible
3523 // that we just replaced a constrained DOF with another
3524 // constrained DOF.
3526
3527 this->build_constraint_matrix (Cnew, elem_dofs, true);
3528
3529 if ((C.n() == Cnew.m()) &&
3530 (Cnew.n() == elem_dofs.size())) // If the constraint matrix
3531 C.right_multiply(Cnew); // is constrained...
3532
3533 libmesh_assert_equal_to (C.n(), elem_dofs.size());
3534 }
3535}
3536
3537
3538
3541 std::vector<dof_id_type> & elem_dofs,
3542 int qoi_index,
3543 const bool called_recursively) const
3544{
3545 LOG_SCOPE_IF("build_constraint_matrix_and_vector()", "DofMap", !called_recursively);
3546
3547 // Create a set containing the DOFs we already depend on
3548 typedef std::set<dof_id_type> RCSet;
3549 RCSet dof_set;
3550
3551 bool we_have_constraints = false;
3552
3553 // Next insert any other dofs the current dofs might be constrained
3554 // in terms of. Note that in this case we may not be done: Those
3555 // may in turn depend on others. So, we need to repeat this process
3556 // in that case until the system depends only on unconstrained
3557 // degrees of freedom.
3558 for (const auto & dof : elem_dofs)
3559 if (this->is_constrained_dof(dof))
3560 {
3561 we_have_constraints = true;
3562
3563 // If the DOF is constrained
3564 DofConstraints::const_iterator
3565 pos = _dof_constraints.find(dof);
3566
3567 libmesh_assert (pos != _dof_constraints.end());
3568
3569 const DofConstraintRow & constraint_row = pos->second;
3570
3571 // Constraint rows in p refinement may be empty
3572 //libmesh_assert (!constraint_row.empty());
3573
3574 for (const auto & item : constraint_row)
3575 dof_set.insert (item.first);
3576 }
3577
3578 // May be safe to return at this point
3579 // (but remember to stop the perflog)
3580 if (!we_have_constraints)
3581 return;
3582
3583 for (const auto & dof : elem_dofs)
3584 dof_set.erase (dof);
3585
3586 // If we added any DOFS then we need to do this recursively.
3587 // It is possible that we just added a DOF that is also
3588 // constrained!
3589 //
3590 // Also, we need to handle the special case of an element having DOFs
3591 // constrained in terms of other, local DOFs
3592 if (!dof_set.empty() || // case 1: constrained in terms of other DOFs
3593 !called_recursively) // case 2: constrained in terms of our own DOFs
3594 {
3595 const DofConstraintValueMap * rhs_values = nullptr;
3596 if (qoi_index < 0)
3597 rhs_values = &_primal_constraint_values;
3598 else if (auto it = _adjoint_constraint_values.find(qoi_index);
3599 it != _adjoint_constraint_values.end())
3600 rhs_values = &it->second;
3601
3602 const unsigned int old_size =
3603 cast_int<unsigned int>(elem_dofs.size());
3604
3605 // Add new dependency dofs to the end of the current dof set
3606 elem_dofs.insert(elem_dofs.end(),
3607 dof_set.begin(), dof_set.end());
3608
3609 // Now we can build the constraint matrix and vector.
3610 // Note that resize also zeros for a DenseMatrix and DenseVector
3611 C.resize (old_size,
3612 cast_int<unsigned int>(elem_dofs.size()));
3613 H.resize (old_size);
3614
3615 // Create the C constraint matrix.
3616 for (unsigned int i=0; i != old_size; i++)
3617 if (this->is_constrained_dof(elem_dofs[i]))
3618 {
3619 // If the DOF is constrained
3620 DofConstraints::const_iterator
3621 pos = _dof_constraints.find(elem_dofs[i]);
3622
3623 libmesh_assert (pos != _dof_constraints.end());
3624
3625 const DofConstraintRow & constraint_row = pos->second;
3626
3627 // p refinement creates empty constraint rows
3628 // libmesh_assert (!constraint_row.empty());
3629
3630 for (const auto & item : constraint_row)
3631 for (unsigned int j=0,
3632 n_elem_dofs = cast_int<unsigned int>(elem_dofs.size());
3633 j != n_elem_dofs; j++)
3634 if (elem_dofs[j] == item.first)
3635 C(i,j) = item.second;
3636
3637 if (rhs_values)
3638 {
3639 if (const auto rhsit = rhs_values->find(elem_dofs[i]);
3640 rhsit != rhs_values->end())
3641 H(i) = rhsit->second;
3642 }
3643 }
3644 else
3645 {
3646 C(i,i) = 1.;
3647 }
3648
3649 // May need to do this recursively. It is possible
3650 // that we just replaced a constrained DOF with another
3651 // constrained DOF.
3654
3655 this->build_constraint_matrix_and_vector (Cnew, Hnew, elem_dofs,
3656 qoi_index, true);
3657
3658 if ((C.n() == Cnew.m()) && // If the constraint matrix
3659 (Cnew.n() == elem_dofs.size())) // is constrained...
3660 {
3661 // If x = Cy + h and y = Dz + g
3662 // Then x = (CD)z + (Cg + h)
3663 C.vector_mult_add(H, 1, Hnew);
3664
3665 C.right_multiply(Cnew);
3666 }
3667
3668 libmesh_assert_equal_to (C.n(), elem_dofs.size());
3669 }
3670}
3671
3672
3674{
3675 // This function must be run on all processors at once
3676 parallel_object_only();
3677
3678 // Return immediately if there's nothing to gather
3679 if (this->n_processors() == 1)
3680 return;
3681
3682 // We might get to return immediately if none of the processors
3683 // found any constraints
3684 unsigned int has_constraints = !_dof_constraints.empty()
3685#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
3686 || !_node_constraints.empty()
3687#endif // LIBMESH_ENABLE_NODE_CONSTRAINTS
3688 ;
3689 this->comm().max(has_constraints);
3690 if (!has_constraints)
3691 return;
3692
3693 // If we have heterogeneous adjoint constraints we need to
3694 // communicate those too.
3695 const unsigned int max_qoi_num =
3697 0 : _adjoint_constraint_values.rbegin()->first+1;
3698
3699#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
3700 // We may need to send nodes ahead of data about them
3701 std::vector<Parallel::Request> packed_range_sends;
3702
3703 // We may be receiving packed_range sends out of order with
3704 // parallel_sync tags, so make sure they're received correctly.
3705 Parallel::MessageTag range_tag = this->comm().get_unique_tag();
3706
3707 // We only need to do these sends on a distributed mesh
3708 const bool dist_mesh = !mesh.is_serial();
3709#endif
3710
3711 // We might have calculated constraints for constrained dofs
3712 // which have support on other processors.
3713 // Push these out first.
3714 {
3715 std::map<processor_id_type, std::set<dof_id_type>> pushed_ids;
3716
3717#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
3718 std::map<processor_id_type, std::set<dof_id_type>> pushed_node_ids;
3719#endif
3720
3721 const unsigned int sys_num = this->sys_number();
3722
3723 // Collect the constraints to push to each processor
3724 for (auto & elem : as_range(mesh.active_not_local_elements_begin(),
3725 mesh.active_not_local_elements_end()))
3726 {
3727 const unsigned short n_nodes = elem->n_nodes();
3728
3729 // Just checking dof_indices on the foreign element isn't
3730 // enough. Consider a central hanging node between a coarse
3731 // Q2/Q1 element and its finer neighbors on a higher-ranked
3732 // processor. The coarse element's processor will own the node,
3733 // and will thereby own the pressure dof on that node, despite
3734 // the fact that that pressure dof doesn't directly exist on the
3735 // coarse element!
3736 //
3737 // So, we loop through dofs manually.
3738
3739 {
3740 const unsigned int n_vars = elem->n_vars(sys_num);
3741 for (unsigned int v=0; v != n_vars; ++v)
3742 {
3743 const unsigned int n_comp = elem->n_comp(sys_num,v);
3744 for (unsigned int c=0; c != n_comp; ++c)
3745 {
3746 const unsigned int id =
3747 elem->dof_number(sys_num,v,c);
3748 if (this->is_constrained_dof(id))
3749 pushed_ids[elem->processor_id()].insert(id);
3750 }
3751 }
3752 }
3753
3754 for (unsigned short n = 0; n != n_nodes; ++n)
3755 {
3756 const Node & node = elem->node_ref(n);
3757 const unsigned int n_vars = node.n_vars(sys_num);
3758 for (unsigned int v=0; v != n_vars; ++v)
3759 {
3760 const unsigned int n_comp = node.n_comp(sys_num,v);
3761 for (unsigned int c=0; c != n_comp; ++c)
3762 {
3763 const unsigned int id =
3764 node.dof_number(sys_num,v,c);
3765 if (this->is_constrained_dof(id))
3766 pushed_ids[elem->processor_id()].insert(id);
3767 }
3768 }
3769 }
3770
3771#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
3772 for (unsigned short n = 0; n != n_nodes; ++n)
3773 if (this->is_constrained_node(elem->node_ptr(n)))
3774 pushed_node_ids[elem->processor_id()].insert(elem->node_id(n));
3775#endif
3776 }
3777
3778 // Rewrite those id sets as vectors for sending and receiving,
3779 // then find the corresponding data for each id, then push it all.
3780 std::map<processor_id_type, std::vector<dof_id_type>>
3781 pushed_id_vecs, received_id_vecs;
3782 for (auto & p : pushed_ids)
3783 pushed_id_vecs[p.first].assign(p.second.begin(), p.second.end());
3784
3785 std::map<processor_id_type, std::vector<std::vector<std::pair<dof_id_type,Real>>>>
3786 pushed_keys_vals, received_keys_vals;
3787 std::map<processor_id_type, std::vector<std::vector<Number>>> pushed_rhss, received_rhss;
3788 for (auto & p : pushed_id_vecs)
3789 {
3790 auto & keys_vals = pushed_keys_vals[p.first];
3791 keys_vals.reserve(p.second.size());
3792
3793 auto & rhss = pushed_rhss[p.first];
3794 rhss.reserve(p.second.size());
3795 for (auto & pushed_id : p.second)
3796 {
3797 const DofConstraintRow & row = _dof_constraints[pushed_id];
3798 keys_vals.emplace_back(row.begin(), row.end());
3799
3800 rhss.push_back(std::vector<Number>(max_qoi_num+1));
3801 std::vector<Number> & rhs = rhss.back();
3802 DofConstraintValueMap::const_iterator rhsit =
3803 _primal_constraint_values.find(pushed_id);
3804 rhs[max_qoi_num] =
3805 (rhsit == _primal_constraint_values.end()) ?
3806 0 : rhsit->second;
3807 for (unsigned int q = 0; q != max_qoi_num; ++q)
3808 {
3809 AdjointDofConstraintValues::const_iterator adjoint_map_it =
3811
3812 if (adjoint_map_it == _adjoint_constraint_values.end())
3813 continue;
3814
3815 const DofConstraintValueMap & constraint_map =
3816 adjoint_map_it->second;
3817
3818 DofConstraintValueMap::const_iterator adj_rhsit =
3819 constraint_map.find(pushed_id);
3820
3821 rhs[q] =
3822 (adj_rhsit == constraint_map.end()) ?
3823 0 : adj_rhsit->second;
3824 }
3825 }
3826 }
3827
3828 auto ids_action_functor =
3829 [& received_id_vecs]
3830 (processor_id_type pid,
3831 const std::vector<dof_id_type> & data)
3832 {
3833 received_id_vecs[pid] = data;
3834 };
3835
3837 (this->comm(), pushed_id_vecs, ids_action_functor);
3838
3839 auto keys_vals_action_functor =
3840 [& received_keys_vals]
3841 (processor_id_type pid,
3842 const std::vector<std::vector<std::pair<dof_id_type,Real>>> & data)
3843 {
3844 received_keys_vals[pid] = data;
3845 };
3846
3848 (this->comm(), pushed_keys_vals, keys_vals_action_functor);
3849
3850 auto rhss_action_functor =
3851 [& received_rhss]
3852 (processor_id_type pid,
3853 const std::vector<std::vector<Number>> & data)
3854 {
3855 received_rhss[pid] = data;
3856 };
3857
3859 (this->comm(), pushed_rhss, rhss_action_functor);
3860
3861 // Now we have all the DofConstraint rows and rhs values received
3862 // from others, so add the DoF constraints that we've been sent
3863
3864#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
3865 std::map<processor_id_type, std::vector<dof_id_type>>
3866 pushed_node_id_vecs, received_node_id_vecs;
3867 for (auto & p : pushed_node_ids)
3868 pushed_node_id_vecs[p.first].assign(p.second.begin(), p.second.end());
3869
3870 std::map<processor_id_type, std::vector<std::vector<std::pair<dof_id_type,Real>>>>
3871 pushed_node_keys_vals, received_node_keys_vals;
3872 std::map<processor_id_type, std::vector<Point>> pushed_offsets, received_offsets;
3873
3874 for (auto & p : pushed_node_id_vecs)
3875 {
3876 const processor_id_type pid = p.first;
3877
3878 // FIXME - this could be an unordered set, given a
3879 // hash<pointers> specialization
3880 std::set<const Node *> nodes_requested;
3881
3882 auto & node_keys_vals = pushed_node_keys_vals[pid];
3883 node_keys_vals.reserve(p.second.size());
3884
3885 auto & offsets = pushed_offsets[pid];
3886 offsets.reserve(p.second.size());
3887
3888 for (auto & pushed_node_id : p.second)
3889 {
3890 const Node * node = mesh.node_ptr(pushed_node_id);
3891 NodeConstraintRow & row = _node_constraints[node].first;
3892 const std::size_t row_size = row.size();
3893 node_keys_vals.push_back
3894 (std::vector<std::pair<dof_id_type,Real>>());
3895 std::vector<std::pair<dof_id_type,Real>> & this_node_kv =
3896 node_keys_vals.back();
3897 this_node_kv.reserve(row_size);
3898 for (const auto & j : row)
3899 {
3900 this_node_kv.emplace_back(j.first->id(), j.second);
3901
3902 // If we're not sure whether our send
3903 // destination already has this node, let's give
3904 // it a copy.
3905 if (j.first->processor_id() != pid && dist_mesh)
3906 nodes_requested.insert(j.first);
3907 }
3908
3909 offsets.push_back(_node_constraints[node].second);
3910
3911 }
3912
3913 // Constraining nodes might not even exist on our
3914 // correspondant's subset of a distributed mesh, so let's
3915 // make them exist.
3916 if (dist_mesh)
3917 {
3918 packed_range_sends.push_back(Parallel::Request());
3919 this->comm().send_packed_range
3920 (pid, &mesh, nodes_requested.begin(), nodes_requested.end(),
3921 packed_range_sends.back(), range_tag);
3922 }
3923 }
3924
3925 auto node_ids_action_functor =
3926 [& received_node_id_vecs]
3927 (processor_id_type pid,
3928 const std::vector<dof_id_type> & data)
3929 {
3930 received_node_id_vecs[pid] = data;
3931 };
3932
3934 (this->comm(), pushed_node_id_vecs, node_ids_action_functor);
3935
3936 auto node_keys_vals_action_functor =
3937 [& received_node_keys_vals]
3938 (processor_id_type pid,
3939 const std::vector<std::vector<std::pair<dof_id_type,Real>>> & data)
3940 {
3941 received_node_keys_vals[pid] = data;
3942 };
3943
3945 (this->comm(), pushed_node_keys_vals,
3946 node_keys_vals_action_functor);
3947
3948 auto node_offsets_action_functor =
3949 [& received_offsets]
3950 (processor_id_type pid,
3951 const std::vector<Point> & data)
3952 {
3953 received_offsets[pid] = data;
3954 };
3955
3957 (this->comm(), pushed_offsets, node_offsets_action_functor);
3958
3959#endif
3960
3961 // Add all the dof constraints that I've been sent
3962 for (auto & [pid, pushed_ids_to_me] : received_id_vecs)
3963 {
3964 libmesh_assert(received_keys_vals.count(pid));
3965 libmesh_assert(received_rhss.count(pid));
3966 const auto & pushed_keys_vals_to_me = received_keys_vals.at(pid);
3967 const auto & pushed_rhss_to_me = received_rhss.at(pid);
3968
3969 libmesh_assert_equal_to (pushed_ids_to_me.size(),
3970 pushed_keys_vals_to_me.size());
3971 libmesh_assert_equal_to (pushed_ids_to_me.size(),
3972 pushed_rhss_to_me.size());
3973
3974 for (auto i : index_range(pushed_ids_to_me))
3975 {
3976 dof_id_type constrained = pushed_ids_to_me[i];
3977
3978 // If we don't already have a constraint for this dof,
3979 // add the one we were sent
3980 if (!this->is_constrained_dof(constrained))
3981 {
3982 DofConstraintRow & row = _dof_constraints[constrained];
3983 for (auto & kv : pushed_keys_vals_to_me[i])
3984 {
3985 libmesh_assert_less(kv.first, this->n_dofs());
3986 row[kv.first] = kv.second;
3987 }
3988
3989 const Number primal_rhs = pushed_rhss_to_me[i][max_qoi_num];
3990
3991 if (libmesh_isnan(primal_rhs))
3992 libmesh_assert(pushed_keys_vals_to_me[i].empty());
3993
3994 if (primal_rhs != Number(0))
3995 _primal_constraint_values[constrained] = primal_rhs;
3996 else
3997 _primal_constraint_values.erase(constrained);
3998
3999 for (unsigned int q = 0; q != max_qoi_num; ++q)
4000 {
4001 AdjointDofConstraintValues::iterator adjoint_map_it =
4003
4004 const Number adj_rhs = pushed_rhss_to_me[i][q];
4005
4006 if ((adjoint_map_it == _adjoint_constraint_values.end()) &&
4007 adj_rhs == Number(0))
4008 continue;
4009
4010 if (adjoint_map_it == _adjoint_constraint_values.end())
4011 adjoint_map_it = _adjoint_constraint_values.emplace
4012 (q, DofConstraintValueMap()).first;
4013
4014 DofConstraintValueMap & constraint_map =
4015 adjoint_map_it->second;
4016
4017 if (adj_rhs != Number(0))
4018 constraint_map[constrained] = adj_rhs;
4019 else
4020 constraint_map.erase(constrained);
4021 }
4022 }
4023 }
4024 }
4025
4026#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
4027 // Add all the node constraints that I've been sent
4028 for (auto & [pid, pushed_node_ids_to_me] : received_node_id_vecs)
4029 {
4030 // Before we act on any new constraint rows, we may need to
4031 // make sure we have all the nodes involved!
4032 if (dist_mesh)
4035 (Node**)nullptr, range_tag);
4036
4037 libmesh_assert(received_node_keys_vals.count(pid));
4038 libmesh_assert(received_offsets.count(pid));
4039 const auto & pushed_node_keys_vals_to_me = received_node_keys_vals.at(pid);
4040 const auto & pushed_offsets_to_me = received_offsets.at(pid);
4041
4042 libmesh_assert_equal_to (pushed_node_ids_to_me.size(),
4043 pushed_node_keys_vals_to_me.size());
4044 libmesh_assert_equal_to (pushed_node_ids_to_me.size(),
4045 pushed_offsets_to_me.size());
4046
4047 for (auto i : index_range(pushed_node_ids_to_me))
4048 {
4049 dof_id_type constrained_id = pushed_node_ids_to_me[i];
4050
4051 // If we don't already have a constraint for this node,
4052 // add the one we were sent
4053 const Node * constrained = mesh.node_ptr(constrained_id);
4054 if (!this->is_constrained_node(constrained))
4055 {
4056 NodeConstraintRow & row = _node_constraints[constrained].first;
4057 for (auto & kv : pushed_node_keys_vals_to_me[i])
4058 {
4059 const Node * key_node = mesh.node_ptr(kv.first);
4060 libmesh_assert(key_node);
4061 row[key_node] = kv.second;
4062 }
4063 _node_constraints[constrained].second = pushed_offsets_to_me[i];
4064 }
4065 }
4066 }
4067#endif // LIBMESH_ENABLE_NODE_CONSTRAINTS
4068 }
4069
4070 // Now start checking for any other constraints we need
4071 // to know about, requesting them recursively.
4072
4073 // Create sets containing the DOFs and nodes we already depend on
4074 typedef std::set<dof_id_type> DoF_RCSet;
4075 DoF_RCSet unexpanded_dofs;
4076
4077 for (const auto & i : _dof_constraints)
4078 unexpanded_dofs.insert(i.first);
4079
4080 // Gather all the dof constraints we need
4081 this->gather_constraints(mesh, unexpanded_dofs, false);
4082
4083 // Gather all the node constraints we need
4084#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
4085 typedef std::set<const Node *> Node_RCSet;
4086 Node_RCSet unexpanded_nodes;
4087
4088 for (const auto & i : _node_constraints)
4089 unexpanded_nodes.insert(i.first);
4090
4091 // We have to keep recursing while the unexpanded set is
4092 // nonempty on *any* processor
4093 bool unexpanded_set_nonempty = !unexpanded_nodes.empty();
4094 this->comm().max(unexpanded_set_nonempty);
4095
4096 while (unexpanded_set_nonempty)
4097 {
4098 // Let's make sure we don't lose sync in this loop.
4099 parallel_object_only();
4100
4101 // Request sets
4102 Node_RCSet node_request_set;
4103
4104 // Request sets to send to each processor
4105 std::map<processor_id_type, std::vector<dof_id_type>>
4106 requested_node_ids;
4107
4108 // And the sizes of each
4109 std::map<processor_id_type, dof_id_type> node_ids_on_proc;
4110
4111 // Fill (and thereby sort and uniq!) the main request sets
4112 for (const auto & i : unexpanded_nodes)
4113 {
4114 NodeConstraintRow & row = _node_constraints[i].first;
4115 for (const auto & j : row)
4116 {
4117 const Node * const node = j.first;
4118 libmesh_assert(node);
4119
4120 // If it's non-local and we haven't already got a
4121 // constraint for it, we might need to ask for one
4122 if ((node->processor_id() != this->processor_id()) &&
4123 !_node_constraints.count(node))
4124 node_request_set.insert(node);
4125 }
4126 }
4127
4128 // Clear the unexpanded constraint sets; we're about to expand
4129 // them
4130 unexpanded_nodes.clear();
4131
4132 // Count requests by processor
4133 for (const auto & node : node_request_set)
4134 {
4135 libmesh_assert(node);
4136 libmesh_assert_less (node->processor_id(), this->n_processors());
4137 node_ids_on_proc[node->processor_id()]++;
4138 }
4139
4140 for (auto pair : node_ids_on_proc)
4141 requested_node_ids[pair.first].reserve(pair.second);
4142
4143 // Prepare each processor's request set
4144 for (const auto & node : node_request_set)
4145 requested_node_ids[node->processor_id()].push_back(node->id());
4146
4147 typedef std::vector<std::pair<dof_id_type, Real>> row_datum;
4148
4149 auto node_row_gather_functor =
4150 [this,
4151 & mesh,
4152 dist_mesh,
4153 & packed_range_sends,
4154 & range_tag]
4155 (processor_id_type pid,
4156 const std::vector<dof_id_type> & ids,
4157 std::vector<row_datum> & data)
4158 {
4159 // FIXME - this could be an unordered set, given a
4160 // hash<pointers> specialization
4161 std::set<const Node *> nodes_requested;
4162
4163 // Fill those requests
4164 const std::size_t query_size = ids.size();
4165
4166 data.resize(query_size);
4167 for (std::size_t i=0; i != query_size; ++i)
4168 {
4169 dof_id_type constrained_id = ids[i];
4170 const Node * constrained_node = mesh.node_ptr(constrained_id);
4171 if (_node_constraints.count(constrained_node))
4172 {
4173 const NodeConstraintRow & row = _node_constraints[constrained_node].first;
4174 std::size_t row_size = row.size();
4175 data[i].reserve(row_size);
4176 for (const auto & j : row)
4177 {
4178 const Node * node = j.first;
4179 data[i].emplace_back(node->id(), j.second);
4180
4181 // If we're not sure whether our send
4182 // destination already has this node, let's give
4183 // it a copy.
4184 if (node->processor_id() != pid && dist_mesh)
4185 nodes_requested.insert(node);
4186
4187 // We can have 0 nodal constraint
4188 // coefficients, where no Lagrange constraint
4189 // exists but non-Lagrange basis constraints
4190 // might.
4191 // libmesh_assert(j.second);
4192 }
4193 }
4194 else
4195 {
4196 // We have to distinguish "constraint with no
4197 // constraining nodes" (e.g. due to user node
4198 // constraint equations) from "no constraint".
4199 // We'll use invalid_id for the latter.
4200 data[i].emplace_back(DofObject::invalid_id, Real(0));
4201 }
4202 }
4203
4204 // Constraining nodes might not even exist on our
4205 // correspondant's subset of a distributed mesh, so let's
4206 // make them exist.
4207 if (dist_mesh)
4208 {
4209 packed_range_sends.push_back(Parallel::Request());
4210 this->comm().send_packed_range
4211 (pid, &mesh, nodes_requested.begin(), nodes_requested.end(),
4212 packed_range_sends.back(), range_tag);
4213 }
4214 };
4215
4216 typedef Point node_rhs_datum;
4217
4218 auto node_rhs_gather_functor =
4219 [this,
4220 & mesh]
4222 const std::vector<dof_id_type> & ids,
4223 std::vector<node_rhs_datum> & data)
4224 {
4225 // Fill those requests
4226 const std::size_t query_size = ids.size();
4227
4228 data.resize(query_size);
4229 for (std::size_t i=0; i != query_size; ++i)
4230 {
4231 dof_id_type constrained_id = ids[i];
4232 const Node * constrained_node = mesh.node_ptr(constrained_id);
4233 if (_node_constraints.count(constrained_node))
4234 data[i] = _node_constraints[constrained_node].second;
4235 else
4236 data[i](0) = std::numeric_limits<Real>::quiet_NaN();
4237 }
4238 };
4239
4240 auto node_row_action_functor =
4241 [this,
4242 & mesh,
4243 dist_mesh,
4244 & range_tag,
4245 & unexpanded_nodes]
4246 (processor_id_type pid,
4247 const std::vector<dof_id_type> & ids,
4248 const std::vector<row_datum> & data)
4249 {
4250 // Before we act on any new constraint rows, we may need to
4251 // make sure we have all the nodes involved!
4252 if (dist_mesh)
4255 (Node**)nullptr, range_tag);
4256
4257 // Add any new constraint rows we've found
4258 const std::size_t query_size = ids.size();
4259
4260 for (std::size_t i=0; i != query_size; ++i)
4261 {
4262 const dof_id_type constrained_id = ids[i];
4263
4264 // An empty row is an constraint with an empty row; for
4265 // no constraint we use a "no row" placeholder
4266 if (data[i].empty())
4267 {
4268 const Node * constrained_node = mesh.node_ptr(constrained_id);
4269 NodeConstraintRow & row = _node_constraints[constrained_node].first;
4270 row.clear();
4271 }
4272 else if (data[i][0].first != DofObject::invalid_id)
4273 {
4274 const Node * constrained_node = mesh.node_ptr(constrained_id);
4275 NodeConstraintRow & row = _node_constraints[constrained_node].first;
4276 row.clear();
4277 for (auto & pair : data[i])
4278 {
4279 const Node * key_node =
4280 mesh.node_ptr(pair.first);
4281 libmesh_assert(key_node);
4282 row[key_node] = pair.second;
4283 }
4284
4285 // And prepare to check for more recursive constraints
4286 unexpanded_nodes.insert(constrained_node);
4287 }
4288 }
4289 };
4290
4291 auto node_rhs_action_functor =
4292 [this,
4293 & mesh]
4295 const std::vector<dof_id_type> & ids,
4296 const std::vector<node_rhs_datum> & data)
4297 {
4298 // Add rhs data for any new node constraint rows we've found
4299 const std::size_t query_size = ids.size();
4300
4301 for (std::size_t i=0; i != query_size; ++i)
4302 {
4303 dof_id_type constrained_id = ids[i];
4304 const Node * constrained_node = mesh.node_ptr(constrained_id);
4305
4306 if (!libmesh_isnan(data[i](0)))
4307 _node_constraints[constrained_node].second = data[i];
4308 else
4309 _node_constraints.erase(constrained_node);
4310 }
4311 };
4312
4313 // Now request node constraint rows from other processors
4314 row_datum * node_row_ex = nullptr;
4316 (this->comm(), requested_node_ids, node_row_gather_functor,
4317 node_row_action_functor, node_row_ex);
4318
4319 // And request node constraint right hand sides from other procesors
4320 node_rhs_datum * node_rhs_ex = nullptr;
4322 (this->comm(), requested_node_ids, node_rhs_gather_functor,
4323 node_rhs_action_functor, node_rhs_ex);
4324
4325
4326 // We have to keep recursing while the unexpanded set is
4327 // nonempty on *any* processor
4328 unexpanded_set_nonempty = !unexpanded_nodes.empty();
4329 this->comm().max(unexpanded_set_nonempty);
4330 }
4331 Parallel::wait(packed_range_sends);
4332#endif // LIBMESH_ENABLE_NODE_CONSTRAINTS
4333}
4334
4335
4336
4338{
4339 // We've computed our local constraints, but they may depend on
4340 // non-local constraints that we'll need to take into account.
4342
4344 {
4345 // Optionally check for constraint loops and throw an error
4346 // if they're detected. We always do this check below in dbg/devel
4347 // mode but here we optionally do it in opt mode as well.
4349 }
4350
4351 // Adjoints will be constrained where the primal is
4352 // Therefore, we will expand the adjoint_constraint_values
4353 // map whenever the primal_constraint_values map is expanded
4354
4355 // First, figure out the total number of QoIs
4356 const unsigned int max_qoi_num =
4358 0 : _adjoint_constraint_values.rbegin()->first+1;
4359
4360 // Create a set containing the DOFs we already depend on
4361 typedef std::set<dof_id_type> RCSet;
4362 RCSet unexpanded_set;
4363
4364 for (const auto & i : _dof_constraints)
4365 unexpanded_set.insert(i.first);
4366
4367 while (!unexpanded_set.empty())
4368 for (RCSet::iterator i = unexpanded_set.begin();
4369 i != unexpanded_set.end(); /* nothing */)
4370 {
4371 // If the DOF is constrained
4372 DofConstraints::iterator
4373 pos = _dof_constraints.find(*i);
4374
4375 libmesh_assert (pos != _dof_constraints.end());
4376
4377 DofConstraintRow & constraint_row = pos->second;
4378
4379 DofConstraintValueMap::iterator rhsit =
4381 Number constraint_rhs = (rhsit == _primal_constraint_values.end()) ?
4382 0 : rhsit->second;
4383
4384 // A vector of DofConstraintValueMaps for each adjoint variable
4385 std::vector<DofConstraintValueMap::iterator> adjoint_rhs_iterators;
4386 adjoint_rhs_iterators.resize(max_qoi_num);
4387
4388 // Another to hold the adjoint constraint rhs
4389 std::vector<Number> adjoint_constraint_rhs(max_qoi_num, 0.0);
4390
4391 // Find and gather recursive constraints for each adjoint variable
4392 for (auto & adjoint_map : _adjoint_constraint_values)
4393 {
4394 const std::size_t q = adjoint_map.first;
4395 adjoint_rhs_iterators[q] = adjoint_map.second.find(*i);
4396
4397 adjoint_constraint_rhs[q] =
4398 (adjoint_rhs_iterators[q] == adjoint_map.second.end()) ?
4399 0 : adjoint_rhs_iterators[q]->second;
4400 }
4401
4402 std::vector<dof_id_type> constraints_to_expand;
4403
4404 for (const auto & item : constraint_row)
4405 if (item.first != *i && this->is_constrained_dof(item.first))
4406 {
4407 unexpanded_set.insert(item.first);
4408 constraints_to_expand.push_back(item.first);
4409 }
4410
4411 for (const auto & expandable : constraints_to_expand)
4412 {
4413 const Real this_coef = constraint_row[expandable];
4414
4415 DofConstraints::const_iterator
4416 subpos = _dof_constraints.find(expandable);
4417
4418 libmesh_assert (subpos != _dof_constraints.end());
4419
4420 const DofConstraintRow & subconstraint_row = subpos->second;
4421
4422 for (const auto & item : subconstraint_row)
4423 {
4424 // Assert that the constraint does not form a cycle.
4425 libmesh_assert(item.first != expandable);
4426 constraint_row[item.first] += item.second * this_coef;
4427 }
4428
4429 if (auto subrhsit = _primal_constraint_values.find(expandable);
4430 subrhsit != _primal_constraint_values.end())
4431 constraint_rhs += subrhsit->second * this_coef;
4432
4433 // Find and gather recursive constraints for each adjoint variable
4434 for (const auto & adjoint_map : _adjoint_constraint_values)
4435 {
4436 if (auto adjoint_subrhsit = adjoint_map.second.find(expandable);
4437 adjoint_subrhsit != adjoint_map.second.end())
4438 adjoint_constraint_rhs[adjoint_map.first] += adjoint_subrhsit->second * this_coef;
4439 }
4440
4441 constraint_row.erase(expandable);
4442 }
4443
4444 if (rhsit == _primal_constraint_values.end())
4445 {
4446 if (constraint_rhs != Number(0))
4447 _primal_constraint_values[*i] = constraint_rhs;
4448 else
4449 _primal_constraint_values.erase(*i);
4450 }
4451 else
4452 {
4453 if (constraint_rhs != Number(0))
4454 rhsit->second = constraint_rhs;
4455 else
4456 _primal_constraint_values.erase(rhsit);
4457 }
4458
4459 // Finally fill in the adjoint constraints for each adjoint variable if possible
4460 for (auto & adjoint_map : _adjoint_constraint_values)
4461 {
4462 const std::size_t q = adjoint_map.first;
4463
4464 if(adjoint_rhs_iterators[q] == adjoint_map.second.end())
4465 {
4466 if (adjoint_constraint_rhs[q] != Number(0))
4467 (adjoint_map.second)[*i] = adjoint_constraint_rhs[q];
4468 else
4469 adjoint_map.second.erase(*i);
4470 }
4471 else
4472 {
4473 if (adjoint_constraint_rhs[q] != Number(0))
4474 adjoint_rhs_iterators[q]->second = adjoint_constraint_rhs[q];
4475 else
4476 adjoint_map.second.erase(adjoint_rhs_iterators[q]);
4477 }
4478 }
4479
4480 if (constraints_to_expand.empty())
4481 i = unexpanded_set.erase(i);
4482 else
4483 ++i;
4484 }
4485
4486 // In parallel we can't guarantee that nodes/dofs which constrain
4487 // others are on processors which are aware of that constraint, yet
4488 // we need such awareness for sparsity pattern generation. So send
4489 // other processors any constraints they might need to know about.
4490 this->scatter_constraints(mesh);
4491
4492 // Now that we have our root constraint dependencies sorted out, add
4493 // them to the send_list
4494 this->add_constraints_to_send_list(mesh);
4495}
4496
4497
4498#ifdef LIBMESH_ENABLE_CONSTRAINTS
4500{
4501 // Eventually make this officially libmesh_deprecated();
4503}
4504
4506{
4507 // Create a set containing the DOFs we already depend on
4508 typedef std::set<dof_id_type> RCSet;
4509 RCSet unexpanded_set;
4510
4511 // Use dof_constraints_copy in this method so that we don't
4512 // mess with _dof_constraints.
4513 DofConstraints dof_constraints_copy = _dof_constraints;
4514
4515 for (const auto & i : dof_constraints_copy)
4516 unexpanded_set.insert(i.first);
4517
4518 while (!unexpanded_set.empty())
4519 for (RCSet::iterator i = unexpanded_set.begin();
4520 i != unexpanded_set.end(); /* nothing */)
4521 {
4522 // If the DOF is constrained
4523 DofConstraints::iterator
4524 pos = dof_constraints_copy.find(*i);
4525
4526 libmesh_assert (pos != dof_constraints_copy.end());
4527
4528 DofConstraintRow & constraint_row = pos->second;
4529
4530 // Comment out "rhs" parts of this method copied from process_constraints
4531 // DofConstraintValueMap::iterator rhsit =
4532 // _primal_constraint_values.find(*i);
4533 // Number constraint_rhs = (rhsit == _primal_constraint_values.end()) ?
4534 // 0 : rhsit->second;
4535
4536 std::vector<dof_id_type> constraints_to_expand;
4537
4538 for (const auto & item : constraint_row)
4539 if (item.first != *i && this->is_constrained_dof(item.first))
4540 {
4541 unexpanded_set.insert(item.first);
4542 constraints_to_expand.push_back(item.first);
4543 }
4544
4545 for (const auto & expandable : constraints_to_expand)
4546 {
4547 const Real this_coef = constraint_row[expandable];
4548
4549 DofConstraints::const_iterator
4550 subpos = dof_constraints_copy.find(expandable);
4551
4552 libmesh_assert (subpos != dof_constraints_copy.end());
4553
4554 const DofConstraintRow & subconstraint_row = subpos->second;
4555
4556 for (const auto & item : subconstraint_row)
4557 {
4558 libmesh_error_msg_if(item.first == expandable, "Constraint loop detected");
4559
4560 constraint_row[item.first] += item.second * this_coef;
4561 }
4562
4563 // Comment out "rhs" parts of this method copied from process_constraints
4564 // DofConstraintValueMap::const_iterator subrhsit =
4565 // _primal_constraint_values.find(expandable);
4566 // if (subrhsit != _primal_constraint_values.end())
4567 // constraint_rhs += subrhsit->second * this_coef;
4568
4569 constraint_row.erase(expandable);
4570 }
4571
4572 // Comment out "rhs" parts of this method copied from process_constraints
4573 // if (rhsit == _primal_constraint_values.end())
4574 // {
4575 // if (constraint_rhs != Number(0))
4576 // _primal_constraint_values[*i] = constraint_rhs;
4577 // else
4578 // _primal_constraint_values.erase(*i);
4579 // }
4580 // else
4581 // {
4582 // if (constraint_rhs != Number(0))
4583 // rhsit->second = constraint_rhs;
4584 // else
4585 // _primal_constraint_values.erase(rhsit);
4586 // }
4587
4588 if (constraints_to_expand.empty())
4589 i = unexpanded_set.erase(i);
4590 else
4591 ++i;
4592 }
4593}
4594#else
4597{
4598 // Do nothing
4599}
4600#endif
4601
4602
4604{
4605 // At this point each processor with a constrained node knows
4606 // the corresponding constraint row, but we also need each processor
4607 // with a constrainer node to know the corresponding row(s).
4608
4609 // This function must be run on all processors at once
4610 parallel_object_only();
4611
4612 // Return immediately if there's nothing to gather
4613 if (this->n_processors() == 1)
4614 return;
4615
4616 // We might get to return immediately if none of the processors
4617 // found any constraints
4618 unsigned int has_constraints = !_dof_constraints.empty()
4619#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
4620 || !_node_constraints.empty()
4621#endif // LIBMESH_ENABLE_NODE_CONSTRAINTS
4622 ;
4623 this->comm().max(has_constraints);
4624 if (!has_constraints)
4625 return;
4626
4627 // We may be receiving packed_range sends out of order with
4628 // parallel_sync tags, so make sure they're received correctly.
4629 Parallel::MessageTag range_tag = this->comm().get_unique_tag();
4630
4631#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
4632 std::map<processor_id_type, std::set<dof_id_type>> pushed_node_ids;
4633#endif // LIBMESH_ENABLE_NODE_CONSTRAINTS
4634
4635 std::map<processor_id_type, std::set<dof_id_type>> pushed_ids;
4636
4637 // Collect the dof constraints I need to push to each processor
4638 dof_id_type constrained_proc_id = 0;
4639 for (const auto & [constrained, row] : _dof_constraints)
4640 {
4641 while (constrained >= _end_df[constrained_proc_id])
4642 constrained_proc_id++;
4643
4644 if (constrained_proc_id != this->processor_id())
4645 continue;
4646
4647 for (auto & j : row)
4648 {
4649 const dof_id_type constraining = j.first;
4650
4651 processor_id_type constraining_proc_id = 0;
4652 while (constraining >= _end_df[constraining_proc_id])
4653 constraining_proc_id++;
4654
4655 if (constraining_proc_id != this->processor_id() &&
4656 constraining_proc_id != constrained_proc_id)
4657 pushed_ids[constraining_proc_id].insert(constrained);
4658 }
4659 }
4660
4661 // Pack the dof constraint rows and rhs's to push
4662
4663 std::map<processor_id_type,
4664 std::vector<std::vector<std::pair<dof_id_type, Real>>>>
4665 pushed_keys_vals, pushed_keys_vals_to_me;
4666
4667 std::map<processor_id_type, std::vector<std::pair<dof_id_type, Number>>>
4668 pushed_ids_rhss, pushed_ids_rhss_to_me;
4669
4670 auto gather_ids =
4671 [this,
4672 & pushed_ids,
4673 & pushed_keys_vals,
4674 & pushed_ids_rhss]
4675 ()
4676 {
4677 for (const auto & [pid, pid_ids] : pushed_ids)
4678 {
4679 const std::size_t ids_size = pid_ids.size();
4680 std::vector<std::vector<std::pair<dof_id_type, Real>>> &
4681 keys_vals = pushed_keys_vals[pid];
4682 std::vector<std::pair<dof_id_type,Number>> &
4683 ids_rhss = pushed_ids_rhss[pid];
4684 keys_vals.resize(ids_size);
4685 ids_rhss.resize(ids_size);
4686
4687 std::size_t push_i;
4688 std::set<dof_id_type>::const_iterator it;
4689 for (push_i = 0, it = pid_ids.begin();
4690 it != pid_ids.end(); ++push_i, ++it)
4691 {
4692 const dof_id_type constrained = *it;
4693 DofConstraintRow & row = _dof_constraints[constrained];
4694 keys_vals[push_i].assign(row.begin(), row.end());
4695
4696 DofConstraintValueMap::const_iterator rhsit =
4697 _primal_constraint_values.find(constrained);
4698 ids_rhss[push_i].first = constrained;
4699 ids_rhss[push_i].second =
4700 (rhsit == _primal_constraint_values.end()) ?
4701 0 : rhsit->second;
4702 }
4703 }
4704 };
4705
4706 gather_ids();
4707
4708 auto ids_rhss_action_functor =
4709 [& pushed_ids_rhss_to_me]
4710 (processor_id_type pid,
4711 const std::vector<std::pair<dof_id_type, Number>> & data)
4712 {
4713 pushed_ids_rhss_to_me[pid] = data;
4714 };
4715
4716 auto keys_vals_action_functor =
4717 [& pushed_keys_vals_to_me]
4718 (processor_id_type pid,
4719 const std::vector<std::vector<std::pair<dof_id_type, Real>>> & data)
4720 {
4721 pushed_keys_vals_to_me[pid] = data;
4722 };
4723
4725 (this->comm(), pushed_ids_rhss, ids_rhss_action_functor);
4727 (this->comm(), pushed_keys_vals, keys_vals_action_functor);
4728
4729 // Now work on traded dof constraint rows
4730 auto receive_dof_constraints =
4731 [this,
4732 & pushed_ids_rhss_to_me,
4733 & pushed_keys_vals_to_me]
4734 ()
4735 {
4736 for (const auto & [pid, ids_rhss] : pushed_ids_rhss_to_me)
4737 {
4738 const auto & keys_vals = pushed_keys_vals_to_me[pid];
4739
4740 libmesh_assert_equal_to
4741 (ids_rhss.size(), keys_vals.size());
4742
4743 // Add the dof constraints that I've been sent
4744 for (auto i : index_range(ids_rhss))
4745 {
4746 dof_id_type constrained = ids_rhss[i].first;
4747
4748 // If we don't already have a constraint for this dof,
4749 // add the one we were sent
4750 if (!this->is_constrained_dof(constrained))
4751 {
4752 DofConstraintRow & row = _dof_constraints[constrained];
4753 for (auto & key_val : keys_vals[i])
4754 {
4755 libmesh_assert_less(key_val.first, this->n_dofs());
4756 row[key_val.first] = key_val.second;
4757 }
4758 if (ids_rhss[i].second != Number(0))
4759 _primal_constraint_values[constrained] =
4760 ids_rhss[i].second;
4761 else
4762 _primal_constraint_values.erase(constrained);
4763 }
4764 }
4765 }
4766 };
4767
4768 receive_dof_constraints();
4769
4770#ifdef LIBMESH_ENABLE_NODE_CONSTRAINTS
4771 // Collect the node constraints to push to each processor
4772 for (auto & i : _node_constraints)
4773 {
4774 const Node * constrained = i.first;
4775
4776 if (constrained->processor_id() != this->processor_id())
4777 continue;
4778
4779 NodeConstraintRow & row = i.second.first;
4780 for (auto & j : row)
4781 {
4782 const Node * constraining = j.first;
4783
4784 if (constraining->processor_id() != this->processor_id() &&
4785 constraining->processor_id() != constrained->processor_id())
4786 pushed_node_ids[constraining->processor_id()].insert(constrained->id());
4787 }
4788 }
4789
4790 // Pack the node constraint rows and rhss to push
4791 std::map<processor_id_type,
4792 std::vector<std::vector<std::pair<dof_id_type,Real>>>>
4793 pushed_node_keys_vals, pushed_node_keys_vals_to_me;
4794 std::map<processor_id_type, std::vector<std::pair<dof_id_type, Point>>>
4795 pushed_node_ids_offsets, pushed_node_ids_offsets_to_me;
4796 std::map<processor_id_type, std::vector<const Node *>> pushed_node_vecs;
4797
4798 for (const auto & [pid, pid_ids]: pushed_node_ids)
4799 {
4800 const std::size_t ids_size = pid_ids.size();
4801 std::vector<std::vector<std::pair<dof_id_type,Real>>> &
4802 keys_vals = pushed_node_keys_vals[pid];
4803 std::vector<std::pair<dof_id_type, Point>> &
4804 ids_offsets = pushed_node_ids_offsets[pid];
4805 keys_vals.resize(ids_size);
4806 ids_offsets.resize(ids_size);
4807 std::set<Node *> nodes;
4808
4809 std::size_t push_i;
4810 std::set<dof_id_type>::const_iterator it;
4811 for (push_i = 0, it = pid_ids.begin();
4812 it != pid_ids.end(); ++push_i, ++it)
4813 {
4814 Node * constrained = mesh.node_ptr(*it);
4815
4816 if (constrained->processor_id() != pid)
4817 nodes.insert(constrained);
4818
4819 NodeConstraintRow & row = _node_constraints[constrained].first;
4820 std::size_t row_size = row.size();
4821 keys_vals[push_i].reserve(row_size);
4822 for (const auto & j : row)
4823 {
4824 Node * constraining = const_cast<Node *>(j.first);
4825
4826 keys_vals[push_i].emplace_back(constraining->id(), j.second);
4827
4828 if (constraining->processor_id() != pid)
4829 nodes.insert(constraining);
4830 }
4831
4832 ids_offsets[push_i].first = *it;
4833 ids_offsets[push_i].second = _node_constraints[constrained].second;
4834 }
4835
4836 if (!mesh.is_serial())
4837 {
4838 auto & pid_nodes = pushed_node_vecs[pid];
4839 pid_nodes.assign(nodes.begin(), nodes.end());
4840 }
4841 }
4842
4843 auto node_ids_offsets_action_functor =
4844 [& pushed_node_ids_offsets_to_me]
4845 (processor_id_type pid,
4846 const std::vector<std::pair<dof_id_type, Point>> & data)
4847 {
4848 pushed_node_ids_offsets_to_me[pid] = data;
4849 };
4850
4851 auto node_keys_vals_action_functor =
4852 [& pushed_node_keys_vals_to_me]
4853 (processor_id_type pid,
4854 const std::vector<std::vector<std::pair<dof_id_type, Real>>> & data)
4855 {
4856 pushed_node_keys_vals_to_me[pid] = data;
4857 };
4858
4859 // Trade pushed node constraint rows
4861 (this->comm(), pushed_node_ids_offsets, node_ids_offsets_action_functor);
4863 (this->comm(), pushed_node_keys_vals, node_keys_vals_action_functor);
4864
4865 // Constraining nodes might not even exist on our subset of a
4866 // distributed mesh, so let's make them exist.
4867
4868 // Node unpack() now automatically adds them to the context mesh
4869 auto null_node_functor = [](processor_id_type, const std::vector<const Node *> &){};
4870
4871 if (!mesh.is_serial())
4873 (this->comm(), pushed_node_vecs, &mesh, null_node_functor);
4874
4875 for (const auto & [pid, ids_offsets] : pushed_node_ids_offsets_to_me)
4876 {
4877 const auto & keys_vals = pushed_node_keys_vals_to_me[pid];
4878
4879 libmesh_assert_equal_to
4880 (ids_offsets.size(), keys_vals.size());
4881
4882 // Add the node constraints that I've been sent
4883 for (auto i : index_range(ids_offsets))
4884 {
4885 dof_id_type constrained_id = ids_offsets[i].first;
4886
4887 // If we don't already have a constraint for this node,
4888 // add the one we were sent
4889 const Node * constrained = mesh.node_ptr(constrained_id);
4890 if (!this->is_constrained_node(constrained))
4891 {
4892 NodeConstraintRow & row = _node_constraints[constrained].first;
4893 for (auto & key_val : keys_vals[i])
4894 {
4895 const Node * key_node = mesh.node_ptr(key_val.first);
4896 row[key_node] = key_val.second;
4897 }
4898 _node_constraints[constrained].second =
4899 ids_offsets[i].second;
4900 }
4901 }
4902 }
4903#endif // LIBMESH_ENABLE_NODE_CONSTRAINTS
4904
4905 // Next we need to push constraints to processors which don't own
4906 // the constrained dof, don't own the constraining dof, but own an
4907 // element supporting the constraining dof.
4908 //
4909 // We need to be able to quickly look up constrained dof ids by what
4910 // constrains them, so that we can handle the case where we see a
4911 // foreign element containing one of our constraining DoF ids and we
4912 // need to push that constraint.
4913 //
4914 // Getting distributed adaptive sparsity patterns right is hard.
4915
4916 typedef std::map<dof_id_type, std::set<dof_id_type>> DofConstrainsMap;
4917 DofConstrainsMap dof_id_constrains;
4918
4919 for (const auto & [constrained, row] : _dof_constraints)
4920 {
4921 for (const auto & j : row)
4922 {
4923 const dof_id_type constraining = j.first;
4924
4925 dof_id_type constraining_proc_id = 0;
4926 while (constraining >= _end_df[constraining_proc_id])
4927 constraining_proc_id++;
4928
4929 if (constraining_proc_id == this->processor_id())
4930 dof_id_constrains[constraining].insert(constrained);
4931 }
4932 }
4933
4934 // Loop over all foreign elements, find any supporting our
4935 // constrained dof indices.
4936 pushed_ids.clear();
4937
4938 for (const auto & elem : as_range(mesh.active_not_local_elements_begin(),
4939 mesh.active_not_local_elements_end()))
4940 {
4941 std::vector<dof_id_type> my_dof_indices;
4942 this->dof_indices (elem, my_dof_indices);
4943
4944 for (const auto & dof : my_dof_indices)
4945 {
4946 if (auto dcmi = dof_id_constrains.find(dof);
4947 dcmi != dof_id_constrains.end())
4948 {
4949 for (const auto & constrained : dcmi->second)
4950 {
4951 dof_id_type the_constrained_proc_id = 0;
4952 while (constrained >= _end_df[the_constrained_proc_id])
4953 the_constrained_proc_id++;
4954
4955 const processor_id_type elemproc = elem->processor_id();
4956 if (elemproc != the_constrained_proc_id)
4957 pushed_ids[elemproc].insert(constrained);
4958 }
4959 }
4960 }
4961 }
4962
4963 pushed_ids_rhss.clear();
4964 pushed_ids_rhss_to_me.clear();
4965 pushed_keys_vals.clear();
4966 pushed_keys_vals_to_me.clear();
4967
4968 gather_ids();
4969
4970 // Trade pushed dof constraint rows
4972 (this->comm(), pushed_ids_rhss, ids_rhss_action_functor);
4974 (this->comm(), pushed_keys_vals, keys_vals_action_functor);
4975
4976 receive_dof_constraints();
4977
4978 // Finally, we need to handle the case of remote dof coupling. If a
4979 // processor's element is coupled to a ghost element, then the
4980 // processor needs to know about all constraints which affect the
4981 // dofs on that ghost element, so we'll have to query the ghost
4982 // element's owner.
4983
4984 GhostingFunctor::map_type elements_to_couple;
4985 DofMap::CouplingMatricesSet temporary_coupling_matrices;
4986
4988 (elements_to_couple,
4989 temporary_coupling_matrices,
4991 this->coupling_functors_end(),
4992 mesh.active_local_elements_begin(),
4993 mesh.active_local_elements_end(),
4994 this->processor_id());
4995
4996 // Each ghost-coupled element's owner should get a request for its dofs
4997 std::set<dof_id_type> requested_dofs;
4998
4999 for (const auto & pr : elements_to_couple)
5000 {
5001 const Elem * elem = pr.first;
5002
5003 // FIXME - optimize for the non-fully-coupled case?
5004 std::vector<dof_id_type> element_dofs;
5005 this->dof_indices(elem, element_dofs);
5006
5007 for (auto dof : element_dofs)
5008 requested_dofs.insert(dof);
5009 }
5010
5011 this->gather_constraints(mesh, requested_dofs, false);
5012}
5013
5014
5016 std::set<dof_id_type> & unexpanded_dofs,
5017 bool /*look_for_constrainees*/)
5018{
5019 typedef std::set<dof_id_type> DoF_RCSet;
5020
5021 // If we have heterogeneous adjoint constraints we need to
5022 // communicate those too.
5023 const unsigned int max_qoi_num =
5025 0 : _adjoint_constraint_values.rbegin()->first+1;
5026
5027 // We have to keep recursing while the unexpanded set is
5028 // nonempty on *any* processor
5029 bool unexpanded_set_nonempty = !unexpanded_dofs.empty();
5030 this->comm().max(unexpanded_set_nonempty);
5031
5032 while (unexpanded_set_nonempty)
5033 {
5034 // Let's make sure we don't lose sync in this loop.
5035 parallel_object_only();
5036
5037 // Request sets
5038 DoF_RCSet dof_request_set;
5039
5040 // Request sets to send to each processor
5041 std::map<processor_id_type, std::vector<dof_id_type>>
5042 requested_dof_ids;
5043
5044 // And the sizes of each
5045 std::map<processor_id_type, dof_id_type>
5046 dof_ids_on_proc;
5047
5048 // Fill (and thereby sort and uniq!) the main request sets
5049 for (const auto & unexpanded_dof : unexpanded_dofs)
5050 {
5051 // If we were asked for a DoF and we don't already have a
5052 // constraint for it, then we need to check for one.
5053 if (auto pos = _dof_constraints.find(unexpanded_dof);
5054 pos == _dof_constraints.end())
5055 {
5056 if (!this->local_index(unexpanded_dof) &&
5057 !_dof_constraints.count(unexpanded_dof) )
5058 dof_request_set.insert(unexpanded_dof);
5059 }
5060 // If we were asked for a DoF and we already have a
5061 // constraint for it, then we need to check if the
5062 // constraint is recursive.
5063 else
5064 {
5065 const DofConstraintRow & row = pos->second;
5066 for (const auto & j : row)
5067 {
5068 const dof_id_type constraining_dof = j.first;
5069
5070 // If it's non-local and we haven't already got a
5071 // constraint for it, we might need to ask for one
5072 if (!this->local_index(constraining_dof) &&
5073 !_dof_constraints.count(constraining_dof))
5074 dof_request_set.insert(constraining_dof);
5075 }
5076 }
5077 }
5078
5079 // Clear the unexpanded constraint set; we're about to expand it
5080 unexpanded_dofs.clear();
5081
5082 // Count requests by processor
5083 processor_id_type proc_id = 0;
5084 for (const auto & i : dof_request_set)
5085 {
5086 while (i >= _end_df[proc_id])
5087 proc_id++;
5088 dof_ids_on_proc[proc_id]++;
5089 }
5090
5091 for (auto & pair : dof_ids_on_proc)
5092 {
5093 requested_dof_ids[pair.first].reserve(pair.second);
5094 }
5095
5096 // Prepare each processor's request set
5097 proc_id = 0;
5098 for (const auto & i : dof_request_set)
5099 {
5100 while (i >= _end_df[proc_id])
5101 proc_id++;
5102 requested_dof_ids[proc_id].push_back(i);
5103 }
5104
5105 typedef std::vector<std::pair<dof_id_type, Real>> row_datum;
5106
5107 typedef std::vector<Number> rhss_datum;
5108
5109 auto row_gather_functor =
5110 [this]
5112 const std::vector<dof_id_type> & ids,
5113 std::vector<row_datum> & data)
5114 {
5115 // Fill those requests
5116 const std::size_t query_size = ids.size();
5117
5118 data.resize(query_size);
5119 for (std::size_t i=0; i != query_size; ++i)
5120 {
5121 dof_id_type constrained = ids[i];
5122 if (_dof_constraints.count(constrained))
5123 {
5124 DofConstraintRow & row = _dof_constraints[constrained];
5125 std::size_t row_size = row.size();
5126 data[i].reserve(row_size);
5127 for (const auto & j : row)
5128 {
5129 data[i].push_back(j);
5130
5131 // We should never have an invalid constraining
5132 // dof id
5134
5135 // We should never have a 0 constraint
5136 // coefficient; that's implicit via sparse
5137 // constraint storage
5138 //
5139 // But we can't easily control how users add
5140 // constraints, so we can't safely assert that
5141 // we're being efficient here.
5142 //
5143 // libmesh_assert(j.second);
5144 }
5145 }
5146 else
5147 {
5148 // We have to distinguish "constraint with no
5149 // constraining dofs" (e.g. due to Dirichlet
5150 // constraint equations) from "no constraint".
5151 // We'll use invalid_id for the latter.
5152 data[i].emplace_back(DofObject::invalid_id, Real(0));
5153 }
5154 }
5155 };
5156
5157 auto rhss_gather_functor =
5158 [this,
5159 max_qoi_num]
5161 const std::vector<dof_id_type> & ids,
5162 std::vector<rhss_datum> & data)
5163 {
5164 // Fill those requests
5165 const std::size_t query_size = ids.size();
5166
5167 data.resize(query_size);
5168 for (std::size_t i=0; i != query_size; ++i)
5169 {
5170 dof_id_type constrained = ids[i];
5171 data[i].clear();
5172 if (_dof_constraints.count(constrained))
5173 {
5174 DofConstraintValueMap::const_iterator rhsit =
5175 _primal_constraint_values.find(constrained);
5176 data[i].push_back
5177 ((rhsit == _primal_constraint_values.end()) ?
5178 0 : rhsit->second);
5179
5180 for (unsigned int q = 0; q != max_qoi_num; ++q)
5181 {
5182 AdjointDofConstraintValues::const_iterator adjoint_map_it =
5184
5185 if (adjoint_map_it == _adjoint_constraint_values.end())
5186 {
5187 data[i].push_back(0);
5188 continue;
5189 }
5190
5191 const DofConstraintValueMap & constraint_map =
5192 adjoint_map_it->second;
5193
5194 DofConstraintValueMap::const_iterator adj_rhsit =
5195 constraint_map.find(constrained);
5196 data[i].push_back
5197 ((adj_rhsit == constraint_map.end()) ?
5198 0 : adj_rhsit->second);
5199 }
5200 }
5201 }
5202 };
5203
5204 auto row_action_functor =
5205 [this,
5206 & unexpanded_dofs]
5208 const std::vector<dof_id_type> & ids,
5209 const std::vector<row_datum> & data)
5210 {
5211 // Add any new constraint rows we've found
5212 const std::size_t query_size = ids.size();
5213
5214 for (std::size_t i=0; i != query_size; ++i)
5215 {
5216 const dof_id_type constrained = ids[i];
5217
5218 // An empty row is an constraint with an empty row; for
5219 // no constraint we use a "no row" placeholder
5220 if (data[i].empty())
5221 {
5222 DofConstraintRow & row = _dof_constraints[constrained];
5223 row.clear();
5224 }
5225 else if (data[i][0].first != DofObject::invalid_id)
5226 {
5227 DofConstraintRow & row = _dof_constraints[constrained];
5228 row.clear();
5229 for (auto & pair : data[i])
5230 {
5231 libmesh_assert_less(pair.first, this->n_dofs());
5232 row[pair.first] = pair.second;
5233 }
5234
5235 // And prepare to check for more recursive constraints
5236 unexpanded_dofs.insert(constrained);
5237 }
5238 }
5239 };
5240
5241 auto rhss_action_functor =
5242 [this,
5243 max_qoi_num]
5245 const std::vector<dof_id_type> & ids,
5246 const std::vector<rhss_datum> & data)
5247 {
5248 // Add rhs data for any new constraint rows we've found
5249 const std::size_t query_size = ids.size();
5250
5251 for (std::size_t i=0; i != query_size; ++i)
5252 {
5253 if (!data[i].empty())
5254 {
5255 dof_id_type constrained = ids[i];
5256 if (data[i][0] != Number(0))
5257 _primal_constraint_values[constrained] = data[i][0];
5258 else
5259 _primal_constraint_values.erase(constrained);
5260
5261 for (unsigned int q = 0; q != max_qoi_num; ++q)
5262 {
5263 AdjointDofConstraintValues::iterator adjoint_map_it =
5265
5266 if ((adjoint_map_it == _adjoint_constraint_values.end()) &&
5267 data[i][q+1] == Number(0))
5268 continue;
5269
5270 if (adjoint_map_it == _adjoint_constraint_values.end())
5271 adjoint_map_it = _adjoint_constraint_values.emplace
5272 (q, DofConstraintValueMap()).first;
5273
5274 DofConstraintValueMap & constraint_map =
5275 adjoint_map_it->second;
5276
5277 if (data[i][q+1] != Number(0))
5278 constraint_map[constrained] =
5279 data[i][q+1];
5280 else
5281 constraint_map.erase(constrained);
5282 }
5283 }
5284 }
5285
5286 };
5287
5288 // Now request constraint rows from other processors
5289 row_datum * row_ex = nullptr;
5291 (this->comm(), requested_dof_ids, row_gather_functor,
5292 row_action_functor, row_ex);
5293
5294 // And request constraint right hand sides from other procesors
5295 rhss_datum * rhs_ex = nullptr;
5297 (this->comm(), requested_dof_ids, rhss_gather_functor,
5298 rhss_action_functor, rhs_ex);
5299
5300 // We have to keep recursing while the unexpanded set is
5301 // nonempty on *any* processor
5302 unexpanded_set_nonempty = !unexpanded_dofs.empty();
5303 this->comm().max(unexpanded_set_nonempty);
5304 }
5305}
5306
5308{
5309 // This function must be run on all processors at once
5310 parallel_object_only();
5311
5312 // Return immediately if there's nothing to gather
5313 if (this->n_processors() == 1)
5314 return;
5315
5316 // We might get to return immediately if none of the processors
5317 // found any constraints
5318 unsigned int has_constraints = !_dof_constraints.empty();
5319 this->comm().max(has_constraints);
5320 if (!has_constraints)
5321 return;
5322
5323 auto add_row = [this](const DofConstraintRow & constraint_row) {
5324 for (const auto & j : constraint_row)
5325 {
5326 dof_id_type constraint_dependency = j.first;
5327
5328 // No point in adding one of our own dofs to the send_list
5329 if (this->local_index(constraint_dependency))
5330 continue;
5331
5332 _send_list.push_back(constraint_dependency);
5333 }
5334 };
5335
5336 // We usually only need dependencies of our own constrained dofs
5337 for (const auto & [constrained_dof, constraint_row] : _dof_constraints)
5338 if (this->local_index(constrained_dof))
5339 add_row(constraint_row);
5340
5341 // If we only need constraint DoFs constraining DoFs which are
5342 // algebraically local, we're done.
5344 return;
5345
5346 // If we use StaticCondensation, though, we may need constraint DoFs
5347 // constraining DoFs which are not local (they're on someone else's
5348 // node) but which are supported on local elements. Let's get those
5349 // too if we have to.
5350 //
5351 // Kokkos-MOOSE also requires that, because it cannot use VecSetValues
5352 // and MatSetValues which can dynamically cache remote entries. Instead,
5353 // it allocates ghost entries in advance based on libMesh send_list and
5354 // accumulates to those, and does the assembly at once. When ghost DOFs
5355 // are constrained, it has to add residual/Jacobian contributions to the
5356 // dependencies of ghost DOFs locally as well.
5357 //
5358 // We'll potentially be hitting the same constrained DoFs from
5359 // multiple directions.
5360 for (auto & elem : mesh.active_local_element_ptr_range())
5361 {
5362 std::vector<dof_id_type> di;
5363 this->dof_indices (elem, di);
5364 for (const auto & dof_id : di)
5365 if (!this->local_index(dof_id))
5366 if (auto pos = _dof_constraints.find(dof_id);
5367 pos != _dof_constraints.end())
5368 add_row(pos->second);
5369 }
5370}
5371
5372
5373
5374#endif // LIBMESH_ENABLE_CONSTRAINTS
5375
5376
5377#ifdef LIBMESH_ENABLE_AMR
5378
5379void DofMap::constrain_p_dofs (unsigned int var,
5380 const Elem * elem,
5381 unsigned int s,
5382 unsigned int p)
5383{
5384 // We're constraining dofs on elem which correspond to p refinement
5385 // levels above p - this only makes sense if elem's p refinement
5386 // level is above p.
5387 libmesh_assert_greater (elem->p_level(), p);
5388 libmesh_assert_less (s, elem->n_sides());
5389
5390 const unsigned int sys_num = this->sys_number();
5391 FEType fe_type = this->variable_type(var);
5392
5393 const unsigned int n_nodes = elem->n_nodes();
5394 for (unsigned int n = 0; n != n_nodes; ++n)
5395 if (elem->is_node_on_side(n, s))
5396 {
5397 const Node & node = elem->node_ref(n);
5398 const unsigned int low_nc =
5399 FEInterface::n_dofs_at_node (fe_type, p, elem, n);
5400 const unsigned int high_nc =
5401 FEInterface::n_dofs_at_node (fe_type, elem, n);
5402
5403 // since we may be running this method concurrently
5404 // on multiple threads we need to acquire a lock
5405 // before modifying the _dof_constraints object.
5406 Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
5407
5408 if (elem->is_vertex(n))
5409 {
5410 // Add "this is zero" constraint rows for high p vertex
5411 // dofs
5412 for (unsigned int i = low_nc; i != high_nc; ++i)
5413 {
5414 _dof_constraints[node.dof_number(sys_num,var,i)].clear();
5415 _primal_constraint_values.erase(node.dof_number(sys_num,var,i));
5416 }
5417 }
5418 else
5419 {
5420 const unsigned int total_dofs = node.n_comp(sys_num, var);
5421 libmesh_assert_greater_equal (total_dofs, high_nc);
5422 // Add "this is zero" constraint rows for high p
5423 // non-vertex dofs, which are numbered in reverse
5424 for (unsigned int j = low_nc; j != high_nc; ++j)
5425 {
5426 const unsigned int i = total_dofs - j - 1;
5427 _dof_constraints[node.dof_number(sys_num,var,i)].clear();
5428 _primal_constraint_values.erase(node.dof_number(sys_num,var,i));
5429 }
5430 }
5431 }
5432}
5433
5434#endif // LIBMESH_ENABLE_AMR
5435
5436
5437#ifdef LIBMESH_ENABLE_DIRICHLET
5438void DofMap::add_dirichlet_boundary (const DirichletBoundary & dirichlet_boundary)
5439{
5440 _dirichlet_boundaries->push_back(std::make_unique<DirichletBoundary>(dirichlet_boundary));
5441}
5442
5443
5445 unsigned int qoi_index)
5446{
5447 unsigned int old_size = cast_int<unsigned int>
5449 for (unsigned int i = old_size; i <= qoi_index; ++i)
5450 _adjoint_dirichlet_boundaries.push_back(std::make_unique<DirichletBoundaries>());
5451
5452 // Make copy of DirichletBoundary, owned by _adjoint_dirichlet_boundaries
5453 _adjoint_dirichlet_boundaries[qoi_index]->push_back
5454 (std::make_unique<DirichletBoundary>(dirichlet_boundary));
5455}
5456
5457
5459{
5460 if (_adjoint_dirichlet_boundaries.size() > q)
5461 return true;
5462
5463 return false;
5464}
5465
5466
5467const DirichletBoundaries *
5469{
5470 libmesh_assert_greater(_adjoint_dirichlet_boundaries.size(),q);
5471 return _adjoint_dirichlet_boundaries[q].get();
5472}
5473
5474
5477{
5478 unsigned int old_size = cast_int<unsigned int>
5480 for (unsigned int i = old_size; i <= q; ++i)
5481 _adjoint_dirichlet_boundaries.push_back(std::make_unique<DirichletBoundaries>());
5482
5483 return _adjoint_dirichlet_boundaries[q].get();
5484}
5485
5486
5488{
5489 // Find a boundary condition matching the one to be removed
5490 auto lam = [&boundary_to_remove](const auto & bdy)
5491 {return bdy->b == boundary_to_remove.b && bdy->variables == boundary_to_remove.variables;};
5492
5493 auto it = std::find_if(_dirichlet_boundaries->begin(), _dirichlet_boundaries->end(), lam);
5494
5495 // Assert it was actually found and remove it from the vector
5497 _dirichlet_boundaries->erase(it);
5498}
5499
5500
5502 unsigned int qoi_index)
5503{
5504 libmesh_assert_greater(_adjoint_dirichlet_boundaries.size(),
5505 qoi_index);
5506
5507 auto lam = [&boundary_to_remove](const auto & bdy)
5508 {return bdy->b == boundary_to_remove.b && bdy->variables == boundary_to_remove.variables;};
5509
5510 auto it = std::find_if(_adjoint_dirichlet_boundaries[qoi_index]->begin(),
5511 _adjoint_dirichlet_boundaries[qoi_index]->end(),
5512 lam);
5513
5514 // Assert it was actually found and remove it from the vector
5515 libmesh_assert (it != _adjoint_dirichlet_boundaries[qoi_index]->end());
5516 _adjoint_dirichlet_boundaries[qoi_index]->erase(it);
5517}
5518
5519
5521 const DirichletBoundary & boundary) const
5522{
5523 const std::set<boundary_id_type>& mesh_side_bcids =
5525 const std::set<boundary_id_type>& mesh_edge_bcids =
5527 const std::set<boundary_id_type>& mesh_node_bcids =
5529 const std::set<boundary_id_type>& dbc_bcids = boundary.b;
5530
5531 // DirichletBoundary id sets should be consistent across all ranks
5532 libmesh_assert(mesh.comm().verify(dbc_bcids.size()));
5533
5534 for (const auto & bc_id : dbc_bcids)
5535 {
5536 // DirichletBoundary id sets should be consistent across all ranks
5537 libmesh_assert(mesh.comm().verify(bc_id));
5538
5539 bool found_bcid = (mesh_side_bcids.find(bc_id) != mesh_side_bcids.end() ||
5540 mesh_edge_bcids.find(bc_id) != mesh_edge_bcids.end() ||
5541 mesh_node_bcids.find(bc_id) != mesh_node_bcids.end());
5542
5543 // On a distributed mesh, boundary id sets may *not* be
5544 // consistent across all ranks, since not all ranks see all
5545 // boundaries
5546 mesh.comm().max(found_bcid);
5547
5548 libmesh_error_msg_if(!found_bcid,
5549 "Could not find Dirichlet boundary id " << bc_id << " in mesh!");
5550 }
5551}
5552
5553#endif // LIBMESH_ENABLE_DIRICHLET
5554
5555
5556#ifdef LIBMESH_ENABLE_PERIODIC
5557
5559{
5560 auto inverse_boundary = periodic_boundary.clone(PeriodicBoundaryBase::INVERSE);
5561 this->add_periodic_boundary(periodic_boundary, *inverse_boundary);
5562}
5563
5564
5565
5567 const PeriodicBoundaryBase & inverse_boundary)
5568{
5569 libmesh_assert_equal_to (boundary.myboundary, inverse_boundary.pairedboundary);
5570 libmesh_assert_equal_to (boundary.pairedboundary, inverse_boundary.myboundary);
5571 libmesh_assert(boundary.get_variables() == inverse_boundary.get_variables());
5572
5573 // See if we already have a periodic boundary associated myboundary...
5574 PeriodicBoundaryBase * existing_boundary =
5575 _periodic_boundaries->boundary(boundary.myboundary);
5576
5577 if (!existing_boundary)
5578 {
5579 // ...if not, clone the inputs and add them to the
5580 // PeriodicBoundaries object.
5581 // These will be cleaned up automatically in the
5582 // _periodic_boundaries destructor.
5583 _periodic_boundaries->emplace(boundary.myboundary, boundary.clone());
5584 _periodic_boundaries->emplace(inverse_boundary.myboundary, inverse_boundary.clone());
5585 }
5586 else
5587 {
5588 // ...otherwise, merge this object's variable IDs with the
5589 // existing boundary object's.
5590 existing_boundary->merge(boundary);
5591
5592 // Do the same merging process for the inverse boundary. The
5593 // inverse had better already exist!
5594 PeriodicBoundaryBase * existing_inverse_boundary =
5595 _periodic_boundaries->boundary(boundary.pairedboundary);
5596 libmesh_assert(existing_inverse_boundary);
5597 existing_inverse_boundary->merge(inverse_boundary);
5598
5599 // If we had to merge different *types* of boundaries then
5600 // something likely has gone wrong.
5601#ifdef LIBMESH_HAVE_RTTI
5602 // typeid needs to be given references, not just pointers, to
5603 // return a derived class name.
5604 libmesh_assert(typeid(boundary) == typeid(*existing_boundary));
5605 libmesh_assert(typeid(inverse_boundary) == typeid(*existing_inverse_boundary));
5606#endif
5607 }
5608}
5609
5610
5611#endif
5612
5613
5614} // namespace libMesh
Number exact_value(const Point &p, const Parameters &parameters, const std::string &, const std::string &)
unsigned int dim
void ErrorVector unsigned int
void max(const T &r, T &o, Request &req) const
MessageTag get_unique_tag(int tagvalue=MessageTag::invalid_tag) const
void receive_packed_range(const unsigned int dest_processor_id, Context *context, OutputIter out, const T *output_type, const MessageTag &tag=any_tag) const
Status receive(const unsigned int dest_processor_id, T &buf, const MessageTag &tag=any_tag) const
void min(const T &r, T &o, Request &req) const
timpi_pure bool verify(const T &r) const
void send_packed_range(const unsigned int dest_processor_id, const Context *context, Iter range_begin, const Iter range_end, const MessageTag &tag=no_tag, std::size_t approx_buffer_size=1000000) const
void send(const unsigned int dest_processor_id, const T &buf, const MessageTag &tag=no_tag) const
The BoundaryInfo class contains information relevant to boundary conditions including storing faces,...
void shellface_boundary_ids(const Elem *const elem, const unsigned short int shellface, std::vector< boundary_id_type > &vec_to_fill) const
void edge_boundary_ids(const Elem *const elem, const unsigned short int edge, std::vector< boundary_id_type > &vec_to_fill) const
const std::set< boundary_id_type > & get_edge_boundary_ids() const
void boundary_ids(const Node *node, std::vector< boundary_id_type > &vec_to_fill) const
Fills a user-provided std::vector with the boundary ids associated with Node node.
const std::set< boundary_id_type > & get_boundary_ids() const
const std::set< boundary_id_type > & get_node_boundary_ids() const
Defines a dense matrix for use in Finite Element-type computations.
void vector_mult(DenseVector< T > &dest, const DenseVector< T > &arg) const
Performs the matrix-vector multiplication, dest := (*this) * arg.
void cholesky_solve(const DenseVector< T2 > &b, DenseVector< T2 > &x)
For symmetric positive definite (SPD) matrices.
void resize(const unsigned int new_m, const unsigned int new_n)
Resizes the matrix to the specified size and calls zero().
virtual void right_multiply(const DenseMatrixBase< T > &M2) override final
Performs the operation: (*this) <- (*this) * M3.
void vector_mult_transpose(DenseVector< T > &dest, const DenseVector< T > &arg) const
Performs the matrix-vector multiplication, dest := (*this)^T * arg.
void left_multiply_transpose(const DenseMatrix< T > &A)
Left multiplies by the transpose of the matrix A.
void vector_mult_add(DenseVector< T > &dest, const T factor, const DenseVector< T > &arg) const
Performs the scaled matrix-vector multiplication, dest += factor * (*this) * arg.
virtual void zero() override final
Sets all elements of the matrix to 0 and resets any decomposition flag which may have been previously...
Defines a dense vector for use in Finite Element-type computations.
void resize(const unsigned int n)
Resize the vector.
virtual void zero() override final
Set every element in the vector to 0.
virtual unsigned int size() const override final
const std::vector< dof_id_type > & get_dof_indices() const
Accessor for element dof indices.
const System & get_system() const
Accessor for associated system.
We're using a class instead of a typedef to allow forward declarations and future flexibility.
This class allows one to associate Dirichlet boundary values with a given set of mesh boundary ids an...
std::vector< unsigned int > variables
std::set< boundary_id_type > b
std::unique_ptr< FunctionBase< Number > > f
Real jacobian_tolerance
Defaults to zero, but can be set to a custom small negative value to try and avoid spurious zero (or ...
std::unique_ptr< FunctionBase< Gradient > > g
std::unique_ptr< FEMFunctionBase< Number > > f_fem
std::unique_ptr< FEMFunctionBase< Gradient > > g_fem
Storage for DofConstraint right hand sides for a particular problem.
Definition dof_map.h:124
The constraint matrix storage format.
Definition dof_map.h:112
std::vector< dof_id_type > _end_df
Last DOF index (plus 1) on processor p.
dof_id_type end_dof() const
dof_id_type first_dof() const
This class handles the numbering of degrees of freedom on a mesh.
Definition dof_map.h:181
dof_id_type n_dofs() const
bool _verify_dirichlet_bc_consistency
Flag which determines whether we should do some additional checking of the consistency of the Dirichl...
Definition dof_map.h:2343
void remove_adjoint_dirichlet_boundary(const DirichletBoundary &dirichlet_boundary, unsigned int q)
Removes from the system the specified Dirichlet boundary for the adjoint equation defined by Quantity...
void constrain_p_dofs(unsigned int var, const Elem *elem, unsigned int s, unsigned int p)
Constrains degrees of freedom on side s of element elem which correspond to variable number var and t...
unsigned int n_variables() const override
Definition dof_map.h:743
const std::vector< dof_id_type > & get_send_list() const
Definition dof_map.h:540
void allgather_recursive_constraints(MeshBase &)
Gathers constraint equation dependencies from other processors.
GhostingFunctorIterator coupling_functors_begin() const
Beginning of range of coupling functors.
Definition dof_map.h:373
DofConstraintValueMap _primal_constraint_values
Definition dof_map.h:2289
void check_dirichlet_bcid_consistency(const MeshBase &mesh, const DirichletBoundary &boundary) const
Check that all the ids in dirichlet_bcids are actually present in the mesh.
void gather_constraints(MeshBase &mesh, std::set< dof_id_type > &unexpanded_dofs, bool look_for_constrainees)
Helper function for querying about constraint equations on other processors.
std::vector< dof_id_type > _send_list
A list containing all the global DOF indices that affect the solution on my processor.
Definition dof_map.h:2166
std::unique_ptr< DirichletBoundaries > _dirichlet_boundaries
Data structure containing Dirichlet functions.
Definition dof_map.h:2315
void check_for_cyclic_constraints()
Throw an error if we detect any constraint loops, i.e.
void heterogeneously_constrain_element_vector(const DenseMatrix< Number > &matrix, DenseVector< Number > &rhs, std::vector< dof_id_type > &elem_dofs, bool asymmetric_constraint_rows=true, int qoi_index=-1) const
Constrains the element vector.
Definition dof_map.h:2521
std::vector< std::unique_ptr< DirichletBoundaries > > _adjoint_dirichlet_boundaries
Data structure containing Dirichlet functions.
Definition dof_map.h:2321
dof_id_type n_constrained_dofs() const
void dof_indices(const Elem *const elem, std::vector< dof_id_type > &di) const
Definition dof_map.C:2203
const DirichletBoundaries * get_adjoint_dirichlet_boundaries(unsigned int q) const
void heterogeneously_constrain_element_residual(DenseVector< Number > &rhs, std::vector< dof_id_type > &elem_dofs, NumericVector< Number > &solution_local) const
Constrains the element residual.
void scatter_constraints(MeshBase &)
Sends constraint equations to constraining processors.
void heterogeneously_constrain_element_jacobian_and_residual(DenseMatrix< Number > &matrix, DenseVector< Number > &rhs, std::vector< dof_id_type > &elem_dofs, NumericVector< Number > &solution_local) const
Constrains the element Jacobian and residual.
void add_dirichlet_boundary(const DirichletBoundary &dirichlet_boundary)
Adds a copy of the specified Dirichlet boundary to the system.
void process_mesh_constraint_rows(const MeshBase &mesh)
Adds any spline constraints from the Mesh to our DoF constraints.
void add_constraints_to_send_list(const MeshBase &mesh)
Adds entries to the _send_list vector corresponding to DoFs which are dependencies for constraint equ...
GhostingFunctorIterator coupling_functors_end() const
End of range of coupling functors.
Definition dof_map.h:379
bool _need_ghost_constraints
Default false; set to true if the dependencies of constrained ghost DOFs supported by local elements ...
Definition dof_map.h:2258
void build_constraint_matrix(DenseMatrix< Number > &C, std::vector< dof_id_type > &elem_dofs, const bool called_recursively=false) const
Build the constraint matrix C associated with the element degree of freedom indices elem_dofs.
void enforce_constraints_on_residual(const NonlinearImplicitSystem &system, NumericVector< Number > *rhs, NumericVector< Number > const *solution, bool homogeneous=true) const
Definition dof_map.h:2540
void constrain_element_matrix(DenseMatrix< Number > &matrix, std::vector< dof_id_type > &elem_dofs, bool asymmetric_constraint_rows=true) const
Constrains the element matrix.
Definition dof_map.h:2498
unsigned int n_vars() const
Definition dof_map.h:2956
void print_dof_constraints(std::ostream &os=libMesh::out, bool print_nonlocal=false) const
Prints (from processor 0) all DoF and Node constraints.
void constrain_element_residual(DenseVector< Number > &rhs, std::vector< dof_id_type > &elem_dofs, NumericVector< Number > &solution_local) const
Constrains the element residual.
void add_adjoint_dirichlet_boundary(const DirichletBoundary &dirichlet_boundary, unsigned int q)
Adds a copy of the specified Dirichlet boundary to the system, corresponding to the adjoint problem d...
const FEType & variable_type(const unsigned int i) const
Definition dof_map.h:2401
std::pair< Real, Real > max_constraint_error(const System &system, NumericVector< Number > *v=nullptr) const
Tests the constrained degrees of freedom on the numeric vector v, which represents a solution defined...
void create_dof_constraints(const MeshBase &, Real time=0)
Rebuilds the raw degree of freedom and DofObject constraints, based on attached DirichletBoundary obj...
unsigned int sys_number() const
Definition dof_map.h:2353
unsigned int variable_number(std::string_view var) const
Definition dof_map.h:3010
void constrain_nothing(std::vector< dof_id_type > &dofs) const
Does not actually constrain anything, but modifies dofs in the same way as any of the constrain funct...
Definition dof_map.h:2529
NodeConstraints _node_constraints
Data structure containing DofObject constraints.
Definition dof_map.h:2298
AdjointDofConstraintValues _adjoint_constraint_values
Definition dof_map.h:2291
bool is_constrained_dof(const dof_id_type dof) const
Definition dof_map.h:2439
void constrain_element_vector(DenseVector< Number > &rhs, std::vector< dof_id_type > &dofs, bool asymmetric_constraint_rows=true) const
Constrains the element vector.
Definition dof_map.h:2507
static void merge_ghost_functor_outputs(GhostingFunctor::map_type &elements_to_ghost, CouplingMatricesSet &temporary_coupling_matrices, const GhostingFunctorIterator &gf_begin, const GhostingFunctorIterator &gf_end, const MeshBase::const_element_iterator &elems_begin, const MeshBase::const_element_iterator &elems_end, processor_id_type p)
Definition dof_map.C:1587
bool local_index(dof_id_type dof_index) const
Definition dof_map.h:974
const Variable & variable(const unsigned int c) const override
Definition dof_map.h:2371
void enforce_constraints_exactly(const System &system, NumericVector< Number > *v=nullptr, bool homogeneous=false) const
Constrains the numeric vector v, which represents a solution defined on the mesh.
Definition dof_map.h:2531
void enforce_constraints_on_jacobian(const NonlinearImplicitSystem &system, SparseMatrix< Number > *jac) const
Definition dof_map.h:2546
bool has_adjoint_dirichlet_boundaries(unsigned int q) const
dof_id_type n_local_constrained_dofs() const
std::unique_ptr< PeriodicBoundaries > _periodic_boundaries
Data structure containing periodic boundaries.
Definition dof_map.h:2307
void constrain_element_dyad_matrix(DenseVector< Number > &v, DenseVector< Number > &w, std::vector< dof_id_type > &row_dofs, bool asymmetric_constraint_rows=true) const
Constrains a dyadic element matrix B = v w'.
Definition dof_map.h:2524
std::set< std::unique_ptr< CouplingMatrix >, Utility::CompareUnderlying > CouplingMatricesSet
Definition dof_map.h:2006
bool has_static_condensation() const
Checks whether we have static condensation.
Definition dof_map.h:1804
dof_id_type n_local_dofs() const
void add_adjoint_constraint_row(const unsigned int qoi_index, const dof_id_type dof_number, const DofConstraintRow &constraint_row, const Number constraint_rhs, const bool forbid_constraint_overwrite)
Adds a copy of the user-defined row to the constraint matrix, using an inhomogeneous right-hand-side ...
bool is_constrained_node(const Node *node) const
Definition dof_map.h:2423
void build_constraint_matrix_and_vector(DenseMatrix< Number > &C, DenseVector< Number > &H, std::vector< dof_id_type > &elem_dofs, int qoi_index=-1, const bool called_recursively=false) const
Build the constraint matrix C and the forcing vector H associated with the element degree of freedom ...
void add_constraint_row(const dof_id_type dof_number, const DofConstraintRow &constraint_row, const Number constraint_rhs, const bool forbid_constraint_overwrite)
Adds a copy of the user-defined row to the constraint matrix, using an inhomogeneous right-hand-side ...
void heterogeneously_constrain_element_matrix_and_vector(DenseMatrix< Number > &matrix, DenseVector< Number > &rhs, std::vector< dof_id_type > &elem_dofs, bool asymmetric_constraint_rows=true, int qoi_index=-1) const
Constrains the element matrix and vector.
Definition dof_map.h:2517
void add_periodic_boundary(const PeriodicBoundaryBase &periodic_boundary)
Adds a copy of the specified periodic boundary to the system.
void process_constraints(MeshBase &)
Postprocesses any constrained degrees of freedom to be constrained only in terms of unconstrained dof...
void enforce_adjoint_constraints_exactly(NumericVector< Number > &v, unsigned int q) const
Heterogeneously constrains the numeric vector v, which represents an adjoint solution defined on the ...
Definition dof_map.h:2535
void remove_dirichlet_boundary(const DirichletBoundary &dirichlet_boundary)
Removes the specified Dirichlet boundary from the system.
std::unique_ptr< SparsityPattern::Build > build_sparsity(const MeshBase &mesh, bool calculate_constrained=false, bool use_condensed_system=false) const
Builds a sparsity pattern for matrices using the current degree-of-freedom numbering and coupling.
Definition dof_map.C:63
bool _error_on_constraint_loop
This flag indicates whether or not we do an opt-mode check for the presence of constraint loops,...
Definition dof_map.h:2092
std::string get_local_constraints(bool print_nonlocal=false) const
Gets a string reporting all DoF and Node constraints local to this processor.
void constrain_element_matrix_and_vector(DenseMatrix< Number > &matrix, DenseVector< Number > &rhs, std::vector< dof_id_type > &elem_dofs, bool asymmetric_constraint_rows=true) const
Constrains the element matrix and vector.
Definition dof_map.h:2511
DofConstraints _dof_constraints
Data structure containing DOF constraints.
Definition dof_map.h:2287
unsigned int n_comp(const unsigned int s, const unsigned int var) const
Definition dof_object.h:992
dof_id_type dof_number(const unsigned int s, const unsigned int var, const unsigned int comp) const
processor_id_type processor_id() const
Definition dof_object.h:895
static constexpr dof_id_type invalid_id
An invalid id to distinguish an uninitialized DofObject.
Definition dof_object.h:473
dof_id_type id() const
Definition dof_object.h:833
unsigned int n_vars(const unsigned int s, const unsigned int vg) const
Definition dof_object.h:957
This is the base class from which all geometric element types are derived.
Definition elem.h:96
virtual bool is_node_on_side(const unsigned int n, const unsigned int s) const =0
bool active() const
Definition elem.h:3079
const Point & point(const unsigned int i) const
Definition elem.h:2583
const Node & node_ref(const unsigned int i) const
Definition elem.h:2659
virtual unsigned int n_nodes() const =0
subdomain_id_type subdomain_id() const
Definition elem.h:2712
const Node * node_ptr(const unsigned int i) const
Definition elem.h:2637
virtual bool is_vertex(const unsigned int i) const =0
virtual bool is_node_on_edge(const unsigned int n, const unsigned int e) const =0
virtual unsigned int n_edges() const =0
virtual unsigned int n_sides() const =0
dof_id_type node_id(const unsigned int i) const
Definition elem.h:2605
unsigned int p_level() const
Definition elem.h:3246
virtual bool is_edge_on_side(const unsigned int e, const unsigned int s) const =0
NumericVector< Number > * rhs
The system matrix.
static void compute_node_constraints(NodeConstraints &constraints, const Elem *elem)
Computes the nodal constraint contributions (for non-conforming adapted meshes), using Lagrange geome...
virtual void edge_reinit(const Elem *elem, const unsigned int edge, const Real tolerance=TOLERANCE, const std::vector< Point > *pts=nullptr, const std::vector< Real > *weights=nullptr)=0
Reinitializes all the physical element-dependent data based on the edge of the element elem.
static void compute_periodic_node_constraints(NodeConstraints &constraints, const PeriodicBoundaries &boundaries, const MeshBase &mesh, const PointLocatorBase *point_locator, const Elem *elem)
Computes the node position constraint equation contributions (for meshes with periodic boundary condi...
virtual_for_inffe const std::vector< Real > & get_JxW() const
virtual_for_inffe const std::vector< Point > & get_xyz() const
virtual void reinit(const Elem *elem, const std::vector< Point > *const pts=nullptr, const std::vector< Real > *const weights=nullptr)=0
This is at the core of this class.
const FEMap & get_fe_map() const
This class forms the foundation from which generic finite elements may be derived.
Definition fe_base.h:86
const std::vector< std::vector< OutputShape > > & get_phi() const
Definition fe_base.h:207
const std::vector< std::vector< OutputGradient > > & get_dphi() const
Definition fe_base.h:252
static void dofs_on_side(const Elem *const elem, const unsigned int dim, const FEType &fe_t, unsigned int s, std::vector< unsigned int > &di, const bool add_p_level=true)
Fills the vector di with the local degree of freedom indices associated with side s of element elem A...
static unsigned int n_vec_dim(const MeshBase &mesh, const FEType &fe_type)
static FEContinuity get_continuity(const FEType &fe_type)
Returns the input FEType's FEContinuity based on the underlying FEFamily and potentially the Order,...
static FEFieldType field_type(const FEType &fe_type)
static void compute_periodic_constraints(DofConstraints &constraints, DofMap &dof_map, const PeriodicBoundaries &boundaries, const MeshBase &mesh, const PointLocatorBase *point_locator, const unsigned int variable_number, const Elem *elem)
Computes the constraint matrix contributions (for periodic boundary conditions) corresponding to vari...
static unsigned int n_dofs_at_node(const unsigned int dim, const FEType &fe_t, const ElemType t, const unsigned int n)
static void dofs_on_edge(const Elem *const elem, const unsigned int dim, const FEType &fe_t, unsigned int e, std::vector< unsigned int > &di, const bool add_p_level=true)
Fills the vector di with the local degree of freedom indices associated with edge e of element elem A...
static void compute_constraints(DofConstraints &constraints, DofMap &dof_map, const unsigned int variable_number, const Elem *elem)
Computes the constraint matrix contributions (for non-conforming adapted meshes) corresponding to var...
This class provides all data required for a physics package (e.g.
Definition fem_context.h:64
void get_side_fe(unsigned int var, FEGenericBase< OutputShape > *&fe) const
Accessor for edge/face (2D/3D) finite element object for variable var for the largest dimension in th...
void get_edge_fe(unsigned int var, FEGenericBase< OutputShape > *&fe) const
Accessor for edge (3D only!) finite element object for variable var.
virtual void pre_fe_reinit(const System &, const Elem *e)
Reinitializes local data vectors/matrices on the current geometric element.
const QBase & get_element_qrule() const
Accessor for element interior quadrature rule for the dimension of the current _elem.
const QBase & get_edge_qrule() const
Accessor for element edge quadrature rule.
void get_element_fe(unsigned int var, FEGenericBase< OutputShape > *&fe) const
Accessor for interior finite element object for variable var for the largest dimension in the mesh.
void set_algebraic_type(const AlgebraicType atype)
Setting which determines whether to initialize algebraic structures (elem_*) on each element and set ...
const QBase & get_side_qrule() const
Accessor for element side quadrature rule for the dimension of the current _elem.
FEMFunctionBase is a base class from which users can derive in order to define "function-like" object...
virtual void init_context(const FEMContext &)
Prepares a context object for use.
virtual Output component(const FEMContext &, unsigned int i, const Point &p, Real time=0.)
void set_jacobian_tolerance(Real tol)
Set the Jacobian tolerance used for determining when the mapping fails.
Definition fe_map.h:641
class FEType hides (possibly multiple) FEFamily and approximation orders, thereby enabling specialize...
Definition fe_type.h:197
FEFamily family
The type of finite element.
Definition fe_type.h:228
Base class for functors that can be evaluated at a point and (optionally) time.
virtual Output component(unsigned int i, const Point &p, Real time=0.)
std::map< const Elem *, const CouplingMatrix *, CompareDofObjectsByPIDAndThenID > map_type
What elements do we care about and what variables do we care about on each element?
SparseMatrix< Number > * matrix
The system matrix.
The IntRange templated class is intended to make it easy to loop over integers which are indices of a...
Definition int_range.h:54
static std::unique_ptr< LinearSolver< T > > build(const libMesh::Parallel::Communicator &comm_in, const SolverPackage solver_package=libMesh::default_solver_package())
Builds a LinearSolver using the linear solver package specified by solver_package.
This is the MeshBase class.
Definition mesh_base.h:81
virtual bool is_serial() const
Definition mesh_base.h:357
const BoundaryInfo & get_boundary_info() const
The information about boundary ids on the mesh.
Definition mesh_base.h:170
bool is_prepared() const
Definition mesh_base.C:1065
virtual const Node * node_ptr(const dof_id_type i) const =0
unsigned int mesh_dimension() const
Definition mesh_base.C:435
virtual dof_id_type n_elem() const =0
virtual const Elem * elem_ptr(const dof_id_type i) const =0
constraint_rows_type & get_constraint_rows()
Constraint rows accessors.
Definition mesh_base.h:1940
dof_id_type n_constraint_rows() const
Returns how many total constraint rows we have.
Definition mesh_base.h:2691
std::unique_ptr< PointLocatorBase > sub_point_locator() const
Definition mesh_base.C:1848
The Node constraint storage format.
Definition dof_map.h:160
A Node is like a Point, but with more information.
Definition node.h:55
Manages consistently variables, degrees of freedom, coefficient vectors, matrices and non-linear solv...
Provides a uniform interface to vector storage schemes for different linear algebra libraries.
virtual void set(const numeric_index_type i, const T value)=0
Sets v(i) = value.
virtual void get(const std::vector< numeric_index_type > &index, T *values) const
Access multiple components at once.
virtual numeric_index_type last_local_index() const =0
ParallelType type() const
virtual void close()=0
Calls the NumericVector's internal assembly routines, ensuring that the values are consistent across ...
static std::unique_ptr< NumericVector< T > > build(const Parallel::Communicator &comm, SolverPackage solver_package=libMesh::default_solver_package(), ParallelType parallel_type=AUTOMATIC)
Builds a NumericVector on the processors in communicator comm using the linear solver package specifi...
virtual void localize(std::vector< T > &v_local) const =0
Creates a copy of the global vector in the local vector v_local.
virtual numeric_index_type size() const =0
virtual bool closed() const
virtual numeric_index_type local_size() const =0
virtual numeric_index_type first_local_index() const =0
processor_id_type processor_id() const
const Parallel::Communicator & comm() const
processor_id_type n_processors() const
We're using a class instead of a typedef to allow forward declarations and future flexibility.
The base class for defining periodic boundaries.
const std::set< unsigned int > & get_variables() const
Get the set of variables for this periodic boundary condition.
boundary_id_type myboundary
The boundary ID of this boundary and its counterpart.
void merge(const PeriodicBoundaryBase &pb)
virtual std::unique_ptr< PeriodicBoundaryBase > clone(TransformationType t=FORWARD) const =0
If we want the DofMap to be able to make copies of references and store them in the underlying map,...
A Point defines a location in LIBMESH_DIM dimensional Real space.
Definition point.h:41
unsigned int n_points() const
Definition quadrature.h:131
This class provides single index access to FieldType (i.e.
Generic sparse matrix.
static std::unique_ptr< SparseMatrix< T > > build(const Parallel::Communicator &comm, const SolverPackage solver_package=libMesh::default_solver_package(), const MatrixBuildType matrix_build_type=MatrixBuildType::AUTOMATIC)
Builds a SparseMatrix<T> using the linear solver package specified by solver_package.
virtual void set(const numeric_index_type i, const numeric_index_type j, const T value)=0
Set the element (i,j) to value.
The StoredRange class defines a contiguous, divisible set of objects.
StoredRange< iterator_type, object_type > & reset(const iterator_type &first, const iterator_type &last)
Resets the StoredRange to contain [first,last).
Manages consistently variables, degrees of freedom, and coefficient vectors.
Definition system.h:100
std::unique_ptr< NumericVector< Number > > current_local_solution
All the values I need to compute my contribution to the simulation at hand.
Definition system.h:1667
std::unique_ptr< NumericVector< Number > > solution
Data structure to hold solution values.
Definition system.h:1655
const DofMap & get_dof_map() const
Definition system.h:2417
const MeshBase & get_mesh() const
Definition system.h:2401
This class defines the notion of a variable in the system.
Definition variable.h:51
unsigned int first_scalar_number() const
Definition variable.h:138
bool active_on_subdomain(subdomain_id_type sid) const
Definition variable.h:167
System * system() const
Definition variable.h:114
unsigned int number() const
Definition variable.h:128
const FEType & type() const
Definition variable.h:144
This class defines a vector in LIBMESH_DIM dimensional Real or Complex space.
static const Real b
MeshBase & mesh
void pull_parallel_vector_data(const Communicator &comm, const MapToVectors &queries, GatherFunctor &gather_data, const ActionFunctor &act_on_data, const datum *example)
Status wait(Request &r)
void push_parallel_vector_data(const Communicator &comm, MapToVectors &&data, const ActionFunctor &act_on_data)
Tnew cast_int(Told oldvar)
void push_parallel_packed_range(const Communicator &comm, MapToContainers &&data, Context *context, const ActionFunctor &act_on_data)
void libmesh_assert_valid_boundary_ids(const MeshBase &mesh)
A function for verifying that boundary condition ids match across processors.
const Elem & get(const ElemType type_in)
spin_mutex spin_mtx
A convenient spin mutex object which can be used for obtaining locks.
Definition threads.C:30
void parallel_for(const Range &range, const Body &body, unsigned int n_threads=libMesh::n_threads())
Execute the provided function object in parallel on the specified range.
std::string enum_to_string(const T e)
The libMesh namespace provides an interface to certain functionality in the library.
std::map< const Node *, Real, std::less< const Node * >, Threads::scalable_allocator< std::pair< const Node *const, Real > > > NodeConstraintRow
A row of the Node constraint mapping.
Definition dof_map.h:148
SimpleRange< IndexType > as_range(const std::pair< IndexType, IndexType > &p)
Helper function that allows us to treat a homogenous pair as a range.
auto index_range(const T &sizable)
Helper function that returns an IntRange<std::size_t> representing all the indices of the passed-in v...
Definition int_range.h:153
int8_t boundary_id_type
Definition id_types.h:51
libmesh_assert(ctx)
LIBMESH_DEVICE_INLINE bool libmesh_isnan(T x)
std::map< dof_id_type, Real, std::less< dof_id_type >, Threads::scalable_allocator< std::pair< const dof_id_type, Real > > > DofConstraintRow
A row of the Dof constraint matrix.
Definition dof_map.h:100
static constexpr Real TOLERANCE
uint8_t dof_id_type
Definition id_types.h:67
@ RATIONAL_BERNSTEIN
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
uint8_t processor_id_type
Definition id_types.h:104
IntRange< T > make_range(T beg, T end)
The 2-parameter make_range() helper function returns an IntRange<T> when both input parameters are of...
Definition int_range.h:176
A do-nothing class for templated methods that expect output iterator arguments.
const dof_id_type n_nodes
Definition tecplot_io.C:67