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.
compressible_navier_stokes_explicit_solving_strategy.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: Ruben Zorrilla, Eduard Gómez
11 //
12 //
13 
14 #if !defined(KRATOS_COMPRESSIBLE_NAVIER_STOKES_EXPLICIT_SOLVING_STRATEGY_BASE)
15 #define KRATOS_COMPRESSIBLE_NAVIER_STOKES_EXPLICIT_SOLVING_STRATEGY_BASE
16 
17 // System includes
18 
19 // External includes
20 
21 // Project includes
22 #include "includes/define.h"
24 #include "includes/model_part.h"
26 #include "utilities/math_utils.h"
28 
29 // Application includes
33 
34 namespace Kratos
35 {
36 
39 
43 
47 
51 
55 
60 template <typename TBaseExplicitStrategy>
62 : public TBaseExplicitStrategy
63 {
64 public:
67 
69 
70  typedef TBaseExplicitStrategy BaseType;
71 
74 
76  typedef typename TBaseExplicitStrategy::LocalSystemVectorType LocalSystemVectorType;
77 
80 
84 
91  ModelPart &rModelPart,
92  Parameters ThisParameters)
93  : BaseType(rModelPart)
94  {
96 
97  // Validate and assign defaults
98  ThisParameters = this->ValidateAndAssignParameters(ThisParameters, this->GetDefaultParameters());
99  this->AssignSettings(ThisParameters);
100 
101  KRATOS_CATCH("")
102  }
103 
111  ModelPart &rModelPart,
112  typename ExplicitBuilderType::Pointer pExplicitBuilder,
113  bool MoveMeshFlag = false,
114  int RebuildLevel = 0)
115  : BaseType(rModelPart, pExplicitBuilder, MoveMeshFlag, RebuildLevel)
116  {
117  }
118 
125  ModelPart &rModelPart,
126  bool MoveMeshFlag = false,
127  int RebuildLevel = 0)
128  : BaseType(rModelPart, MoveMeshFlag, RebuildLevel)
129  {
130  }
131 
135 
139 
143 
144 
148 
149  int Check() override
150  {
151  int err_code = BaseType::Check();
152 
153  // Check that the process info already contains the OSS activation variable
154  const auto& r_process_info = BaseType::GetModelPart().GetProcessInfo();
155  KRATOS_ERROR_IF_NOT(r_process_info.Has(OSS_SWITCH)) << "OSS_SWITCH variable has not been set in the ProcessInfo container. Please set it in the strategy \'Initialize\'." << std::endl;
156 
157  // Shock capturing process check
158  if (ShockCapturingEnabled()) {
159  GetShockCapturingProcess()->Check();
160  }
161 
162  return err_code;
163  }
164 
170  {
171  KRATOS_TRY
172 
173  Parameters default_parameters = Parameters(R"(
174  {
175  "explicit_solving_strategy" : "",
176  "move_mesh_flag": false,
177  "calculate_non_conservative_magnitudes" : true,
178  "shock_capturing_settings" : { }
179  })");
180 
181  // Getting base class default parameters
182  const Parameters base_default_parameters = BaseType::GetDefaultParameters();
183  default_parameters.RecursivelyAddMissingParameters(base_default_parameters);
184  return default_parameters;
185 
186  KRATOS_CATCH("")
187  }
188 
193  void AssignSettings(const Parameters ThisParameters) override
194  {
195  // Base class assign settings call
196  BaseType::AssignSettings(ThisParameters);
197  mCalculateNonConservativeMagnitudes = ThisParameters["calculate_non_conservative_magnitudes"].GetBool();
198 
199  SetUpShockCapturing(ThisParameters["shock_capturing_settings"]);
200 
201  if (mpShockCapturingProcess && !mCalculateNonConservativeMagnitudes) {
202  KRATOS_WARNING("CompressibleNavierStokesExplicitSolvingStrategy4")
203  << "\'shock_capturing\' requires \'calculate_non_conservative_magnitudes\' to be active. Activating it." << std::endl;
204  mCalculateNonConservativeMagnitudes = true;
205  }
206  }
207 
213  virtual void Initialize() override
214  {
215  auto& r_model_part = BaseType::GetModelPart();
216  const auto& r_process_info = r_model_part.GetProcessInfo();
217 
218  BaseType::Initialize();
219 
220  // Initialize the postprocess non-historical variables
221  block_for_each(r_model_part.Nodes(), [](Node& rNode){
222  rNode.SetValue(MACH, 0.0);
223  rNode.SetValue(SOUND_VELOCITY, 0.0);
224  });
225 
226  // If required, initialize the OSS projection variables
227  if (r_process_info[OSS_SWITCH]) {
228  block_for_each(r_model_part.Nodes(), [](Node& rNode){
229  rNode.SetValue(DENSITY_PROJECTION, 0.0);
230  rNode.SetValue(TOTAL_ENERGY_PROJECTION, 0.0);
231  rNode.SetValue(MOMENTUM_PROJECTION, ZeroVector(3));
232  });
233  }
234 
235  // If required, initialize the physics-based shock capturing variables
236  if (ShockCapturingEnabled()) {
237  GetShockCapturingProcess()->ExecuteInitialize();
238  }
239  }
240 
241  virtual void InitializeSolutionStep() override
242  {
244 
245  if (mFirstStep && ConservativeMagnitudeCalculationEnabled()) {
246  // This needs to be here because the initial conditions are set during ExecuteInitializeSolutionStep.
248  }
249 
250  if (ShockCapturingEnabled()) {
251  GetShockCapturingProcess()->ExecuteInitializeSolutionStep();
252  }
253  }
254 
260  virtual void FinalizeSolutionStep() override
261  {
262  BaseType::FinalizeSolutionStep();
263 
264  // Apply the momentum slip condition
265  if (SlipConditionEnabled()) {
267  }
268 
269  // Postprocess the non-conservative magnitudes
270  // This needs to be done before the shock capturing as it is based on these
273  }
274 
275  // Perform the shock capturing detection and artificial values calculation
276  // This needs to be done at the end of the step in order to include the future shock
277  // capturing magnitudes in the next automatic dt calculation
278  if (ShockCapturingEnabled()) {
279  GetShockCapturingProcess()->ExecuteFinalizeSolutionStep();
280  }
281 
282  mFirstStep = false;
283  }
284 
286  virtual std::string Info() const override = 0;
287 
289  virtual void PrintInfo(std::ostream &rOStream) const override
290  {
291  rOStream << Info();
292  }
293 
295  virtual void PrintData(std::ostream &rOStream) const override
296  {
297  rOStream << Info();
298  }
299 
301 
302 protected:
305 
306 
310 
311 
315 
316 
320 
321  void SetUpShockCapturing(Parameters ShockCapturingParameters)
322  {
323  KRATOS_TRY
324 
325  auto defaults = Parameters(R"(
326  {
327  "type" : "physics_based",
328  "Parameters" : {
329  "model_part_name" : ""
330  }
331  }
332  )");
333  defaults["Parameters"]["model_part_name"].SetString(BaseType::GetModelPart().Name());
334 
335  ShockCapturingParameters.ValidateAndAssignDefaults(defaults);
336  ShockCapturingParameters.RecursivelyAddMissingParameters(defaults);
337 
338  using ShockCapturingFactoryType = Process::UniquePointer (*)(ModelPart&, Parameters);
339 
340  const std::map<const std::string, ShockCapturingFactoryType> shock_capturing_factory_map
341  {
342  {"none" , [](ModelPart& m, Parameters p) -> Process::UniquePointer {return nullptr;}},
343  {"physics_based", [](ModelPart& m, Parameters p) -> Process::UniquePointer {return Kratos::make_unique<ShockCapturingPhysicsBasedProcess>(m, p);}},
344  {"entropy_based", [](ModelPart& m, Parameters p) -> Process::UniquePointer {return Kratos::make_unique<ShockCapturingEntropyViscosityProcess>(m, p);}}
345  };
346 
347  const auto sc_type = ShockCapturingParameters["type"].GetString();
348 
349  const auto it = shock_capturing_factory_map.find(sc_type);
350  if(it != shock_capturing_factory_map.end())
351  {
352  mpShockCapturingProcess = it->second(BaseType::GetModelPart(), ShockCapturingParameters["Parameters"]);
353  }
354  else
355  {
356  std::stringstream msg;
357  msg << "Provided shock capturing type \""<< sc_type <<"\" does not match any of the available ones.\n";
358  msg << "Please choose one from the following list:\n";
359  for(const auto& keyvaluepair: shock_capturing_factory_map)
360  {
361  msg <<" - " << keyvaluepair.first << "\n";
362  }
363  msg << std::endl;
364 
365  KRATOS_ERROR << msg.str();
366  }
367 
368  KRATOS_CATCH("")
369  }
370 
372  {
373  // Get model part data
374  auto& r_model_part = BaseType::GetModelPart();
375  const int n_nodes = r_model_part.NumberOfNodes();
376  const auto& r_process_info = r_model_part.GetProcessInfo();
377  const unsigned int block_size = r_process_info[DOMAIN_SIZE] + 2;
378 
379  // Get the required data from the explicit builder and solver
380  // The lumped mass vector will be used to get the NODAL_AREA for the residuals projection
381  const auto p_explicit_bs = BaseType::pGetExplicitBuilder();
382  const auto& r_lumped_mass_vector = p_explicit_bs->GetLumpedMassMatrixVector();
383 
384  // Initialize the projection values
385  block_for_each(r_model_part.Nodes(), [](Node& rNode){
386  rNode.GetValue(DENSITY_PROJECTION) = 0.0;
387  rNode.GetValue(MOMENTUM_PROJECTION) = ZeroVector(3);
388  rNode.GetValue(TOTAL_ENERGY_PROJECTION) = 0.0;
389  });
390 
391  // Calculate the residuals projection
392  std::tuple<double, double, array_1d<double,3>> oss_proj_tls;
393  block_for_each(r_model_part.Elements(), oss_proj_tls, [&](Element& rElement, std::tuple<double, double, array_1d<double,3>>& rOssProjTLS){
394  double& rho_proj = std::get<0>(rOssProjTLS);
395  double& tot_ener_proj = std::get<1>(rOssProjTLS);
396  array_1d<double,3>& mom_proj = std::get<2>(rOssProjTLS);
397  rElement.Calculate(DENSITY_PROJECTION, rho_proj, r_process_info);
398  rElement.Calculate(MOMENTUM_PROJECTION, mom_proj, r_process_info);
399  rElement.Calculate(TOTAL_ENERGY_PROJECTION, tot_ener_proj, r_process_info);
400  });
401 
402  // Do thhe nodal weighting
403  // Note that to avoid calculating the NODAL_AREA we took from the first DOF of the lumped mass vector
405  auto it_node = r_model_part.NodesBegin() + iNode;
406  const double nodal_area = r_lumped_mass_vector[iNode * block_size];
407  it_node->GetValue(DENSITY_PROJECTION) /= nodal_area;
408  it_node->GetValue(MOMENTUM_PROJECTION) /= nodal_area;
409  it_node->GetValue(TOTAL_ENERGY_PROJECTION) /= nodal_area;
410  });
411 
412  }
413 
422  {
423  // Get fluid properties from first element in mesh
424  // Note that in here we assume that the fluid is single-phase
425  auto& r_model_part = BaseType::GetModelPart();
426  const auto& r_prop = r_model_part.ElementsBegin()->GetProperties();
427  const double c_v = r_prop.GetValue(SPECIFIC_HEAT); // Specific heat at constant volume
428  const double gamma = r_prop.GetValue(HEAT_CAPACITY_RATIO); // Heat capacity ratio
429  const double R = (gamma - 1.0) * c_v; // Ideal gas constant
430 
431  // Loop the nodes to calculate the non-conservative magnitudes
432  array_1d<double,3> aux_vel;
433  block_for_each(r_model_part.Nodes(), aux_vel,[&] (Node &rNode, array_1d<double,3>&rVelocity) {
434  const auto& r_mom = rNode.FastGetSolutionStepValue(MOMENTUM);
435  const double& r_rho = rNode.FastGetSolutionStepValue(DENSITY);
436  const double& r_tot_ener = rNode.FastGetSolutionStepValue(TOTAL_ENERGY);
437  rVelocity = r_mom / r_rho;
438  const double temp = (r_tot_ener / r_rho - 0.5 * inner_prod(rVelocity, rVelocity)) / c_v;
439  const double sound_velocity = std::sqrt(gamma * R * temp);
440  rNode.FastGetSolutionStepValue(VELOCITY) = rVelocity;
441  rNode.FastGetSolutionStepValue(TEMPERATURE) = temp;
442  rNode.FastGetSolutionStepValue(PRESSURE) = r_rho * R * temp;
443  rNode.GetValue(SOUND_VELOCITY) = sound_velocity;
444  rNode.GetValue(MACH) = norm_2(rVelocity) / sound_velocity;
445  });
446  }
447 
454  {
455  auto &r_model_part = BaseType::GetModelPart();
456 
457  block_for_each(r_model_part.Nodes(), [](Node& rNode){
458  if (rNode.Is(SLIP)) {
459  auto unit_normal = rNode.FastGetSolutionStepValue(NORMAL);
460  unit_normal /= norm_2(unit_normal);
461  auto& r_mom = rNode.FastGetSolutionStepValue(MOMENTUM);
462  const double r_mom_n = inner_prod(r_mom, unit_normal);
463  noalias(r_mom) -= r_mom_n * unit_normal;
464  }
465  });
466  }
467 
468  virtual void InitializeEverySubstep()
469  {
470  // Calculate the Orthogonal SubsScales projections
471  auto& r_model_part = BaseType::GetModelPart();
472  auto& r_process_info = r_model_part.GetProcessInfo();
473 
474  // Calculate the Orthogonal SubsScales projections
475  if (r_process_info[OSS_SWITCH]) {
476  CalculateOrthogonalSubScalesProjection();
477  }
478  }
479 
480  virtual void FinalizeEverySubstep()
481  {
482  // Apply the momentum slip condition
483  //TODO: THIS SHOULDN'T BE REQUIRED --> DOING IT AFTER THE FINAL UPDATE MUST BE ENOUGH
484  if (SlipConditionEnabled()) {
485  ApplySlipCondition();
486  }
487  }
488 
489  bool ShockCapturingEnabled() const noexcept
490  {
491  return mpShockCapturingProcess != nullptr;
492  }
493 
495  {
496  return mCalculateNonConservativeMagnitudes;
497  }
498 
499  bool SlipConditionEnabled() const noexcept
500  {
501  return mApplySlipCondition;
502  }
503 
504 
508 
509  const Process::UniquePointer& GetShockCapturingProcess()
510  {
511  return mpShockCapturingProcess;
512  }
513 
517 
518 
522 
523 
525 private:
528 
529 
533 
534  bool mFirstStep = true;
535  bool mApplySlipCondition = true;
536  bool mCalculateNonConservativeMagnitudes = true;
537  Process::UniquePointer mpShockCapturingProcess = nullptr;
538 
542 
543 
547 
548 
552 
553 
557 
558 
562 
563 
565 }; /* Class CompressibleNavierStokesExplicitSolvingStrategy */
566 
568 
571 
573 
574 } /* namespace Kratos.*/
575 
576 #endif /* KRATOS_COMPRESSIBLE_NAVIER_STOKES_EXPLICIT_SOLVING_STRATEGY_BASE defined */
Explicit solving strategy base class.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:63
TBaseExplicitStrategy::LocalSystemVectorType LocalSystemVectorType
The local vector definition.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:76
CompressibleNavierStokesExplicitSolvingStrategy(ModelPart &rModelPart, bool MoveMeshFlag=false, int RebuildLevel=0)
Default constructor.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:124
const Process::UniquePointer & GetShockCapturingProcess()
Definition: compressible_navier_stokes_explicit_solving_strategy.h:509
CompressibleNavierStokesExplicitSolvingStrategy(const CompressibleNavierStokesExplicitSolvingStrategy &Other)=delete
void SetUpShockCapturing(Parameters ShockCapturingParameters)
Definition: compressible_navier_stokes_explicit_solving_strategy.h:321
bool ShockCapturingEnabled() const noexcept
Definition: compressible_navier_stokes_explicit_solving_strategy.h:489
TBaseExplicitStrategy BaseType
The base class definition.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:70
void CalculateOrthogonalSubScalesProjection()
Definition: compressible_navier_stokes_explicit_solving_strategy.h:371
BaseType::ExplicitBuilderType ExplicitBuilderType
The explicit builder and solver definition.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:73
virtual void PrintData(std::ostream &rOStream) const override
Print object's data.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:295
CompressibleNavierStokesExplicitSolvingStrategy(ModelPart &rModelPart, Parameters ThisParameters)
Default constructor. (with parameters)
Definition: compressible_navier_stokes_explicit_solving_strategy.h:90
virtual std::string Info() const override=0
Turn back information as a string.
void CalculateNonConservativeMagnitudes()
Calculates the non-conservative magnitudes This function calculates the non-conservative magnitudes f...
Definition: compressible_navier_stokes_explicit_solving_strategy.h:421
bool ConservativeMagnitudeCalculationEnabled() const noexcept
Definition: compressible_navier_stokes_explicit_solving_strategy.h:494
bool SlipConditionEnabled() const noexcept
Definition: compressible_navier_stokes_explicit_solving_strategy.h:499
KRATOS_CLASS_POINTER_DEFINITION(CompressibleNavierStokesExplicitSolvingStrategy)
Pointer definition of CompressibleNavierStokesExplicitSolvingStrategy.
virtual void Initialize() override
Initialization of member variables and prior operations In this method we call the base strategy init...
Definition: compressible_navier_stokes_explicit_solving_strategy.h:213
virtual void FinalizeEverySubstep()
Definition: compressible_navier_stokes_explicit_solving_strategy.h:480
void ApplySlipCondition()
Appy the slip condition This method substracts the normal projection of the momentum for all the node...
Definition: compressible_navier_stokes_explicit_solving_strategy.h:453
void AssignSettings(const Parameters ThisParameters) override
This method assigns settings to member variables.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:193
virtual void InitializeEverySubstep()
Definition: compressible_navier_stokes_explicit_solving_strategy.h:468
int Check() override
Definition: compressible_navier_stokes_explicit_solving_strategy.h:149
virtual void FinalizeSolutionStep() override
Finalize the step In this method we calculate the final linearised time derivatives after the final u...
Definition: compressible_navier_stokes_explicit_solving_strategy.h:260
Parameters GetDefaultParameters() const override
This method provides the defaults parameters to avoid conflicts between the different constructors.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:169
virtual void InitializeSolutionStep() override
Definition: compressible_navier_stokes_explicit_solving_strategy.h:241
virtual void PrintInfo(std::ostream &rOStream) const override
Print information about this object.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:289
CompressibleNavierStokesExplicitSolvingStrategy(ModelPart &rModelPart, typename ExplicitBuilderType::Pointer pExplicitBuilder, bool MoveMeshFlag=false, int RebuildLevel=0)
Default constructor.
Definition: compressible_navier_stokes_explicit_solving_strategy.h:110
Base class for all Elements.
Definition: element.h:60
This class is useful for index iteration over containers.
Definition: parallel_utilities.h:451
void for_each(TUnaryFunction &&f)
Definition: parallel_utilities.h:514
This class aims to manage meshes for multi-physics simulations.
Definition: model_part.h:77
std::size_t SizeType
Definition: model_part.h:107
This class defines the node.
Definition: node.h:65
This class provides to Kratos a data structure for I/O based on the standard of JSON.
Definition: kratos_parameters.h:59
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
void ValidateAndAssignDefaults(const Parameters &rDefaultParameters)
This function is designed to verify that the parameters under testing match the form prescribed by th...
Definition: kratos_parameters.cpp:1306
std::string GetString() const
This method returns the string contained in the current Parameter.
Definition: kratos_parameters.cpp:684
bool GetBool() const
This method returns the boolean contained in the current Parameter.
Definition: kratos_parameters.cpp:675
#define KRATOS_CATCH(MoreInfo)
Definition: define.h:110
#define KRATOS_TRY
Definition: define.h:109
#define KRATOS_ERROR
Definition: exception.h:161
#define KRATOS_ERROR_IF_NOT(conditional)
Definition: exception.h:163
#define KRATOS_WARNING(label)
Definition: logger.h:265
void InitializeSolutionStep(ConstructionUtility &rThisUtil, std::string ThermalSubModelPartName, std::string MechanicalSubModelPartName, std::string HeatFluxSubModelPartName, std::string HydraulicPressureSubModelPartName, bool thermal_conditions, bool mechanical_conditions, int phase)
Definition: add_custom_utilities_to_python.cpp:45
REF: G. R. Cowper, GAUSSIAN QUADRATURE FORMULAS FOR TRIANGLES.
Definition: mesh_condition.cpp:21
void block_for_each(TIterator itBegin, TIterator itEnd, TFunction &&rFunction)
Execute a functor on all items of a range in parallel.
Definition: parallel_utilities.h:299
ExplicitBuilder< SparseSpaceType, LocalSpaceType > ExplicitBuilderType
Definition: register_factories.h:37
int n_nodes
Definition: generate_total_lagrangian_mixed_volumetric_strain_element.py:15
int block_size
Definition: generate_total_lagrangian_mixed_volumetric_strain_element.py:16
float gamma
Definition: generate_two_fluid_navier_stokes.py:131
R
Definition: isotropic_damage_automatic_differentiation.py:172
tuple const
Definition: ode_solve.py:403
int m
Definition: run_marine_rain_substepping.py:8
p
Definition: sensitivityMatrix.py:52