KratosMultiphysics
KRATOS Multiphysics (Kratos) is a framework for building parallel, multi-disciplinary simulation software, aiming at modularity, extensibility, and high performance. Kratos is written in C++, and counts with an extensive Python interface.
residual_criteria.h
Go to the documentation of this file.
1 // | / |
2 // ' / __| _` | __| _ \ __|
3 // . \ | ( | | ( |\__ `
4 // _|\_\_| \__,_|\__|\___/ ____/
5 // Multi-Physics
6 //
7 // License: BSD License
8 // Kratos default license: kratos/license.txt
9 //
10 // Main authors: Riccardo Rossi
11 //
12 
13 #pragma once
14 
15 // System includes
16 
17 // External includes
18 #include <limits>
19 
20 // Project includes
21 #include "includes/model_part.h"
26 
27 namespace Kratos
28 {
31 
35 
39 
43 
47 
55 template<class TSparseSpace,
56  class TDenseSpace
57  >
59  : public ConvergenceCriteria< TSparseSpace, TDenseSpace >
60 {
61 public:
64 
67 
70 
73 
75  using TDataType = typename BaseType::TDataType;
76 
79 
81  using DofType = typename Node::DofType;
82 
85 
88 
90  using IndexType = std::size_t;
91 
93  using SizeType = std::size_t;
94 
98 
100  explicit ResidualCriteria()
101  : BaseType()
102  {
103  }
104 
109  explicit ResidualCriteria(Kratos::Parameters ThisParameters)
110  : BaseType()
111  {
112  // Validate and assign defaults
113  ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters());
114  this->AssignSettings(ThisParameters);
115 
116  this->mActualizeRHSIsNeeded = true;
117  }
118 
125  TDataType NewRatioTolerance,
126  TDataType AlwaysConvergedNorm)
127  : BaseType(),
128  mRatioTolerance(NewRatioTolerance),
129  mAlwaysConvergedNorm(AlwaysConvergedNorm)
130  {
131  this->mActualizeRHSIsNeeded = true;
132  }
133 
138  explicit ResidualCriteria( ResidualCriteria const& rOther )
139  :BaseType(rOther)
145  ,mActiveDofs(rOther.mActiveDofs)
147  {
148  this->mActualizeRHSIsNeeded = true;
149  }
150 
154  ~ResidualCriteria() override {}
155 
159 
161  ResidualCriteria& operator=(ResidualCriteria const& rOther) = delete;
162 
166 
171  typename BaseType::Pointer Create(Parameters ThisParameters) const override
172  {
173  return Kratos::make_shared<ClassType>(ThisParameters);
174  }
175 
187  ModelPart& rModelPart,
188  DofsArrayType& rDofSet,
189  const TSystemMatrixType& rA,
190  const TSystemVectorType& rDx,
191  const TSystemVectorType& rb
192  ) override
193  {
194  if (TSparseSpace::Size(rb) != 0) { //if we are solving for something
195  // Some values
196  const int rank = rModelPart.GetCommunicator().GetDataCommunicator().Rank();
197 
198  // Calculate the residual norm
199  SizeType size_residual;
200  CalculateResidualNorm(rModelPart, mCurrentResidualNorm, size_residual, rDofSet, rb);
201 
202  TDataType ratio{};
203  if(mInitialResidualNorm < std::numeric_limits<TDataType>::epsilon()) {
204  ratio = 0.0;
205  } else {
207  }
208 
209  const TDataType float_size_residual = static_cast<TDataType>(size_residual);
210  const TDataType absolute_norm = (mCurrentResidualNorm/float_size_residual);
211 
212  KRATOS_INFO_IF("RESIDUAL CRITERION", this->GetEchoLevel() > 1 && rank == 0) << " :: [ Initial residual norm = " << mInitialResidualNorm << "; Current residual norm = " << mCurrentResidualNorm << "]" << std::endl;
213  KRATOS_INFO_IF("RESIDUAL CRITERION", this->GetEchoLevel() > 0 && rank == 0) << " :: [ Obtained ratio = " << ratio << "; Expected ratio = " << mRatioTolerance << "; Absolute norm = " << absolute_norm << "; Expected norm = " << mAlwaysConvergedNorm << "]" << std::endl;
214 
215  rModelPart.GetProcessInfo()[CONVERGENCE_RATIO] = ratio;
216  rModelPart.GetProcessInfo()[RESIDUAL_NORM] = absolute_norm;
217 
218  const bool has_achieved_convergence = ratio <= mRatioTolerance || absolute_norm < mAlwaysConvergedNorm;
219  KRATOS_INFO_IF("RESIDUAL CRITERION", has_achieved_convergence && this->GetEchoLevel() > 0 && rank == 0) << "Convergence is achieved" << std::endl;
220  return has_achieved_convergence;
221  } else {
222  return true;
223  }
224  }
225 
235  ModelPart& rModelPart,
236  DofsArrayType& rDofSet,
237  const TSystemMatrixType& rA,
238  const TSystemVectorType& rDx,
239  const TSystemVectorType& rb
240  ) override
241  {
242  BaseType::InitializeSolutionStep(rModelPart, rDofSet, rA, rDx, rb);
243 
244  // Filling mActiveDofs when MPC exist
245  if (rModelPart.NumberOfMasterSlaveConstraints() > 0) {
246  ComputeActiveDofs(rModelPart, rDofSet);
247  }
248 
249  SizeType size_residual;
250  CalculateResidualNorm(rModelPart, mInitialResidualNorm, size_residual, rDofSet, rb);
251  }
252 
262  ModelPart& rModelPart,
263  DofsArrayType& rDofSet,
264  const TSystemMatrixType& rA,
265  const TSystemVectorType& rDx,
266  const TSystemVectorType& rb
267  ) override
268  {
269  BaseType::FinalizeSolutionStep(rModelPart, rDofSet, rA, rDx, rb);
270  }
271 
277  {
278  Parameters default_parameters = Parameters(R"(
279  {
280  "name" : "residual_criteria",
281  "residual_absolute_tolerance" : 1.0e-4,
282  "residual_relative_tolerance" : 1.0e-9
283  })");
284 
285  // Getting base class default parameters
286  const Parameters base_default_parameters = BaseType::GetDefaultParameters();
287  default_parameters.RecursivelyAddMissingParameters(base_default_parameters);
288  return default_parameters;
289  }
290 
295  static std::string Name()
296  {
297  return "residual_criteria";
298  }
299 
303 
307 
311 
313  std::string Info() const override
314  {
315  return "ResidualCriteria";
316  }
317 
319  void PrintInfo(std::ostream& rOStream) const override
320  {
321  rOStream << Info();
322  }
323 
325  void PrintData(std::ostream& rOStream) const override
326  {
327  rOStream << Info();
328  }
329 
333 
335 protected:
338 
342 
344 
346 
348 
350 
352 
353  std::vector<int> mActiveDofs;
354 
356 
360 
364 
370  virtual void ComputeActiveDofs(
371  ModelPart& rModelPart,
372  const ModelPart::DofsArrayType& rDofSet
373  )
374  {
375  // Filling mActiveDofs when MPC exist
377  }
378 
388  const DofType& rDof,
389  const int Rank
390  )
391  {
392  const IndexType dof_id = rDof.EquationId();
393  if constexpr (!TSparseSpace::IsDistributedSpace()) {
394  return mActiveDofs[dof_id] == 1;
395  } else {
396  KRATOS_DEBUG_ERROR_IF((dof_id - mInitialDoFId) >= mActiveDofs.size() && (rDof.GetSolutionStepValue(PARTITION_INDEX) == Rank)) << "DofId is greater than the size of the active Dofs vector. DofId: " << dof_id << "\tInitialDoFId: " << mInitialDoFId << "\tActiveDofs size: " << mActiveDofs.size() << std::endl;
397  return (mActiveDofs[dof_id - mInitialDoFId] == 1 && (rDof.GetSolutionStepValue(PARTITION_INDEX) == Rank));
398  }
399  }
400 
410  const DofType& rDof,
411  const int Rank
412  )
413  {
414  if constexpr (!TSparseSpace::IsDistributedSpace()) {
415  return rDof.IsFree();
416  } else {
417  return (rDof.IsFree() && (rDof.GetSolutionStepValue(PARTITION_INDEX) == Rank));
418  }
419  }
420 
430  virtual void CalculateResidualNorm(
431  ModelPart& rModelPart,
432  TDataType& rResidualSolutionNorm,
433  SizeType& rDofNum,
434  DofsArrayType& rDofSet,
435  const TSystemVectorType& rb
436  )
437  {
438  // Retrieve the data communicator
439  const auto& r_data_communicator = rModelPart.GetCommunicator().GetDataCommunicator();
440 
441  // The current MPI rank
442  const int rank = r_data_communicator.Rank();
443 
444  // Initialize
445  TDataType residual_solution_norm = TDataType();
446  unsigned int dof_num = 0;
447 
448  // Custom reduction
450 
451  // Auxiliary struct
452  struct TLS {TDataType residual_dof_value{};};
453 
454  // Loop over Dofs
455  if (rModelPart.NumberOfMasterSlaveConstraints() > 0) {
456  std::tie(residual_solution_norm, dof_num) = block_for_each<CustomReduction>(rDofSet, TLS(), [this, &rb, &rank](auto& rDof, TLS& rTLS) {
457  if (this->IsActiveAndLocalDof(rDof, rank)) {
458  rTLS.residual_dof_value = TSparseSpace::GetValue(rb, rDof.EquationId());
459  return std::make_tuple(std::pow(rTLS.residual_dof_value, 2), 1);
460  } else {
461  return std::make_tuple(TDataType(), 0);
462  }
463  });
464  } else {
465  std::tie(residual_solution_norm, dof_num) = block_for_each<CustomReduction>(rDofSet, TLS(), [this, &rb, &rank](auto& rDof, TLS& rTLS) {
466  if (this->IsFreeAndLocalDof(rDof, rank)) {
467  rTLS.residual_dof_value = TSparseSpace::GetValue(rb, rDof.EquationId());
468  return std::make_tuple(std::pow(rTLS.residual_dof_value, 2), 1);
469  } else {
470  return std::make_tuple(TDataType(), 0);
471  }
472  });
473  }
474 
475  rDofNum = static_cast<SizeType>(r_data_communicator.SumAll(dof_num));
476  rResidualSolutionNorm = std::sqrt(r_data_communicator.SumAll(residual_solution_norm));
477  }
478 
483  void AssignSettings(const Parameters ThisParameters) override
484  {
485  BaseType::AssignSettings(ThisParameters);
486  mAlwaysConvergedNorm = ThisParameters["residual_absolute_tolerance"].GetDouble();
487  mRatioTolerance = ThisParameters["residual_relative_tolerance"].GetDouble();
488  }
489 
491 
492 }; // Class ClassName
493 
495 
498 
500 
501 } // namespace Kratos.
virtual const DataCommunicator & GetDataCommunicator() const
Definition: communicator.cpp:340
This is the base class to define the different convergence criterion considered.
Definition: convergence_criteria.h:58
int GetEchoLevel()
This returns the level of echo for the solving strategy.
Definition: convergence_criteria.h:209
bool mActualizeRHSIsNeeded
Definition: convergence_criteria.h:447
virtual Parameters ValidateAndAssignParameters(Parameters ThisParameters, const Parameters DefaultParameters) const
This method validate and assign default parameters.
Definition: convergence_criteria.h:466
TSparseSpace::MatrixType TSystemMatrixType
Matrix type definition.
Definition: convergence_criteria.h:72
ModelPart::DofsArrayType DofsArrayType
DoF array type definition.
Definition: convergence_criteria.h:81
virtual Parameters GetDefaultParameters() const
This method provides the defaults parameters to avoid conflicts between the different constructors.
Definition: convergence_criteria.h:384
TSparseSpace::DataType TDataType
Data type definition.
Definition: convergence_criteria.h:70
TSparseSpace::VectorType TSystemVectorType
Vector type definition.
Definition: convergence_criteria.h:74
virtual void FinalizeSolutionStep(ModelPart &rModelPart, DofsArrayType &rDofSet, const TSystemMatrixType &rA, const TSystemVectorType &rDx, const TSystemVectorType &rb)
This function finalizes the solution step.
Definition: convergence_criteria.h:337
virtual void InitializeSolutionStep(ModelPart &rModelPart, DofsArrayType &rDofSet, const TSystemMatrixType &rA, const TSystemVectorType &rDx, const TSystemVectorType &rb)
This function initializes the solution step.
Definition: convergence_criteria.h:299
virtual void AssignSettings(const Parameters ThisParameters)
This method assigns settings to member variables.
Definition: convergence_criteria.h:479
virtual int Rank() const
Get the parallel rank for this DataCommunicator.
Definition: data_communicator.h:587
This class aims to manage meshes for multi-physics simulations.
Definition: model_part.h:77
Communicator & GetCommunicator()
Definition: model_part.h:1821
SizeType NumberOfMasterSlaveConstraints(IndexType ThisIndex=0) const
Definition: model_part.h:649
ProcessInfo & GetProcessInfo()
Definition: model_part.h:1746
Dof< double > DofType
Dof type.
Definition: node.h:83
This class provides to Kratos a data structure for I/O based on the standard of JSON.
Definition: kratos_parameters.h:59
double GetDouble() const
This method returns the double contained in the current Parameter.
Definition: kratos_parameters.cpp:657
void RecursivelyAddMissingParameters(const Parameters &rDefaultParameters)
This function is designed to verify that the parameters under testing contain at least all parameters...
Definition: kratos_parameters.cpp:1457
A sorted associative container similar to an STL set, but uses a vector to store pointers to its data...
Definition: pointer_vector_set.h:72
This is a convergence criteria that considers the residual as criteria.
Definition: residual_criteria.h:60
std::size_t SizeType
Definition of the size type.
Definition: residual_criteria.h:93
KRATOS_CLASS_POINTER_DEFINITION(ResidualCriteria)
Pointer definition of ResidualCriteria.
virtual void CalculateResidualNorm(ModelPart &rModelPart, TDataType &rResidualSolutionNorm, SizeType &rDofNum, DofsArrayType &rDofSet, const TSystemVectorType &rb)
This method computes the norm of the residual.
Definition: residual_criteria.h:430
std::size_t IndexType
Definition of the IndexType.
Definition: residual_criteria.h:90
ResidualCriteria(ResidualCriteria const &rOther)
Copy constructor.
Definition: residual_criteria.h:138
void AssignSettings(const Parameters ThisParameters) override
This method assigns settings to member variables.
Definition: residual_criteria.h:483
void FinalizeSolutionStep(ModelPart &rModelPart, DofsArrayType &rDofSet, const TSystemMatrixType &rA, const TSystemVectorType &rDx, const TSystemVectorType &rb) override
This function finalizes the solution step.
Definition: residual_criteria.h:261
std::string Info() const override
Turn back information as a string.
Definition: residual_criteria.h:313
typename BaseType::TDataType TDataType
The data type.
Definition: residual_criteria.h:75
ResidualCriteria(Kratos::Parameters ThisParameters)
Default constructor. (with parameters)
Definition: residual_criteria.h:109
bool PostCriteria(ModelPart &rModelPart, DofsArrayType &rDofSet, const TSystemMatrixType &rA, const TSystemVectorType &rDx, const TSystemVectorType &rb) override
Criterion that need to be called after getting the solution.
Definition: residual_criteria.h:186
BaseType::Pointer Create(Parameters ThisParameters) const override
Create method.
Definition: residual_criteria.h:171
TDataType mRatioTolerance
Definition: residual_criteria.h:343
ResidualCriteria & operator=(ResidualCriteria const &rOther)=delete
Deleted assignment operator.
bool IsFreeAndLocalDof(const DofType &rDof, const int Rank)
Check if a Degree of Freedom (Dof) is free.
Definition: residual_criteria.h:409
IndexType mInitialDoFId
This vector contains the dofs that are active.
Definition: residual_criteria.h:355
ResidualCriteria()
Default constructor.
Definition: residual_criteria.h:100
TDataType mAlwaysConvergedNorm
The current norm of the residual.
Definition: residual_criteria.h:349
TDataType mInitialResidualNorm
The ratio threshold for the norm of the residual.
Definition: residual_criteria.h:345
void PrintInfo(std::ostream &rOStream) const override
Print information about this object.
Definition: residual_criteria.h:319
void InitializeSolutionStep(ModelPart &rModelPart, DofsArrayType &rDofSet, const TSystemMatrixType &rA, const TSystemVectorType &rDx, const TSystemVectorType &rb) override
This function initializes the solution step.
Definition: residual_criteria.h:234
~ResidualCriteria() override
Destructor.
Definition: residual_criteria.h:154
static std::string Name()
Returns the name of the class as used in the settings (snake_case format)
Definition: residual_criteria.h:295
void PrintData(std::ostream &rOStream) const override
Print object's data.
Definition: residual_criteria.h:325
ResidualCriteria(TDataType NewRatioTolerance, TDataType AlwaysConvergedNorm)
Constructor 2 arguments.
Definition: residual_criteria.h:124
std::vector< int > mActiveDofs
The norm at the beginning of the iterations.
Definition: residual_criteria.h:353
TDataType mReferenceDispNorm
The absolute value threshold for the norm of the residual.
Definition: residual_criteria.h:351
Parameters GetDefaultParameters() const override
This method provides the defaults parameters to avoid conflicts between the different constructors.
Definition: residual_criteria.h:276
virtual void ComputeActiveDofs(ModelPart &rModelPart, const ModelPart::DofsArrayType &rDofSet)
This method computes the active dofs.
Definition: residual_criteria.h:370
TDataType mCurrentResidualNorm
The reference norm of the residual.
Definition: residual_criteria.h:347
bool IsActiveAndLocalDof(const DofType &rDof, const int Rank)
Check if a Degree of Freedom (Dof) is active.
Definition: residual_criteria.h:387
typename Node::DofType DofType
The definition of the DoF data type.
Definition: residual_criteria.h:81
utility function to do a sum reduction
Definition: reduction_utilities.h:68
#define KRATOS_DEBUG_ERROR_IF(conditional)
Definition: exception.h:171
#define KRATOS_INFO_IF(label, conditional)
Definition: logger.h:251
void ComputeActiveDofs(ModelPart &rModelPart, std::vector< int > &rActiveDofs, const ModelPart::DofsArrayType &rDofSet)
This method computes the active dofs.
Definition: constraint_utilities.cpp:26
static double max(double a, double b)
Definition: GeometryFunctions.h:79
TSpaceType::IndexType Size(TSpaceType &dummy, typename TSpaceType::VectorType const &rV)
Definition: add_strategies_to_python.cpp:111
Parameters GetValue(Parameters &rParameters, const std::string &rEntry)
Definition: add_kratos_parameters_to_python.cpp:53
REF: G. R. Cowper, GAUSSIAN QUADRATURE FORMULAS FOR TRIANGLES.
Definition: mesh_condition.cpp:21
Definition: reduction_utilities.h:310