GetFEM  5.6
getfem_model_solvers.cc
1 /*===========================================================================
2 
3  Copyright (C) 2009-2026 Yves Renard
4 
5  This file is a part of GetFEM
6 
7  GetFEM is free software; you can redistribute it and/or modify it
8  under the terms of the GNU Lesser General Public License as published
9  by the Free Software Foundation; either version 3 of the License, or
10  (at your option) any later version along with the GCC Runtime Library
11  Exception either version 3.1 or (at your option) any later version.
12  This program is distributed in the hope that it will be useful, but
13  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15  License and GCC Runtime Library Exception for more details.
16  You should have received a copy of the GNU Lesser General Public License
17  along with this program. If not, see https://www.gnu.org/licenses/.
18 
19 ===========================================================================*/
20 
22 #include "gmm/gmm_inoutput.h"
23 #include <iomanip>
24 
25 namespace getfem {
26 
27  #define TRACE_SOL 0
28 
29  /* ***************************************************************** */
30  /* Intermediary structure for Newton algorithms with getfem::model. */
31  /* ***************************************************************** */
32 
33  template <typename PLSOLVER>
34  class pb_base {
35  public:
36  typedef typename PLSOLVER::element_type::MATRIX MATRIX;
37  typedef typename PLSOLVER::element_type::VECTOR VECTOR;
38  typedef typename gmm::linalg_traits<VECTOR>::value_type T;
39  typedef typename gmm::number_traits<T>::magnitude_type R;
40 
41  protected:
42  PLSOLVER linear_solver;
43  const MATRIX &K;
44  VECTOR &rhs;
45  VECTOR state;
46 
47  public:
48  virtual const VECTOR &residual() const { return rhs; }
49  // A norm1 seems to be better than a norm2 (at least for contact problems).
50  virtual R residual_norm() { return gmm::vect_norm1(residual()); }
51  virtual const VECTOR &state_vector() const { return state; }
52  virtual VECTOR &state_vector() { return state; }
53  virtual R state_norm() const { return gmm::vect_norm1(state_vector()); }
54 
55  virtual void perturbation() {
56  R res = gmm::vect_norm2(state), ampl = std::max(res*R(1E-20), R(1E-50));
57  std::vector<R> V(gmm::vect_size(state));
59  gmm::add(gmm::scaled(V, ampl), state);
60  }
61 
62  virtual void add_to_residual(VECTOR &extra_rhs, R mult=1.) {
63  if (mult == R(1)) gmm::add(extra_rhs, rhs);
64  else if (mult != R(0)) gmm::add(gmm::scaled(extra_rhs, mult), rhs);
65  }
66 
67  virtual void linear_solve(VECTOR &dr, gmm::iteration &iter) {
68  (*linear_solver)(K, dr, rhs, iter);
69  }
70 
71  pb_base(PLSOLVER linsolv, const MATRIX &K_, VECTOR &rhs_)
72  : linear_solver(linsolv), K(K_), rhs(rhs_), state(gmm::vect_size(rhs_)) {}
73  virtual ~pb_base() {}
74  };
75 
76  /* ***************************************************************** */
77  /* Linear model problem. */
78  /* ***************************************************************** */
79  template <typename PLSOLVER>
80  class lin_model_pb : pb_base<PLSOLVER> {
81  model &md;
82  public:
83  using typename pb_base<PLSOLVER>::VECTOR;
84  using typename pb_base<PLSOLVER>::R;
85  using pb_base<PLSOLVER>::state_vector;
86  using pb_base<PLSOLVER>::linear_solve;
87  void compute_all() { md.assembly(model::BUILD_ALL); }
88 
89  // Normwise backward error |K x - b| / (|K| |x| + |b|) (infinity norms) of
90  // the computed state: a solver independent check that the linear solver
91  // did not fail (e.g. leaving a zero state after a zero pivot). It does
92  // not detect numerically singular matrices: a stable direct solver keeps
93  // a small backward error on them.
94  R backward_error() const {
95  const VECTOR &x = state_vector();
96  VECTOR r(gmm::vect_size(this->rhs));
97  gmm::mult(this->K, x, r);
98  gmm::add(gmm::scaled(this->rhs, typename pb_base<PLSOLVER>::T(-1)), r);
99  R den = gmm::mat_norminf(this->K) * gmm::vect_norminf(x)
100  + gmm::vect_norminf(this->rhs);
101  return (den > R(0)) ? gmm::vect_norminf(r) / den : R(0);
102  }
103 
104  lin_model_pb(model &, PLSOLVER) = delete;
105  };
106 
107  template <>
108  lin_model_pb<rmodel_plsolver_type>::lin_model_pb
109  (model &md_, rmodel_plsolver_type linsolv)
110  : pb_base<rmodel_plsolver_type>
111  (linsolv, md_.real_tangent_matrix(), md_.set_real_rhs()),
112  md(md_)
113  { md.from_variables(state_vector()); }
114  template <>
115  lin_model_pb<cmodel_plsolver_type>::lin_model_pb
116  (model &md_, cmodel_plsolver_type linsolv)
117  : pb_base<cmodel_plsolver_type>
118  (linsolv, md_.complex_tangent_matrix(), md_.set_complex_rhs()),
119  md(md_)
120  { md.from_variables(state_vector()); }
121 
122 
123  /* ***************************************************************** */
124  /* Non-linear model problem. */
125  /* ***************************************************************** */
126  template <typename PLSOLVER>
127  class nonlin_model_pb : protected pb_base<PLSOLVER> {
128  public:
129  using typename pb_base<PLSOLVER>::VECTOR;
130  using typename pb_base<PLSOLVER>::R;
131  protected:
132  model &md;
133  abstract_newton_line_search &ls;
134  private:
135  VECTOR stateinit; // just a temp used in line_search, could also be mutable
136  public:
137  using pb_base<PLSOLVER>::residual;
138  using pb_base<PLSOLVER>::residual_norm;
139  using pb_base<PLSOLVER>::state_vector;
140  using pb_base<PLSOLVER>::state_norm;
141  using pb_base<PLSOLVER>::add_to_residual;
142  using pb_base<PLSOLVER>::perturbation;
143  using pb_base<PLSOLVER>::linear_solve;
144 
145  virtual R approx_external_load_norm() { return md.approx_external_load(); }
146 
147  virtual void compute_tangent_matrix() {
148  md.to_variables(state_vector());
149  md.assembly(model::BUILD_MATRIX);
150  }
151 
152  virtual void compute_residual() {
153  md.to_variables(state_vector());
154  md.assembly(model::BUILD_RHS);
155  }
156 
157  virtual R line_search(VECTOR &dr, const gmm::iteration &iter) {
158  size_type nit = 0;
159  gmm::resize(stateinit, gmm::vect_size(state_vector()));
160  gmm::copy(state_vector(), stateinit);
161  R alpha(1), res, /* res_init, */ R0;
162 
163  /* res_init = */ res = residual_norm();
164  // cout << "first residual = " << residual() << endl << endl;
165  R0 = gmm::real(gmm::vect_sp(dr, residual()));
166  ls.init_search(res, iter.get_iteration(), R0);
167  do {
168  alpha = ls.next_try();
169  gmm::add(stateinit, gmm::scaled(dr, alpha), state_vector());
170 
171  compute_residual();
172  res = residual_norm();
173  // cout << "residual = " << residual() << endl << endl;
174  R0 = gmm::real(gmm::vect_sp(dr, residual()));
175  ++ nit;
176  } while (!ls.is_converged(res, R0));
177 
178  if (alpha != ls.converged_value()) {
179  alpha = ls.converged_value();
180  gmm::add(stateinit, gmm::scaled(dr, alpha), state_vector());
181  res = ls.converged_residual();
182  compute_residual();
183  }
184 
185  return alpha;
186  }
187 
188  nonlin_model_pb(model &md_, abstract_newton_line_search &ls_,
189  PLSOLVER linear_solver_) = delete;
190  };
191 
192  template <>
193  nonlin_model_pb<rmodel_plsolver_type>::nonlin_model_pb
194  (model &md_, abstract_newton_line_search &ls_, rmodel_plsolver_type linsolv)
195  : pb_base<rmodel_plsolver_type>
196  (linsolv, md_.real_tangent_matrix(), md_.set_real_rhs()),
197  md(md_), ls(ls_)
198  { md.from_variables(state_vector()); }
199  template <>
200  nonlin_model_pb<cmodel_plsolver_type>::nonlin_model_pb
201  (model &md_, abstract_newton_line_search &ls_, cmodel_plsolver_type linsolv)
202  : pb_base<cmodel_plsolver_type>
203  (linsolv, md_.complex_tangent_matrix(), md_.set_complex_rhs()),
204  md(md_), ls(ls_)
205  { md.from_variables(state_vector()); }
206 
207 
208 
209  /* ***************************************************************** */
210  /* Non-linear model problem with internal variable condensation. */
211  /* ***************************************************************** */
212  template <typename PLSOLVER>
213  class nonlin_condensed_model_pb : public nonlin_model_pb<PLSOLVER> {
214  public:
215  using typename pb_base<PLSOLVER>::MATRIX;
216  using typename pb_base<PLSOLVER>::VECTOR;
217  using typename pb_base<PLSOLVER>::R;
218 
219  private:
220  using nonlin_model_pb<PLSOLVER>::md;
221  bool condensed_vars;
222  const MATRIX &internal_K;
223  VECTOR &full_rhs;
224 
225  public:
226  virtual const VECTOR &residual() const { return full_rhs; }
227  // A norm1 seems to be better than a norm2 (at least for contact problems).
228  virtual R residual_norm() { return gmm::vect_norm1(full_rhs); }
229 
230  using pb_base<PLSOLVER>::state_vector;
231  using pb_base<PLSOLVER>::state_norm;
232 
233  virtual void add_to_residual(VECTOR &extra_rhs, R mult=1.) {
234  if (mult == R(1)) gmm::add(extra_rhs, full_rhs);
235  else if (mult != R(0)) gmm::add(gmm::scaled(extra_rhs, mult), full_rhs);
236  }
237 
238  using pb_base<PLSOLVER>::perturbation;
239 
240  virtual void linear_solve(VECTOR &dr, gmm::iteration &iter) {
241  VECTOR dr0(md.nb_primary_dof(), R(0));
242  pb_base<PLSOLVER>::linear_solve(dr0, iter);
243  gmm::sub_interval I_prim(0, md.nb_primary_dof()),
244  I_intern(md.nb_primary_dof(), md.nb_internal_dof());
245  gmm::copy(dr0, gmm::sub_vector(dr, I_prim));
246  // recover solution of condensed variables: intern_K*prim_sol + intern_sol
247  gmm::mult(internal_K,
248  gmm::scaled(gmm::sub_vector(dr, I_prim), scalar_type(-1)),
249  md.internal_solution(),
250  gmm::sub_vector(dr, I_intern));
251  }
252 
253  virtual void compute_tangent_matrix() {
254  md.to_variables(state_vector(), condensed_vars);
255  md.assembly(condensed_vars ? model::BUILD_MATRIX_CONDENSED
256  : model::BUILD_MATRIX);
257  }
258 
259  virtual void compute_residual() {
260  md.to_variables(state_vector(), condensed_vars);
261  md.assembly(condensed_vars ? model::BUILD_RHS_WITH_INTERNAL // --> full_rhs
262  : model::BUILD_RHS); // ---> rhs (= full_rhs)
263  }
264 
265  nonlin_condensed_model_pb(model &md_, abstract_newton_line_search &ls_,
266  PLSOLVER linear_solver_) = delete;
267  };
268 
269  template <>
270  nonlin_condensed_model_pb<rmodel_plsolver_type>::nonlin_condensed_model_pb
271  (model &md_, abstract_newton_line_search &ls_, rmodel_plsolver_type linsolv)
272  : nonlin_model_pb<rmodel_plsolver_type>(md_, ls_, linsolv),
273  condensed_vars(md_.has_internal_variables()),
274  internal_K(md_.real_tangent_matrix(condensed_vars)),
275  full_rhs(md_.set_real_rhs(condensed_vars))
276  {
277  gmm::resize(state_vector(), md.nb_dof(condensed_vars));
278  md.from_variables(state_vector(), condensed_vars);
279  }
280 
281  template <>
282  nonlin_condensed_model_pb<cmodel_plsolver_type>::nonlin_condensed_model_pb
283  (model &md_, abstract_newton_line_search &ls_, cmodel_plsolver_type linsolv)
284  : nonlin_model_pb<cmodel_plsolver_type>(md_, ls_, linsolv),
285  condensed_vars(false), internal_K(md_.complex_tangent_matrix()),
286  full_rhs(md_.set_complex_rhs())
287  {
288  GMM_ASSERT1(false, "No support for internal variable condensation in "
289  "complex valued models.");
290  }
291 
292 
293 
294  /* ***************************************************************** */
295  /* Linear solvers. */
296  /* ***************************************************************** */
297  static rmodel_plsolver_type rdefault_linear_solver(const model &md) {
298  return default_linear_solver<model_real_sparse_matrix,
299  model_real_plain_vector>(md);
300  }
301 
302  static cmodel_plsolver_type cdefault_linear_solver(const model &md) {
303  return default_linear_solver<model_complex_sparse_matrix,
304  model_complex_plain_vector>(md);
305  }
306 
307  void default_newton_line_search::init_search(double r, size_t git, double) {
308  alpha_min_ratio = 0.9;
309  alpha_min = 1e-10;
310  alpha_max_ratio = 10.0;
311  alpha_mult = 0.25;
312  itmax = size_type(-1);
313  glob_it = git; if (git <= 1) count_pat = 0;
314  conv_alpha = alpha = alpha_old = 1.;
315  conv_r = first_res = r; it = 0;
316  count = 0;
317  max_ratio_reached = false;
318  }
319 
320  double default_newton_line_search::next_try() {
321  alpha_old = alpha; ++it;
322  // alpha *= 0.5;
323  if (alpha >= 0.4) alpha *= 0.5; else alpha *= alpha_mult;
324  return alpha_old;
325  }
326 
327  bool default_newton_line_search::is_converged(double r, double) {
328  // cout << "r = " << r << " alpha = " << alpha_old << " count_pat = " << count_pat << endl;
329  if (!max_ratio_reached && r < first_res * alpha_max_ratio) {
330  alpha_max_ratio_reached = alpha_old; r_max_ratio_reached = r;
331  it_max_ratio_reached = it; max_ratio_reached = true;
332  }
333  if (max_ratio_reached &&
334  r < r_max_ratio_reached * 0.5 &&
335  r > first_res * 1.1 && it <= it_max_ratio_reached+1) {
336  alpha_max_ratio_reached = alpha_old; r_max_ratio_reached = r;
337  it_max_ratio_reached = it;
338  }
339  if (count == 0 || r < conv_r)
340  { conv_r = r; conv_alpha = alpha_old; count = 1; }
341  if (conv_r < first_res) ++count;
342 
343  if (r < first_res * alpha_min_ratio)
344  { count_pat = 0; return true; }
345  if (count>=5 || (alpha < alpha_min && max_ratio_reached) || alpha<1e-15) {
346  if (conv_r < first_res * 0.99) count_pat = 0;
347  if (/*gmm::random() * 50. < -log(conv_alpha)-4.0 ||*/ count_pat >= 3)
348  { conv_r=r_max_ratio_reached; conv_alpha=alpha_max_ratio_reached; }
349  if (conv_r >= first_res * 0.999) count_pat++;
350  return true;
351  }
352  return false;
353  }
354 
355 
356  /* ***************************************************************** */
357  /* Computation of initial values of velocity/acceleration for */
358  /* time integration schemes. */
359  /* ***************************************************************** */
360 
361  template <typename PLSOLVER>
362  void compute_init_values(model &md, gmm::iteration &iter,
363  PLSOLVER lsolver,
364  abstract_newton_line_search &ls) {
365 
366  typename PLSOLVER::element_type::VECTOR state(md.nb_dof());
367  md.from_variables(state);
368  md.cancel_init_step();
369  md.set_time_integration(2);
370  scalar_type dt = md.get_time_step();
371  scalar_type ddt = md.get_init_time_step();
372  scalar_type t = md.get_time();
373 
374  // Solve for ddt
375  md.set_time_step(ddt);
376  gmm::iteration iter1 = iter;
377  standard_solve(md, iter1, lsolver, ls);
378  md.copy_init_time_derivative();
379 
380  // Restore the model state
381  md.set_time_step(dt);
382  md.set_time(t);
383  md.to_variables(state);
384  md.set_time_integration(1);
385  }
386 
387  /* ***************************************************************** */
388  /* Standard solve. */
389  /* ***************************************************************** */
390 
391  template <typename PLSOLVER>
392  void standard_solve(model &md, gmm::iteration &iter,
393  PLSOLVER lsolver,
394  abstract_newton_line_search &ls) {
395 
396  int time_integration = md.is_time_integration();
397  if (time_integration) {
398  if (time_integration == 1 && md.is_init_step()) {
399  compute_init_values(md, iter, lsolver, ls);
400  return;
401  }
402  md.set_time(md.get_time() + md.get_time_step());
403  md.call_init_affine_dependent_variables(time_integration);
404  }
405 
406  if (md.is_linear()) {
407  lin_model_pb<PLSOLVER> mdpb(md, lsolver);
408  mdpb.compute_all();
409  mdpb.linear_solve(mdpb.state_vector(), iter);
410  // A failed linear solve must not go unnoticed: on a singular system
411  // some direct solvers only print a warning and leave a zero state.
412  // Report it through iter.converged().
413  double berr = double(mdpb.backward_error());
414  if (iter.get_noisy())
415  cout << "backward error of the linear solve: " << berr << endl;
416  if (!(berr <= std::max(iter.get_resmax(), 1E-8))) { // also catches NaN
417  GMM_WARNING1("the linear system has not been solved accurately "
418  "(backward error " << berr << "): singular matrix?");
419  iter.enforce_converged(false);
420  }
421  md.to_variables(mdpb.state_vector()); // copy the state vector into the model variables
422  } else {
423  std::unique_ptr<nonlin_model_pb<PLSOLVER>> mdpb;
424  if (md.has_internal_variables())
425  mdpb = std::make_unique<nonlin_condensed_model_pb<PLSOLVER>>(md, ls, lsolver);
426  else
427  mdpb = std::make_unique<nonlin_model_pb<PLSOLVER>>(md, ls, lsolver);
428  if (dynamic_cast<newton_search_with_step_control *>(&ls))
429  Newton_with_step_control(*mdpb, iter);
430  else
431  classical_Newton(*mdpb, iter);
432  md.to_variables(mdpb->state_vector()); // copy the state vector into the model variables
433  }
434  }
435 
437  rmodel_plsolver_type lsolver,
438  abstract_newton_line_search &ls) {
439  standard_solve<rmodel_plsolver_type>(md, iter, lsolver, ls);
440  }
441 
442  void standard_solve(model &md, gmm::iteration &iter,
443  cmodel_plsolver_type lsolver,
444  abstract_newton_line_search &ls) {
445  standard_solve<cmodel_plsolver_type>(md, iter, lsolver, ls);
446  }
447 
448 
449  void standard_solve(model &md, gmm::iteration &iter,
450  rmodel_plsolver_type lsolver) {
451  default_newton_line_search ls;
452  standard_solve(md, iter, lsolver, ls);
453  }
454 
455  void standard_solve(model &md, gmm::iteration &iter,
456  cmodel_plsolver_type lsolver) {
457  newton_search_with_step_control ls;
458  // default_newton_line_search ls;
459  standard_solve(md, iter, lsolver, ls);
460  }
461 
462  void standard_solve(model &md, gmm::iteration &iter) {
463  newton_search_with_step_control ls;
464  // default_newton_line_search ls;
465  if (md.is_complex())
466  standard_solve(md, iter, cdefault_linear_solver(md), ls);
467  else
468  standard_solve(md, iter, rdefault_linear_solver(md), ls);
469  }
470 
471 
472 
473 } /* end of namespace getfem. */
474 
`‘Model’' variables store the variables, the data and the description of a model.
The Iteration object calculates whether the solution has reached the desired accuracy,...
Definition: gmm_iter.h:52
Standard solvers for model bricks.
void copy(const L1 &l1, L2 &l2)
*‍/
Definition: gmm_blas.h:976
number_traits< typename linalg_traits< V >::value_type >::magnitude_type vect_norm2(const V &v)
Euclidean norm of a vector.
Definition: gmm_blas.h:556
void fill_random(L &l)
fill a vector or matrix with random value (uniform [-1,1]).
Definition: gmm_blas.h:129
number_traits< typename linalg_traits< V >::value_type >::magnitude_type vect_norminf(const V &v)
Infinity norm of a vector.
Definition: gmm_blas.h:692
void resize(V &v, size_type n)
*‍/
Definition: gmm_blas.h:209
void mult(const L1 &l1, const L2 &l2, L3 &l3)
*‍/
Definition: gmm_blas.h:1663
number_traits< typename linalg_traits< V >::value_type >::magnitude_type vect_norm1(const V &v)
1-norm of a vector
Definition: gmm_blas.h:645
void add(const L1 &l1, L2 &l2)
*‍/
Definition: gmm_blas.h:1275
number_traits< typename linalg_traits< M >::value_type >::magnitude_type mat_norminf(const M &m)
*‍/
Definition: gmm_blas.h:835
Input/output on sparse matrices.
size_t size_type
used as the common size type in the library
Definition: bgeot_poly.h:48
size_type alpha(short_type n, short_type d)
Return the value of which is the number of monomials of a polynomial of variables and degree .
Definition: bgeot_poly.cc:46
GEneric Tool for Finite Element Methods.
void standard_solve(model &md, gmm::iteration &iter, rmodel_plsolver_type lsolver, abstract_newton_line_search &ls)
A default solver for the model brick system.