Debian Codegraph @

include/deal.II/trilinos/nox.templates.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 2022 - 2025 by the deal.II authors
5 //
6 // This file is part of the deal.II library.
7 //
8 // Part of the source code is dual licensed under Apache-2.0 WITH
9 // LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10 // governing the source code and code contributions can be found in
11 // LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12 //
13 // ------------------------------------------------------------------------
14
15 #ifndef dealii_trilinos_nox_templates
16 #define dealii_trilinos_nox_templates
17
18 #include <deal.II/base/config.h>
19
20 #ifdef DEAL_II_TRILINOS_WITH_NOX
21
22 # include <deal.II/trilinos/nox.h>
23
24 # include <NOX_Abstract_Group.H>
25 # include <NOX_Abstract_Vector.H>
26 # include <NOX_Solver_Factory.H>
27 # include <NOX_Solver_Generic.H>
28 # include <NOX_StatusTest_Combo.H>
29 # include <NOX_StatusTest_MaxIters.H>
30 # include <NOX_StatusTest_NormF.H>
31 # include <NOX_StatusTest_RelativeNormF.H>
32
33 # include <memory>
34
35 DEAL_II_NAMESPACE_OPEN
36
37 # ifndef DOXYGEN
38
39 namespace TrilinosWrappers
40 {
41 namespace internal
42 {
43 namespace NOXWrappers
44 {
45 /**
46 * A function that calls the function object given by its first argument
47 * with the set of arguments following at the end. If the call returns
48 * regularly, the current function returns zero to indicate success. If
49 * the call fails with an exception, then the current function returns
50 * with an error code of -1. In that case, the exception thrown by `f`
51 * is captured and `eptr` is set to the exception. In case of success,
52 * `eptr` is set to `nullptr`.
53 */
54 template <typename F, typename... Args>
55 int
56 call_and_possibly_capture_exception(const F &f,
57 std::exception_ptr &eptr,
58 Args &&...args)
59 {
60 // See whether there is already something in the exception pointer
61 // variable. There is no reason why this should be so, and
62 // we should probably bail out:
63 AssertThrow(eptr == nullptr, ExcInternalError());
64
65 // Call the function and if that succeeds, return zero:
66 try
67 {
68 f(std::forward<Args>(args)...);
69 eptr = nullptr;
70 return 0;
71 }
72 // In case of an exception, capture the exception and
73 // return -1:
74 catch (...)
75 {
76 eptr = std::current_exception();
77 return -1;
78 }
79 }
80
81
82 template <typename VectorType>
83 class Group;
84
85 /**
86 * Implementation of the abstract interface
87 * NOX::Abstract::Vector for deal.II vectors. For details,
88 * see
89 * https://docs.trilinos.org/dev/packages/nox/doc/html/classNOX_1_1Abstract_1_1Vector.html.
90 */
91 template <typename VectorType>
92 class Vector : public NOX::Abstract::Vector
93 {
94 public:
95 /**
96 * Create empty vector.
97 */
98 Vector() = default;
99
100 /**
101 * Wrap an existing vector. The ownership is not transferred.
102 */
103 Vector(VectorType &vector)
104 {
105 this->vector.reset(&vector, [](auto *) { /*nothing to do*/ });
106 }
107
108 /**
109 * Initialize every element of this vector with @p gamma .
110 */
111 NOX::Abstract::Vector &
112 init(double gamma) override
113 {
114 *vector = static_cast<typename VectorType::value_type>(gamma);
115 return *this;
116 }
117
118 /**
119 * Initialize each element of this vector with a random value.
120 */
121 NOX::Abstract::Vector &
122 random(bool useSeed = false, int seed = 1) override
123 {
124 AssertThrow(false, ExcNotImplemented());
125
126 (void)useSeed;
127 (void)seed;
128
129 return *this;
130 }
131
132 /**
133 * Put element-wise absolute values of source vector @p y into this vector.
134 */
135 NOX::Abstract::Vector &
136 abs(const NOX::Abstract::Vector &y) override
137 {
138 AssertThrow(false, ExcNotImplemented());
139
140 (void)y;
141
142 return *this;
143 }
144
145 /**
146 * Copy source vector @p y into this vector.
147 */
148 NOX::Abstract::Vector &
149 operator=(const NOX::Abstract::Vector &y) override
150 {
151 if (vector == nullptr)
152 vector = std::shared_ptr<VectorType>();
153
154 const auto y_ = dynamic_cast<const Vector<VectorType> *>(&y);
155
156 Assert(y_, ExcInternalError());
157
158 vector->reinit(*y_->vector);
159
160 *vector = *y_->vector;
161
162 return *this;
163 }
164
165 /**
166 * Put element-wise reciprocal of source vector @p y into this vector.
167 */
168 NOX::Abstract::Vector &
169 reciprocal(const NOX::Abstract::Vector &y) override
170 {
171 AssertThrow(false, ExcNotImplemented());
172
173 (void)y;
174
175 return *this;
176 }
177
178 /**
179 * Scale each element of this vector by @p gamma .
180 */
181 NOX::Abstract::Vector &
182 scale(double gamma) override
183 {
184 *vector *= static_cast<typename VectorType::value_type>(gamma);
185
186 return *this;
187 }
188
189 /**
190 * Scale this vector element-by-element by the vector @p a.
191 */
192 NOX::Abstract::Vector &
193 scale(const NOX::Abstract::Vector &a) override
194 {
195 const auto a_ = dynamic_cast<const Vector<VectorType> *>(&a);
196
197 Assert(a_, ExcInternalError());
198
199 vector->scale(*a_->vector);
200
201 return *this;
202 }
203
204 /**
205 * Compute `x = (alpha * a) + (gamma * x)` where `x` is this vector.
206 */
207 NOX::Abstract::Vector &
208 update(double alpha,
209 const NOX::Abstract::Vector &a,
210 double gamma = 0.0) override
211 {
212 const auto a_ = dynamic_cast<const Vector<VectorType> *>(&a);
213
214 Assert(a_, ExcInternalError());
215
216 vector->sadd(static_cast<typename VectorType::value_type>(gamma),
217 static_cast<typename VectorType::value_type>(alpha),
218 *a_->vector);
219
220 return *this;
221 }
222
223 /**
224 * Compute `x = (alpha * a) + (beta * b) + (gamma * x)` where `x` is
225 * this vector.
226 */
227 NOX::Abstract::Vector &
228 update(double alpha,
229 const NOX::Abstract::Vector &a,
230 double beta,
231 const NOX::Abstract::Vector &b,
232 double gamma = 0.0) override
233 {
234 const auto a_ = dynamic_cast<const Vector<VectorType> *>(&a);
235 const auto b_ = dynamic_cast<const Vector<VectorType> *>(&b);
236
237 Assert(a_, ExcInternalError());
238 Assert(b_, ExcInternalError());
239
240 vector->operator*=(
241 static_cast<typename VectorType::value_type>(gamma));
242 vector->add(static_cast<typename VectorType::value_type>(alpha),
243 *a_->vector,
244 static_cast<typename VectorType::value_type>(beta),
245 *b_->vector);
246
247 return *this;
248 }
249
250 /**
251 * Create a new Vector of the same underlying type by cloning "this",
252 * and return a pointer to the new vector.
253 */
254 Teuchos::RCP<NOX::Abstract::Vector>
255 clone(NOX::CopyType copy_type) const override
256 {
257 auto new_vector = Teuchos::rcp(new Vector<VectorType>());
258 new_vector->vector = std::make_shared<VectorType>();
259 new_vector->vector->reinit(*this->vector);
260
261 if (copy_type == NOX::CopyType::DeepCopy)
262 *new_vector->vector = *this->vector;
263 else
264 Assert(copy_type == NOX::CopyType::ShapeCopy, ExcInternalError());
265
266 return new_vector;
267 }
268
269 /**
270 * Return the vector norm.
271 */
272 double
273 norm(NOX::Abstract::Vector::NormType type =
274 NOX::Abstract::Vector::TwoNorm) const override
275 {
276 if (type == NOX::Abstract::Vector::NormType::TwoNorm)
277 return vector->l2_norm();
278 if (type == NOX::Abstract::Vector::NormType::OneNorm)
279 return vector->l1_norm();
280 if (type == NOX::Abstract::Vector::NormType::MaxNorm)
281 return vector->linfty_norm();
282
283 DEAL_II_ASSERT_UNREACHABLE();
284
285 return 0.0;
286 }
287
288 /**
289 * Return the vector's weighted 2-norm.
290 */
291 double
292 norm(const NOX::Abstract::Vector &weights) const override
293 {
294 AssertThrow(false, ExcNotImplemented());
295
296 (void)weights;
297
298 return 0.0;
299 }
300
301 /**
302 * Return the inner product of the vector with @p y.
303 */
304 double
305 innerProduct(const NOX::Abstract::Vector &y) const override
306 {
307 const auto y_ = dynamic_cast<const Vector<VectorType> *>(&y);
308
309 Assert(y_, ExcInternalError());
310
311 return (*vector) * (*y_->vector);
312 }
313
314 /**
315 * Return the length of vector.
316 */
317 NOX::size_type
318 length() const override
319 {
320 return vector->size();
321 }
322
323 /**
324 * Return underlying vector.
325 */
326 operator VectorType &() const
327 {
328 AssertThrow(vector, ExcInternalError());
329
330 return *vector;
331 }
332
333 private:
334 /**
335 * The underlying deal.II vector.
336 */
337 std::shared_ptr<VectorType> vector;
338
339 friend Group<VectorType>;
340 };
341
342 /**
343 * Implementation of the abstract interface
344 * NOX::Abstract::Group for deal.II vectors and deal.II solvers. For
345 * details, see
346 * https://docs.trilinos.org/dev/packages/nox/doc/html/classNOX_1_1Abstract_1_1Group.html.
347 */
348 template <typename VectorType>
349 class Group : public NOX::Abstract::Group
350 {
351 public:
352 /**
353 * Constructor. The class is initialized by the solution vector and
354 * functions to compute the residual, to set up the Jacobian, and
355 * to solve the Jacobian.
356 */
357 Group(
358 VectorType &solution,
359 const std::function<int(const VectorType &, VectorType &)> &residual,
360 const std::function<int(const VectorType &)> &setup_jacobian,
361 const std::function<int(const VectorType &, VectorType &)>
362 &apply_jacobian,
363 const std::function<int(const VectorType &,
364 VectorType &,
365 const double)> &solve_with_jacobian)
366 : x(solution)
367 , residual(residual)
368 , setup_jacobian(setup_jacobian)
369 , apply_jacobian(apply_jacobian)
370 , solve_with_jacobian(solve_with_jacobian)
371 , is_valid_f(false)
372 , is_valid_j(false)
373 {}
374
375 /**
376 * Copies the source group into this group.
377 */
378 NOX::Abstract::Group &
379 operator=(const NOX::Abstract::Group &source) override
380 {
381 if (this != &source)
382 {
383 const auto other =
384 dynamic_cast<const Group<VectorType> *>(&source);
385
386 Assert(other, ExcInternalError());
387
388 if (other->x.vector)
389 {
390 if (this->x.vector == nullptr)
391 this->x.vector = std::make_shared<VectorType>();
392
393 *this->x.vector = *other->x.vector;
394 }
395 else
396 {
397 this->x.vector = {};
398 }
399
400 if (other->f.vector)
401 {
402 if (this->f.vector == nullptr)
403 this->f.vector = std::make_shared<VectorType>();
404
405 *this->f.vector = *other->f.vector;
406 }
407 else
408 {
409 this->f.vector = {};
410 }
411
412 if (other->gradient.vector)
413 {
414 if (this->gradient.vector == nullptr)
415 this->gradient.vector = std::make_shared<VectorType>();
416
417 *this->gradient.vector = *other->gradient.vector;
418 }
419 else
420 {
421 this->gradient.vector = {};
422 }
423
424 if (other->newton.vector)
425 {
426 if (this->newton.vector == nullptr)
427 this->newton.vector = std::make_shared<VectorType>();
428
429 *this->newton.vector = *other->newton.vector;
430 }
431 else
432 {
433 this->newton.vector = {};
434 }
435
436 this->residual = other->residual;
437 this->setup_jacobian = other->setup_jacobian;
438 this->apply_jacobian = other->apply_jacobian;
439 this->solve_with_jacobian = other->solve_with_jacobian;
440
441 this->is_valid_f = other->is_valid_f;
442 this->is_valid_j = other->is_valid_j;
443 }
444
445 return *this;
446 }
447
448 /**
449 * Set the solution vector `x` to @p y.
450 */
451 void
452 setX(const NOX::Abstract::Vector &y) override
453 {
454 reset();
455
456 x = y;
457 }
458
459 /**
460 * Compute the solution update `x = grp.x + step * d`.
461 */
462 void
463 computeX(const NOX::Abstract::Group &grp,
464 const NOX::Abstract::Vector &d,
465 double step) override
466 {
467 reset();
468
469 const auto grp_ = dynamic_cast<const Group *>(&grp);
470
471 Assert(grp_, ExcInternalError());
472
473 x.update(1.0, grp_->x, step, d);
474 }
475
476 /**
477 * Compute and store the residual update `F(x)`.
478 */
479 NOX::Abstract::Group::ReturnType
480 computeF() override
481 {
482 if (isF() == false)
483 {
484 f.vector = std::make_shared<VectorType>();
485 f.vector->reinit(*x.vector);
486
487 if (residual(*x.vector, *f.vector) != 0)
488 return NOX::Abstract::Group::Failed;
489
490 is_valid_f = true;
491 }
492
493 return NOX::Abstract::Group::Ok;
494 }
495
496 /**
497 * Return `true` if the residual vector `F` is valid.
498 */
499 bool
500 isF() const override
501 {
502 return is_valid_f;
503 }
504
505 /**
506 * Compute and store the Jacobian.
507 */
508 NOX::Abstract::Group::ReturnType
509 computeJacobian() override
510 {
511 if (isJacobian() == false)
512 {
513 if (setup_jacobian(*x.vector) != 0)
514 return NOX::Abstract::Group::Failed;
515
516 is_valid_j = true;
517 }
518
519 return NOX::Abstract::Group::Ok;
520 }
521
522 /**
523 * Return `true` if the Jacobian is valid.
524 */
525 bool
526 isJacobian() const override
527 {
528 return is_valid_j;
529 }
530
531 /**
532 * Return the (total) solution vector.
533 */
534 const NOX::Abstract::Vector &
535 getX() const override
536 {
537 return x;
538 }
539
540 /**
541 * Return the residual `F(x)`.
542 */
543 const NOX::Abstract::Vector &
544 getF() const override
545 {
546 return f;
547 }
548
549 /**
550 * Return the 2-norm of `F(x)`.
551 */
552 double
553 getNormF() const override
554 {
555 return f.norm();
556 }
557
558 /**
559 * Return the gradient.
560 */
561 const NOX::Abstract::Vector &
562 getGradient() const override
563 {
564 return gradient;
565 }
566
567 /**
568 * Return the Newton descent direction.
569 */
570 const NOX::Abstract::Vector &
571 getNewton() const override
572 {
573 return newton;
574 }
575
576 /**
577 * Return a reference counting pointer to solution vector.
578 */
579 Teuchos::RCP<const NOX::Abstract::Vector>
580 getXPtr() const override
581 {
582 AssertThrow(false, ExcNotImplemented());
583 return {};
584 }
585
586 /**
587 * Return a reference counting pointer to the residual `F(x)`.
588 */
589 Teuchos::RCP<const NOX::Abstract::Vector>
590 getFPtr() const override
591 {
592 AssertThrow(false, ExcNotImplemented());
593 return {};
594 }
595
596 /**
597 * Return a reference counting pointer to gradient.
598 */
599 Teuchos::RCP<const NOX::Abstract::Vector>
600 getGradientPtr() const override
601 {
602 AssertThrow(false, ExcNotImplemented());
603 return {};
604 }
605
606 /**
607 * Return a reference counting pointer to the Newton descent direction.
608 */
609 Teuchos::RCP<const NOX::Abstract::Vector>
610 getNewtonPtr() const override
611 {
612 AssertThrow(false, ExcNotImplemented());
613 return {};
614 }
615
616 /**
617 * Create a new Group of the same derived type as this one by
618 * cloning this one, and return a reference counting pointer to
619 * the new group.
620 */
621 Teuchos::RCP<NOX::Abstract::Group>
622 clone(NOX::CopyType copy_type) const override
623 {
624 auto new_group =
625 Teuchos::rcp(new Group<VectorType>(*x.vector,
626 residual,
627 setup_jacobian,
628 apply_jacobian,
629 solve_with_jacobian));
630
631 if (x.vector)
632 {
633 new_group->x.vector = std::make_shared<VectorType>();
634 new_group->x.vector->reinit(*x.vector);
635 }
636
637 if (f.vector)
638 {
639 new_group->f.vector = std::make_shared<VectorType>();
640 new_group->f.vector->reinit(*f.vector);
641 }
642
643 if (gradient.vector)
644 {
645 new_group->gradient.vector = std::make_shared<VectorType>();
646 new_group->gradient.vector->reinit(*gradient.vector);
647 }
648
649 if (newton.vector)
650 {
651 new_group->newton.vector = std::make_shared<VectorType>();
652 new_group->newton.vector->reinit(*newton.vector);
653 }
654
655 if (copy_type == NOX::CopyType::DeepCopy)
656 {
657 if (x.vector)
658 *new_group->x.vector = *x.vector;
659
660 if (f.vector)
661 *new_group->f.vector = *f.vector;
662
663 if (gradient.vector)
664 *new_group->gradient.vector = *gradient.vector;
665
666 if (newton.vector)
667 *new_group->newton.vector = *newton.vector;
668
669 new_group->is_valid_f = is_valid_f;
670 new_group->is_valid_j = is_valid_j;
671 }
672 else
673 Assert(copy_type == NOX::CopyType::ShapeCopy, ExcInternalError());
674
675 return new_group;
676 }
677
678 /**
679 * Compute the Newton direction, using the chosen
680 * parameters for the linear solve.
681 */
682 NOX::Abstract::Group::ReturnType
683 computeNewton(Teuchos::ParameterList &p) override
684 {
685 if (isNewton())
686 return NOX::Abstract::Group::Ok;
687
688 if (isF() == false || isJacobian() == false)
689 return NOX::Abstract::Group::BadDependency;
690
691 if (newton.vector == nullptr)
692 newton.vector = std::make_shared<VectorType>();
693
694 newton.vector->reinit(*f.vector, false);
695
696 const double tolerance = p.get<double>("Tolerance");
697
698 if (solve_with_jacobian(*f.vector, *newton.vector, tolerance) != 0)
699 return NOX::Abstract::Group::NotConverged;
700
701 newton.scale(-1.0);
702
703 return NOX::Abstract::Group::Ok;
704 }
705
706 /**
707 * Applies the Jacobian to the given @p input vector and assigns
708 * the output to the @p result.
709 */
710 NOX::Abstract::Group::ReturnType
711 applyJacobian(const NOX::Abstract::Vector &input,
712 NOX::Abstract::Vector &result) const override
713 {
714 if (apply_jacobian == nullptr)
715 return NOX::Abstract::Group::NotDefined;
716
717 if (!isJacobian())
718 return NOX::Abstract::Group::BadDependency;
719
720 const auto *input_ = dynamic_cast<const Vector<VectorType> *>(&input);
721 const auto *result_ =
722 dynamic_cast<const Vector<VectorType> *>(&result);
723
724 if (apply_jacobian(*input_->vector, *result_->vector) != 0)
725 return NOX::Abstract::Group::Failed;
726
727 return NOX::Abstract::Group::Ok;
728 }
729
730 private:
731 /**
732 * Reset the state of this object.
733 */
734 void
735 reset()
736 {
737 is_valid_f = false;
738 is_valid_j = false;
739 }
740
741 /**
742 * An internal vector for the current solution.
743 */
744 Vector<VectorType> x;
745
746 /**
747 * An internal vector for the residual.
748 */
749 Vector<VectorType> f;
750
751 /**
752 * An internal vector for the solution gradient.
753 */
754 Vector<VectorType> gradient;
755
756 /**
757 * An internal vector for the newton step.
758 */
759 Vector<VectorType> newton;
760
761 /**
762 * A helper function to compute residual.
763 */
764 std::function<int(const VectorType &x, VectorType &f)> residual;
765
766 /**
767 * A helper function to set up Jacobian.
768 */
769 std::function<int(const VectorType &x)> setup_jacobian;
770
771 /**
772 * A helper function to apply Jacobian.
773 */
774 std::function<int(const VectorType &x, VectorType &v)> apply_jacobian;
775
776 /**
777 * A helper function to solve Jacobian.
778 */
779 std::function<
780 int(const VectorType &f, VectorType &x, const double tolerance)>
781 solve_with_jacobian;
782
783 /**
784 * A flag that indicates if the has residual been computed.
785 */
786 bool is_valid_f;
787
788 /**
789 * A flag that indicates if the Jacobian has been computed.
790 */
791 bool is_valid_j;
792 };
793
794
795 /**
796 * Wrapper class around the user function that allows to check
797 * convergence.
798 */
799 template <typename VectorType>
800 class NOXCheck : public NOX::StatusTest::Generic
801 {
802 public:
803 /**
804 * Constructor.
805 */
806 NOXCheck(const std::function<SolverControl::State(const unsigned int,
807 const double,
808 const VectorType &,
809 const VectorType &)>
810 check_iteration_status)
811 : check_iteration_status(check_iteration_status)
812 , status(NOX::StatusTest::Unevaluated)
813 {}
814
815 /**
816 * Check the status of the nonlinear solver.
817 */
818 NOX::StatusTest::StatusType
819 checkStatus(const NOX::Solver::Generic &problem,
820 NOX::StatusTest::CheckType checkType) override
821 {
822 if (checkType == NOX::StatusTest::None)
823 {
824 status = NOX::StatusTest::Unevaluated;
825 }
826 else
827 {
828 if (check_iteration_status == nullptr)
829 {
830 status = NOX::StatusTest::Converged;
831 }
832 else
833 {
834 // unwrap the various vectors
835 const VectorType &x = *dynamic_cast<
836 const internal::NOXWrappers::Vector<VectorType> *>(
837 &problem.getSolutionGroup().getX());
838 const VectorType &f = *dynamic_cast<
839 const internal::NOXWrappers::Vector<VectorType> *>(
840 &problem.getSolutionGroup().getF());
841
842 // forward to the user-provided function and check
843 // convergence
844 const auto state = this->check_iteration_status(
845 problem.getNumIterations(), f.l2_norm(), x, f);
846
847 // translate the returned value back to Trilinos data
848 // structure
849 switch (state)
850 {
851 case SolverControl::iterate:
852 status = NOX::StatusTest::Unconverged;
853 break;
854 case SolverControl::failure:
855 status = NOX::StatusTest::Failed;
856 break;
857 case SolverControl::success:
858 status = NOX::StatusTest::Converged;
859 break;
860 default:
861 AssertThrow(false, ExcNotImplemented());
862 }
863 }
864 }
865
866 return status;
867 }
868
869 /**
870 * Return the last value that was given by `checkStatus()`.
871 */
872 NOX::StatusTest::StatusType
873 getStatus() const override
874 {
875 return status;
876 }
877
878 /**
879 * Print the last value that was given by `checkStatus()`
880 */
881 virtual std::ostream &
882 print(std::ostream &stream, int indent = 0) const override
883 {
884 for (int j = 0; j < indent; ++j)
885 stream << ' ';
886 stream << status << std::endl;
887 return stream;
888 }
889
890 private:
891 /**
892 * The user function that allows the solver to check for
893 * convergence.
894 */
895 const std::function<SolverControl::State(const unsigned int i,
896 const double f_norm,
897 const VectorType &x,
898 const VectorType &f)>
899 check_iteration_status;
900
901 /**
902 * The last returned value of `checkStatus()`.
903 */
904 NOX::StatusTest::StatusType status;
905 };
906 } // namespace NOXWrappers
907 } // namespace internal
908
909
910
911 template <typename VectorType>
912 NOXSolver<VectorType>::AdditionalData::AdditionalData(
913 const unsigned int max_iter,
914 const double abs_tol,
915 const double rel_tol,
916 const unsigned int threshold_nonlinear_iterations,
917 const unsigned int threshold_n_linear_iterations,
918 const bool reuse_solver)
919 : max_iter(max_iter)
920 , abs_tol(abs_tol)
921 , rel_tol(rel_tol)
922 , threshold_nonlinear_iterations(threshold_nonlinear_iterations)
923 , threshold_n_linear_iterations(threshold_n_linear_iterations)
924 , reuse_solver(reuse_solver)
925 {}
926
927
928
929 template <typename VectorType>
930 NOXSolver<VectorType>::NOXSolver(
931 AdditionalData &additional_data,
932 const Teuchos::RCP<Teuchos::ParameterList> &parameters)
933 : additional_data(additional_data)
934 , parameters(parameters)
935 , n_residual_evaluations(0)
936 , n_jacobian_applications(0)
937 , n_nonlinear_iterations(0)
938 , n_last_linear_iterations(0)
939 , pending_exception(nullptr)
940 {}
941
942
943 template <typename VectorType>
944 NOXSolver<VectorType>::~NOXSolver()
945 {
946 Assert(pending_exception == nullptr, ExcInternalError());
947 }
948
949
950
951 template <typename VectorType>
952 void
953 NOXSolver<VectorType>::clear()
954 {
955 // clear internal counters
956 n_residual_evaluations = 0;
957 n_jacobian_applications = 0;
958 n_nonlinear_iterations = 0;
959 n_last_linear_iterations = 0;
960 }
961
962
963
964 template <typename VectorType>
965 unsigned int
966 NOXSolver<VectorType>::solve(VectorType &solution)
967 {
968 if (additional_data.reuse_solver == false)
969 clear(); // clear state
970
971 // create group
972 const auto group = Teuchos::rcp(new internal::NOXWrappers::Group<
973 VectorType>(
974 /* Starting vector */
975 solution,
976
977 /* Residual function */
978 [&](const VectorType &x, VectorType &f) -> int {
979 Assert(
980 residual,
981 ExcMessage(
982 "No residual function has been attached to the NOXSolver object."));
983
984 ++n_residual_evaluations;
985
986 // evaluate residual
987 return internal::NOXWrappers::call_and_possibly_capture_exception(
988 residual, pending_exception, x, f);
989 },
990
991 /* setup_jacobian function */
992 [&](const VectorType &x) -> int {
993 Assert(
994 setup_jacobian,
995 ExcMessage(
996 "No setup_jacobian function has been attached to the NOXSolver object."));
997
998 // setup Jacobian
999 int flag = internal::NOXWrappers::call_and_possibly_capture_exception(
1000 setup_jacobian, pending_exception, x);
1001
1002 if (flag != 0)
1003 return flag;
1004
1005 if (setup_preconditioner)
1006 {
1007 // check if preconditioner needs to be updated
1008 bool update_preconditioner =
1009 ((additional_data.threshold_nonlinear_iterations > 0) &&
1010 ((n_nonlinear_iterations %
1011 additional_data.threshold_nonlinear_iterations) == 0)) ||
1012 (solve_with_jacobian_and_track_n_linear_iterations &&
1013 (n_last_linear_iterations >
1014 additional_data.threshold_n_linear_iterations));
1015
1016 if (update_preconditioner_predicate)
1017 update_preconditioner |= update_preconditioner_predicate();
1018
1019 if (update_preconditioner)
1020 flag = internal::NOXWrappers::call_and_possibly_capture_exception(
1021 setup_preconditioner, pending_exception, x);
1022 }
1023
1024 return flag;
1025 },
1026
1027 /* apply_jacobian function */
1028 [&](const VectorType &x, VectorType &v) -> int {
1029 Assert(
1030 apply_jacobian,
1031 ExcMessage(
1032 "No apply_jacobian function has been attached to the NOXSolver object."));
1033
1034 ++n_jacobian_applications;
1035
1036 // apply Jacobian
1037 return internal::NOXWrappers::call_and_possibly_capture_exception(
1038 apply_jacobian, pending_exception, x, v);
1039 },
1040
1041 /* solve_with_jacobian function */
1042 [&](const VectorType &f, VectorType &x, const double tolerance) -> int {
1043 ++n_nonlinear_iterations;
1044
1045 int ret_code = 0;
1046
1047 // invert Jacobian
1048 if (solve_with_jacobian)
1049 {
1050 Assert(
1051 !solve_with_jacobian_and_track_n_linear_iterations,
1052 ExcMessage(
1053 "It does not make sense to provide both solve_with_jacobian and "
1054 "solve_with_jacobian_and_track_n_linear_iterations!"));
1055
1056 // without tracking of linear iterations
1057 ret_code =
1058 internal::NOXWrappers::call_and_possibly_capture_exception(
1059 solve_with_jacobian, pending_exception, f, x, tolerance);
1060 }
1061 else if (solve_with_jacobian_and_track_n_linear_iterations)
1062 {
1063 // With tracking of linear iterations. The callback function we
1064 // have here is using an integer return type, which is not
1065 // what internal::NOXWrappers::call_and_possibly_capture_exception
1066 // knows how to deal with. As a consequence, package the call
1067 // and assignment of the return value into a lambda function;
1068 // if the call to the user-defined callback fails, this will
1069 // trigger an exception that will propagate through the lambda
1070 // function and be treated correctly by the logic in
1071 // internal::NOXWrappers::call_and_possibly_capture_exception.
1072 ret_code =
1073 internal::NOXWrappers::call_and_possibly_capture_exception(
1074 [&]() {
1075 this->n_last_linear_iterations =
1076 solve_with_jacobian_and_track_n_linear_iterations(
1077 f, x, tolerance);
1078 },
1079 pending_exception);
1080 }
1081 else
1082 {
1083 Assert(
1084 false,
1085 ExcMessage(
1086 "Neither a solve_with_jacobian or a "
1087 "solve_with_jacobian_and_track_n_linear_iterations function "
1088 "has been attached to the NOXSolver object."));
1089
1090 DEAL_II_NOT_IMPLEMENTED();
1091 ret_code = 1;
1092 }
1093
1094 // NOX has a recovery feature that is enabled by default. In this case,
1095 // if a solve_with_jacobian or a
1096 // solve_with_jacobian_and_track_n_linear_iterations function triggers
1097 // an exception and therefore call_and_possibly_capture_exception
1098 // returns code different from 0, then NOX does not interrupt the
1099 // solution process but rather performs a recovery step. To ensure this
1100 // feature is available to the user, we need to suppress the exception
1101 // in this case, since it is exactly that, what NOX expects from our
1102 // callbacks.
1103 const bool do_rescue =
1104 parameters->sublist("Newton").get("Rescue Bad Newton Solve", true);
1105 if (do_rescue && (pending_exception != nullptr))
1106 {
1107 try
1108 {
1109 std::rethrow_exception(pending_exception);
1110 }
1111 catch (const RecoverableUserCallbackError &exc)
1112 {
1113 pending_exception = nullptr;
1114
1115 // If the callback threw a recoverable exception, and if
1116 // recovery is enabled, then eat the exception and return the
1117 // error code.
1118 return ret_code;
1119 }
1120 catch (...)
1121 {
1122 // If not a recoverable exception, then just re-throw the
1123 // exception and hope that NOX knows what to do with propagating
1124 // exceptions (i.e., does not create a resource leak, for
1125 // example).
1126 pending_exception = nullptr;
1127 throw;
1128 }
1129 }
1130 else
1131 // Rescue not allowed, or there was no exception -> simply return
1132 // the value produced by the callback.
1133 return ret_code;
1134 }));
1135
1136 // setup solver control
1137 auto check =
1138 Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::OR));
1139
1140 if (this->check_iteration_status)
1141 {
1142 const auto info =
1143 Teuchos::rcp(new internal::NOXWrappers::NOXCheck<VectorType>(
1144 this->check_iteration_status));
1145 check->addStatusTest(info);
1146 }
1147
1148 if (additional_data.abs_tol > 0.0)
1149 {
1150 const auto additional_data_norm_f_abs =
1151 Teuchos::rcp(new NOX::StatusTest::NormF(additional_data.abs_tol));
1152 check->addStatusTest(additional_data_norm_f_abs);
1153 }
1154
1155 if (additional_data.rel_tol > 0.0)
1156 {
1157 const auto additional_data_norm_f_rel = Teuchos::rcp(
1158 new NOX::StatusTest::RelativeNormF(additional_data.rel_tol));
1159 check->addStatusTest(additional_data_norm_f_rel);
1160 }
1161
1162 if (additional_data.max_iter > 0)
1163 {
1164 const auto additional_data_max_iterations =
1165 Teuchos::rcp(new NOX::StatusTest::MaxIters(additional_data.max_iter));
1166 check->addStatusTest(additional_data_max_iterations);
1167 }
1168
1169 // create non-linear solver
1170 const auto solver = NOX::Solver::buildSolver(group, check, parameters);
1171
1172 // Solve, then check whether an exception was thrown by one of the user
1173 // callback functions. If so, exit by rethrowing the exception that
1174 // we had previously saved. This also calls the destructors of all of
1175 // the member variables above, so we do not have to clean things up by hand.
1176 //
1177 // NOX has the annoying habit of reporting success through a return code,
1178 // but if a user callback function throws an exception (which we translate
1179 // into a return code of -1), then it throws its own exception. So we
1180 // have to check both the return code and also catch exceptions :-(
1181 try
1182 {
1183 const auto status = solver->solve();
1184
1185 if (status == NOX::StatusTest::Converged)
1186 return solver->getNumIterations();
1187 else
1188 {
1189 // See if NOX aborted because we had thrown an exception in a user
1190 // callback:
1191 if (pending_exception)
1192 {
1193 std::exception_ptr this_exception = pending_exception;
1194 pending_exception = nullptr;
1195
1196 std::rethrow_exception(this_exception);
1197 }
1198
1199 // If that was not the case, NOX just didn't converge:
1200 AssertThrow(status == NOX::StatusTest::Converged,
1201 ExcNOXNoConvergence());
1202 }
1203 }
1204 // See if NOX returned by triggering an exception.
1205 # if DEAL_II_TRILINOS_VERSION_GTE(14, 2, 0)
1206 // Starting with Trilinos version 14.2.0 NOX started to throw a
1207 // std::runtime_error instead of a plain char*.
1208 catch (const std::runtime_error &exc)
1209 {
1210 const char *s = exc.what();
1211 # else
1212 // In a sign of generally poor software design, NOX prior to Trilinos
1213 // version 14.2.0 throws an exception that is not of a class derived
1214 // from std::exception, but just a char*. That's a nuisance -- you just
1215 // have to know :-(
1216 catch (const char *s)
1217 {
1218 # endif
1219 // Like above, see if NOX aborted because there was an exception
1220 // in a user callback. In that case, collate the errors if we can
1221 // (namely, if the user exception was derived from std::exception),
1222 // and otherwise just let the user exception propagate (then swallowing
1223 // the NOX exception):
1224 if (pending_exception)
1225 {
1226 std::exception_ptr this_exception = pending_exception;
1227 pending_exception = nullptr;
1228
1229 try
1230 {
1231 std::rethrow_exception(this_exception);
1232 }
1233 catch (const std::exception &e)
1234 {
1235 // Collate the exception texts:
1236 throw ExcMessage(
1237 "NOX aborted with an error text of <" + std::string(s) +
1238 "> after a user callback function had thrown an exception " +
1239 "with the following message:\n" + e.what());
1240 }
1241 catch (...)
1242 {
1243 // Let user exception propagate if of a different type:
1244 throw;
1245 }
1246 }
1247
1248 // NOX just happened to throw an exception, but it wasn't because there
1249 // was a user callback exception before. Convert the char* to something
1250 // more readable:
1251 AssertThrow(false,
1252 ExcMessage("NOX aborted with an error text of <" +
1253 std::string(s) + ">."));
1254 }
1255
1256 return 0; // unreachable
1257 }
1258
1259 } // namespace TrilinosWrappers
1260
1261 # endif
1262
1263 DEAL_II_NAMESPACE_CLOSE
1264
1265 #else
1266
1267 // Make sure the scripts that create the C++20 module input files have
1268 // something to latch on if the preprocessor #ifdef above would
1269 // otherwise lead to an empty content of the file.
1270 DEAL_II_NAMESPACE_OPEN
1271 DEAL_II_NAMESPACE_CLOSE
1272
1273 #endif
1274
1275 #endif