https://mooseframework.inl.gov
Loading...
Searching...
No Matches
NonlinearSystemBase.C
Go to the documentation of this file.
1//* This file is part of the MOOSE framework
2//* https://mooseframework.inl.gov
3//*
4//* All rights reserved, see COPYRIGHT for full restrictions
5//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6//*
7//* Licensed under LGPL 2.1, please see LICENSE for details
8//* https://www.gnu.org/licenses/lgpl-2.1.html
9
10#include "NonlinearSystemBase.h"
11#include "AuxiliarySystem.h"
12#include "Problem.h"
13#include "FEProblem.h"
14#include "MooseVariableFE.h"
15#include "MooseVariableScalar.h"
16#include "PetscSupport.h"
17#include "Factory.h"
18#include "ParallelUniqueId.h"
19#include "ThreadedElementLoop.h"
20#include "MaterialData.h"
23#include "ComputeFVFluxThread.h"
28#include "ComputeDiracThread.h"
35#include "TimeKernel.h"
36#include "BoundaryCondition.h"
37#include "DirichletBCBase.h"
38#include "NodalBCBase.h"
39#include "IntegratedBCBase.h"
40#include "DGKernel.h"
41#include "InterfaceKernelBase.h"
42#include "ElementDamper.h"
43#include "NodalDamper.h"
44#include "GeneralDamper.h"
45#include "DisplacedProblem.h"
46#include "NearestNodeLocator.h"
47#include "PenetrationLocator.h"
48#include "NodalConstraint.h"
49#include "NodeFaceConstraint.h"
51#include "MortarConstraint.h"
52#include "ElemElemConstraint.h"
53#include "ScalarKernelBase.h"
54#include "Parser.h"
55#include "Split.h"
57#include "MooseMesh.h"
58#include "MooseUtils.h"
59#include "MooseApp.h"
60#include "NodalKernelBase.h"
61#include "DiracKernelBase.h"
62#include "TimeIntegrator.h"
63#include "Predictor.h"
64#include "Assembly.h"
65#include "ElementPairLocator.h"
66#include "ODETimeKernel.h"
69#include "ADKernel.h"
70#include "ADDirichletBCBase.h"
71#include "Moose.h"
72#include "ConsoleStream.h"
73#include "MooseError.h"
74#include "FVElementalKernel.h"
77#include "FVFluxKernel.h"
78#include "FVBoundaryCondition.h"
79#include "FVInterfaceKernel.h"
81#include "GeneralUserObject.h"
83#include "HDGKernel.h"
85#include "Convergence.h"
86
87// libMesh
88#include "libmesh/nonlinear_solver.h"
89#include "libmesh/quadrature_gauss.h"
90#include "libmesh/dense_vector.h"
91#include "libmesh/boundary_info.h"
92#include "libmesh/petsc_matrix.h"
93#include "libmesh/petsc_vector.h"
94#include "libmesh/petsc_nonlinear_solver.h"
95#include "libmesh/numeric_vector.h"
96#include "libmesh/mesh.h"
97#include "libmesh/dense_subvector.h"
98#include "libmesh/dense_submatrix.h"
99#include "libmesh/dof_map.h"
100#include "libmesh/sparse_matrix.h"
101#include "libmesh/petsc_matrix.h"
102#include "libmesh/default_coupling.h"
103#include "libmesh/diagonal_matrix.h"
104#include "libmesh/fe_interface.h"
105#include "libmesh/petsc_solver_exception.h"
106
107#include <ios>
108#include <type_traits>
109
110#include "petscsnes.h"
111#include <PetscDMMoose.h>
112EXTERN_C_BEGIN
113extern PetscErrorCode DMCreate_Moose(DM);
115
116namespace
117{
118template <typename T>
119void
121 const std::string & system_name,
122 const unsigned int system_number,
123 const THREAD_ID tid,
124 std::vector<SetupInterface *> & results)
125{
126 static_assert(std::is_base_of_v<MooseObject, T>);
127 static_assert(std::is_base_of_v<SetupInterface, T>);
128
129 std::vector<T *> objects;
130 warehouse.query()
131 .template condition<AttribSystem>(system_name)
132 .template condition<AttribSysNum>(system_number)
133 .template condition<AttribThread>(tid)
134 .queryInto(objects);
135
136 for (auto * object : objects)
137 results.push_back(object);
138}
139}
140
142 System & sys,
143 const std::string & name)
144 : SolverSystem(fe_problem, fe_problem, name, Moose::VAR_SOLVER),
145 PerfGraphInterface(fe_problem.getMooseApp().perfGraph(), "NonlinearSystemBase"),
146 _sys(sys),
147 _last_nl_rnorm(0.),
148 _current_nl_its(0),
149 _residual_ghosted(NULL),
150 _Re_time_tag(-1),
151 _Re_time(NULL),
152 _Re_non_time_tag(-1),
153 _Re_non_time(NULL),
154 _scalar_kernels(/*threaded=*/false),
155 _nodal_bcs(/*threaded=*/false),
156 _preset_nodal_bcs(/*threaded=*/false),
157 _ad_preset_nodal_bcs(/*threaded=*/false),
158#ifdef MOOSE_KOKKOS_ENABLED
159 _kokkos_kernels(/*threaded=*/false),
160 _kokkos_integrated_bcs(/*threaded=*/false),
161 _kokkos_nodal_bcs(/*threaded=*/false),
162 _kokkos_preset_nodal_bcs(/*threaded=*/false),
163 _kokkos_nodal_kernels(/*threaded=*/false),
164#endif
165 _general_dampers(/*threaded=*/false),
166 _splits(/*threaded=*/false),
167 _increment_vec(NULL),
168 _use_finite_differenced_preconditioner(false),
169 _fdcoloring(nullptr),
170 _fsp(nullptr),
171 _add_implicit_geometric_coupling_entries_to_jacobian(false),
172 _assemble_constraints_separately(false),
173 _need_residual_ghosted(false),
174 _debugging_residuals(false),
175 _doing_dg(false),
176 _n_iters(0),
177 _n_linear_iters(0),
178 _n_residual_evaluations(0),
179 _final_residual(0.),
180 _computing_pre_smo_residual(false),
181 _pre_smo_residual(0),
182 _initial_residual(0),
183 _use_pre_smo_residual(false),
184 _print_all_var_norms(false),
185 _has_save_in(false),
186 _has_diag_save_in(false),
187 _has_nodalbc_save_in(false),
188 _has_nodalbc_diag_save_in(false),
189 _computed_scaling(false),
190 _compute_scaling_once(true),
191 _resid_vs_jac_scaling_param(0),
192 _off_diagonals_in_auto_scaling(false),
193 _auto_scaling_initd(false)
194{
196 // Don't need to add the matrix - it already exists (for now)
198
199 // The time matrix tag is not normally used - but must be added to the system
200 // in case it is so that objects can have 'time' in their matrix tags by default
202
203 _Re_tag = _fe_problem.addVectorTag("RESIDUAL");
204
206
208 {
209 auto & dof_map = _sys.get_dof_map();
210 dof_map.remove_algebraic_ghosting_functor(dof_map.default_algebraic_ghosting());
211 dof_map.set_implicit_neighbor_dofs(false);
212 }
213}
214
216
217void
219{
221
223 setupDampers();
224
225 if (_residual_copy.get())
226 _residual_copy->init(_sys.n_dofs(), false, SERIAL);
227
228#ifdef MOOSE_KOKKOS_ENABLED
231#endif
232}
233
234void
236{
237 // reinit is called on meshChanged() in FEProblemBase. We could implement meshChanged() instead.
238 // Subdomains might have changed
239 for (auto & functor : _displaced_mortar_functors)
240 functor.second.setupMortarMaterials();
241 for (auto & functor : _undisplaced_mortar_functors)
242 functor.second.setupMortarMaterials();
243}
244
245void
251
252std::vector<SetupInterface *>
254{
255 std::vector<SetupInterface *> fv_objects;
256 auto & warehouse = _fe_problem.theWarehouse();
257
258 appendFVSetupObjects<FVElementalKernel>(
259 warehouse, "FVElementalKernel", number(), tid, fv_objects);
260 appendFVSetupObjects<FVFluxKernel>(warehouse, "FVFluxKernel", number(), tid, fv_objects);
261 appendFVSetupObjects<FVBoundaryCondition>(warehouse, "FVDirichletBC", number(), tid, fv_objects);
262 appendFVSetupObjects<FVBoundaryCondition>(warehouse, "FVFluxBC", number(), tid, fv_objects);
263 appendFVSetupObjects<FVInterfaceKernel>(
264 warehouse, "FVInterfaceKernel", number(), tid, fv_objects);
265
266 return fv_objects;
267}
268
269void
271{
272 TIME_SECTION("nlInitialSetup", 2, "Setting Up Nonlinear System");
273
275
276 {
277 TIME_SECTION("kernelsInitialSetup", 2, "Setting Up Kernels/BCs/Constraints");
278
279 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
280 {
284 if (_doing_dg)
287
291
292 if (_fe_problem.haveFV())
293 for (auto * fv_object : getFVSetupObjects(tid))
294 fv_object->initialSetup();
295 }
296
303
304#ifdef MOOSE_KOKKOS_ENABLED
309#endif
310 }
311
312 {
313 TIME_SECTION("mortarSetup", 2, "Initializing Mortar Interfaces");
314
315 auto create_mortar_functors = [this](const bool displaced)
316 {
317 // go over mortar interfaces and construct functors
318 const auto & mortar_interfaces = _fe_problem.getMortarInterfaces(displaced);
319 for (const auto & [primary_secondary_boundary_pair, interface_config] : mortar_interfaces)
320 {
321 if (!_constraints.hasActiveMortarConstraints(primary_secondary_boundary_pair, displaced))
322 continue;
323
324 auto & mortar_constraints =
325 _constraints.getActiveMortarConstraints(primary_secondary_boundary_pair, displaced);
326
327 auto & subproblem = displaced ? cast_ref<SubProblem &>(*_fe_problem.getDisplacedProblem())
328 : cast_ref<SubProblem &>(_fe_problem);
329
330 auto & mortar_functors =
332
333 mortar_functors.emplace(primary_secondary_boundary_pair,
334 ComputeMortarFunctor(mortar_constraints,
335 *interface_config.amg,
338 displaced,
339 subproblem.assembly(0, number())));
340 }
341 };
342
343 create_mortar_functors(false);
344 create_mortar_functors(true);
345 }
346
348 {
350 _scaling_matrix = std::make_unique<OffDiagonalScalingMatrix<Number>>(_communicator);
351 else
352 _scaling_matrix = std::make_unique<libMesh::DiagonalMatrix<Number>>(_communicator);
353 }
354
355 if (_preconditioner)
356 _preconditioner->initialSetup();
357}
358
359void
394
395void
397{
398 SolverSystem::customSetup(exec_type);
399
400 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
401 {
402 _kernels.customSetup(exec_type, tid);
403 _nodal_kernels.customSetup(exec_type, tid);
404 _dirac_kernels.customSetup(exec_type, tid);
405 if (_doing_dg)
406 _dg_kernels.customSetup(exec_type, tid);
407 _interface_kernels.customSetup(exec_type, tid);
408 _element_dampers.customSetup(exec_type, tid);
409 _nodal_dampers.customSetup(exec_type, tid);
410 _integrated_bcs.customSetup(exec_type, tid);
411
412 if (_fe_problem.haveFV())
413 for (auto * fv_object : getFVSetupObjects(tid))
414 fv_object->customSetup(exec_type);
415 }
416 _scalar_kernels.customSetup(exec_type);
417 _constraints.customSetup(exec_type);
418 _general_dampers.customSetup(exec_type);
419 _nodal_bcs.customSetup(exec_type);
422
423#ifdef MOOSE_KOKKOS_ENABLED
424 _kokkos_kernels.customSetup(exec_type);
428#endif
429}
430
431void
433{
434 if (_fsp)
435 _fsp->setupDM();
436}
437
438void
439NonlinearSystemBase::addKernel(const std::string & kernel_name,
440 const std::string & name,
441 InputParameters & parameters)
442{
443 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
444 {
445 // Create the kernel object via the factory and add to warehouse
446 std::shared_ptr<KernelBase> kernel =
447 _factory.create<KernelBase>(kernel_name, name, parameters, tid);
448 _kernels.addObject(kernel, tid);
449 postAddResidualObject(*kernel);
450 // Add to theWarehouse, a centralized storage for all moose objects
451 _fe_problem.theWarehouse().add(kernel);
452 }
453
454 if (parameters.get<std::vector<AuxVariableName>>("save_in").size() > 0)
455 _has_save_in = true;
456 if (parameters.get<std::vector<AuxVariableName>>("diag_save_in").size() > 0)
457 _has_diag_save_in = true;
458}
459
460void
461NonlinearSystemBase::addHDGKernel(const std::string & kernel_name,
462 const std::string & name,
463 InputParameters & parameters)
464{
465 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
466 {
467 // Create the kernel object via the factory and add to warehouse
468 auto kernel = _factory.create<HDGKernel>(kernel_name, name, parameters, tid);
469 _kernels.addObject(kernel, tid);
470 _hybridized_kernels.addObject(kernel, tid);
471 // Add to theWarehouse, a centralized storage for all moose objects
472 _fe_problem.theWarehouse().add(kernel);
473 postAddResidualObject(*kernel);
474 }
475}
476
477void
478NonlinearSystemBase::addNodalKernel(const std::string & kernel_name,
479 const std::string & name,
480 InputParameters & parameters)
481{
482 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
483 {
484 // Create the kernel object via the factory and add to the warehouse
485 std::shared_ptr<NodalKernelBase> kernel =
486 _factory.create<NodalKernelBase>(kernel_name, name, parameters, tid);
487 _nodal_kernels.addObject(kernel, tid);
488 // Add to theWarehouse, a centralized storage for all moose objects
489 _fe_problem.theWarehouse().add(kernel);
490 postAddResidualObject(*kernel);
491 }
492
493 if (parameters.have_parameter<std::vector<AuxVariableName>>("save_in") &&
494 parameters.get<std::vector<AuxVariableName>>("save_in").size() > 0)
495 _has_save_in = true;
496 if (parameters.have_parameter<std::vector<AuxVariableName>>("save_in") &&
497 parameters.get<std::vector<AuxVariableName>>("diag_save_in").size() > 0)
498 _has_diag_save_in = true;
499}
500
501void
502NonlinearSystemBase::addScalarKernel(const std::string & kernel_name,
503 const std::string & name,
504 InputParameters & parameters)
505{
506 std::shared_ptr<ScalarKernelBase> kernel =
507 _factory.create<ScalarKernelBase>(kernel_name, name, parameters);
508 postAddResidualObject(*kernel);
509 // Add to theWarehouse, a centralized storage for all moose objects
510 _fe_problem.theWarehouse().add(kernel);
512}
513
514void
516 const std::string & name,
517 InputParameters & parameters)
518{
519 // ThreadID
520 THREAD_ID tid = 0;
521
522 // Create the object
523 std::shared_ptr<BoundaryCondition> bc =
524 _factory.create<BoundaryCondition>(bc_name, name, parameters, tid);
526
527 // Active BoundaryIDs for the object
528 const std::set<BoundaryID> & boundary_ids = bc->boundaryIDs();
529 auto bc_var = dynamic_cast<const MooseVariableFieldBase *>(&bc->variable());
530 _vars[tid].addBoundaryVar(boundary_ids, bc_var);
531
532 // Cast to the various types of BCs
533 std::shared_ptr<NodalBCBase> nbc = std::dynamic_pointer_cast<NodalBCBase>(bc);
534 std::shared_ptr<IntegratedBCBase> ibc = std::dynamic_pointer_cast<IntegratedBCBase>(bc);
535
536 // NodalBCBase
537 if (nbc)
538 {
539 if (nbc->checkNodalVar() && !nbc->variable().isNodal())
540 mooseError("Trying to use nodal boundary condition '",
541 nbc->name(),
542 "' on a non-nodal variable '",
543 nbc->variable().name(),
544 "'.");
545
547 // Add to theWarehouse, a centralized storage for all moose objects
549 _vars[tid].addBoundaryVars(boundary_ids, nbc->getCoupledVars());
550
551 if (parameters.get<std::vector<AuxVariableName>>("save_in").size() > 0)
553 if (parameters.get<std::vector<AuxVariableName>>("diag_save_in").size() > 0)
555
556 // DirichletBCs that are preset
557 std::shared_ptr<DirichletBCBase> dbc = std::dynamic_pointer_cast<DirichletBCBase>(bc);
558 if (dbc && dbc->preset())
560
561 std::shared_ptr<ADDirichletBCBase> addbc = std::dynamic_pointer_cast<ADDirichletBCBase>(bc);
562 if (addbc && addbc->preset())
564 }
565
566 // IntegratedBCBase
567 else if (ibc)
568 {
569 _integrated_bcs.addObject(ibc, tid);
570 // Add to theWarehouse, a centralized storage for all moose objects
572 _vars[tid].addBoundaryVars(boundary_ids, ibc->getCoupledVars());
573
574 if (parameters.get<std::vector<AuxVariableName>>("save_in").size() > 0)
575 _has_save_in = true;
576 if (parameters.get<std::vector<AuxVariableName>>("diag_save_in").size() > 0)
577 _has_diag_save_in = true;
578
579 for (tid = 1; tid < libMesh::n_threads(); tid++)
580 {
581 // Create the object
582 bc = _factory.create<BoundaryCondition>(bc_name, name, parameters, tid);
583
584 // Give users opportunity to set some parameters
586
587 // Active BoundaryIDs for the object
588 const std::set<BoundaryID> & boundary_ids = bc->boundaryIDs();
589 _vars[tid].addBoundaryVar(boundary_ids, bc_var);
590
591 ibc = std::static_pointer_cast<IntegratedBCBase>(bc);
592
593 _integrated_bcs.addObject(ibc, tid);
594 _vars[tid].addBoundaryVars(boundary_ids, ibc->getCoupledVars());
595 }
596 }
597
598 else
599 mooseError("Unknown BoundaryCondition type for object named ", bc->name());
600}
601
602void
603NonlinearSystemBase::addConstraint(const std::string & c_name,
604 const std::string & name,
605 InputParameters & parameters)
606{
607 std::shared_ptr<Constraint> constraint = _factory.create<Constraint>(c_name, name, parameters);
608 _constraints.addObject(constraint);
609 postAddResidualObject(*constraint);
610
612 if (constraint && constraint->addCouplingEntriesToJacobian())
614}
615
616void
617NonlinearSystemBase::addDiracKernel(const std::string & kernel_name,
618 const std::string & name,
619 InputParameters & parameters)
620{
621 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
622 {
623 std::shared_ptr<DiracKernelBase> kernel =
624 _factory.create<DiracKernelBase>(kernel_name, name, parameters, tid);
625 postAddResidualObject(*kernel);
626 _dirac_kernels.addObject(kernel, tid);
627 // Add to theWarehouse, a centralized storage for all moose objects
628 _fe_problem.theWarehouse().add(kernel);
629 }
630}
631
632void
633NonlinearSystemBase::addDGKernel(std::string dg_kernel_name,
634 const std::string & name,
635 InputParameters & parameters)
636{
637 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
638 {
639 auto dg_kernel = _factory.create<DGKernelBase>(dg_kernel_name, name, parameters, tid);
640 _dg_kernels.addObject(dg_kernel, tid);
641 // Add to theWarehouse, a centralized storage for all moose objects
642 _fe_problem.theWarehouse().add(dg_kernel);
643 postAddResidualObject(*dg_kernel);
644 }
645
646 _doing_dg = true;
647
648 if (parameters.get<std::vector<AuxVariableName>>("save_in").size() > 0)
649 _has_save_in = true;
650 if (parameters.get<std::vector<AuxVariableName>>("diag_save_in").size() > 0)
651 _has_diag_save_in = true;
652}
653
654void
655NonlinearSystemBase::addInterfaceKernel(std::string interface_kernel_name,
656 const std::string & name,
657 InputParameters & parameters)
658{
659 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
660 {
661 std::shared_ptr<InterfaceKernelBase> interface_kernel =
662 _factory.create<InterfaceKernelBase>(interface_kernel_name, name, parameters, tid);
663 postAddResidualObject(*interface_kernel);
664
665 const std::set<BoundaryID> & boundary_ids = interface_kernel->boundaryIDs();
666 auto ik_var = dynamic_cast<const MooseVariableFieldBase *>(&interface_kernel->variable());
667 _vars[tid].addBoundaryVar(boundary_ids, ik_var);
668
669 _interface_kernels.addObject(interface_kernel, tid);
670 // Add to theWarehouse, a centralized storage for all moose objects
671 _fe_problem.theWarehouse().add(interface_kernel);
672 _vars[tid].addBoundaryVars(boundary_ids, interface_kernel->getCoupledVars());
673 }
674}
675
676void
677NonlinearSystemBase::addDamper(const std::string & damper_name,
678 const std::string & name,
679 InputParameters & parameters)
680{
681 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
682 {
683 std::shared_ptr<Damper> damper = _factory.create<Damper>(damper_name, name, parameters, tid);
684
685 // Attempt to cast to the damper types
686 std::shared_ptr<ElementDamper> ed = std::dynamic_pointer_cast<ElementDamper>(damper);
687 std::shared_ptr<NodalDamper> nd = std::dynamic_pointer_cast<NodalDamper>(damper);
688 std::shared_ptr<GeneralDamper> gd = std::dynamic_pointer_cast<GeneralDamper>(damper);
689
690 if (gd)
691 {
693 break; // not threaded
694 }
695 else if (ed)
697 else if (nd)
698 _nodal_dampers.addObject(nd, tid);
699 else
700 mooseError("Invalid damper type");
701 }
702}
703
704void
705NonlinearSystemBase::addSplit(const std::string & split_name,
706 const std::string & name,
707 InputParameters & parameters)
708{
709 std::shared_ptr<Split> split = _factory.create<Split>(split_name, name, parameters);
710 _splits.addObject(split);
711 // Add to theWarehouse, a centralized storage for all moose objects
713}
714
715std::shared_ptr<Split>
716NonlinearSystemBase::getSplit(const std::string & name)
717{
719}
720
721bool
723{
725 return false;
726
727 // The legacy behavior (#10464) _always_ performs the pre-SMO residual evaluation
728 // regardless of whether it is needed.
729 //
730 // This is not ideal and has been fixed by #23472. This legacy option ensures a smooth transition
731 // to the new behavior. Modules and Apps that want to migrate to the new behavior should set this
732 // parameter to false.
733 if (_app.parameters().get<bool>("use_legacy_initial_residual_evaluation_behavior"))
734 return true;
735
737}
738
739Real
744
745Real
747{
749 mooseError("pre-SMO residual is requested but not evaluated.");
750
751 return _pre_smo_residual;
752}
753
754Real
759
760void
765
766void
767NonlinearSystemBase::zeroVectorForResidual(const std::string & vector_name)
768{
769 for (unsigned int i = 0; i < _vecs_to_zero_for_residual.size(); ++i)
770 if (vector_name == _vecs_to_zero_for_residual[i])
771 return;
772
773 _vecs_to_zero_for_residual.push_back(vector_name);
774}
775
776void
777NonlinearSystemBase::computeResidualTag(NumericVector<Number> & residual, TagID tag_id)
778{
779 _nl_vector_tags.clear();
780 _nl_vector_tags.insert(tag_id);
782
784
786
788}
789
790void
791NonlinearSystemBase::computeResidual(NumericVector<Number> & residual, TagID tag_id)
792{
793 mooseDeprecated(" Please use computeResidualTag");
794
795 computeResidualTag(residual, tag_id);
796}
797
798void
799NonlinearSystemBase::computeResidualTags(const std::set<TagID> & tags)
800{
801 parallel_object_only();
802
803 TIME_SECTION("nl::computeResidualTags", 5);
804
807
808 bool required_residual = tags.find(residualVectorTag()) == tags.end() ? false : true;
809
811
812 // not suppose to do anythin on matrix
814
816
817 for (const auto & numeric_vec : _vecs_to_zero_for_residual)
818 if (hasVector(numeric_vec))
819 {
820 NumericVector<Number> & vec = getVector(numeric_vec);
821 vec.close();
822 vec.zero();
823 }
824
825 try
826 {
827 zeroTaggedVectors(tags);
829 closeTaggedVectors(tags);
830
831 if (required_residual)
832 {
833 auto & residual = getVector(residualVectorTag());
834 if (!_time_integrators.empty())
835 {
836 for (auto & ti : _time_integrators)
837 ti->postResidual(residual);
838 }
839 else
840 residual += *_Re_non_time;
841 residual.close();
842 }
844 // We don't want to do nodal bcs or anything else
845 return;
846
848 closeTaggedVectors(tags);
849
850 // If we are debugging residuals we need one more assignment to have the ghosted copy up to
851 // date
852 if (_need_residual_ghosted && _debugging_residuals && required_residual)
853 {
854 auto & residual = getVector(residualVectorTag());
855
856 *_residual_ghosted = residual;
858 }
859 // Need to close and update the aux system in case residuals were saved to it.
862 if (hasSaveIn())
864 }
865 catch (MooseException & e)
866 {
867 // The buck stops here, we have already handled the exception by
868 // calling stopSolve(), it is now up to PETSc to return a
869 // "diverged" reason during the next solve.
870 }
871
872 // not supposed to do anything on matrix
874
876}
877
878void
879NonlinearSystemBase::computeResidualAndJacobianTags(const std::set<TagID> & vector_tags,
880 const std::set<TagID> & matrix_tags)
881{
882 const bool required_residual =
883 vector_tags.find(residualVectorTag()) == vector_tags.end() ? false : true;
884
885 try
886 {
887 zeroTaggedVectors(vector_tags);
888 computeResidualAndJacobianInternal(vector_tags, matrix_tags);
889 closeTaggedVectors(vector_tags);
890 closeTaggedMatrices(matrix_tags);
891
892 if (required_residual)
893 {
894 auto & residual = getVector(residualVectorTag());
895 if (!_time_integrators.empty())
896 {
897 for (auto & ti : _time_integrators)
898 ti->postResidual(residual);
899 }
900 else
901 residual += *_Re_non_time;
902 residual.close();
903 }
904
905 computeNodalBCsResidualAndJacobian(vector_tags, matrix_tags);
906 closeTaggedVectors(vector_tags);
907 closeTaggedMatrices(matrix_tags);
908 }
909 catch (MooseException & e)
910 {
911 // The buck stops here, we have already handled the exception by
912 // calling stopSolve(), it is now up to PETSc to return a
913 // "diverged" reason during the next solve.
914 }
915}
916
917void
919{
920 for (auto & ti : _time_integrators)
921 ti->preSolve();
922 if (_predictor.get())
923 _predictor->timestepSetup();
924}
925
926void
928{
930
931 NumericVector<Number> & initial_solution(solution());
932 if (_predictor.get())
933 {
934 if (_predictor->shouldApply())
935 {
936 TIME_SECTION("applyPredictor", 2, "Applying Predictor");
937
938 _predictor->apply(initial_solution);
939 _fe_problem.predictorCleanup(initial_solution);
940 }
941 else
942 _console << " Skipping predictor this step" << std::endl;
943 }
944
945 // do nodal BC
946 {
947 TIME_SECTION("initialBCs", 2, "Applying BCs To Initial Condition");
948
950 for (const auto & bnode : bnd_nodes)
951 {
952 BoundaryID boundary_id = bnode->_bnd_id;
953 Node * node = bnode->_node;
954
955 if (node->processor_id() == processor_id())
956 {
957 bool has_preset_nodal_bcs = _preset_nodal_bcs.hasActiveBoundaryObjects(boundary_id);
958 bool has_ad_preset_nodal_bcs = _ad_preset_nodal_bcs.hasActiveBoundaryObjects(boundary_id);
959
960 // reinit variables in nodes
961 if (has_preset_nodal_bcs || has_ad_preset_nodal_bcs)
962 _fe_problem.reinitNodeFace(node, boundary_id, 0);
963
964 if (has_preset_nodal_bcs)
965 {
966 const auto & preset_bcs = _preset_nodal_bcs.getActiveBoundaryObjects(boundary_id);
967 for (const auto & preset_bc : preset_bcs)
968 preset_bc->computeValue(initial_solution);
969 }
970 if (has_ad_preset_nodal_bcs)
971 {
972 const auto & preset_bcs_res = _ad_preset_nodal_bcs.getActiveBoundaryObjects(boundary_id);
973 for (const auto & preset_bc : preset_bcs_res)
974 preset_bc->computeValue(initial_solution);
975 }
976 }
977 }
978 }
979
980#ifdef MOOSE_KOKKOS_ENABLED
983#endif
984
985 _sys.solution->close();
986 update();
987
988 // Set constraint secondary values
989 setConstraintSecondaryValues(initial_solution, false);
990
992 setConstraintSecondaryValues(initial_solution, true);
993}
994
995void
996NonlinearSystemBase::setPredictor(std::shared_ptr<Predictor> predictor)
997{
998 _predictor = predictor;
999}
1000
1001void
1003{
1005
1006 _kernels.subdomainSetup(subdomain, tid);
1007 _nodal_kernels.subdomainSetup(subdomain, tid);
1008 _element_dampers.subdomainSetup(subdomain, tid);
1009 _nodal_dampers.subdomainSetup(subdomain, tid);
1010}
1011
1012NumericVector<Number> &
1014{
1015 if (!_Re_time)
1016 {
1018
1019 // Most applications don't need the expense of ghosting
1020 libMesh::ParallelType ptype = _need_residual_ghosted ? GHOSTED : PARALLEL;
1021 _Re_time = &addVector(_Re_time_tag, false, ptype);
1022 }
1023 else if (_need_residual_ghosted && _Re_time->type() == PARALLEL)
1024 {
1025 const auto vector_name = _subproblem.vectorTagName(_Re_time_tag);
1026
1027 // If an application changes its mind, the libMesh API lets us
1028 // change the vector.
1029 _Re_time = &system().add_vector(vector_name, false, GHOSTED);
1030 }
1031
1032 return *_Re_time;
1033}
1034
1035NumericVector<Number> &
1037{
1038 if (!_Re_non_time)
1039 {
1041
1042 // Most applications don't need the expense of ghosting
1043 libMesh::ParallelType ptype = _need_residual_ghosted ? GHOSTED : PARALLEL;
1044 _Re_non_time = &addVector(_Re_non_time_tag, false, ptype);
1045 }
1046 else if (_need_residual_ghosted && _Re_non_time->type() == PARALLEL)
1047 {
1048 const auto vector_name = _subproblem.vectorTagName(_Re_non_time_tag);
1049
1050 // If an application changes its mind, the libMesh API lets us
1051 // change the vector.
1052 _Re_non_time = &system().add_vector(vector_name, false, GHOSTED);
1053 }
1054
1055 return *_Re_non_time;
1056}
1057
1058NumericVector<Number> &
1060{
1061 mooseDeprecated("Please use getVector()");
1062 switch (tag)
1063 {
1064 case 0:
1065 return getResidualNonTimeVector();
1066
1067 case 1:
1068 return getResidualTimeVector();
1069
1070 default:
1071 mooseError("The required residual vector is not available");
1072 }
1073}
1074
1075void
1077{
1078 THREAD_ID tid = 0; // constraints are going to be done single-threaded
1079 residual.close();
1081 {
1082 const auto & ncs = _constraints.getActiveNodalConstraints();
1083 for (const auto & nc : ncs)
1084 {
1085 std::vector<dof_id_type> & secondary_node_ids = nc->getSecondaryNodeId();
1086 std::vector<dof_id_type> & primary_node_ids = nc->getPrimaryNodeId();
1087
1088 if ((secondary_node_ids.size() > 0) && (primary_node_ids.size() > 0))
1089 {
1090 nc->reinitConstraintNodes();
1091 nc->computeResidual(residual);
1092 }
1093 }
1095 residual.close();
1096 }
1097}
1098
1099bool
1100NonlinearSystemBase::enforceNodalConstraintsJacobian(const SparseMatrix<Number> & jacobian_to_view)
1101{
1102 if (!hasMatrix(systemMatrixTag()))
1103 mooseError(" A system matrix is required");
1104
1105 THREAD_ID tid = 0; // constraints are going to be done single-threaded
1106
1108 {
1109 const auto & ncs = _constraints.getActiveNodalConstraints();
1110 for (const auto & nc : ncs)
1111 {
1112 std::vector<dof_id_type> & secondary_node_ids = nc->getSecondaryNodeId();
1113 std::vector<dof_id_type> & primary_node_ids = nc->getPrimaryNodeId();
1114
1115 if ((secondary_node_ids.size() > 0) && (primary_node_ids.size() > 0))
1116 {
1117 nc->reinitConstraintNodes();
1118 nc->computeJacobian(jacobian_to_view);
1119 }
1120 }
1122
1123 return true;
1124 }
1125 else
1126 return false;
1127}
1128
1129void
1130NonlinearSystemBase::reinitNodeFace(const Node & secondary_node,
1131 const BoundaryID secondary_boundary,
1132 const PenetrationInfo & info,
1133 const bool displaced)
1134{
1135 auto & subproblem = displaced ? cast_ref<SubProblem &>(*_fe_problem.getDisplacedProblem())
1136 : cast_ref<SubProblem &>(_fe_problem);
1137
1138 const Elem * primary_elem = info._elem;
1139 unsigned int primary_side = info._side_num;
1140 std::vector<Point> points;
1141 points.push_back(info._closest_point);
1142
1143 // *These next steps MUST be done in this order!*
1144 // ADL: This is a Chesterton's fence situation. I don't know which calls exactly the above comment
1145 // is referring to. If I had to guess I would guess just the reinitNodeFace and prepareAssembly
1146 // calls since the former will size the variable's dof indices and then the latter will resize the
1147 // residual/Jacobian based off the variable's cached dof indices size
1148
1149 // This reinits the variables that exist on the secondary node
1150 _fe_problem.reinitNodeFace(&secondary_node, secondary_boundary, 0);
1151
1152 // This will set aside residual and jacobian space for the variables that have dofs on
1153 // the secondary node
1155
1156 _fe_problem.setNeighborSubdomainID(primary_elem, 0);
1157
1158 //
1159 // Reinit material on undisplaced mesh
1160 //
1161
1162 const Elem * const undisplaced_primary_elem =
1163 displaced ? _mesh.elemPtr(primary_elem->id()) : primary_elem;
1164 const Point undisplaced_primary_physical_point =
1165 [&points, displaced, primary_elem, undisplaced_primary_elem]()
1166 {
1167 if (displaced)
1168 {
1169 const Point reference_point =
1170 FEMap::inverse_map(primary_elem->dim(), primary_elem, points[0]);
1171 return FEMap::map(primary_elem->dim(), undisplaced_primary_elem, reference_point);
1172 }
1173 else
1174 // If our penetration locator is on the reference mesh, then our undisplaced
1175 // physical point is simply the point coming from the penetration locator
1176 return points[0];
1177 }();
1178
1180 undisplaced_primary_elem, primary_side, {undisplaced_primary_physical_point}, 0);
1181 // Stateful material properties are only initialized for neighbor material data for internal faces
1182 // for discontinuous Galerkin methods or for conforming interfaces for interface kernels. We don't
1183 // have either of those use cases here where we likely have disconnected meshes
1184 _fe_problem.reinitMaterialsNeighbor(primary_elem->subdomain_id(), 0, /*swap_stateful=*/false);
1185
1186 // Reinit points for constraint enforcement
1187 if (displaced)
1188 subproblem.reinitNeighborPhys(primary_elem, primary_side, points, 0);
1189}
1190
1191void
1192NonlinearSystemBase::setConstraintSecondaryValues(NumericVector<Number> & solution, bool displaced)
1193{
1194
1195 if (displaced)
1196 mooseAssert(_fe_problem.getDisplacedProblem(),
1197 "If we're calling this method with displaced = true, then we better well have a "
1198 "displaced problem");
1199 auto & subproblem = displaced ? cast_ref<SubProblem &>(*_fe_problem.getDisplacedProblem())
1200 : cast_ref<SubProblem &>(_fe_problem);
1201 const auto & penetration_locators = subproblem.geomSearchData()._penetration_locators;
1202
1203 bool constraints_applied = false;
1204
1205 for (const auto & it : penetration_locators)
1206 {
1207 PenetrationLocator & pen_loc = *(it.second);
1208
1209 std::vector<dof_id_type> & secondary_nodes = pen_loc._nearest_node._secondary_nodes;
1210
1211 BoundaryID secondary_boundary = pen_loc._secondary_boundary;
1212 BoundaryID primary_boundary = pen_loc._primary_boundary;
1213
1214 if (_constraints.hasActiveNodeFaceConstraints(secondary_boundary, displaced))
1215 {
1216 const auto & constraints =
1217 _constraints.getActiveNodeFaceConstraints(secondary_boundary, displaced);
1218 std::unordered_set<unsigned int> needed_mat_props;
1219 for (const auto & constraint : constraints)
1220 {
1221 const auto & mp_deps = constraint->getMatPropDependencies();
1222 needed_mat_props.insert(mp_deps.begin(), mp_deps.end());
1223 }
1224 _fe_problem.setActiveMaterialProperties(needed_mat_props, /*tid=*/0);
1225
1226 for (unsigned int i = 0; i < secondary_nodes.size(); i++)
1227 {
1228 dof_id_type secondary_node_num = secondary_nodes[i];
1229 Node & secondary_node = _mesh.nodeRef(secondary_node_num);
1230
1231 if (secondary_node.processor_id() == processor_id())
1232 {
1233 if (pen_loc._penetration_info[secondary_node_num])
1234 {
1235 PenetrationInfo & info = *pen_loc._penetration_info[secondary_node_num];
1236
1237 reinitNodeFace(secondary_node, secondary_boundary, info, displaced);
1238
1239 for (const auto & nfc : constraints)
1240 {
1241 if (nfc->isExplicitConstraint())
1242 continue;
1243 // Return if this constraint does not correspond to the primary-secondary pair
1244 // prepared by the outer loops.
1245 // This continue statement is required when, e.g. one secondary surface constrains
1246 // more than one primary surface.
1247 if (nfc->secondaryBoundary() != secondary_boundary ||
1248 nfc->primaryBoundary() != primary_boundary)
1249 continue;
1250
1251 if (nfc->shouldApply())
1252 {
1253 constraints_applied = true;
1254 nfc->computeSecondaryValue(solution);
1255 }
1256
1257 if (nfc->hasWritableCoupledVariables())
1258 {
1259 Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
1260 for (auto * var : nfc->getWritableCoupledVariables())
1261 {
1262 if (var->isNodalDefined())
1263 var->insert(_fe_problem.getAuxiliarySystem().solution());
1264 }
1265 }
1266 }
1267 }
1268 }
1269 }
1270 }
1271 }
1272
1273 // go over NodeELemConstraints
1274 std::set<dof_id_type> unique_secondary_node_ids;
1275
1276 for (const auto & secondary_id : _mesh.meshSubdomains())
1277 {
1278 for (const auto & primary_id : _mesh.meshSubdomains())
1279 {
1280 if (_constraints.hasActiveNodeElemConstraints(secondary_id, primary_id, displaced))
1281 {
1282 const auto & constraints =
1283 _constraints.getActiveNodeElemConstraints(secondary_id, primary_id, displaced);
1284
1285 // get unique set of ids of all nodes on current block
1286 unique_secondary_node_ids.clear();
1287 const MeshBase & meshhelper = _mesh.getMesh();
1288 for (const auto & elem : as_range(meshhelper.active_subdomain_elements_begin(secondary_id),
1289 meshhelper.active_subdomain_elements_end(secondary_id)))
1290 {
1291 for (auto & n : elem->node_ref_range())
1292 unique_secondary_node_ids.insert(n.id());
1293 }
1294
1295 for (auto secondary_node_id : unique_secondary_node_ids)
1296 {
1297 Node & secondary_node = _mesh.nodeRef(secondary_node_id);
1298
1299 // check if secondary node is on current processor
1300 if (secondary_node.processor_id() == processor_id())
1301 {
1302 // This reinits the variables that exist on the secondary node
1303 _fe_problem.reinitNodeFace(&secondary_node, secondary_id, 0);
1304
1305 // This will set aside residual and jacobian space for the variables that have dofs
1306 // on the secondary node
1308
1309 for (const auto & nec : constraints)
1310 {
1311 if (nec->shouldApply())
1312 {
1313 constraints_applied = true;
1314 nec->computeSecondaryValue(solution);
1315 }
1316 }
1317 }
1318 }
1319 }
1320 }
1321 }
1322
1323 // See if constraints were applied anywhere
1324 _communicator.max(constraints_applied);
1325
1326 if (constraints_applied)
1327 {
1328 solution.close();
1329 update();
1330 }
1331}
1332
1333void
1334NonlinearSystemBase::constraintResiduals(NumericVector<Number> & residual, bool displaced)
1335{
1336 // Make sure the residual is in a good state
1337 residual.close();
1338
1339 if (displaced)
1340 mooseAssert(_fe_problem.getDisplacedProblem(),
1341 "If we're calling this method with displaced = true, then we better well have a "
1342 "displaced problem");
1343 auto & subproblem = displaced ? cast_ref<SubProblem &>(*_fe_problem.getDisplacedProblem())
1344 : cast_ref<SubProblem &>(_fe_problem);
1345 const auto & penetration_locators = subproblem.geomSearchData()._penetration_locators;
1346
1347 bool constraints_applied;
1348 bool residual_has_inserted_values = false;
1350 constraints_applied = false;
1351 for (const auto & it : penetration_locators)
1352 {
1354 {
1355 // Reset the constraint_applied flag before each new constraint, as they need to be
1356 // assembled separately
1357 constraints_applied = false;
1358 }
1359 PenetrationLocator & pen_loc = *(it.second);
1360
1361 std::vector<dof_id_type> & secondary_nodes = pen_loc._nearest_node._secondary_nodes;
1362
1363 BoundaryID secondary_boundary = pen_loc._secondary_boundary;
1364 BoundaryID primary_boundary = pen_loc._primary_boundary;
1365
1366 bool has_writable_variables(false);
1367
1368 if (_constraints.hasActiveNodeFaceConstraints(secondary_boundary, displaced))
1369 {
1370 const auto & constraints =
1371 _constraints.getActiveNodeFaceConstraints(secondary_boundary, displaced);
1372
1373 for (unsigned int i = 0; i < secondary_nodes.size(); i++)
1374 {
1375 dof_id_type secondary_node_num = secondary_nodes[i];
1376 Node & secondary_node = _mesh.nodeRef(secondary_node_num);
1377
1378 if (secondary_node.processor_id() == processor_id())
1379 {
1380 if (pen_loc._penetration_info[secondary_node_num])
1381 {
1382 PenetrationInfo & info = *pen_loc._penetration_info[secondary_node_num];
1383
1384 reinitNodeFace(secondary_node, secondary_boundary, info, displaced);
1385
1386 for (const auto & nfc : constraints)
1387 {
1388 // Return if this constraint does not correspond to the primary-secondary pair
1389 // prepared by the outer loops.
1390 // This continue statement is required when, e.g. one secondary surface constrains
1391 // more than one primary surface.
1392 if (nfc->secondaryBoundary() != secondary_boundary ||
1393 nfc->primaryBoundary() != primary_boundary)
1394 continue;
1395
1396 if (nfc->shouldApply())
1397 {
1398 constraints_applied = true;
1399 nfc->computeResidual();
1400
1401 if (nfc->overwriteSecondaryResidual())
1402 {
1403 // The below will actually overwrite the residual for every single dof that
1404 // lives on the node. We definitely don't want to do that!
1405 // _fe_problem.setResidual(residual, 0);
1406
1407 const auto & secondary_var = nfc->variable();
1408 const auto & secondary_dofs = secondary_var.dofIndices();
1409 mooseAssert(secondary_dofs.size() == secondary_var.count(),
1410 "We are on a node so there should only be one dof per variable (for "
1411 "an ArrayVariable we should have a number of dofs equal to the "
1412 "number of components");
1413
1414 // Assume that if the user is overwriting the secondary residual, then they are
1415 // supplying residuals that do not correspond to their other physics
1416 // (e.g. Kernels), hence we should not apply a scalingFactor that is normally
1417 // based on the order of their other physics (e.g. Kernels)
1418 std::vector<Number> values = {nfc->secondaryResidual()};
1419 residual.insert(values, secondary_dofs);
1420 residual_has_inserted_values = true;
1421 }
1422 else
1425 }
1426 if (nfc->hasWritableCoupledVariables())
1427 {
1428 Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
1429 has_writable_variables = true;
1430 for (auto * var : nfc->getWritableCoupledVariables())
1431 {
1432 if (var->isNodalDefined())
1433 var->insert(_fe_problem.getAuxiliarySystem().solution());
1434 }
1435 }
1436 }
1437 }
1438 }
1439 }
1440 }
1441 _communicator.max(has_writable_variables);
1442
1443 if (has_writable_variables)
1444 {
1445 // Explicit contact dynamic constraints write to auxiliary variables and update the old
1446 // displacement solution on the constraint boundaries. Close solutions and update system
1447 // accordingly.
1450 solutionOld().close();
1451 }
1452
1454 {
1455 // Make sure that secondary contribution to primary are assembled, and ghosts have been
1456 // exchanged, as current primaries might become secondaries on next iteration and will need to
1457 // contribute their former secondaries' contributions to the future primaries. See if
1458 // constraints were applied anywhere
1459 _communicator.max(constraints_applied);
1460
1461 if (constraints_applied)
1462 {
1463 // If any of the above constraints inserted values in the residual, it needs to be
1464 // assembled before adding the cached residuals below.
1465 _communicator.max(residual_has_inserted_values);
1466 if (residual_has_inserted_values)
1467 {
1468 residual.close();
1469 residual_has_inserted_values = false;
1470 }
1472 residual.close();
1473
1475 *_residual_ghosted = residual;
1476 }
1477 }
1478 }
1480 {
1481 _communicator.max(constraints_applied);
1482
1483 if (constraints_applied)
1484 {
1485 // If any of the above constraints inserted values in the residual, it needs to be assembled
1486 // before adding the cached residuals below.
1487 _communicator.max(residual_has_inserted_values);
1488 if (residual_has_inserted_values)
1489 residual.close();
1490
1492 residual.close();
1493
1495 *_residual_ghosted = residual;
1496 }
1497 }
1498
1499 // go over element-element constraint interface
1500 THREAD_ID tid = 0;
1501 const auto & element_pair_locators = subproblem.geomSearchData()._element_pair_locators;
1502 for (const auto & it : element_pair_locators)
1503 {
1504 ElementPairLocator & elem_pair_loc = *(it.second);
1505
1506 if (_constraints.hasActiveElemElemConstraints(it.first, displaced))
1507 {
1508 // ElemElemConstraint objects
1509 const auto & element_constraints =
1510 _constraints.getActiveElemElemConstraints(it.first, displaced);
1511
1512 // go over pair elements
1513 const std::list<std::pair<const Elem *, const Elem *>> & elem_pairs =
1514 elem_pair_loc.getElemPairs();
1515 for (const auto & pr : elem_pairs)
1516 {
1517 const Elem * elem1 = pr.first;
1518 const Elem * elem2 = pr.second;
1519
1520 if (elem1->processor_id() != processor_id())
1521 continue;
1522
1523 const ElementPairInfo & info = elem_pair_loc.getElemPairInfo(pr);
1524
1525 // for each element process constraints on the
1526 for (const auto & ec : element_constraints)
1527 {
1529 subproblem.reinitElemPhys(elem1, info._elem1_constraint_q_point, tid);
1531 subproblem.reinitNeighborPhys(elem2, info._elem2_constraint_q_point, tid);
1532
1533 ec->prepareShapes(ec->variable().number());
1534 ec->prepareNeighborShapes(ec->variable().number());
1535
1536 ec->reinit(info);
1537 ec->computeResidual();
1540 }
1542 }
1543 }
1544 }
1545
1546 // go over NodeElemConstraints
1547 std::set<dof_id_type> unique_secondary_node_ids;
1548
1549 constraints_applied = false;
1550 residual_has_inserted_values = false;
1551 bool has_writable_variables = false;
1552 for (const auto & secondary_id : _mesh.meshSubdomains())
1553 {
1554 for (const auto & primary_id : _mesh.meshSubdomains())
1555 {
1556 if (_constraints.hasActiveNodeElemConstraints(secondary_id, primary_id, displaced))
1557 {
1558 const auto & constraints =
1559 _constraints.getActiveNodeElemConstraints(secondary_id, primary_id, displaced);
1560
1561 // get unique set of ids of all nodes on current block
1562 unique_secondary_node_ids.clear();
1563 const MeshBase & meshhelper = _mesh.getMesh();
1564 for (const auto & elem : as_range(meshhelper.active_subdomain_elements_begin(secondary_id),
1565 meshhelper.active_subdomain_elements_end(secondary_id)))
1566 {
1567 for (auto & n : elem->node_ref_range())
1568 unique_secondary_node_ids.insert(n.id());
1569 }
1570
1571 for (auto secondary_node_id : unique_secondary_node_ids)
1572 {
1573 Node & secondary_node = _mesh.nodeRef(secondary_node_id);
1574 // check if secondary node is on current processor
1575 if (secondary_node.processor_id() == processor_id())
1576 {
1577 // This reinits the variables that exist on the secondary node
1578 _fe_problem.reinitNodeFace(&secondary_node, secondary_id, 0);
1579
1580 // This will set aside residual and jacobian space for the variables that have dofs
1581 // on the secondary node
1583
1584 for (const auto & nec : constraints)
1585 {
1586 if (nec->shouldApply())
1587 {
1588 constraints_applied = true;
1589 nec->computeResidual();
1590
1591 if (nec->overwriteSecondaryResidual())
1592 {
1593 _fe_problem.setResidual(residual, 0);
1594 residual_has_inserted_values = true;
1595 }
1596 else
1599 }
1600 if (nec->hasWritableCoupledVariables())
1601 {
1602 Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
1603 has_writable_variables = true;
1604 for (auto * var : nec->getWritableCoupledVariables())
1605 {
1606 if (var->isNodalDefined())
1607 var->insert(_fe_problem.getAuxiliarySystem().solution());
1608 }
1609 }
1610 }
1612 }
1613 }
1614 }
1615 }
1616 }
1617 _communicator.max(constraints_applied);
1618
1619 if (constraints_applied)
1620 {
1621 // If any of the above constraints inserted values in the residual, it needs to be assembled
1622 // before adding the cached residuals below.
1623 _communicator.max(residual_has_inserted_values);
1624 if (residual_has_inserted_values)
1625 residual.close();
1626
1628 residual.close();
1629
1631 *_residual_ghosted = residual;
1632 }
1633 _communicator.max(has_writable_variables);
1634
1635 if (has_writable_variables)
1636 {
1637 // Explicit contact dynamic constraints write to auxiliary variables and update the old
1638 // displacement solution on the constraint boundaries. Close solutions and update system
1639 // accordingly.
1642 solutionOld().close();
1643 }
1644
1645 // We may have additional tagged vectors that also need to be accumulated
1647}
1648
1649void
1650NonlinearSystemBase::overwriteNodeFace(NumericVector<Number> & soln)
1651{
1652 // Overwrite results from integrator in case we have explicit dynamics contact constraints
1654 ? cast_ref<SubProblem &>(*_fe_problem.getDisplacedProblem())
1655 : cast_ref<SubProblem &>(_fe_problem);
1656 const auto & penetration_locators = subproblem.geomSearchData()._penetration_locators;
1657
1658 for (const auto & it : penetration_locators)
1659 {
1660 PenetrationLocator & pen_loc = *(it.second);
1661
1662 const auto & secondary_nodes = pen_loc._nearest_node._secondary_nodes;
1663 const BoundaryID secondary_boundary = pen_loc._secondary_boundary;
1664 const BoundaryID primary_boundary = pen_loc._primary_boundary;
1665
1666 if (_constraints.hasActiveNodeFaceConstraints(secondary_boundary, true))
1667 {
1668 const auto & constraints =
1669 _constraints.getActiveNodeFaceConstraints(secondary_boundary, true);
1670 for (const auto i : index_range(secondary_nodes))
1671 {
1672 const auto secondary_node_num = secondary_nodes[i];
1673 const Node & secondary_node = _mesh.nodeRef(secondary_node_num);
1674
1675 if (secondary_node.processor_id() == processor_id())
1676 if (pen_loc._penetration_info[secondary_node_num])
1677 for (const auto & nfc : constraints)
1678 {
1679 if (!nfc->isExplicitConstraint())
1680 continue;
1681
1682 // Return if this constraint does not correspond to the primary-secondary pair
1683 // prepared by the outer loops.
1684 // This continue statement is required when, e.g. one secondary surface constrains
1685 // more than one primary surface.
1686 if (nfc->secondaryBoundary() != secondary_boundary ||
1687 nfc->primaryBoundary() != primary_boundary)
1688 continue;
1689
1690 nfc->overwriteBoundaryVariables(soln, secondary_node);
1691 }
1692 }
1693 }
1694 }
1695 soln.close();
1696}
1697
1698void
1700{
1701 TIME_SECTION("residualSetup", 3);
1702
1704
1705 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); tid++)
1706 {
1710 if (_doing_dg)
1716 }
1723
1724#ifdef MOOSE_KOKKOS_ENABLED
1729#endif
1730
1731 // Avoid recursion
1732 if (this == &_fe_problem.currentNonlinearSystem())
1734}
1735
1736void
1738{
1739 parallel_object_only();
1740
1741 TIME_SECTION("computeResidualInternal", 3);
1742
1743 residualSetup();
1744
1745 // Residual contributions from UOs - for now this is used for ray tracing
1746 // and ray kernels that contribute to the residual (think line sources)
1747 std::vector<GeneralUserObject *> uos;
1749 .query()
1750 .condition<AttribSystem>("UserObject")
1751 .condition<AttribExecOns>(EXEC_PRE_KERNELS)
1752 .queryInto(uos);
1753 for (auto & uo : uos)
1754 uo->residualSetup();
1755 for (auto & uo : uos)
1756 {
1757 uo->initialize();
1758 uo->execute();
1759 uo->finalize();
1760 }
1761
1762 // reinit scalar variables
1763 for (unsigned int tid = 0; tid < libMesh::n_threads(); tid++)
1765
1766#ifdef MOOSE_KOKKOS_ENABLED
1769#endif
1770
1771 // residual contributions from the domain
1772 PARALLEL_TRY
1773 {
1774 TIME_SECTION("Kernels", 3 /*, "Computing Kernels"*/);
1775
1776 const ConstElemRange & elem_range = _fe_problem.getCurrentAlgebraicElementRange();
1777
1779 Threads::parallel_reduce(elem_range, cr);
1780
1781 // We pass face information directly to FV residual objects for their evaluation. Consequently
1782 // we must make sure to do separate threaded loops for 1) undisplaced face information objects
1783 // and undisplaced residual objects and 2) displaced face information objects and displaced
1784 // residual objects
1785 using FVRange = StoredRange<MooseMesh::const_face_info_iterator, const FaceInfo *>;
1786 if (_fe_problem.haveFV())
1787 {
1789 _fe_problem, this->number(), tags, /*on_displaced=*/false);
1791 Threads::parallel_reduce(faces, fvr);
1792 }
1795 {
1797 _fe_problem, this->number(), tags, /*on_displaced=*/true);
1798 FVRange faces(displaced_problem->mesh().ownedFaceInfoBegin(),
1799 displaced_problem->mesh().ownedFaceInfoEnd());
1800 Threads::parallel_reduce(faces, fvr);
1801 }
1802
1803 unsigned int n_threads = libMesh::n_threads();
1804 for (unsigned int i = 0; i < n_threads;
1805 i++) // Add any cached residuals that might be hanging around
1807 }
1808 PARALLEL_CATCH;
1809
1810 // residual contributions from the scalar kernels
1811 PARALLEL_TRY
1812 {
1813 // do scalar kernels (not sure how to thread this)
1815 {
1816 TIME_SECTION("ScalarKernels", 3 /*, "Computing ScalarKernels"*/);
1817
1818 MooseObjectWarehouse<ScalarKernelBase> * scalar_kernel_warehouse;
1819 // This code should be refactored once we can do tags for scalar
1820 // kernels
1821 // Should redo this based on Warehouse
1822 if (!tags.size() || tags.size() == _fe_problem.numVectorTags(Moose::VECTOR_TAG_RESIDUAL))
1823 scalar_kernel_warehouse = &_scalar_kernels;
1824 else if (tags.size() == 1)
1825 scalar_kernel_warehouse =
1826 &(_scalar_kernels.getVectorTagObjectWarehouse(*(tags.begin()), 0));
1827 else
1828 // scalar_kernels is not threading
1829 scalar_kernel_warehouse = &(_scalar_kernels.getVectorTagsObjectWarehouse(tags, 0));
1830
1831 bool have_scalar_contributions = false;
1832 const auto & scalars = scalar_kernel_warehouse->getActiveObjects();
1833 for (const auto & scalar_kernel : scalars)
1834 {
1835 scalar_kernel->reinit();
1836 const std::vector<dof_id_type> & dof_indices = scalar_kernel->variable().dofIndices();
1837 const DofMap & dof_map = scalar_kernel->variable().dofMap();
1838 const dof_id_type first_dof = dof_map.first_dof();
1839 const dof_id_type end_dof = dof_map.end_dof();
1840 for (dof_id_type dof : dof_indices)
1841 {
1842 if (dof >= first_dof && dof < end_dof)
1843 {
1844 scalar_kernel->computeResidual();
1845 have_scalar_contributions = true;
1846 break;
1847 }
1848 }
1849 }
1850 if (have_scalar_contributions)
1852 }
1853 }
1854 PARALLEL_CATCH;
1855
1856 // residual contributions from Block NodalKernels
1857 PARALLEL_TRY
1858 {
1860 {
1861 TIME_SECTION("NodalKernels", 3 /*, "Computing NodalKernels"*/);
1862
1864
1865 const ConstNodeRange & range = _fe_problem.getCurrentAlgebraicNodeRange();
1866
1867 if (range.begin() != range.end())
1868 {
1869 _fe_problem.reinitNode(*range.begin(), 0);
1870
1871 Threads::parallel_reduce(range, cnk);
1872
1873 unsigned int n_threads = libMesh::n_threads();
1874 for (unsigned int i = 0; i < n_threads;
1875 i++) // Add any cached residuals that might be hanging around
1877 }
1878 }
1879 }
1880 PARALLEL_CATCH;
1881
1883 // We computed the volumetric objects. We can return now before we get into
1884 // any strongly enforced constraint conditions or penalty-type objects
1885 // (DGKernels, IntegratedBCs, InterfaceKernels, Constraints)
1886 return;
1887
1888 // residual contributions from boundary NodalKernels
1889 PARALLEL_TRY
1890 {
1892 {
1893 TIME_SECTION("NodalKernelBCs", 3 /*, "Computing NodalKernelBCs"*/);
1894
1896
1898
1899 Threads::parallel_reduce(bnd_node_range, cnk);
1900
1901 unsigned int n_threads = libMesh::n_threads();
1902 for (unsigned int i = 0; i < n_threads;
1903 i++) // Add any cached residuals that might be hanging around
1905 }
1906 }
1907 PARALLEL_CATCH;
1908
1910
1911 if (_residual_copy.get())
1912 {
1915 }
1916
1918 {
1922 }
1923
1924 PARALLEL_TRY { computeDiracContributions(tags, {}, Moose::ComputeType::Residual); }
1925 PARALLEL_CATCH;
1926
1928 {
1930 PARALLEL_CATCH;
1932 }
1933
1934 // Add in Residual contributions from other Constraints
1936 {
1937 PARALLEL_TRY
1938 {
1939 // Undisplaced Constraints
1941
1942 // Displaced Constraints
1945
1948 }
1949 PARALLEL_CATCH;
1951 }
1952
1953 // Accumulate the occurrence of solution invalid warnings for the current iteration cumulative
1954 // counters
1957}
1958
1959void
1961 const std::set<TagID> & matrix_tags)
1962{
1963 TIME_SECTION("computeResidualAndJacobianInternal", 3);
1964
1965 // These residual objects are only computed in the separate residual/Jacobian paths. Erroring
1966 // here prevents them from being silently dropped, which would produce wrong answers
1968 mooseDocumentedError("moose",
1969 33531,
1970 "residual_and_jacobian_together does not yet support ScalarKernels. Their "
1971 "contributions would be silently dropped. Please use "
1972 "residual_and_jacobian_together = false");
1974 mooseDocumentedError("moose",
1975 33531,
1976 "residual_and_jacobian_together does not yet support NodalKernels. Their "
1977 "contributions would be silently dropped. Please use "
1978 "residual_and_jacobian_together = false");
1981 "moose",
1982 33531,
1983 "residual_and_jacobian_together does not yet support nodal constraints. Their "
1984 "contributions would be silently dropped. Please use "
1985 "residual_and_jacobian_together = false");
1986
1987 // Make matrix ready to use
1989
1990 for (auto tag : matrix_tags)
1991 {
1992 if (!hasMatrix(tag))
1993 continue;
1994
1995 auto & jacobian = getMatrix(tag);
1996 // Necessary for speed
1997 if (auto petsc_matrix = dynamic_cast<PetscMatrix<Number> *>(&jacobian))
1998 {
1999 LibmeshPetscCall(MatSetOption(petsc_matrix->mat(),
2000 MAT_KEEP_NONZERO_PATTERN, // This is changed in 3.1
2001 PETSC_TRUE));
2003 LibmeshPetscCall(
2004 MatSetOption(petsc_matrix->mat(), MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
2006 LibmeshPetscCall(MatSetOption(
2007 cast_ref<PetscMatrix<Number> &>(jacobian).mat(), MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
2008 }
2009 }
2010
2011 residualSetup();
2012
2013 // Residual contributions from UOs - for now this is used for ray tracing
2014 // and ray kernels that contribute to the residual (think line sources)
2015 std::vector<UserObject *> uos;
2017 .query()
2018 .condition<AttribSystem>("UserObject")
2019 .condition<AttribExecOns>(EXEC_PRE_KERNELS)
2020 .queryInto(uos);
2021 for (auto & uo : uos)
2022 uo->residualSetup();
2023 for (auto & uo : uos)
2024 {
2025 uo->initialize();
2026 uo->execute();
2027 uo->finalize();
2028 }
2029
2030 // reinit scalar variables
2031 for (unsigned int tid = 0; tid < libMesh::n_threads(); tid++)
2033
2034#ifdef MOOSE_KOKKOS_ENABLED
2036 computeKokkosResidualAndJacobian(vector_tags, matrix_tags);
2037#endif
2038
2039 // residual contributions from the domain
2040 PARALLEL_TRY
2041 {
2042 TIME_SECTION("Kernels", 3 /*, "Computing Kernels"*/);
2043
2044 const ConstElemRange & elem_range = _fe_problem.getCurrentAlgebraicElementRange();
2045
2046 ComputeResidualAndJacobianThread crj(_fe_problem, vector_tags, matrix_tags);
2047 Threads::parallel_reduce(elem_range, crj);
2048
2049 using FVRange = StoredRange<MooseMesh::const_face_info_iterator, const FaceInfo *>;
2050 if (_fe_problem.haveFV())
2051 {
2053 _fe_problem, this->number(), vector_tags, matrix_tags, /*on_displaced=*/false);
2055 Threads::parallel_reduce(faces, fvrj);
2056 }
2059 {
2061 _fe_problem, this->number(), vector_tags, matrix_tags, /*on_displaced=*/true);
2062 FVRange faces(displaced_problem->mesh().ownedFaceInfoBegin(),
2063 displaced_problem->mesh().ownedFaceInfoEnd());
2064 Threads::parallel_reduce(faces, fvr);
2065 }
2066
2068
2069 unsigned int n_threads = libMesh::n_threads();
2070 for (unsigned int i = 0; i < n_threads;
2071 i++) // Add any cached residuals that might be hanging around
2072 {
2075 }
2076 }
2077 PARALLEL_CATCH;
2078
2079 // residual and Jacobian contributions from DiracKernels, computed together in a single pass
2080 PARALLEL_TRY
2081 {
2083 }
2084 PARALLEL_CATCH;
2085}
2086
2087void
2088NonlinearSystemBase::computeNodalBCsResidual(NumericVector<Number> & residual)
2089{
2090 _nl_vector_tags.clear();
2091
2092 const auto & residual_vector_tags = _fe_problem.getVectorTags(Moose::VECTOR_TAG_RESIDUAL);
2093 for (const auto & residual_vector_tag : residual_vector_tags)
2094 _nl_vector_tags.insert(residual_vector_tag._id);
2095
2099}
2100
2101void
2102NonlinearSystemBase::computeNodalBCsResidual(NumericVector<Number> & residual,
2103 const std::set<TagID> & tags)
2104{
2106
2108
2110}
2111
2112void
2114{
2115#ifdef MOOSE_KOKKOS_ENABLED
2118#endif
2119
2120 // We need to close the diag_save_in variables on the aux system before NodalBCBases clear the
2121 // dofs on boundary nodes
2122 if (_has_save_in)
2124
2125 // Select nodal kernels
2126 MooseObjectWarehouse<NodalBCBase> * nbc_warehouse;
2127
2128 if (tags.size() == _fe_problem.numVectorTags(Moose::VECTOR_TAG_RESIDUAL) || !tags.size())
2129 nbc_warehouse = &_nodal_bcs;
2130 else if (tags.size() == 1)
2131 nbc_warehouse = &(_nodal_bcs.getVectorTagObjectWarehouse(*(tags.begin()), 0));
2132 else
2133 nbc_warehouse = &(_nodal_bcs.getVectorTagsObjectWarehouse(tags, 0));
2134
2135 // Return early if there is no nodal kernel
2136 if (!nbc_warehouse->hasActiveObjects())
2137 return;
2138
2139 PARALLEL_TRY
2140 {
2142
2143 if (!bnd_nodes.empty())
2144 {
2145 TIME_SECTION("NodalBCs", 3 /*, "Computing NodalBCs"*/);
2146
2147 for (const auto & bnode : bnd_nodes)
2148 {
2149 BoundaryID boundary_id = bnode->_bnd_id;
2150 Node * node = bnode->_node;
2151
2152 if (node->processor_id() == processor_id() &&
2153 nbc_warehouse->hasActiveBoundaryObjects(boundary_id))
2154 {
2155 // reinit variables in nodes
2156 _fe_problem.reinitNodeFace(node, boundary_id, 0);
2157
2158 const auto & bcs = nbc_warehouse->getActiveBoundaryObjects(boundary_id);
2159 for (const auto & nbc : bcs)
2160 if (nbc->shouldApply())
2161 nbc->computeResidual();
2162 }
2163 }
2164 }
2165 }
2166 PARALLEL_CATCH;
2167
2168 if (_Re_time)
2169 _Re_time->close();
2171}
2172
2173void
2175{
2176 // We need to close the save_in variables on the aux system before NodalBCBases clear the dofs
2177 // on boundary nodes
2180
2181 MooseObjectWarehouse<NodalBCBase> * nbc_warehouse;
2182
2183 // Select nodal kernels
2184 if (tags.size() == _fe_problem.numMatrixTags() || !tags.size())
2185 nbc_warehouse = &_nodal_bcs;
2186 else if (tags.size() == 1)
2187 nbc_warehouse = &(_nodal_bcs.getMatrixTagObjectWarehouse(*(tags.begin()), 0));
2188 else
2189 nbc_warehouse = &(_nodal_bcs.getMatrixTagsObjectWarehouse(tags, 0));
2190
2191 // Return early if there is no nodal kernel
2192 if (!nbc_warehouse->hasActiveObjects())
2193 return;
2194
2195 PARALLEL_TRY
2196 {
2197 // We may be switching from add to set. Moreover, we rely on a call to MatZeroRows to enforce
2198 // the nodal boundary condition constraints which requires that the matrix be truly assembled
2199 // as opposed to just flushed. Consequently we can't do the following despite any desire to
2200 // keep our initial sparsity pattern honored (see https://gitlab.com/petsc/petsc/-/issues/852)
2201 //
2202 // flushTaggedMatrices(tags);
2203 closeTaggedMatrices(tags);
2204
2205 // Cache the information about which BCs are coupled to which
2206 // variables, so we don't have to figure it out for each node.
2207 std::map<std::string, std::set<unsigned int>> bc_involved_vars;
2208 const std::set<BoundaryID> & all_boundary_ids = _mesh.getBoundaryIDs();
2209 for (const auto & bid : all_boundary_ids)
2210 {
2211 // Get reference to all the NodalBCs for this ID. This is only
2212 // safe if there are NodalBCBases there to be gotten...
2213 if (nbc_warehouse->hasActiveBoundaryObjects(bid))
2214 {
2215 const auto & bcs = nbc_warehouse->getActiveBoundaryObjects(bid);
2216 for (const auto & bc : bcs)
2217 {
2218 const std::vector<MooseVariableFEBase *> & coupled_moose_vars = bc->getCoupledMooseVars();
2219
2220 // Create the set of "involved" MOOSE nonlinear vars, which includes all coupled vars
2221 // and the BC's own variable
2222 std::set<unsigned int> & var_set = bc_involved_vars[bc->name()];
2223 for (const auto & coupled_var : coupled_moose_vars)
2224 if (coupled_var->kind() == Moose::VAR_SOLVER)
2225 var_set.insert(coupled_var->number());
2226
2227 var_set.insert(bc->variable().number());
2228 }
2229 }
2230 }
2231
2232 // reinit scalar variables again. This reinit does not re-fill any of the scalar variable
2233 // solution arrays because that was done above. It only will reorder the derivative
2234 // information for AD calculations to be suitable for NodalBC calculations
2235 for (unsigned int tid = 0; tid < libMesh::n_threads(); tid++)
2236 _fe_problem.reinitScalars(tid, true);
2237
2238 // Get variable coupling list. We do all the NodalBCBase stuff on
2239 // thread 0... The couplingEntries() data structure determines
2240 // which variables are "coupled" as far as the preconditioner is
2241 // concerned, not what variables a boundary condition specifically
2242 // depends on.
2243 auto & coupling_entries = _fe_problem.couplingEntries(/*_tid=*/0, this->number());
2244
2245 // Compute Jacobians for NodalBCBases
2247 for (const auto & bnode : bnd_nodes)
2248 {
2249 BoundaryID boundary_id = bnode->_bnd_id;
2250 Node * node = bnode->_node;
2251
2252 if (nbc_warehouse->hasActiveBoundaryObjects(boundary_id) &&
2253 node->processor_id() == processor_id())
2254 {
2255 _fe_problem.reinitNodeFace(node, boundary_id, 0);
2256
2257 const auto & bcs = nbc_warehouse->getActiveBoundaryObjects(boundary_id);
2258 for (const auto & bc : bcs)
2259 {
2260 // Get the set of involved MOOSE vars for this BC
2261 std::set<unsigned int> & var_set = bc_involved_vars[bc->name()];
2262
2263 // Loop over all the variables whose Jacobian blocks are
2264 // actually being computed, call computeOffDiagJacobian()
2265 // for each one which is actually coupled (otherwise the
2266 // value is zero.)
2267 for (const auto & it : coupling_entries)
2268 {
2269 unsigned int ivar = it.first->number(), jvar = it.second->number();
2270
2271 // We are only going to call computeOffDiagJacobian() if:
2272 // 1.) the BC's variable is ivar
2273 // 2.) jvar is "involved" with the BC (including jvar==ivar), and
2274 // 3.) the BC should apply.
2275 if ((bc->variable().number() == ivar) && var_set.count(jvar) && bc->shouldApply())
2276 bc->computeOffDiagJacobian(jvar);
2277 }
2278
2279 // only if this coupling is being used by the preconditioner (otherwise the value is
2280 // zero)
2281 const auto & coupled_scalar_vars = bc->getCoupledMooseScalarVars();
2282 for (const auto & jvariable : coupled_scalar_vars)
2283 if (hasScalarVariable(jvariable->name()) &&
2284 _fe_problem.areCoupled(bc->variable().number(), jvariable->number(), number()))
2285 bc->computeOffDiagJacobianScalar(jvariable->number());
2286 }
2287 }
2288 } // end loop over boundary nodes
2289
2290 // Set the cached NodalBCBase values in the Jacobian matrix
2291 _fe_problem.assembly(0, number()).setCachedJacobian(Assembly::GlobalDataKey{});
2292 }
2293 PARALLEL_CATCH;
2294}
2295
2296void
2298 [[maybe_unused]] const std::set<TagID> & vector_tags,
2299 [[maybe_unused]] const std::set<TagID> & matrix_tags)
2300{
2301#ifdef MOOSE_KOKKOS_ENABLED
2303 computeKokkosNodalBCsResidual(vector_tags);
2304#endif
2305
2306 // Return early if there is no nodal kernel
2308 return;
2309
2310 PARALLEL_TRY
2311 {
2313
2314 if (!bnd_nodes.empty())
2315 {
2316 TIME_SECTION("NodalBCs", 3 /*, "Computing NodalBCs"*/);
2317
2318 for (const auto & bnode : bnd_nodes)
2319 {
2320 BoundaryID boundary_id = bnode->_bnd_id;
2321 Node * node = bnode->_node;
2322
2323 if (node->processor_id() == processor_id())
2324 {
2325 // reinit variables in nodes
2326 _fe_problem.reinitNodeFace(node, boundary_id, 0);
2327 if (_nodal_bcs.hasActiveBoundaryObjects(boundary_id))
2328 {
2329 const auto & bcs = _nodal_bcs.getActiveBoundaryObjects(boundary_id);
2330 for (const auto & nbc : bcs)
2331 if (nbc->shouldApply())
2332 nbc->computeResidualAndJacobian();
2333 }
2334 }
2335 }
2336 }
2337 }
2338 PARALLEL_CATCH;
2339
2340 // Set the cached NodalBCBase values in the Jacobian matrix
2341 _fe_problem.assembly(0, number()).setCachedJacobian(Assembly::GlobalDataKey{});
2342}
2343
2344void
2345NonlinearSystemBase::getNodeDofs(dof_id_type node_id, std::vector<dof_id_type> & dofs)
2346{
2347 const Node & node = _mesh.nodeRef(node_id);
2348 unsigned int s = number();
2349 if (node.has_dofs(s))
2350 {
2351 for (unsigned int v = 0; v < nVariables(); v++)
2352 for (unsigned int c = 0; c < node.n_comp(s, v); c++)
2353 dofs.push_back(node.dof_number(s, v, c));
2354 }
2355}
2356
2357void
2359 GeometricSearchData & geom_search_data,
2360 std::unordered_map<dof_id_type, std::vector<dof_id_type>> & graph)
2361{
2362 const auto & node_to_elem_map = _mesh.nodeToElemMap();
2363 const auto & nearest_node_locators = geom_search_data._nearest_node_locators;
2364 for (const auto & it : nearest_node_locators)
2365 {
2366 std::vector<dof_id_type> & secondary_nodes = it.second->_secondary_nodes;
2367
2368 for (const auto & secondary_node : secondary_nodes)
2369 {
2370 std::set<dof_id_type> unique_secondary_indices;
2371 std::set<dof_id_type> unique_primary_indices;
2372
2373 auto node_to_elem_pair = node_to_elem_map.find(secondary_node);
2374 if (node_to_elem_pair != node_to_elem_map.end())
2375 {
2376 const std::vector<dof_id_type> & elems = node_to_elem_pair->second;
2377
2378 // Get the dof indices from each elem connected to the node
2379 for (const auto & cur_elem : elems)
2380 {
2381 std::vector<dof_id_type> dof_indices;
2382 dofMap().dof_indices(_mesh.elemPtr(cur_elem), dof_indices);
2383
2384 for (const auto & dof : dof_indices)
2385 unique_secondary_indices.insert(dof);
2386 }
2387 }
2388
2389 std::vector<dof_id_type> primary_nodes = it.second->_neighbor_nodes[secondary_node];
2390
2391 for (const auto & primary_node : primary_nodes)
2392 {
2393 auto primary_node_to_elem_pair = node_to_elem_map.find(primary_node);
2394 mooseAssert(primary_node_to_elem_pair != node_to_elem_map.end(),
2395 "Missing entry in node to elem map");
2396 const std::vector<dof_id_type> & primary_node_elems = primary_node_to_elem_pair->second;
2397
2398 // Get the dof indices from each elem connected to the node
2399 for (const auto & cur_elem : primary_node_elems)
2400 {
2401 std::vector<dof_id_type> dof_indices;
2402 dofMap().dof_indices(_mesh.elemPtr(cur_elem), dof_indices);
2403
2404 for (const auto & dof : dof_indices)
2405 unique_primary_indices.insert(dof);
2406 }
2407 }
2408
2409 for (const auto & secondary_id : unique_secondary_indices)
2410 for (const auto & primary_id : unique_primary_indices)
2411 {
2412 graph[secondary_id].push_back(primary_id);
2413 graph[primary_id].push_back(secondary_id);
2414 }
2415 }
2416 }
2417
2418 // handle node-to-node constraints
2419 const auto & ncs = _constraints.getActiveNodalConstraints();
2420 for (const auto & nc : ncs)
2421 {
2422 std::vector<dof_id_type> primary_dofs;
2423 std::vector<dof_id_type> & primary_node_ids = nc->getPrimaryNodeId();
2424 for (const auto & node_id : primary_node_ids)
2425 {
2426 Node * node = _mesh.queryNodePtr(node_id);
2427 if (node && node->processor_id() == this->processor_id())
2428 {
2429 getNodeDofs(node_id, primary_dofs);
2430 }
2431 }
2432
2433 _communicator.allgather(primary_dofs);
2434
2435 std::vector<dof_id_type> secondary_dofs;
2436 std::vector<dof_id_type> & secondary_node_ids = nc->getSecondaryNodeId();
2437 for (const auto & node_id : secondary_node_ids)
2438 {
2439 Node * node = _mesh.queryNodePtr(node_id);
2440 if (node && node->processor_id() == this->processor_id())
2441 {
2442 getNodeDofs(node_id, secondary_dofs);
2443 }
2444 }
2445
2446 _communicator.allgather(secondary_dofs);
2447
2448 for (const auto & primary_id : primary_dofs)
2449 for (const auto & secondary_id : secondary_dofs)
2450 {
2451 graph[primary_id].push_back(secondary_id);
2452 graph[secondary_id].push_back(primary_id);
2453 }
2454 }
2455
2456 // Make every entry sorted and unique
2457 for (auto & it : graph)
2458 {
2459 std::vector<dof_id_type> & row = it.second;
2460 std::sort(row.begin(), row.end());
2461 std::vector<dof_id_type>::iterator uit = std::unique(row.begin(), row.end());
2462 row.resize(uit - row.begin());
2463 }
2464}
2465
2466void
2468{
2469 if (!hasMatrix(systemMatrixTag()))
2470 mooseError("Need a system matrix ");
2471
2472 // At this point, have no idea how to make
2473 // this work with tag system
2474 auto & jacobian = getMatrix(systemMatrixTag());
2475
2476 std::unordered_map<dof_id_type, std::vector<dof_id_type>> graph;
2477
2478 findImplicitGeometricCouplingEntries(geom_search_data, graph);
2479
2480 for (const auto & it : graph)
2481 {
2482 dof_id_type dof = it.first;
2483 const auto & row = it.second;
2484
2485 for (const auto & coupled_dof : row)
2486 jacobian.add(dof, coupled_dof, 0);
2487 }
2488}
2489
2490void
2491NonlinearSystemBase::constraintJacobians(const SparseMatrix<Number> & jacobian_to_view,
2492 bool displaced)
2493{
2494 if (!hasMatrix(systemMatrixTag()))
2495 mooseError("A system matrix is required");
2496
2497 auto & jacobian = getMatrix(systemMatrixTag());
2498
2500 LibmeshPetscCall(MatSetOption(cast_ref<PetscMatrix<Number> &>(jacobian).mat(),
2501 MAT_NEW_NONZERO_ALLOCATION_ERR,
2502 PETSC_FALSE));
2504 LibmeshPetscCall(MatSetOption(
2505 cast_ref<PetscMatrix<Number> &>(jacobian).mat(), MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
2506
2507 std::vector<numeric_index_type> zero_rows;
2508
2509 if (displaced)
2510 mooseAssert(_fe_problem.getDisplacedProblem(),
2511 "If we're calling this method with displaced = true, then we better well have a "
2512 "displaced problem");
2513 auto & subproblem = displaced ? cast_ref<SubProblem &>(*_fe_problem.getDisplacedProblem())
2514 : cast_ref<SubProblem &>(_fe_problem);
2515 const auto & penetration_locators = subproblem.geomSearchData()._penetration_locators;
2516
2517 bool constraints_applied;
2519 constraints_applied = false;
2520 for (const auto & it : penetration_locators)
2521 {
2523 {
2524 // Reset the constraint_applied flag before each new constraint, as they need to be
2525 // assembled separately
2526 constraints_applied = false;
2527 }
2528 PenetrationLocator & pen_loc = *(it.second);
2529
2530 std::vector<dof_id_type> & secondary_nodes = pen_loc._nearest_node._secondary_nodes;
2531
2532 BoundaryID secondary_boundary = pen_loc._secondary_boundary;
2533 BoundaryID primary_boundary = pen_loc._primary_boundary;
2534
2535 zero_rows.clear();
2536 if (_constraints.hasActiveNodeFaceConstraints(secondary_boundary, displaced))
2537 {
2538 const auto & constraints =
2539 _constraints.getActiveNodeFaceConstraints(secondary_boundary, displaced);
2540
2541 for (const auto & secondary_node_num : secondary_nodes)
2542 {
2543 Node & secondary_node = _mesh.nodeRef(secondary_node_num);
2544
2545 if (secondary_node.processor_id() == processor_id())
2546 {
2547 if (pen_loc._penetration_info[secondary_node_num])
2548 {
2549 PenetrationInfo & info = *pen_loc._penetration_info[secondary_node_num];
2550
2551 reinitNodeFace(secondary_node, secondary_boundary, info, displaced);
2553
2554 for (const auto & nfc : constraints)
2555 {
2556 if (nfc->isExplicitConstraint())
2557 continue;
2558 // Return if this constraint does not correspond to the primary-secondary pair
2559 // prepared by the outer loops.
2560 // This continue statement is required when, e.g. one secondary surface constrains
2561 // more than one primary surface.
2562 if (nfc->secondaryBoundary() != secondary_boundary ||
2563 nfc->primaryBoundary() != primary_boundary)
2564 continue;
2565
2566 nfc->_jacobian = &jacobian_to_view;
2567
2568 if (nfc->shouldApply())
2569 {
2570 constraints_applied = true;
2571
2572 // Begin the diagonal node-face constraint accumulation phase for neighbor Jacobian
2573 // blocks.
2575
2576 nfc->prepareShapes(nfc->variable().number());
2577 nfc->prepareNeighborShapes(nfc->variable().number());
2578
2579 nfc->computeJacobian();
2580
2581 if (nfc->overwriteSecondaryJacobian())
2582 {
2583 // Add this variable's dof's row to be zeroed
2584 zero_rows.push_back(nfc->variable().nodalDofIndex());
2585 }
2586
2587 std::vector<dof_id_type> secondary_dofs(1, nfc->variable().nodalDofIndex());
2588
2589 // Assume that if the user is overwriting the secondary Jacobian, then they are
2590 // supplying Jacobians that do not correspond to their other physics
2591 // (e.g. Kernels), hence we should not apply a scalingFactor that is normally
2592 // based on the order of their other physics (e.g. Kernels)
2593 Real scaling_factor =
2594 nfc->overwriteSecondaryJacobian() ? 1. : nfc->variable().scalingFactor();
2595
2596 // Cache the jacobian block for the secondary side
2597 nfc->addJacobian(_fe_problem.assembly(0, number()),
2598 nfc->_Kee,
2599 secondary_dofs,
2600 nfc->_connected_dof_indices,
2601 scaling_factor);
2602
2603 // Cache Ken, Kne, Knn
2604 if (nfc->addCouplingEntriesToJacobian())
2605 {
2606 // Make sure we use a proper scaling factor (e.g. don't use an interior scaling
2607 // factor when we're overwriting secondary stuff)
2608 nfc->addJacobian(_fe_problem.assembly(0, number()),
2609 nfc->_Ken,
2610 secondary_dofs,
2611 nfc->primaryVariable().dofIndicesNeighbor(),
2612 scaling_factor);
2613
2614 // Use _connected_dof_indices to get all the correct columns
2615 nfc->addJacobian(_fe_problem.assembly(0, number()),
2616 nfc->_Kne,
2617 nfc->primaryVariable().dofIndicesNeighbor(),
2618 nfc->_connected_dof_indices,
2619 nfc->primaryVariable().scalingFactor());
2620
2621 // We've handled Ken and Kne, finally handle Knn
2623 }
2624
2625 // Do the off-diagonals next
2626 const std::vector<MooseVariableFEBase *> coupled_vars = nfc->getCoupledMooseVars();
2627 for (const auto & jvar : coupled_vars)
2628 {
2629 // Only compute jacobians for nonlinear variables
2630 if (jvar->kind() != Moose::VAR_SOLVER)
2631 continue;
2632
2633 // Only compute Jacobian entries if this coupling is being used by the
2634 // preconditioner
2635 if (nfc->variable().number() == jvar->number() ||
2637 nfc->variable().number(), jvar->number(), this->number()))
2638 continue;
2639
2640 // Begin the off-diagonal node-face constraint accumulation phase for
2641 // element and neighbor Jacobian blocks.
2644
2645 nfc->prepareShapes(nfc->variable().number());
2646 nfc->prepareNeighborShapes(jvar->number());
2647
2648 nfc->computeOffDiagJacobian(jvar->number());
2649
2650 // Cache the jacobian block for the secondary side
2651 nfc->addJacobian(_fe_problem.assembly(0, number()),
2652 nfc->_Kee,
2653 secondary_dofs,
2654 nfc->_connected_dof_indices,
2655 scaling_factor);
2656
2657 // Cache Ken, Kne, Knn
2658 if (nfc->addCouplingEntriesToJacobian())
2659 {
2660 // Make sure we use a proper scaling factor (e.g. don't use an interior scaling
2661 // factor when we're overwriting secondary stuff)
2662 nfc->addJacobian(_fe_problem.assembly(0, number()),
2663 nfc->_Ken,
2664 secondary_dofs,
2665 jvar->dofIndicesNeighbor(),
2666 scaling_factor);
2667
2668 // Use _connected_dof_indices to get all the correct columns
2669 nfc->addJacobian(_fe_problem.assembly(0, number()),
2670 nfc->_Kne,
2671 nfc->variable().dofIndicesNeighbor(),
2672 nfc->_connected_dof_indices,
2673 nfc->variable().scalingFactor());
2674
2675 // We've handled Ken and Kne, finally handle Knn
2677 }
2678 }
2679 }
2680 }
2681 }
2682 }
2683 }
2684 }
2686 {
2687 // See if constraints were applied anywhere
2688 _communicator.max(constraints_applied);
2689
2690 if (constraints_applied)
2691 {
2692 LibmeshPetscCall(MatSetOption(cast_ref<PetscMatrix<Number> &>(jacobian).mat(),
2693 MAT_KEEP_NONZERO_PATTERN, // This is changed in 3.1
2694 PETSC_TRUE));
2695
2696 jacobian.close();
2697 jacobian.zero_rows(zero_rows, 0.0);
2698 jacobian.close();
2700 jacobian.close();
2701 }
2702 }
2703 }
2705 {
2706 // See if constraints were applied anywhere
2707 _communicator.max(constraints_applied);
2708
2709 if (constraints_applied)
2710 {
2711 LibmeshPetscCall(MatSetOption(cast_ref<PetscMatrix<Number> &>(jacobian).mat(),
2712 MAT_KEEP_NONZERO_PATTERN, // This is changed in 3.1
2713 PETSC_TRUE));
2714
2715 jacobian.close();
2716 jacobian.zero_rows(zero_rows, 0.0);
2717 jacobian.close();
2719 jacobian.close();
2720 }
2721 }
2722
2723 THREAD_ID tid = 0;
2724 // go over element-element constraint interface
2725 const auto & element_pair_locators = subproblem.geomSearchData()._element_pair_locators;
2726 for (const auto & it : element_pair_locators)
2727 {
2728 ElementPairLocator & elem_pair_loc = *(it.second);
2729
2730 if (_constraints.hasActiveElemElemConstraints(it.first, displaced))
2731 {
2732 // ElemElemConstraint objects
2733 const auto & element_constraints =
2734 _constraints.getActiveElemElemConstraints(it.first, displaced);
2735
2736 // go over pair elements
2737 const std::list<std::pair<const Elem *, const Elem *>> & elem_pairs =
2738 elem_pair_loc.getElemPairs();
2739 for (const auto & pr : elem_pairs)
2740 {
2741 const Elem * elem1 = pr.first;
2742 const Elem * elem2 = pr.second;
2743
2744 if (elem1->processor_id() != processor_id())
2745 continue;
2746
2747 const ElementPairInfo & info = elem_pair_loc.getElemPairInfo(pr);
2748
2749 // for each element process constraints on the
2750 for (const auto & ec : element_constraints)
2751 {
2753 subproblem.reinitElemPhys(elem1, info._elem1_constraint_q_point, tid);
2755 subproblem.reinitNeighborPhys(elem2, info._elem2_constraint_q_point, tid);
2756
2757 // Begin the element-element constraint accumulation phase for element and neighbor
2758 // Jacobian blocks.
2761
2762 ec->prepareShapes(ec->variable().number());
2763 ec->prepareNeighborShapes(ec->variable().number());
2764
2765 ec->reinit(info);
2766 ec->computeJacobian();
2769 }
2771 }
2772 }
2773 }
2774
2775 // go over NodeElemConstraints
2776 std::set<dof_id_type> unique_secondary_node_ids;
2777 constraints_applied = false;
2778 for (const auto & secondary_id : _mesh.meshSubdomains())
2779 {
2780 for (const auto & primary_id : _mesh.meshSubdomains())
2781 {
2782 if (_constraints.hasActiveNodeElemConstraints(secondary_id, primary_id, displaced))
2783 {
2784 const auto & constraints =
2785 _constraints.getActiveNodeElemConstraints(secondary_id, primary_id, displaced);
2786
2787 // get unique set of ids of all nodes on current block
2788 unique_secondary_node_ids.clear();
2789 const MeshBase & meshhelper = _mesh.getMesh();
2790 for (const auto & elem : as_range(meshhelper.active_subdomain_elements_begin(secondary_id),
2791 meshhelper.active_subdomain_elements_end(secondary_id)))
2792 {
2793 for (auto & n : elem->node_ref_range())
2794 unique_secondary_node_ids.insert(n.id());
2795 }
2796
2797 for (auto secondary_node_id : unique_secondary_node_ids)
2798 {
2799 const Node & secondary_node = _mesh.nodeRef(secondary_node_id);
2800 // check if secondary node is on current processor
2801 if (secondary_node.processor_id() == processor_id())
2802 {
2803 // This reinits the variables that exist on the secondary node
2804 _fe_problem.reinitNodeFace(&secondary_node, secondary_id, 0);
2805
2807
2808 for (const auto & nec : constraints)
2809 {
2810 if (nec->shouldApply())
2811 {
2812 constraints_applied = true;
2813
2814 // Begin the diagonal node-element constraint accumulation phase for
2815 // element and neighbor Jacobian blocks.
2818
2819 nec->_jacobian = &jacobian_to_view;
2820 nec->prepareShapes(nec->variable().number());
2821 nec->prepareNeighborShapes(nec->variable().number());
2822
2823 nec->computeJacobian();
2824
2825 if (nec->overwriteSecondaryJacobian())
2826 {
2827 // Add this variable's dof's row to be zeroed
2828 zero_rows.push_back(nec->variable().nodalDofIndex());
2829 }
2830
2831 std::vector<dof_id_type> secondary_dofs(1, nec->variable().nodalDofIndex());
2832
2833 // Cache the jacobian block for the secondary side
2834 nec->addJacobian(_fe_problem.assembly(0, number()),
2835 nec->_Kee,
2836 secondary_dofs,
2837 nec->_connected_dof_indices,
2838 nec->variable().scalingFactor());
2839
2840 // Cache the jacobian block for the primary side
2841 nec->addJacobian(_fe_problem.assembly(0, number()),
2842 nec->_Kne,
2843 nec->primaryVariable().dofIndicesNeighbor(),
2844 nec->_connected_dof_indices,
2845 nec->primaryVariable().scalingFactor());
2846
2849
2850 // Do the off-diagonals next
2851 const std::vector<MooseVariableFEBase *> coupled_vars = nec->getCoupledMooseVars();
2852 for (const auto & jvar : coupled_vars)
2853 {
2854 // Only compute jacobians for nonlinear variables
2855 if (jvar->kind() != Moose::VAR_SOLVER)
2856 continue;
2857
2858 // Only compute Jacobian entries if this coupling is being used by the
2859 // preconditioner
2860 if (nec->variable().number() == jvar->number() ||
2862 nec->variable().number(), jvar->number(), this->number()))
2863 continue;
2864
2865 // Begin the off-diagonal node-element constraint accumulation phase for
2866 // element and neighbor Jacobian blocks.
2869
2870 nec->prepareShapes(nec->variable().number());
2871 nec->prepareNeighborShapes(jvar->number());
2872
2873 nec->computeOffDiagJacobian(jvar->number());
2874
2875 // Cache the jacobian block for the secondary side
2876 nec->addJacobian(_fe_problem.assembly(0, number()),
2877 nec->_Kee,
2878 secondary_dofs,
2879 nec->_connected_dof_indices,
2880 nec->variable().scalingFactor());
2881
2882 // Cache the jacobian block for the primary side
2883 nec->addJacobian(_fe_problem.assembly(0, number()),
2884 nec->_Kne,
2885 nec->variable().dofIndicesNeighbor(),
2886 nec->_connected_dof_indices,
2887 nec->variable().scalingFactor());
2888
2891 }
2892 }
2893 }
2894 }
2895 }
2896 }
2897 }
2898 }
2899 // See if constraints were applied anywhere
2900 _communicator.max(constraints_applied);
2901
2902 if (constraints_applied)
2903 {
2904 LibmeshPetscCall(MatSetOption(cast_ref<PetscMatrix<Number> &>(jacobian).mat(),
2905 MAT_KEEP_NONZERO_PATTERN, // This is changed in 3.1
2906 PETSC_TRUE));
2907
2908 jacobian.close();
2909 jacobian.zero_rows(zero_rows, 0.0);
2910 jacobian.close();
2912 jacobian.close();
2913 }
2914}
2915
2916void
2918{
2919 MooseObjectWarehouse<ScalarKernelBase> * scalar_kernel_warehouse;
2920
2921 if (!tags.size() || tags.size() == _fe_problem.numMatrixTags())
2922 scalar_kernel_warehouse = &_scalar_kernels;
2923 else if (tags.size() == 1)
2924 scalar_kernel_warehouse = &(_scalar_kernels.getMatrixTagObjectWarehouse(*(tags.begin()), 0));
2925 else
2926 scalar_kernel_warehouse = &(_scalar_kernels.getMatrixTagsObjectWarehouse(tags, 0));
2927
2928 // Compute the diagonal block for scalar variables
2929 if (scalar_kernel_warehouse->hasActiveObjects())
2930 {
2931 const auto & scalars = scalar_kernel_warehouse->getActiveObjects();
2932
2933 _fe_problem.reinitScalars(/*tid=*/0);
2934
2936
2937 bool have_scalar_contributions = false;
2938 for (const auto & kernel : scalars)
2939 {
2940 if (!kernel->computesJacobian())
2941 continue;
2942
2943 kernel->reinit();
2944 const std::vector<dof_id_type> & dof_indices = kernel->variable().dofIndices();
2945 const DofMap & dof_map = kernel->variable().dofMap();
2946 const dof_id_type first_dof = dof_map.first_dof();
2947 const dof_id_type end_dof = dof_map.end_dof();
2948 for (dof_id_type dof : dof_indices)
2949 {
2950 if (dof >= first_dof && dof < end_dof)
2951 {
2952 kernel->computeJacobian();
2953 _fe_problem.addJacobianOffDiagScalar(kernel->variable().number());
2954 have_scalar_contributions = true;
2955 break;
2956 }
2957 }
2958 }
2959
2960 if (have_scalar_contributions)
2962 }
2963}
2964
2965void
3000
3001void
3003{
3004 TIME_SECTION("computeJacobianInternal", 3);
3005
3007
3008 // Make matrix ready to use
3010
3011 for (auto tag : tags)
3012 {
3013 if (!hasMatrix(tag))
3014 continue;
3015
3016 auto & jacobian = getMatrix(tag);
3017 // Necessary for speed
3018 if (auto petsc_matrix = dynamic_cast<PetscMatrix<Number> *>(&jacobian))
3019 {
3020 LibmeshPetscCall(MatSetOption(petsc_matrix->mat(),
3021 MAT_KEEP_NONZERO_PATTERN, // This is changed in 3.1
3022 PETSC_TRUE));
3024 LibmeshPetscCall(
3025 MatSetOption(petsc_matrix->mat(), MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
3027 LibmeshPetscCall(MatSetOption(
3028 cast_ref<PetscMatrix<Number> &>(jacobian).mat(), MAT_IGNORE_ZERO_ENTRIES, PETSC_TRUE));
3029 }
3030 }
3031
3032 jacobianSetup();
3033
3034 // Jacobian contributions from UOs - for now this is used for ray tracing
3035 // and ray kernels that contribute to the Jacobian (think line sources)
3036 std::vector<UserObject *> uos;
3038 .query()
3039 .condition<AttribSystem>("UserObject")
3040 .condition<AttribExecOns>(EXEC_PRE_KERNELS)
3041 .queryInto(uos);
3042 for (auto & uo : uos)
3043 uo->jacobianSetup();
3044 for (auto & uo : uos)
3045 {
3046 uo->initialize();
3047 uo->execute();
3048 uo->finalize();
3049 }
3050
3051 // reinit scalar variables
3052 for (unsigned int tid = 0; tid < libMesh::n_threads(); tid++)
3054
3055#ifdef MOOSE_KOKKOS_ENABLED
3058#endif
3059
3060 PARALLEL_TRY
3061 {
3062 // We would like to compute ScalarKernels, block NodalKernels, FVFluxKernels, and mortar objects
3063 // up front because we want these included whether we are computing an ordinary Jacobian or a
3064 // Jacobian for determining variable scaling factors
3066
3067 // Block restricted Nodal Kernels
3069 {
3071 const ConstNodeRange & range = _fe_problem.getCurrentAlgebraicNodeRange();
3072 Threads::parallel_reduce(range, cnkjt);
3073
3074 unsigned int n_threads = libMesh::n_threads();
3075 for (unsigned int i = 0; i < n_threads;
3076 i++) // Add any cached jacobians that might be hanging around
3078 }
3079
3080 using FVRange = StoredRange<MooseMesh::const_face_info_iterator, const FaceInfo *>;
3081 if (_fe_problem.haveFV())
3082 {
3083 // the same loop works for both residual and jacobians because it keys
3084 // off of FEProblem's _currently_computing_jacobian parameter
3086 _fe_problem, this->number(), tags, /*on_displaced=*/false);
3088 Threads::parallel_reduce(faces, fvj);
3089 }
3092 {
3094 _fe_problem, this->number(), tags, /*on_displaced=*/true);
3095 FVRange faces(displaced_problem->mesh().ownedFaceInfoBegin(),
3096 displaced_problem->mesh().ownedFaceInfoEnd());
3097 Threads::parallel_reduce(faces, fvr);
3098 }
3099
3101
3102 // Get our element range for looping over
3103 const ConstElemRange & elem_range = _fe_problem.getCurrentAlgebraicElementRange();
3104
3106 {
3107 // Only compute Jacobians corresponding to the diagonals of volumetric compute objects
3108 // because this typically gives us a good representation of the physics. NodalBCs and
3109 // Constraints can introduce dramatically different scales (often order unity).
3110 // IntegratedBCs and/or InterfaceKernels may use penalty factors. DGKernels may be ok, but
3111 // they are almost always used in conjunction with Kernels
3113 Threads::parallel_reduce(elem_range, cj);
3114 unsigned int n_threads = libMesh::n_threads();
3115 for (unsigned int i = 0; i < n_threads;
3116 i++) // Add any Jacobian contributions still hanging around
3118
3119 // Check whether any exceptions were thrown and propagate this information for parallel
3120 // consistency before
3121 // 1) we do parallel communication when closing tagged matrices
3122 // 2) early returning before reaching our PARALLEL_CATCH below
3124
3125 closeTaggedMatrices(tags);
3126
3127 return;
3128 }
3129
3130 switch (_fe_problem.coupling())
3131 {
3133 {
3135 Threads::parallel_reduce(elem_range, cj);
3136
3137 unsigned int n_threads = libMesh::n_threads();
3138 for (unsigned int i = 0; i < n_threads;
3139 i++) // Add any Jacobian contributions still hanging around
3141
3142 // Boundary restricted Nodal Kernels
3144 {
3147
3148 Threads::parallel_reduce(bnd_range, cnkjt);
3149 unsigned int n_threads = libMesh::n_threads();
3150 for (unsigned int i = 0; i < n_threads;
3151 i++) // Add any cached jacobians that might be hanging around
3153 }
3154 }
3155 break;
3156
3157 default:
3159 {
3161 Threads::parallel_reduce(elem_range, cj);
3162 unsigned int n_threads = libMesh::n_threads();
3163
3164 for (unsigned int i = 0; i < n_threads; i++)
3166
3167 // Boundary restricted Nodal Kernels
3169 {
3172
3173 Threads::parallel_reduce(bnd_range, cnkjt);
3174 unsigned int n_threads = libMesh::n_threads();
3175 for (unsigned int i = 0; i < n_threads;
3176 i++) // Add any cached jacobians that might be hanging around
3178 }
3179 }
3180 break;
3181 }
3182
3184
3185 static bool first = true;
3186
3187 // This adds zeroes into geometric coupling entries to ensure they stay in the matrix
3188 if ((_fe_problem.restoreOriginalNonzeroPattern() || first) &&
3190 {
3191 first = false;
3193
3196 }
3197 }
3198 PARALLEL_CATCH;
3199
3200 // Have no idea how to have constraints work
3201 // with the tag system
3202 PARALLEL_TRY
3203 {
3204 // Add in Jacobian contributions from other Constraints
3205 if (_fe_problem._has_constraints && tags.count(systemMatrixTag()))
3206 {
3207 // Some constraints need to be able to read values from the Jacobian, which requires that it
3208 // be closed/assembled
3209 auto & system_matrix = getMatrix(systemMatrixTag());
3210 std::unique_ptr<SparseMatrix<Number>> hash_copy;
3211 const SparseMatrix<Number> * view_jac_ptr;
3212 auto make_readable_jacobian = [&]()
3213 {
3214#if PETSC_RELEASE_GREATER_EQUALS(3, 23, 0)
3215 if (system_matrix.use_hash_table())
3216 {
3217 hash_copy = cast_ref<PetscMatrix<Number> &>(system_matrix).copy_from_hash();
3218 view_jac_ptr = hash_copy.get();
3219 }
3220 else
3221 view_jac_ptr = &system_matrix;
3222#else
3223 view_jac_ptr = &system_matrix;
3224#endif
3225 if (view_jac_ptr == &system_matrix)
3226 system_matrix.close();
3227 };
3228
3229 make_readable_jacobian();
3230
3231 // Nodal Constraints
3232 const bool had_nodal_constraints = enforceNodalConstraintsJacobian(*view_jac_ptr);
3233 if (had_nodal_constraints)
3234 // We have to make a new readable Jacobian
3235 make_readable_jacobian();
3236
3237 // Undisplaced Constraints
3238 constraintJacobians(*view_jac_ptr, false);
3239
3240 // Displaced Constraints
3242 constraintJacobians(*view_jac_ptr, true);
3243 }
3244 }
3245 PARALLEL_CATCH;
3246
3248 closeTaggedMatrices(tags);
3249
3250 // We need to close the save_in variables on the aux system before NodalBCBases clear the dofs
3251 // on boundary nodes
3254
3255 if (hasDiagSaveIn())
3257
3258 // Accumulate the occurrence of solution invalid warnings for the current iteration cumulative
3259 // counters
3262}
3263
3264void
3265NonlinearSystemBase::computeJacobian(SparseMatrix<Number> & jacobian)
3266{
3267 _nl_matrix_tags.clear();
3268
3269 auto & tags = _fe_problem.getMatrixTags();
3270
3271 for (auto & tag : tags)
3272 _nl_matrix_tags.insert(tag.second);
3273
3275}
3276
3277void
3278NonlinearSystemBase::computeJacobian(SparseMatrix<Number> & jacobian, const std::set<TagID> & tags)
3279{
3281
3282 computeJacobianTags(tags);
3283
3285}
3286
3287void
3288NonlinearSystemBase::computeJacobianTags(const std::set<TagID> & tags)
3289{
3290 TIME_SECTION("computeJacobianTags", 5);
3291
3293
3294 try
3295 {
3297 }
3298 catch (MooseException & e)
3299 {
3300 // The buck stops here, we have already handled the exception by
3301 // calling stopSolve(), it is now up to PETSc to return a
3302 // "diverged" reason during the next solve.
3303 }
3304}
3305
3306void
3308{
3309 _nl_matrix_tags.clear();
3310
3311 auto & tags = _fe_problem.getMatrixTags();
3312 for (auto & tag : tags)
3313 _nl_matrix_tags.insert(tag.second);
3314
3316}
3317
3318void
3320 const std::set<TagID> & tags)
3321{
3322 TIME_SECTION("computeJacobianBlocks", 3);
3324
3325 for (unsigned int i = 0; i < blocks.size(); i++)
3326 {
3327 SparseMatrix<Number> & jacobian = blocks[i]->_jacobian;
3328
3329 LibmeshPetscCall(MatSetOption(cast_ref<PetscMatrix<Number> &>(jacobian).mat(),
3330 MAT_KEEP_NONZERO_PATTERN, // This is changed in 3.1
3331 PETSC_TRUE));
3333 LibmeshPetscCall(MatSetOption(cast_ref<PetscMatrix<Number> &>(jacobian).mat(),
3334 MAT_NEW_NONZERO_ALLOCATION_ERR,
3335 PETSC_TRUE));
3336
3337 jacobian.zero();
3338 }
3339
3340 for (unsigned int tid = 0; tid < libMesh::n_threads(); tid++)
3342
3343 PARALLEL_TRY
3344 {
3345 const ConstElemRange & elem_range = _fe_problem.getCurrentAlgebraicElementRange();
3347 Threads::parallel_reduce(elem_range, cjb);
3348 }
3349 PARALLEL_CATCH;
3350
3351 for (unsigned int i = 0; i < blocks.size(); i++)
3352 blocks[i]->_jacobian.close();
3353
3354 for (unsigned int i = 0; i < blocks.size(); i++)
3355 {
3356 libMesh::System & precond_system = blocks[i]->_precond_system;
3357 SparseMatrix<Number> & jacobian = blocks[i]->_jacobian;
3358
3359 unsigned int ivar = blocks[i]->_ivar;
3360 unsigned int jvar = blocks[i]->_jvar;
3361
3362 // Dirichlet BCs
3363 std::vector<numeric_index_type> zero_rows;
3364 PARALLEL_TRY
3365 {
3367 for (const auto & bnode : bnd_nodes)
3368 {
3369 BoundaryID boundary_id = bnode->_bnd_id;
3370 Node * node = bnode->_node;
3371
3372 if (_nodal_bcs.hasActiveBoundaryObjects(boundary_id))
3373 {
3374 const auto & bcs = _nodal_bcs.getActiveBoundaryObjects(boundary_id);
3375
3376 if (node->processor_id() == processor_id())
3377 {
3378 _fe_problem.reinitNodeFace(node, boundary_id, 0);
3379
3380 for (const auto & bc : bcs)
3381 if (bc->variable().number() == ivar && bc->shouldApply())
3382 {
3383 // The first zero is for the variable number... there is only one variable in
3384 // each mini-system The second zero only works with Lagrange elements!
3385 zero_rows.push_back(node->dof_number(precond_system.number(), 0, 0));
3386 }
3387 }
3388 }
3389 }
3390 }
3391 PARALLEL_CATCH;
3392
3393 jacobian.close();
3394
3395 // This zeroes the rows corresponding to Dirichlet BCs and puts a 1.0 on the diagonal
3396 if (ivar == jvar)
3397 jacobian.zero_rows(zero_rows, 1.0);
3398 else
3399 jacobian.zero_rows(zero_rows, 0.0);
3400
3401 jacobian.close();
3402 }
3403}
3404
3405void
3436
3437Real
3438NonlinearSystemBase::computeDamping(const NumericVector<Number> & solution,
3439 const NumericVector<Number> & update)
3440{
3441 // Default to no damping
3442 Real damping = 1.0;
3443 bool has_active_dampers = false;
3444
3445 try
3446 {
3448 {
3449 PARALLEL_TRY
3450 {
3451 TIME_SECTION("computeDampers", 3, "Computing Dampers");
3452 has_active_dampers = true;
3456 damping = std::min(cid.damping(), damping);
3457 }
3458 PARALLEL_CATCH;
3459 }
3460
3462 {
3463 PARALLEL_TRY
3464 {
3465 TIME_SECTION("computeDamping::element", 3, "Computing Element Damping");
3466
3467 has_active_dampers = true;
3471 damping = std::min(cndt.damping(), damping);
3472 }
3473 PARALLEL_CATCH;
3474 }
3475
3477 {
3478 PARALLEL_TRY
3479 {
3480 TIME_SECTION("computeDamping::general", 3, "Computing General Damping");
3481
3482 has_active_dampers = true;
3483 const auto & gdampers = _general_dampers.getActiveObjects();
3484 for (const auto & damper : gdampers)
3485 {
3486 Real gd_damping = damper->computeDamping(solution, update);
3487 try
3488 {
3489 damper->checkMinDamping(gd_damping);
3490 }
3491 catch (MooseException & e)
3492 {
3494 }
3495 damping = std::min(gd_damping, damping);
3496 }
3497 }
3498 PARALLEL_CATCH;
3499 }
3500 }
3501 catch (MooseException & e)
3502 {
3503 // The buck stops here, we have already handled the exception by
3504 // calling stopSolve(), it is now up to PETSc to return a
3505 // "diverged" reason during the next solve.
3506 }
3507 catch (std::exception & e)
3508 {
3509 // Allow the libmesh error/exception on negative jacobian
3510 const std::string & message = e.what();
3511 if (message.find("Jacobian") == std::string::npos)
3512 throw;
3513 }
3514
3515 _communicator.min(damping);
3516
3517 if (has_active_dampers && damping < 1.0)
3518 _console << " Damping factor: " << damping << std::endl;
3519
3520 return damping;
3521}
3522
3523void
3524NonlinearSystemBase::computeDiracContributions(const std::set<TagID> & vector_tags,
3525 const std::set<TagID> & matrix_tags,
3526 const Moose::ComputeType compute_type)
3527{
3529
3530 std::set<const Elem *> dirac_elements;
3531
3533 {
3534 TIME_SECTION("computeDirac", 3, "Computing DiracKernels");
3535
3536 // TODO: Need a threading fix... but it's complicated!
3537 for (THREAD_ID tid = 0; tid < libMesh::n_threads(); ++tid)
3538 {
3539 const auto & dkernels = _dirac_kernels.getActiveObjects(tid);
3540 for (const auto & dkernel : dkernels)
3541 {
3542 dkernel->clearPoints();
3543 dkernel->addPoints();
3544 }
3545 }
3546
3547 ComputeDiracThread cd(_fe_problem, vector_tags, matrix_tags, compute_type);
3548
3549 _fe_problem.getDiracElements(dirac_elements);
3550
3551 DistElemRange range(dirac_elements.begin(), dirac_elements.end(), 1);
3552 // TODO: Make Dirac work thread!
3553 // Threads::parallel_reduce(range, cd);
3554
3555 cd(range);
3556
3557 // AD DiracKernels computing the residual and Jacobian together cache their residual
3558 // contributions (via addResidualsAndJacobian), so those must be flushed too
3559 if (compute_type != Moose::ComputeType::Jacobian)
3560 for (const auto tid : make_range(libMesh::n_threads()))
3562
3563 if (compute_type != Moose::ComputeType::Residual)
3564 for (const auto tid : make_range(libMesh::n_threads()))
3566 }
3567}
3568
3569NumericVector<Number> &
3571{
3572 if (!_residual_copy.get())
3573 _residual_copy = NumericVector<Number>::build(_communicator);
3574
3575 return *_residual_copy;
3576}
3577
3578NumericVector<Number> &
3580{
3582 if (!_residual_ghosted)
3583 {
3584 // The first time we realize we need a ghosted residual vector,
3585 // we add it.
3586 _residual_ghosted = &addVector("residual_ghosted", false, GHOSTED);
3587
3588 // If we've already realized we need time and/or non-time
3589 // residual vectors, but we haven't yet realized they need to be
3590 // ghosted, fix that now.
3591 //
3592 // If an application changes its mind, the libMesh API lets us
3593 // change the vector.
3594 if (_Re_time)
3595 {
3596 const auto vector_name = _subproblem.vectorTagName(_Re_time_tag);
3597 _Re_time = &system().add_vector(vector_name, false, GHOSTED);
3598 }
3599 if (_Re_non_time)
3600 {
3601 const auto vector_name = _subproblem.vectorTagName(_Re_non_time_tag);
3602 _Re_non_time = &system().add_vector(vector_name, false, GHOSTED);
3603 }
3604 }
3605 return *_residual_ghosted;
3606}
3607
3608void
3610 std::vector<dof_id_type> & n_nz,
3611 std::vector<dof_id_type> & n_oz)
3612{
3614 {
3616
3617 std::unordered_map<dof_id_type, std::vector<dof_id_type>> graph;
3618
3620
3623 graph);
3624
3625 const dof_id_type first_dof_on_proc = dofMap().first_dof(processor_id());
3626 const dof_id_type end_dof_on_proc = dofMap().end_dof(processor_id());
3627
3628 // The total number of dofs on and off processor
3629 const dof_id_type n_dofs_on_proc = dofMap().n_local_dofs();
3630 const dof_id_type n_dofs_not_on_proc = dofMap().n_dofs() - dofMap().n_local_dofs();
3631
3632 for (const auto & git : graph)
3633 {
3634 dof_id_type dof = git.first;
3635 dof_id_type local_dof = dof - first_dof_on_proc;
3636
3637 if (dof < first_dof_on_proc || dof >= end_dof_on_proc)
3638 continue;
3639
3640 const auto & row = git.second;
3641
3642 SparsityPattern::Row & sparsity_row = sparsity[local_dof];
3643
3644 unsigned int original_row_length = sparsity_row.size();
3645
3646 sparsity_row.insert(sparsity_row.end(), row.begin(), row.end());
3647
3649 sparsity_row.begin(), sparsity_row.begin() + original_row_length, sparsity_row.end());
3650
3651 // Fix up nonzero arrays
3652 for (const auto & coupled_dof : row)
3653 {
3654 if (coupled_dof < first_dof_on_proc || coupled_dof >= end_dof_on_proc)
3655 {
3656 if (n_oz[local_dof] < n_dofs_not_on_proc)
3657 n_oz[local_dof]++;
3658 }
3659 else
3660 {
3661 if (n_nz[local_dof] < n_dofs_on_proc)
3662 n_nz[local_dof]++;
3663 }
3664 }
3665 }
3666 }
3667}
3668
3669void
3670NonlinearSystemBase::setSolutionUDot(const NumericVector<Number> & u_dot)
3671{
3672 *_u_dot = u_dot;
3673}
3674
3675void
3676NonlinearSystemBase::setSolutionUDotDot(const NumericVector<Number> & u_dotdot)
3677{
3678 *_u_dotdot = u_dotdot;
3679}
3680
3681void
3682NonlinearSystemBase::setSolutionUDotOld(const NumericVector<Number> & u_dot_old)
3683{
3684 *_u_dot_old = u_dot_old;
3685}
3686
3687void
3688NonlinearSystemBase::setSolutionUDotDotOld(const NumericVector<Number> & u_dotdot_old)
3689{
3690 *_u_dotdot_old = u_dotdot_old;
3691}
3692
3693void
3694NonlinearSystemBase::setPreconditioner(std::shared_ptr<MoosePreconditioner> pc)
3695{
3696 if (_preconditioner.get() != nullptr)
3697 mooseError("More than one active Preconditioner detected");
3698
3699 _preconditioner = pc;
3700}
3701
3702MoosePreconditioner const *
3704{
3705 return _preconditioner.get();
3706}
3707
3708void
3710{
3711 _increment_vec = &_sys.add_vector("u_increment", true, GHOSTED);
3712}
3713
3714void
3716 const std::set<MooseVariable *> & damped_vars)
3717{
3718 for (const auto & var : damped_vars)
3719 var->computeIncrementAtQps(*_increment_vec);
3720}
3721
3722void
3724 const std::set<MooseVariable *> & damped_vars)
3725{
3726 for (const auto & var : damped_vars)
3727 var->computeIncrementAtNode(*_increment_vec);
3728}
3729
3730void
3731NonlinearSystemBase::checkKernelCoverage(const std::set<SubdomainID> & mesh_subdomains) const
3732{
3733 // Obtain all blocks and variables covered by all kernels
3734 std::set<SubdomainID> input_subdomains;
3735 std::set<std::string> kernel_variables;
3736
3737 bool global_kernels_exist = false;
3738 global_kernels_exist |= _scalar_kernels.hasActiveObjects();
3739 global_kernels_exist |= _nodal_kernels.hasActiveObjects();
3740
3741 _kernels.subdomainsCovered(input_subdomains, kernel_variables);
3742 _dg_kernels.subdomainsCovered(input_subdomains, kernel_variables);
3743 _nodal_kernels.subdomainsCovered(input_subdomains, kernel_variables);
3744 _scalar_kernels.subdomainsCovered(input_subdomains, kernel_variables);
3745 _constraints.subdomainsCovered(input_subdomains, kernel_variables);
3746
3747#ifdef MOOSE_KOKKOS_ENABLED
3748 _kokkos_kernels.subdomainsCovered(input_subdomains, kernel_variables);
3749 _kokkos_nodal_kernels.subdomainsCovered(input_subdomains, kernel_variables);
3750#endif
3751
3752 if (_fe_problem.haveFV())
3753 {
3754 std::vector<FVElementalKernel *> fv_elemental_kernels;
3756 .query()
3757 .template condition<AttribSystem>("FVElementalKernel")
3758 .queryInto(fv_elemental_kernels);
3759
3760 for (auto fv_kernel : fv_elemental_kernels)
3761 {
3762 if (fv_kernel->blockRestricted())
3763 for (auto block_id : fv_kernel->blockIDs())
3764 input_subdomains.insert(block_id);
3765 else
3766 global_kernels_exist = true;
3767 kernel_variables.insert(fv_kernel->variable().name());
3768
3769 // Check for lagrange multiplier
3770 if (dynamic_cast<FVScalarLagrangeMultiplierConstraint *>(fv_kernel))
3771 kernel_variables.insert(dynamic_cast<FVScalarLagrangeMultiplierConstraint *>(fv_kernel)
3772 ->lambdaVariable()
3773 .name());
3774 }
3775
3776 std::vector<FVFluxKernel *> fv_flux_kernels;
3778 .query()
3779 .template condition<AttribSystem>("FVFluxKernel")
3780 .queryInto(fv_flux_kernels);
3781
3782 for (auto fv_kernel : fv_flux_kernels)
3783 {
3784 if (fv_kernel->blockRestricted())
3785 for (auto block_id : fv_kernel->blockIDs())
3786 input_subdomains.insert(block_id);
3787 else
3788 global_kernels_exist = true;
3789 kernel_variables.insert(fv_kernel->variable().name());
3790 }
3791
3792 std::vector<FVInterfaceKernel *> fv_interface_kernels;
3794 .query()
3795 .template condition<AttribSystem>("FVInterfaceKernel")
3796 .queryInto(fv_interface_kernels);
3797
3798 for (auto fvik : fv_interface_kernels)
3799 if (auto scalar_fvik = dynamic_cast<FVScalarLagrangeMultiplierInterface *>(fvik))
3800 kernel_variables.insert(scalar_fvik->lambdaVariable().name());
3801
3802 std::vector<FVFluxBC *> fv_flux_bcs;
3804 .query()
3805 .template condition<AttribSystem>("FVFluxBC")
3806 .queryInto(fv_flux_bcs);
3807
3808 for (auto fvbc : fv_flux_bcs)
3809 if (auto scalar_fvbc = dynamic_cast<FVBoundaryScalarLagrangeMultiplierConstraint *>(fvbc))
3810 kernel_variables.insert(scalar_fvbc->lambdaVariable().name());
3811 }
3812
3813 for (const auto & ibc : _integrated_bcs.getActiveObjects())
3814 {
3815 const auto additional_variables_covered = ibc->additionalROVariables();
3816 kernel_variables.insert(additional_variables_covered.begin(),
3817 additional_variables_covered.end());
3818 }
3819
3820 // Check kernel coverage of subdomains (blocks) in your mesh
3821 if (!global_kernels_exist)
3822 {
3823 std::set<SubdomainID> difference;
3824 std::set_difference(mesh_subdomains.begin(),
3825 mesh_subdomains.end(),
3826 input_subdomains.begin(),
3827 input_subdomains.end(),
3828 std::inserter(difference, difference.end()));
3829
3830 // there supposed to be no kernels on this lower-dimensional subdomain
3831 for (const auto & id : _mesh.interiorLowerDBlocks())
3832 difference.erase(id);
3833 for (const auto & id : _mesh.boundaryLowerDBlocks())
3834 difference.erase(id);
3835
3836 if (!difference.empty())
3837 {
3838 std::vector<SubdomainID> difference_vec =
3839 std::vector<SubdomainID>(difference.begin(), difference.end());
3840 std::vector<SubdomainName> difference_names = _mesh.getSubdomainNames(difference_vec);
3841 std::stringstream missing_block_names;
3842 std::copy(difference_names.begin(),
3843 difference_names.end(),
3844 std::ostream_iterator<std::string>(missing_block_names, " "));
3845 std::stringstream missing_block_ids;
3846 std::copy(difference.begin(),
3847 difference.end(),
3848 std::ostream_iterator<unsigned int>(missing_block_ids, " "));
3849
3850 mooseError("Each subdomain must contain at least one Kernel.\nThe following block(s) lack an "
3851 "active kernel: " +
3852 missing_block_names.str(),
3853 " (ids: ",
3854 missing_block_ids.str(),
3855 ")");
3856 }
3857 }
3858
3859 // Check kernel use of variables
3860 std::set<VariableName> variables(getVariableNames().begin(), getVariableNames().end());
3861
3862 std::set<VariableName> difference;
3863 std::set_difference(variables.begin(),
3864 variables.end(),
3865 kernel_variables.begin(),
3866 kernel_variables.end(),
3867 std::inserter(difference, difference.end()));
3868
3869 // skip checks for varaibles defined on lower-dimensional subdomain
3870 std::set<VariableName> vars(difference);
3871 for (auto & var_name : vars)
3872 {
3873 auto blks = getSubdomainsForVar(var_name);
3874 for (const auto & id : blks)
3875 if (_mesh.interiorLowerDBlocks().count(id) > 0 || _mesh.boundaryLowerDBlocks().count(id) > 0)
3876 difference.erase(var_name);
3877 }
3878
3879 if (!difference.empty())
3880 {
3881 std::stringstream missing_kernel_vars;
3882 std::copy(difference.begin(),
3883 difference.end(),
3884 std::ostream_iterator<std::string>(missing_kernel_vars, " "));
3885 mooseError("Each variable must be referenced by at least one active Kernel.\nThe following "
3886 "variable(s) lack an active kernel: " +
3887 missing_kernel_vars.str());
3888 }
3889}
3890
3891bool
3893{
3894 auto & time_kernels = _kernels.getVectorTagObjectWarehouse(timeVectorTag(), 0);
3895
3896 return time_kernels.hasActiveObjects();
3897}
3898
3899std::vector<std::string>
3901{
3902 std::vector<std::string> variable_names;
3903 const auto & time_kernels = _kernels.getVectorTagObjectWarehouse(timeVectorTag(), 0);
3904 if (time_kernels.hasActiveObjects())
3905 for (const auto & kernel : time_kernels.getObjects())
3906 variable_names.push_back(kernel->variable().name());
3907
3908 return variable_names;
3909}
3910
3911bool
3913{
3914 // IntegratedBCs are for now the only objects we consider to be consuming
3915 // matprops on boundaries.
3917 for (const auto & bc : _integrated_bcs.getActiveBoundaryObjects(bnd_id, tid))
3918 if (std::static_pointer_cast<MaterialPropertyInterface>(bc)->getMaterialPropertyCalled())
3919 return true;
3920
3921 // Thin layer heat transfer in the heat_transfer module is being used on a boundary even though
3922 // it's an interface kernel. That boundary is external, on both sides of a gap in a mesh
3924 for (const auto & ik : _interface_kernels.getActiveBoundaryObjects(bnd_id, tid))
3925 if (std::static_pointer_cast<MaterialPropertyInterface>(ik)->getMaterialPropertyCalled())
3926 return true;
3927
3928 // Because MortarConstraints do not inherit from BoundaryRestrictable, they are not sorted
3929 // by boundary in the MooseObjectWarehouse. So for now, we return true for all boundaries
3930 // Note: constraints are not threaded at this time
3931 if (_constraints.hasActiveObjects(/*tid*/ 0))
3932 for (const auto & ct : _constraints.getActiveObjects(/*tid*/ 0))
3933 if (auto mpi = std::dynamic_pointer_cast<MaterialPropertyInterface>(ct);
3934 mpi && mpi->getMaterialPropertyCalled())
3935 return true;
3936 return false;
3937}
3938
3939bool
3941{
3942 // InterfaceKernels are for now the only objects we consider to be consuming matprops on internal
3943 // boundaries.
3945 for (const auto & ik : _interface_kernels.getActiveBoundaryObjects(bnd_id, tid))
3946 if (std::static_pointer_cast<MaterialPropertyInterface>(ik)->getMaterialPropertyCalled())
3947 return true;
3948 return false;
3949}
3950
3951bool
3953{
3954 // DGKernels are for now the only objects we consider to be consuming matprops on
3955 // internal sides.
3956 if (_dg_kernels.hasActiveBlockObjects(subdomain_id, tid))
3957 for (const auto & dg : _dg_kernels.getActiveBlockObjects(subdomain_id, tid))
3958 if (std::static_pointer_cast<MaterialPropertyInterface>(dg)->getMaterialPropertyCalled())
3959 return true;
3960 // NOTE:
3961 // HDG kernels do not require face material properties on internal sides at this time.
3962 // The idea is to have element locality of HDG for hybridization
3963 return false;
3964}
3965
3966bool
3968{
3969 return _doing_dg;
3970}
3971
3972void
3978
3979void
3981 const std::set<TagID> & vector_tags,
3982 const std::set<TagID> & matrix_tags)
3983{
3984 parallel_object_only();
3985
3986 try
3987 {
3988 for (auto & map_pr : _undisplaced_mortar_functors)
3989 map_pr.second(compute_type, vector_tags, matrix_tags);
3990
3991 for (auto & map_pr : _displaced_mortar_functors)
3992 map_pr.second(compute_type, vector_tags, matrix_tags);
3993 }
3994 catch (MetaPhysicL::LogicError &)
3995 {
3996 mooseError(
3997 "We caught a MetaPhysicL error in NonlinearSystemBase::mortarConstraints. This is very "
3998 "likely due to AD not having a sufficiently large derivative container size. Please run "
3999 "MOOSE configure with the '--with-derivative-size=<n>' option");
4000 }
4001}
4002
4003void
4005{
4007 return;
4008
4009 // Want the libMesh count of variables, not MOOSE, e.g. I don't care about array variable counts
4010 const auto n_vars = system().n_vars();
4011
4012 if (_scaling_group_variables.empty())
4013 {
4014 _var_to_group_var.reserve(n_vars);
4016
4017 for (const auto var_number : make_range(n_vars))
4018 _var_to_group_var.emplace(var_number, var_number);
4019 }
4020 else
4021 {
4022 std::set<unsigned int> var_numbers, var_numbers_covered, var_numbers_not_covered;
4023 for (const auto var_number : make_range(n_vars))
4024 var_numbers.insert(var_number);
4025
4027
4028 for (const auto group_index : index_range(_scaling_group_variables))
4029 for (const auto & var_name : _scaling_group_variables[group_index])
4030 {
4031 if (!hasVariable(var_name) && !hasScalarVariable(var_name))
4032 mooseError("'",
4033 var_name,
4034 "', provided to the 'scaling_group_variables' parameter, does not exist in "
4035 "the nonlinear system.");
4036
4037 const MooseVariableBase & var =
4038 hasVariable(var_name) ? cast_ref<MooseVariableBase &>(getVariable(0, var_name))
4039 : cast_ref<MooseVariableBase &>(getScalarVariable(0, var_name));
4040 auto map_pair = _var_to_group_var.emplace(var.number(), group_index);
4041 if (!map_pair.second)
4042 mooseError("Variable ", var_name, " is contained in multiple scaling grouplings");
4043 var_numbers_covered.insert(var.number());
4044 }
4045
4046 std::set_difference(var_numbers.begin(),
4047 var_numbers.end(),
4048 var_numbers_covered.begin(),
4049 var_numbers_covered.end(),
4050 std::inserter(var_numbers_not_covered, var_numbers_not_covered.begin()));
4051
4052 _num_scaling_groups = _scaling_group_variables.size() + var_numbers_not_covered.size();
4053
4054 auto index = static_cast<unsigned int>(_scaling_group_variables.size());
4055 for (auto var_number : var_numbers_not_covered)
4056 _var_to_group_var.emplace(var_number, index++);
4057 }
4058
4059 _variable_autoscaled.resize(n_vars, true);
4060 const auto & number_to_var_map = _vars[0].numberToVariableMap();
4061
4063 for (const auto i : index_range(_variable_autoscaled))
4064 if (std::find(_ignore_variables_for_autoscaling.begin(),
4066 libmesh_map_find(number_to_var_map, i)->name()) !=
4068 _variable_autoscaled[i] = false;
4069
4070 _auto_scaling_initd = true;
4071}
4072
4073bool
4075{
4077 return true;
4078
4079 _console << "\nPerforming automatic scaling calculation\n" << std::endl;
4080
4081 TIME_SECTION("computeScaling", 3, "Computing Automatic Scaling");
4082
4083 // It's funny but we need to assemble our vector of scaling factors here otherwise we will be
4084 // applying scaling factors of 0 during Assembly of our scaling Jacobian
4086
4087 // container for repeated access of element global dof indices
4088 std::vector<dof_id_type> dof_indices;
4089
4092
4093 std::vector<Real> inverse_scaling_factors(_num_scaling_groups, 0);
4094 std::vector<Real> resid_inverse_scaling_factors(_num_scaling_groups, 0);
4095 std::vector<Real> jac_inverse_scaling_factors(_num_scaling_groups, 0);
4096 auto & dof_map = dofMap();
4097
4098 // what types of scaling do we want?
4099 bool jac_scaling = _resid_vs_jac_scaling_param < 1. - TOLERANCE;
4100 bool resid_scaling = _resid_vs_jac_scaling_param > TOLERANCE;
4101
4102 const NumericVector<Number> & scaling_residual = RHS();
4103
4104 if (jac_scaling)
4105 {
4106 // if (!_auto_scaling_initd)
4107 // We need to reinit this when the number of dofs changes
4108 // but there is no good way to track that
4109 // In theory, it is the job of libmesh system to track this,
4110 // but this special matrix is not owned by libMesh system
4111 // Let us reinit eveytime since it is not expensive
4112 {
4113 auto init_vector = NumericVector<Number>::build(this->comm());
4114 init_vector->init(system().n_dofs(), system().n_local_dofs(), /*fast=*/false, PARALLEL);
4115
4116 _scaling_matrix->clear();
4117 _scaling_matrix->init(*init_vector);
4118 }
4119
4121 // Dispatch to derived classes to ensure that we use the correct matrix tag
4124 }
4125
4126 if (resid_scaling)
4127 {
4130 // Dispatch to derived classes to ensure that we use the correct vector tag
4134 }
4135
4136 // Did something bad happen during residual/Jacobian scaling computation?
4138 return false;
4139
4140 auto examine_dof_indices = [this,
4141 jac_scaling,
4142 resid_scaling,
4143 &dof_map,
4144 &jac_inverse_scaling_factors,
4145 &resid_inverse_scaling_factors,
4146 &scaling_residual](const auto & dof_indices, const auto var_number)
4147 {
4148 for (auto dof_index : dof_indices)
4149 if (dof_map.local_index(dof_index))
4150 {
4151 if (jac_scaling)
4152 {
4153 // For now we will use the diagonal for determining scaling
4154 auto mat_value = (*_scaling_matrix)(dof_index, dof_index);
4155 auto & factor = jac_inverse_scaling_factors[_var_to_group_var[var_number]];
4156 factor = std::max(factor, std::abs(mat_value));
4157 }
4158 if (resid_scaling)
4159 {
4160 auto vec_value = scaling_residual(dof_index);
4161 auto & factor = resid_inverse_scaling_factors[_var_to_group_var[var_number]];
4162 factor = std::max(factor, std::abs(vec_value));
4163 }
4164 }
4165 };
4166
4167 // Compute our scaling factors for the spatial field variables
4168 for (const auto & elem : _fe_problem.getCurrentAlgebraicElementRange())
4169 for (const auto i : make_range(system().n_vars()))
4170 if (_variable_autoscaled[i] && system().variable_type(i).family != SCALAR)
4171 {
4172 dof_map.dof_indices(elem, dof_indices, i);
4173 examine_dof_indices(dof_indices, i);
4174 }
4175
4176 for (const auto i : make_range(system().n_vars()))
4177 if (_variable_autoscaled[i] && system().variable_type(i).family == SCALAR)
4178 {
4179 dof_map.SCALAR_dof_indices(dof_indices, i);
4180 examine_dof_indices(dof_indices, i);
4181 }
4182
4183 if (resid_scaling)
4184 _communicator.max(resid_inverse_scaling_factors);
4185 if (jac_scaling)
4186 _communicator.max(jac_inverse_scaling_factors);
4187
4188 if (jac_scaling && resid_scaling)
4189 for (MooseIndex(inverse_scaling_factors) i = 0; i < inverse_scaling_factors.size(); ++i)
4190 {
4191 // Be careful not to take log(0)
4192 if (!resid_inverse_scaling_factors[i])
4193 {
4194 if (!jac_inverse_scaling_factors[i])
4195 inverse_scaling_factors[i] = 1;
4196 else
4197 inverse_scaling_factors[i] = jac_inverse_scaling_factors[i];
4198 }
4199 else if (!jac_inverse_scaling_factors[i])
4200 // We know the resid is not zero
4201 inverse_scaling_factors[i] = resid_inverse_scaling_factors[i];
4202 else
4203 inverse_scaling_factors[i] =
4204 std::exp(_resid_vs_jac_scaling_param * std::log(resid_inverse_scaling_factors[i]) +
4205 (1 - _resid_vs_jac_scaling_param) * std::log(jac_inverse_scaling_factors[i]));
4206 }
4207 else if (jac_scaling)
4208 inverse_scaling_factors = jac_inverse_scaling_factors;
4209 else if (resid_scaling)
4210 inverse_scaling_factors = resid_inverse_scaling_factors;
4211 else
4212 mooseError("We shouldn't be calling this routine if we're not performing any scaling");
4213
4214 // We have to make sure that our scaling values are not zero
4215 for (auto & scaling_factor : inverse_scaling_factors)
4216 if (scaling_factor == 0)
4217 scaling_factor = 1;
4218
4219 // Now flatten the group scaling factors to the individual variable scaling factors
4220 std::vector<Real> flattened_inverse_scaling_factors(system().n_vars());
4221 for (const auto i : index_range(flattened_inverse_scaling_factors))
4222 flattened_inverse_scaling_factors[i] = inverse_scaling_factors[_var_to_group_var[i]];
4223
4224 // Now set the scaling factors for the variables
4225 applyScalingFactors(flattened_inverse_scaling_factors);
4227 displaced_problem->systemBaseNonlinear(number()).applyScalingFactors(
4228 flattened_inverse_scaling_factors);
4229
4230 _computed_scaling = true;
4231 return true;
4232}
4233
4234void
4236{
4237 if (!hasVector("scaling_factors"))
4238 // No variables have indicated they need scaling
4239 return;
4240
4241 auto & scaling_vector = getVector("scaling_factors");
4242
4243 const auto & lm_mesh = _mesh.getMesh();
4244 const auto & dof_map = dofMap();
4245
4246 const auto & field_variables = _vars[0].fieldVariables();
4247 const auto & scalar_variables = _vars[0].scalars();
4248
4249 std::vector<dof_id_type> dof_indices;
4250
4251 for (const Elem * const elem :
4252 as_range(lm_mesh.active_local_elements_begin(), lm_mesh.active_local_elements_end()))
4253 for (const auto * const field_var : field_variables)
4254 {
4255 const auto & factors = field_var->arrayScalingFactor();
4256 for (const auto i : make_range(field_var->count()))
4257 {
4258 dof_map.dof_indices(elem, dof_indices, field_var->number() + i);
4259 for (const auto dof : dof_indices)
4260 scaling_vector.set(dof, factors[i]);
4261 }
4262 }
4263
4264 for (const auto * const scalar_var : scalar_variables)
4265 {
4266 mooseAssert(scalar_var->count() == 1,
4267 "Scalar variables should always have only one component.");
4268 dof_map.SCALAR_dof_indices(dof_indices, scalar_var->number());
4269 for (const auto dof : dof_indices)
4270 scaling_vector.set(dof, scalar_var->scalingFactor());
4271 }
4272
4273 // Parallel assemble
4274 scaling_vector.close();
4275
4277 // copy into the corresponding displaced system vector because they should be the exact same
4278 displaced_problem->systemBaseNonlinear(number()).getVector("scaling_factors") = scaling_vector;
4279}
4280
4281bool
4283{
4284 // Clear the iteration counters
4286 _current_nl_its = 0;
4287
4288 // Initialize the solution vector using a predictor and known values from nodal bcs
4290
4291 // Now that the initial solution has ben set, potentially perform a residual/Jacobian evaluation
4292 // to determine variable scaling factors
4294 {
4295 const bool scaling_succeeded = computeScaling();
4296 if (!scaling_succeeded)
4297 return false;
4298 }
4299
4300 // We do not know a priori what variable a global degree of freedom corresponds to, so we need a
4301 // map from global dof to scaling factor. We just use a ghosted NumericVector for that mapping
4303
4305
4306 return true;
4307}
4308
4309void
4311{
4312 if (matrixFromColoring())
4313 LibmeshPetscCall(MatFDColoringDestroy(&_fdcoloring));
4314}
4315
4318{
4319 if (!_fsp)
4320 mooseError("No field split preconditioner is present for this system");
4321
4322 return *_fsp;
4323}
4324
boundary_id_type BoundaryID
subdomain_id_type SubdomainID
StoredRange< std::set< const Elem * >::const_iterator, const Elem * > DistElemRange
void mooseDocumentedError(const std::string &repo_name, const unsigned int issue_num, Args &&... args)
Emit a documented error message with the given stringified, concatenated args and terminate the appli...
Definition MooseError.h:332
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
Definition MooseError.h:311
void mooseDeprecated(Args &&... args)
Emit a deprecated code/feature message with the given stringified, concatenated args.
Definition MooseError.h:363
unsigned int TagID
Definition MooseTypes.h:238
unsigned int THREAD_ID
Definition MooseTypes.h:237
const ExecFlagType EXEC_PRE_KERNELS
Definition Moose.C:59
std::array< Real, 2 > values
Definition MortarUtils.C:52
EXTERN_C_BEGIN PetscErrorCode DMCreate_Moose(DM)
std::shared_ptr< DisplacedProblem > displaced_problem
char ** vars
char ** blocks
unsigned int n_vars
Key structure for APIs manipulating global vectors/matrices.
Definition Assembly.h:836
void addCachedJacobian(GlobalDataKey)
Adds the values that have been cached by calling cacheJacobian() and or cacheJacobianNeighbor() to th...
Definition Assembly.C:3835
virtual libMesh::System & system() override
Get the reference to the libMesh system.
Base class for creating new types of boundary conditions.
Specialization for filling multiple "small" preconditioning matrices simulatenously.
const ConsoleStream _console
An instance of helper class to write streams to the Console objects.
const std::vector< std::shared_ptr< ElemElemConstraint > > & getActiveElemElemConstraints(InterfaceID interface_id, bool displaced) const
const std::vector< std::shared_ptr< MortarConstraintBase > > & getActiveMortarConstraints(const std::pair< BoundaryID, BoundaryID > &mortar_interface_key, bool displaced) const
const std::vector< std::shared_ptr< NodeFaceConstraint > > & getActiveNodeFaceConstraints(BoundaryID boundary_id, bool displaced) const
bool hasActiveMortarConstraints(const std::pair< BoundaryID, BoundaryID > &mortar_interface_key, bool displaced) const
bool hasActiveNodeElemConstraints(SubdomainID secondary_id, SubdomainID primary_id, bool displaced) const
bool hasActiveNodalConstraints() const
Deterimine if active objects exist.
void subdomainsCovered(std::set< SubdomainID > &subdomains_covered, std::set< std::string > &unique_variables, THREAD_ID tid=0) const
Update supplied subdomain and variable coverate containters.
void updateActive(THREAD_ID tid=0) override
Update the various active lists.
void addObject(std::shared_ptr< Constraint > object, THREAD_ID tid=0, bool recurse=true) override
Add Constraint object to the warehouse.
bool hasActiveElemElemConstraints(const InterfaceID interface_id, bool displaced) const
const std::vector< std::shared_ptr< NodeElemConstraintBase > > & getActiveNodeElemConstraints(SubdomainID secondary_id, SubdomainID primary_id, bool displaced) const
bool hasActiveNodeFaceConstraints(BoundaryID boundary_id, bool displaced) const
const std::vector< std::shared_ptr< NodalConstraint > > & getActiveNodalConstraints() const
Access methods for active objects.
virtual void residualEnd(THREAD_ID tid=0) const
Base class for all Constraint types.
Definition Constraint.h:20
Base class for convergence criteria.
Definition Convergence.h:26
virtual void preSolve()
Method that gets called in each iteration before the solve.
Definition Convergence.h:58
Serves as a base class for DGKernel and ADDGKernel.
Base class for deriving dampers.
Definition Damper.h:28
DiracKernelBase is the base class for all DiracKernel type classes.
This is the ElementPairInfo class.
This is the ElementPairLocator class.
const ElementPairList & getElemPairs() const
const ElementPairInfo & getElemPairInfo(std::pair< const Elem *, const Elem * > elem_pair) const
Specialization of SubProblem for solving nonlinear equations plus auxiliary equations.
virtual void addJacobianScalar(const THREAD_ID tid=0)
virtual void clearDiracInfo() override
Gets called before Dirac Kernels are asked to add the points they are supposed to be evaluated in.
virtual void cacheResidual(const THREAD_ID tid) override
virtual void reinitNeighborPhys(const Elem *neighbor, unsigned int neighbor_side, const std::vector< Point > &physical_points, const THREAD_ID tid) override
virtual bool haveFV() const override
returns true if this problem includes/needs finite volume functionality.
void jacobianSetup() override
bool areCoupled(const unsigned int ivar, const unsigned int jvar, const unsigned int nl_sys_num) const
virtual void addResidualScalar(const THREAD_ID tid=0)
bool restoreOriginalNonzeroPattern() const
virtual void addCachedResidual(const THREAD_ID tid) override
AuxiliarySystem & getAuxiliarySystem()
virtual void reinitScalars(const THREAD_ID tid, bool reinit_for_derivative_reordering=false) override
fills the VariableValue arrays for scalar variables from the solution vector
virtual void cacheJacobianNeighbor(const THREAD_ID tid) override
virtual void addCachedJacobian(const THREAD_ID tid) override
virtual void reinitOffDiagScalars(const THREAD_ID tid) override
virtual void setException(const std::string &message)
Set an exception, which is stored at this point by toggling a member variable in this class,...
virtual void cacheJacobian(const THREAD_ID tid) override
virtual void addJacobianOffDiagScalar(unsigned int ivar, const THREAD_ID tid=0)
void residualSetup() override
virtual void reinitNodeFace(const Node *node, BoundaryID bnd_id, const THREAD_ID tid) override
virtual std::shared_ptr< const DisplacedProblem > getDisplacedProblem() const
bool getFailNextNonlinearConvergenceCheck() const
Whether it will skip further residual evaluations and fail the next nonlinear convergence check(s)
virtual void setCurrentSubdomainID(const Elem *elem, const THREAD_ID tid) override
virtual void predictorCleanup(NumericVector< libMesh::Number > &ghosted_solution)
Perform cleanup tasks after application of predictor to solution vector.
virtual void getDiracElements(std::set< const Elem * > &elems) override
Fills "elems" with the elements that should be looped over for Dirac Kernels.
virtual GeometricSearchData & geomSearchData() override
bool identifyVariableGroupsInNL() const
Whether to identify variable groups in nonlinear systems.
void computingScalingJacobian(bool computing_scaling_jacobian)
Setter for whether we're computing the scaling jacobian.
bool hasDampers()
Whether or not this system has dampers.
virtual void prepareAssembly(const THREAD_ID tid) override
bool hasKokkosResidualObjects() const
void setCurrentNonlinearSystem(const unsigned int nl_sys_num)
const ConstBndNodeRange & getCurrentAlgebraicBndNodeRange()
SolverParams & solverParams(unsigned int solver_sys_num=0)
Get the solver parameters.
virtual Convergence & getConvergence(const std::string &name, const THREAD_ID tid=0) const
Gets a Convergence object.
const libMesh::ConstElemRange & getCurrentAlgebraicElementRange()
These are the element and nodes that contribute to the jacobian and residual for this local processor...
void reinitMaterialsNeighbor(SubdomainID blk_id, const THREAD_ID tid, bool swap_stateful=true, const std::deque< MaterialBase * > *reinit_mats=nullptr)
reinit materials on the neighboring element face
virtual void reinitNode(const Node *node, const THREAD_ID tid) override
Moose::CouplingType coupling() const
const std::unordered_map< std::pair< BoundaryID, BoundaryID >, MortarInterfaceConfig > & getMortarInterfaces(bool on_displaced) const
virtual void checkExceptionAndStopSolve(bool print_message=true)
Check to see if an exception has occurred on any processor and, if possible, force the solve to fail,...
NonlinearSystemBase & currentNonlinearSystem()
virtual MooseMesh & mesh() override
void setActiveMaterialProperties(const std::unordered_set< unsigned int > &mat_prop_ids, const THREAD_ID tid)
Record and set the material properties required by the current computing thread.
void setCurrentlyComputingResidual(bool currently_computing_residual) final
Set whether or not the problem is in the process of computing the residual.
virtual void updateGeomSearch(GeometricSearchData::GeometricSearchType type=GeometricSearchData::ALL) override
Update this object's geometric search data as well as the displaced problem's if it exists.
virtual Assembly & assembly(const THREAD_ID tid, const unsigned int sys_num) override
std::vector< std::pair< MooseVariableFieldBase *, MooseVariableFieldBase * > > & couplingEntries(const THREAD_ID tid, const unsigned int nl_sys_num)
bool useHashTableMatrixAssembly() const
bool _has_constraints
Whether or not this system has any Constraints.
bool errorOnJacobianNonzeroReallocation() const
Will return True if the user wants to get an error when a nonzero is reallocated in the Jacobian by P...
TheWarehouse & theWarehouse() const
const libMesh::ConstNodeRange & getCurrentAlgebraicNodeRange()
virtual void setResidual(NumericVector< libMesh::Number > &residual, const THREAD_ID tid) override
virtual void addCachedResidualDirectly(NumericVector< libMesh::Number > &residual, const THREAD_ID tid)
Allows for all the residual contributions that are currently cached to be added directly into the vec...
void computingScalingResidual(bool computing_scaling_residual)
Setter for whether we're computing the scaling residual.
void computingNonlinearResid(bool computing_nonlinear_residual) final
Set whether or not the problem is in the process of computing the nonlinear residual.
virtual void prepareAssemblyNeighbor(const THREAD_ID tid)
Begin a fresh neighbor accumulation phase by sizing and zeroing the neighbor blocks.
virtual void cacheResidualNeighbor(const THREAD_ID tid) override
virtual void setNeighborSubdomainID(const Elem *elem, unsigned int side, const THREAD_ID tid) override
bool ignoreZerosInJacobian() const
Will return true if zeros in the Jacobian are to be dropped from the sparsity pattern.
Base class for implementing constraints on boundaries for finite volume variables using scalar Lagran...
Base class for implementing constraints on finite volume variable elemental values using scalar Lagra...
std::shared_ptr< MooseObject > create(const std::string &obj_name, const std::string &name, const InputParameters &parameters, THREAD_ID tid=0, bool print_deprecated=true)
Definition Factory.C:142
Base interface for field split preconditioner.
virtual void setupDM()=0
setup the data management data structure that manages the field split
Scope guard for starting and stopping Floating Point Exception Trapping.
std::map< std::pair< BoundaryID, BoundaryID >, NearestNodeLocator * > _nearest_node_locators
std::map< BoundaryID, std::shared_ptr< ElementPairLocator > > _element_pair_locators
std::map< std::pair< BoundaryID, BoundaryID >, PenetrationLocator * > _penetration_locators
Base kernel for hybridized finite element formulations.
Definition HDGKernel.h:18
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system.
std::vector< std::pair< R1, R2 > > get(const std::string &param1, const std::string &param2) const
Combine two vector parameters into a single vector of pairs.
bool have_parameter(std::string_view name) const
A wrapper around the Parameters base class method.
InterfaceKernelBase is the base class for all InterfaceKernel type classes.
This is the common base class for the three main kernel types implemented in MOOSE,...
Definition KernelBase.h:29
SolutionInvalidity & solutionInvalidity()
Get the SolutionInvalidity for this app.
Definition MooseApp.h:185
const InputParameters & parameters() const
Get the parameters of the object.
Definition MooseBase.h:131
const std::string & name() const
Get the name of the class.
Definition MooseBase.h:103
Class for containing MooseEnum item information.
Provides a way for users to bail out of the current solve.
virtual const char * what() const
Get out the error message.
face_info_iterator ownedFaceInfoEnd()
Definition MooseMesh.C:1467
virtual const Node & nodeRef(const dof_id_type i) const
Definition MooseMesh.C:846
virtual Elem * elemPtr(const dof_id_type i)
Definition MooseMesh.C:3177
MeshBase & getMesh()
Accessor for the underlying libMesh Mesh object.
Definition MooseMesh.C:3512
std::vector< SubdomainName > getSubdomainNames(const std::vector< SubdomainID > &subdomain_ids) const
Get the associated subdomainNames for the subdomain ids that are passed in.
Definition MooseMesh.C:1720
const std::unordered_map< dof_id_type, std::vector< dof_id_type > > & nodeToElemMap()
If not already created, creates a map from every node to all elements to which they are connected.
Definition MooseMesh.C:1241
face_info_iterator ownedFaceInfoBegin()
Iterators to owned faceInfo objects.
Definition MooseMesh.C:1458
const std::set< SubdomainID > & interiorLowerDBlocks() const
Definition MooseMesh.h:1550
std::vector< BoundaryID > getBoundaryIDs(const Elem *const elem, const unsigned short int side) const
Returns a vector of boundary IDs for the requested element on the requested side.
Definition MooseMesh.C:2990
const std::set< SubdomainID > & meshSubdomains() const
Returns a read-only reference to the set of subdomains currently present in the Mesh.
Definition MooseMesh.C:3235
virtual const Node * queryNodePtr(const dof_id_type i) const
Definition MooseMesh.C:872
const std::set< SubdomainID > & boundaryLowerDBlocks() const
Definition MooseMesh.h:1554
MooseObjectWarehouse< T > & getVectorTagObjectWarehouse(TagID tag_id, THREAD_ID tid)
Retrieve a moose object warehouse in which every moose object has the given vector tag.
MooseObjectWarehouse< T > & getMatrixTagsObjectWarehouse(const std::set< TagID > &tags, THREAD_ID tid)
Retrieve a moose object warehouse in which every moose object has one of the given matrix tags.
virtual void updateActive(THREAD_ID tid=0) override
Update the active status of Kernels.
MooseObjectWarehouse< T > & getVectorTagsObjectWarehouse(const std::set< TagID > &tags, THREAD_ID tid)
Retrieve a moose object warehouse in which every moose object at least has one of the given vector ta...
MooseObjectWarehouse< T > & getMatrixTagObjectWarehouse(TagID tag_id, THREAD_ID tid)
Retrieve a moose object warehouse in which every moose object has the given matrix tag.
std::shared_ptr< T > getActiveObject(const std::string &name, THREAD_ID tid=0) const
const std::map< SubdomainID, std::vector< std::shared_ptr< T > > > & getActiveBlockObjects(THREAD_ID tid=0) const
virtual void updateActive(THREAD_ID tid=0)
Updates the active objects storage.
virtual void addObject(std::shared_ptr< T > object, THREAD_ID tid=0, bool recurse=true)
Adds an object to the storage structure.
bool hasActiveObjects(THREAD_ID tid=0) const
const std::map< BoundaryID, std::vector< std::shared_ptr< T > > > & getActiveBoundaryObjects(THREAD_ID tid=0) const
bool hasActiveBlockObjects(THREAD_ID tid=0) const
bool hasActiveBoundaryObjects(THREAD_ID tid=0) const
bool hasObjects(THREAD_ID tid=0) const
Convenience functions for determining if objects exist.
const std::vector< std::shared_ptr< T > > & getActiveObjects(THREAD_ID tid=0) const
Retrieve complete vector to the active all/block/boundary restricted objects for a given thread.
void subdomainsCovered(std::set< SubdomainID > &subdomains_covered, std::set< std::string > &unique_variables, THREAD_ID tid=0) const
Populates a set of covered subdomains and the associated variable names.
A storage container for MooseObjects that inherit from SetupInterface.
virtual void timestepSetup(THREAD_ID tid=0) const
virtual void customSetup(const ExecFlagType &exec_type, THREAD_ID tid=0) const
virtual void subdomainSetup(THREAD_ID tid=0) const
virtual void initialSetup(THREAD_ID tid=0) const
Convenience methods for calling object setup methods.
virtual void residualSetup(THREAD_ID tid=0) const
virtual void addObject(std::shared_ptr< T > object, THREAD_ID tid=0, bool recurse=true) override
Adds an object to the storage structure.
virtual void updateActive(THREAD_ID tid=0) override
Update the active status of Kernels.
virtual void jacobianSetup(THREAD_ID tid=0) const
Base class for MOOSE preconditioners.
Base variable class.
unsigned int number() const
Get variable number coming from libMesh.
This class provides an interface for common operations on field variables of both FE and FV types wit...
std::vector< dof_id_type > _secondary_nodes
Base class for creating new types of nodal kernels.
void computeDiracContributions(const std::set< TagID > &vector_tags, const std::set< TagID > &matrix_tags, Moose::ComputeType compute_type)
void addConstraint(const std::string &c_name, const std::string &name, InputParameters &parameters)
Adds a Constraint.
MooseObjectWarehouse< ADDirichletBCBase > _ad_preset_nodal_bcs
MooseObjectTagWarehouse< ResidualObject > _kokkos_kernels
bool _debugging_residuals
true if debugging residuals
MoosePreconditioner const * getPreconditioner() const
bool preSolve()
Perform some steps to get ready for the solver.
bool _need_residual_ghosted
Whether or not a ghosted copy of the residual needs to be made.
MooseObjectWarehouse< NodalDamper > _nodal_dampers
Nodal Dampers for each thread.
std::size_t _num_scaling_groups
The number of scaling groups.
virtual void computeScalingJacobian()=0
Compute a "Jacobian" for automatic scaling purposes.
void computeKokkosResidualAndJacobian(const std::set< TagID > &vector_tags, const std::set< TagID > &matrix_tags)
virtual std::vector< std::string > timeKernelVariableNames() override
Returns the names of the variables that have time derivative kernels in the system.
Real referenceResidual() const
The reference residual used in relative convergence check.
MooseObjectWarehouse< ElementDamper > _element_dampers
Element Dampers for each thread.
NumericVector< Number > & getResidualNonTimeVector()
Return a numeric vector that is associated with the nontime tag.
FieldSplitPreconditionerBase & getFieldSplitPreconditioner()
MooseObjectTagWarehouse< ResidualObject > _kokkos_nodal_bcs
virtual void jacobianSetup() override
virtual void augmentSparsity(libMesh::SparsityPattern::Graph &sparsity, std::vector< dof_id_type > &n_nz, std::vector< dof_id_type > &n_oz) override
Will modify the sparsity pattern to add logical geometric connections.
Real _resid_vs_jac_scaling_param
The param that indicates the weighting of the residual vs the Jacobian in determining variable scalin...
void zeroVectorForResidual(const std::string &vector_name)
void onTimestepBegin()
Called at the beginning of the time step.
Convergence & convergence()
Retrieves the associated Convergence object.
std::set< TagID > _nl_vector_tags
Vector tags to temporarily store all tags associated with the current system.
std::vector< std::string > _ignore_variables_for_autoscaling
A container for variables that do not partipate in autoscaling.
virtual void subdomainSetup()
void reinitIncrementAtQpsForDampers(THREAD_ID tid, const std::set< MooseVariable * > &damped_vars)
Compute the incremental change in variables at QPs for dampers.
void computeKokkosResidual(const std::set< TagID > &tags)
Compute residual with Kokkos objects.
void setKokkosInitialSolution()
void assembleScalingVector()
Assemble the numeric vector of scaling factors such that it can be used during assembly of the system...
void computeJacobian(libMesh::SparseMatrix< Number > &jacobian, const std::set< TagID > &tags)
Associate jacobian to systemMatrixTag, and then form a matrix for all the tags.
MooseObjectTagWarehouse< ResidualObject > _kokkos_integrated_bcs
NumericVector< Number > & residualVector(TagID tag)
Return a residual vector that is associated with the residual tag.
unsigned int _n_residual_evaluations
Total number of residual evaluations that have been performed.
MooseObjectTagWarehouse< ScalarKernelBase > _scalar_kernels
NumericVector< Number > * _increment_vec
increment vector
bool needInterfaceMaterialOnSide(BoundaryID bnd_id, THREAD_ID tid) const
Indicated whether this system needs material properties on interfaces.
MooseObjectWarehouse< DirichletBCBase > _preset_nodal_bcs
void overwriteNodeFace(NumericVector< Number > &soln)
Called from explicit time stepping to overwrite boundary positions (explicit dynamics).
Real _pre_smo_residual
The pre-SMO residual, see setPreSMOResidual for a detailed explanation.
void updateActive(THREAD_ID tid)
Update active objects of Warehouses owned by NonlinearSystemBase.
NumericVector< Number > * _Re_time
residual vector for time contributions
virtual void setSolutionUDotDotOld(const NumericVector< Number > &u_dotdot_old)
bool computeScaling()
Method used to obtain scaling factors for variables.
std::set< TagID > _nl_matrix_tags
Matrix tags to temporarily store all tags associated with the current system.
void addSplit(const std::string &split_name, const std::string &name, InputParameters &parameters)
Adds a split.
MooseObjectTagWarehouse< DiracKernelBase > _dirac_kernels
Dirac Kernel storage for each thread.
virtual void postAddResidualObject(ResidualObject &)
Called after any ResidualObject-derived objects are added to the system.
bool shouldEvaluatePreSMOResidual() const
We offer the option to check convergence against the pre-SMO residual.
virtual NumericVector< Number > & residualGhosted() override
virtual void preInit() override
This is called prior to the libMesh system has been init'd.
virtual void turnOffJacobian()
Turn off the Jacobian (must be called before equation system initialization)
bool _auto_scaling_initd
Whether we've initialized the automatic scaling data structures.
TagID timeVectorTag() const override
Ideally, we should not need this API.
void computeResidualTags(const std::set< TagID > &tags)
Form multiple tag-associated residual vectors for all the given tags.
virtual void setSolutionUDot(const NumericVector< Number > &udot)
Set transient term used by residual and Jacobian evaluation.
MooseObjectTagWarehouse< NodalKernelBase > _nodal_kernels
NodalKernels for each thread.
void addImplicitGeometricCouplingEntries(GeometricSearchData &geom_search_data)
Adds entries to the Jacobian in the correct positions for couplings coming from dofs being coupled th...
virtual void addNodalKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
Adds a NodalKernel.
MooseObjectWarehouse< ResidualObject > _kokkos_preset_nodal_bcs
void addBoundaryCondition(const std::string &bc_name, const std::string &name, InputParameters &parameters)
Adds a boundary condition.
void computeScalarKernelsJacobians(const std::set< TagID > &tags)
MooseObjectTagWarehouse< NodalBCBase > _nodal_bcs
NumericVector< Number > & getResidualTimeVector()
Return a numeric vector that is associated with the time tag.
void getNodeDofs(dof_id_type node_id, std::vector< dof_id_type > &dofs)
std::vector< std::string > _vecs_to_zero_for_residual
vectors that will be zeroed before a residual computation
virtual void addHDGKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
Adds a hybridized discontinuous Galerkin (HDG) kernel.
bool _doing_dg
true if DG is active (optimization reasons)
void reinitNodeFace(const Node &secondary_node, const BoundaryID secondary_boundary, const PenetrationInfo &info, const bool displaced)
Reinitialize quantities such as variables, residuals, Jacobians, materials for node-face constraints.
void addDiracKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
Adds a Dirac kernel.
std::shared_ptr< Predictor > _predictor
If predictor is active, this is non-NULL.
std::shared_ptr< Split > getSplit(const std::string &name)
Retrieves a split by name.
void computeResidualTag(NumericVector< Number > &residual, TagID tag_id)
Computes residual for a given tag.
void findImplicitGeometricCouplingEntries(GeometricSearchData &geom_search_data, std::unordered_map< dof_id_type, std::vector< dof_id_type > > &graph)
Finds the implicit sparsity graph between geometrically related dofs.
bool _add_implicit_geometric_coupling_entries_to_jacobian
Whether or not to add implicit geometric couplings to the Jacobian for FDP.
virtual bool containsTimeKernel() override
If the system has a kernel that corresponds to a time derivative.
NumericVector< Number > * _residual_ghosted
ghosted form of the residual
void constraintJacobians(const SparseMatrix< Number > &jacobian_to_view, bool displaced)
Add jacobian contributions from Constraints.
void computeResidualAndJacobianInternal(const std::set< TagID > &vector_tags, const std::set< TagID > &matrix_tags)
Compute residual and Jacobian from contributions not related to constraints, such as nodal boundary c...
Real preSMOResidual() const
The pre-SMO residual.
void setInitialResidual(Real r)
Record the initial residual (for later relative convergence check)
std::vector< SetupInterface * > getFVSetupObjects(THREAD_ID tid)
Retrieve every finite volume object belonging to this system on thread tid, as SetupInterfaces,...
MooseObjectTagWarehouse< KernelBase > _kernels
std::vector< bool > _variable_autoscaled
Container to hold flag if variable is to participate in autoscaling.
Real computeDamping(const NumericVector< Number > &solution, const NumericVector< Number > &update)
Compute damping.
bool _has_save_in
If there is any Kernel or IntegratedBC having save_in.
void computeNodalBCsResidual(NumericVector< Number > &residual)
Enforces nodal boundary conditions.
bool _has_diag_save_in
If there is any Kernel or IntegratedBC having diag_save_in.
MooseObjectTagWarehouse< IntegratedBCBase > _integrated_bcs
TagID systemMatrixTag() const override
Return the Matrix Tag ID for System.
virtual libMesh::NonlinearSolver< Number > * nonlinearSolver()=0
virtual NumericVector< Number > & RHS()=0
void reinitIncrementAtNodeForDampers(THREAD_ID tid, const std::set< MooseVariable * > &damped_vars)
Compute the incremental change in variables at nodes for dampers.
bool doingDG() const
Getter for _doing_dg.
virtual void setPreviousNewtonSolution(const NumericVector< Number > &soln)
TagID _Re_time_tag
Tag for time contribution residual.
bool _compute_scaling_once
Whether the scaling factors should only be computed once at the beginning of the simulation through a...
std::unique_ptr< NumericVector< Number > > _residual_copy
Copy of the residual vector, or nullptr if a copy is not needed.
TagID _Re_non_time_tag
Tag for non-time contribution residual.
ConvergenceName _convergence_name
Associated convergence object name.
void addDGKernel(std::string dg_kernel_name, const std::string &name, InputParameters &parameters)
Adds a DG kernel.
void setupScalingData()
Setup group scaling containers.
void computeJacobianBlocks(std::vector< JacobianBlock * > &blocks)
Computes several Jacobian blocks simultaneously, summing their contributions into smaller preconditio...
void setPredictor(std::shared_ptr< Predictor > predictor)
void computeNodalBCsResidualAndJacobian(const std::set< TagID > &vector_tags, const std::set< TagID > &matrix_tags)
Compute the residual and Jacobian together for nodal boundary conditions.
std::vector< unsigned int > _current_l_its
std::vector< std::vector< std::string > > _scaling_group_variables
A container of variable groupings that can be used in scaling calculations.
MooseObjectWarehouseBase< Split > _splits
Decomposition splits.
void enforceNodalConstraintsResidual(NumericVector< Number > &residual)
Enforce nodal constraints.
virtual void computeScalingResidual()=0
Compute a "residual" for automatic scaling purposes.
void addScalarKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
Adds a scalar kernel.
void addImplicitGeometricCouplingEntriesToJacobian(bool add=true)
If called with true this will add entries into the jacobian to link together degrees of freedom that ...
virtual void initialSetup() override
Setup Functions.
void addInterfaceKernel(std::string interface_kernel_name, const std::string &name, InputParameters &parameters)
Adds an interface kernel.
void addDamper(const std::string &damper_name, const std::string &name, InputParameters &parameters)
Adds a damper.
bool _has_nodalbc_save_in
If there is a nodal BC having save_in.
std::unordered_map< unsigned int, unsigned int > _var_to_group_var
A map from variable index to group variable index and it's associated (inverse) scaling factor.
MooseObjectTagWarehouse< ResidualObject > _kokkos_nodal_kernels
bool _use_pre_smo_residual
Whether to use the pre-SMO initial residual in the relative convergence check.
void reinitMortarFunctors()
Update the mortar functors if the mesh has changed.
MooseObjectWarehouse< GeneralDamper > _general_dampers
General Dampers.
MooseObjectTagWarehouse< InterfaceKernelBase > _interface_kernels
virtual void timestepSetup() override
bool hasDiagSaveIn() const
Weather or not the nonlinear system has diagonal Jacobian save-ins.
bool _assemble_constraints_separately
Whether or not to assemble the residual and Jacobian after the application of each constraint.
std::unordered_map< std::pair< BoundaryID, BoundaryID >, ComputeMortarFunctor > _displaced_mortar_functors
Functors for computing displaced mortar constraints.
virtual NumericVector< Number > & residualCopy() override
void computeKokkosJacobian(const std::set< TagID > &tags)
Compute Jacobian with Kokkos objects.
bool needBoundaryMaterialOnSide(BoundaryID bnd_id, THREAD_ID tid) const
Indicated whether this system needs material properties on boundaries.
void mortarConstraints(Moose::ComputeType compute_type, const std::set< TagID > &vector_tags, const std::set< TagID > &matrix_tags)
Do mortar constraint residual/jacobian computations.
TagID _Re_tag
Used for the residual vector from PETSc.
bool _computed_scaling
Flag used to indicate whether we have already computed the scaling Jacobian.
void setPreconditioner(std::shared_ptr< MoosePreconditioner > pc)
Sets a preconditioner.
virtual ~NonlinearSystemBase()
NonlinearSystemBase(FEProblemBase &problem, libMesh::System &sys, const std::string &name)
void computeNodalBCsJacobian(const std::set< TagID > &tags)
Compute the Jacobian for nodal boundary conditions.
void checkKernelCoverage(const std::set< SubdomainID > &mesh_subdomains) const
void computeResidual(NumericVector< Number > &residual, TagID tag_id)
Form a residual vector for a given tag.
std::unordered_map< std::pair< BoundaryID, BoundaryID >, ComputeMortarFunctor > _undisplaced_mortar_functors
Functors for computing undisplaced mortar constraints.
void computeJacobianTags(const std::set< TagID > &tags)
Computes multiple (tag associated) Jacobian matricese.
bool enforceNodalConstraintsJacobian(const SparseMatrix< Number > &jacobian)
Enforce nodal constraints in the Jacobian.
std::unique_ptr< libMesh::DiagonalMatrix< Number > > _scaling_matrix
A diagonal matrix used for computing scaling.
Real _initial_residual
The initial (i.e., 0th nonlinear iteration) residual, see setPreSMOResidual for a detailed explanatio...
virtual void residualSetup() override
NumericVector< Number > * _Re_non_time
residual vector for non-time contributions
bool _off_diagonals_in_auto_scaling
Whether to include off diagonals when determining automatic scaling factors.
virtual void customSetup(const ExecFlagType &exec_type) override
void constraintResiduals(NumericVector< Number > &residual, bool displaced)
Add residual contributions from Constraints.
virtual void setSolutionUDotOld(const NumericVector< Number > &u_dot_old)
virtual libMesh::System & system() override
Get the reference to the libMesh system.
void computeJacobianInternal(const std::set< TagID > &tags)
Form multiple matrices for all the tags.
void computeResidualInternal(const std::set< TagID > &tags)
Compute the residual for a given tag.
TagID _Ke_system_tag
Tag for system contribution Jacobian.
MooseObjectTagWarehouse< DGKernelBase > _dg_kernels
void setConstraintSecondaryValues(NumericVector< Number > &solution, bool displaced)
Sets the value of constrained variables in the solution vector.
bool needInternalNeighborSideMaterial(SubdomainID subdomain_id, THREAD_ID tid) const
Indicates whether this system needs material properties on internal sides.
void setupDM()
Setup the PETSc DM object (when appropriate)
void setupDampers()
Setup damping stuff (called before we actually start)
const bool & usePreSMOResidual() const
Whether we are using pre-SMO residual in relative convergence checks.
void computeKokkosNodalBCsResidual(const std::set< TagID > &tags)
Compute Kokkos nodal BCs.
FieldSplitPreconditionerBase * _fsp
The field split preconditioner if this sytem is using one.
virtual void setSolutionUDotDot(const NumericVector< Number > &udotdot)
Set transient term used by residual and Jacobian evaluation.
virtual void addKernel(const std::string &kernel_name, const std::string &name, InputParameters &parameters)
Adds a kernel.
bool hasSaveIn() const
Weather or not the nonlinear system has save-ins.
void computeResidualAndJacobianTags(const std::set< TagID > &vector_tags, const std::set< TagID > &matrix_tags)
Form possibly multiple tag-associated vectors and matrices.
ConstraintWarehouse _constraints
Constraints storage object.
MooseObjectTagWarehouse< HDGKernel > _hybridized_kernels
bool _has_nodalbc_diag_save_in
If there is a nodal BC having diag_save_in.
void destroyColoring()
Destroy the coloring object if it exists.
std::shared_ptr< MoosePreconditioner > _preconditioner
Preconditioner.
TagID residualVectorTag() const override
Real initialResidual() const
The initial residual.
Data structure used to hold penetration information.
std::map< dof_id_type, PenetrationInfo * > & _penetration_info
Data structure of nodes and their associated penetration information.
NearestNodeLocator & _nearest_node
Interface for objects interacting with the PerfGraph.
Base class shared by AD and non-AD scalar kernels.
void accumulateIterationIntoTimeStepOccurences()
Pass the number of solution invalid occurrences from current iteration to cumulative counters.
void syncIteration()
Sync iteration counts to main processor Sum across all processors.
virtual void preInit() override
This is called prior to the libMesh system has been init'd.
virtual bool matrixFromColoring() const
Whether a system matrix is formed from coloring.
Base class for split-based preconditioners.
Definition Split.h:26
virtual TagName vectorTagName(const TagID tag) const
Retrieve the name associated with a TagID.
Definition SubProblem.C:210
virtual void reinitElemPhys(const Elem *elem, const std::vector< Point > &phys_points_in_elem, const THREAD_ID tid)=0
std::vector< VectorTag > getVectorTags(const std::set< TagID > &tag_ids) const
Definition SubProblem.C:161
virtual unsigned int numMatrixTags() const
The total number of tags.
Definition SubProblem.h:248
bool defaultGhosting()
Whether or not the user has requested default ghosting ot be on.
Definition SubProblem.h:144
virtual unsigned int numVectorTags(const Moose::VectorTagType type=Moose::VECTOR_TAG_ANY) const
The total number of tags, which can be limited to the tag type.
Definition SubProblem.C:184
virtual Assembly & assembly(const THREAD_ID tid, const unsigned int sys_num)=0
virtual TagID addVectorTag(const TagName &tag_name, const Moose::VectorTagType type=Moose::VECTOR_TAG_RESIDUAL)
Create a Tag.
Definition SubProblem.C:81
virtual void reinitNeighborPhys(const Elem *neighbor, unsigned int neighbor_side, const std::vector< Point > &physical_points, const THREAD_ID tid)=0
virtual TagID addMatrixTag(TagName tag_name)
Create a Tag.
Definition SubProblem.C:300
virtual std::map< TagName, TagID > & getMatrixTags()
Return all matrix tags in the system, where a tag is represented by a map from name to ID.
Definition SubProblem.h:253
virtual GeometricSearchData & geomSearchData()=0
void zeroTaggedVectors(const std::set< TagID > &tags)
Zero all vectors for given tags.
Definition SystemBase.C:692
NumericVector< Number > * _u_dot
solution vector for u^dot
virtual libMesh::SparseMatrix< Number > & getMatrix(TagID tag)
Get a raw SparseMatrix.
MooseApp & _app
virtual void deactivateAllMatrixTags()
Make matrices inactive.
FEProblemBase & _fe_problem
the governing finite element/volume problem
const std::set< SubdomainID > & getSubdomainsForVar(unsigned int var_number) const
Definition SystemBase.h:791
virtual void subdomainSetup()
std::vector< std::shared_ptr< TimeIntegrator > > _time_integrators
Time integrator.
bool hasVector(const std::string &tag_name) const
Check if the named vector exists in the system.
Definition SystemBase.C:921
NumericVector< Number > * _u_dotdot
solution vector for u^dotdot
virtual unsigned int nVariables() const
Get the number of variables in this system.
Definition SystemBase.C:888
MooseVariableFieldBase & getVariable(THREAD_ID tid, const std::string &var_name) const
Gets a reference to a variable of with specified name.
Definition SystemBase.C:89
unsigned int number() const
Gets the number of this system.
Factory & _factory
virtual void activateAllMatrixTags()
Make all existing matrices active.
const std::vector< VariableName > & getVariableNames() const
Definition SystemBase.h:890
virtual NumericVector< Number > & getVector(const std::string &name)
Get a raw NumericVector by name.
Definition SystemBase.C:930
virtual void customSetup(const ExecFlagType &exec_type)
NumericVector< Number > & solutionOld()
Definition SystemBase.h:213
virtual void disassociateMatrixFromTag(libMesh::SparseMatrix< Number > &matrix, TagID tag)
Disassociate a matrix from a tag.
SubProblem & subproblem()
Definition SystemBase.h:102
virtual void initialSetup()
Setup Functions.
virtual void timestepSetup()
virtual void associateVectorToTag(NumericVector< Number > &vec, TagID tag)
Associate a vector for a given tag.
Definition SystemBase.C:978
virtual void jacobianSetup()
virtual void residualSetup()
virtual void disassociateVectorFromTag(NumericVector< Number > &vec, TagID tag)
Disassociate a given vector from a given tag.
Definition SystemBase.C:990
void closeTaggedVectors(const std::set< TagID > &tags)
Close all vectors for given tags.
Definition SystemBase.C:666
virtual MooseVariableScalar & getScalarVariable(THREAD_ID tid, const std::string &var_name) const
Gets a reference to a scalar variable with specified number.
Definition SystemBase.C:144
virtual bool hasScalarVariable(const std::string &var_name) const
Definition SystemBase.C:873
std::vector< VariableWarehouse > _vars
Variable warehouses (one for each thread)
virtual bool hasVariable(const std::string &var_name) const
Query a system for a variable.
Definition SystemBase.C:848
void closeTaggedMatrices(const std::set< TagID > &tags)
Close all matrices associated the tags.
SubProblem & _subproblem
The subproblem for whom this class holds variable data, etc; this can either be the governing finite ...
void applyScalingFactors(const std::vector< Real > &inverse_scaling_factors)
Applies scaling factors to the system's variables.
virtual void associateMatrixToTag(libMesh::SparseMatrix< Number > &matrix, TagID tag)
Associate a matrix to a tag.
NumericVector< Number > * _u_dotdot_old
old solution vector for u^dotdot
virtual const std::string & name() const
virtual bool hasMatrix(TagID tag) const
Check if the tagged matrix exists in the system.
Definition SystemBase.h:388
virtual libMesh::DofMap & dofMap()
Gets writeable reference to the dof map.
NumericVector< Number > & solution()
Definition SystemBase.h:212
NumericVector< Number > * _u_dot_old
old solution vector for u^dot
bool _automatic_scaling
Whether to automatically scale the variables.
NumericVector< Number > & addVector(const std::string &vector_name, const bool project, const libMesh::ParallelType type)
Adds a solution length vector to the system.
Definition SystemBase.C:605
void update()
Update the system (doing libMesh magic)
MooseMesh & _mesh
void max(const T &r, T &o, Request &req) const
void min(const T &r, T &o, Request &req) const
void allgather(const T &send_data, std::vector< T, A > &recv_data) const
QueryCache & condition(Args &&... args)
Adds a new condition to the query.
std::vector< T * > & queryInto(std::vector< T * > &results, Args &&... args)
queryInto executes the query and stores the results in the given vector.
TheWarehouse is a container for MooseObjects that allows querying/filtering over various customizeabl...
Query query()
query creates and returns an initialized a query object for querying objects from the warehouse.
void add(std::shared_ptr< MooseObject > obj)
add adds a new object to the warehouse and stores attributes/metadata about it for running queries/fi...
dof_id_type first_dof(const processor_id_type proc) const
dof_id_type end_dof(const processor_id_type proc) const
dof_id_type n_local_dofs(const unsigned int vn) const
void dof_indices(const Elem *const elem, std::vector< dof_id_type > &di) const
void remove_algebraic_ghosting_functor(GhostingFunctor &evaluable_functor)
void full_sparsity_pattern_needed()
dof_id_type n_dofs(const unsigned int vn) const
virtual void clear()
ParallelType type() const
virtual void close()=0
virtual void localize(std::vector< T > &v_local) const=0
const Parallel::Communicator & _communicator
processor_id_type processor_id() const
const Parallel::Communicator & comm() const
bool empty() const
bool identify_variable_groups() const
dof_id_type n_dofs() const
const FEType & variable_type(const unsigned int i) const
NumericVector< Number > & add_vector(std::string_view vec_name, const bool projections=true, const ParallelType type=PARALLEL)
std::unique_ptr< NumericVector< Number > > solution
void set_basic_system_only()
virtual void update()
unsigned int n_vars() const
const DofMap & get_dof_map() const
unsigned int number() const
void appendFVSetupObjects(TheWarehouse &warehouse, const std::string &system_name, const unsigned int system_number, const THREAD_ID tid, std::vector< SetupInterface * > &results)
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...
ComputeType
The type of nonlinear computation being performed.
Definition MooseTypes.h:835
@ ST_LINEAR
Solving a linear problem.
Definition MooseTypes.h:902
@ VECTOR_TAG_RESIDUAL
const TagName PREVIOUS_NL_SOLUTION_TAG
Definition MooseTypes.C:28
@ COUPLING_DIAG
Definition MooseTypes.h:786
@ COUPLING_CUSTOM
Definition MooseTypes.h:788
@ VAR_SOLVER
Definition MooseTypes.h:770
static void sort_row(const BidirectionalIterator begin, BidirectionalIterator middle, const BidirectionalIterator end)
std::vector< dof_id_type, Threads::scalable_allocator< dof_id_type > > Row
spin_mutex spin_mtx
void parallel_reduce(const Range &range, Body &body, unsigned int n_threads=libMesh::n_threads())
unsigned int n_threads()