https://mooseframework.inl.gov
RhieChowMassFlux.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 // MOOSE includes
11 #include "RhieChowMassFlux.h"
12 #include "SubProblem.h"
13 #include "MooseMesh.h"
14 #include "NS.h"
15 #include "VectorCompositeFunctor.h"
16 #include "PIMPLE.h"
17 #include "SIMPLE.h"
18 #include "PetscVectorReader.h"
19 #include "LinearSystem.h"
21 
22 // libMesh includes
23 #include "libmesh/mesh_base.h"
24 #include "libmesh/elem_range.h"
25 #include "libmesh/petsc_matrix.h"
26 
27 using namespace libMesh;
28 
29 registerMooseObject("NavierStokesApp", RhieChowMassFlux);
30 
33 {
36 
37  params.addClassDescription("Computes H/A and 1/A together with face mass fluxes for segregated "
38  "momentum-pressure equations using linear systems.");
39 
40  params.addRequiredParam<VariableName>(NS::pressure, "The pressure variable.");
41  params.addRequiredParam<VariableName>("u", "The x-component of velocity");
42  params.addParam<VariableName>("v", "The y-component of velocity");
43  params.addParam<VariableName>("w", "The z-component of velocity");
44  params.addRequiredParam<std::string>("p_diffusion_kernel",
45  "The diffusion kernel acting on the pressure.");
46  params.addParam<std::vector<std::vector<std::string>>>(
47  "body_force_kernel_names",
48  {},
49  "The body force kernel names."
50  "this double vector would have size index_x_dim: 'f1x f2x; f1y f2y; f1z f2z'");
51 
52  params.addRequiredParam<MooseFunctorName>(NS::density, "Density functor");
53 
54  // We disable the execution of this, should only provide functions
55  // for the SIMPLE executioner
56  ExecFlagEnum & exec_enum = params.set<ExecFlagEnum>("execute_on", true);
57  exec_enum.addAvailableFlags(EXEC_NONE);
58  exec_enum = {EXEC_NONE};
59  params.suppressParameter<ExecFlagEnum>("execute_on");
60 
61  // Pressure projection
62  params.addParam<MooseEnum>("pressure_projection_method",
63  MooseEnum("standard consistent", "standard"),
64  "The method to use in the pressure projection for Ainv - "
65  "standard (SIMPLE) or consistent (SIMPLEC)");
66  return params;
67 }
68 
70  : RhieChowFaceFluxProvider(params),
72  _moose_mesh(UserObject::_subproblem.mesh()),
73  _mesh(_moose_mesh.getMesh()),
74  _dim(blocksMaxDimension()),
75  _p(dynamic_cast<MooseLinearVariableFVReal *>(
76  &UserObject::_subproblem.getVariable(0, getParam<VariableName>(NS::pressure)))),
77  _vel(_dim, nullptr),
78  _HbyA_flux(_moose_mesh, blockIDs(), "HbyA_flux"),
79  _Ainv(_moose_mesh, blockIDs(), "Ainv"),
80  _face_mass_flux(
81  declareRestartableData<FaceCenteredMapFunctor<Real, std::unordered_map<dof_id_type, Real>>>(
82  "face_flux", _moose_mesh, blockIDs(), "face_values")),
83  _body_force_kernel_names(
84  getParam<std::vector<std::vector<std::string>>>("body_force_kernel_names")),
85  _rho(getFunctor<Real>(NS::density)),
86  _pressure_projection_method(getParam<MooseEnum>("pressure_projection_method"))
87 {
88  if (!_p)
89  paramError(NS::pressure, "the pressure must be a MooseLinearVariableFVReal.");
90  checkBlocks(*_p);
91 
92  std::vector<std::string> vel_names = {"u", "v", "w"};
93  for (const auto i : index_range(_vel))
94  {
95  _vel[i] = dynamic_cast<MooseLinearVariableFVReal *>(
96  &UserObject::_subproblem.getVariable(0, getParam<VariableName>(vel_names[i])));
97 
98  if (!_vel[i])
99  paramError(vel_names[i], "the velocity must be a MOOSELinearVariableFVReal.");
100  checkBlocks(*_vel[i]);
101  }
102 
103  // Register the elemental/face functors which will be queried in the pressure equation
104  for (const auto tid : make_range(libMesh::n_threads()))
105  {
108  }
109 
110  if (!dynamic_cast<SIMPLE *>(getMooseApp().getExecutioner()) &&
111  !dynamic_cast<PIMPLE *>(getMooseApp().getExecutioner()))
112  mooseError(this->name(),
113  " should only be used with a linear segregated thermal-hydraulics solver!");
114 }
115 
116 void
118  const std::vector<LinearSystem *> & momentum_systems,
119  const LinearSystem & pressure_system,
120  const std::vector<unsigned int> & momentum_system_numbers)
121 {
122  _momentum_systems = momentum_systems;
123  _momentum_system_numbers = momentum_system_numbers;
124  _pressure_system = &pressure_system;
126 
128  for (auto & system : _momentum_systems)
129  {
130  _global_momentum_system_numbers.push_back(system->number());
131  _momentum_implicit_systems.push_back(dynamic_cast<LinearImplicitSystem *>(&system->system()));
132  }
133 
135 }
136 
137 void
139 {
140  _HbyA_flux.clear();
141  _Ainv.clear();
142  _face_mass_flux.clear();
144 }
145 
146 void
148 {
149  // We fetch the pressure diffusion kernel to ensure that the face flux correction
150  // is consistent with the pressure discretization in the Poisson equation.
151  std::vector<LinearFVFluxKernel *> flux_kernel;
152  auto base_query = _fe_problem.theWarehouse()
153  .query()
154  .template condition<AttribThread>(_tid)
155  .template condition<AttribSysNum>(_p->sys().number())
156  .template condition<AttribSystem>("LinearFVFluxKernel")
157  .template condition<AttribName>(getParam<std::string>("p_diffusion_kernel"))
158  .queryInto(flux_kernel);
159  if (flux_kernel.size() != 1)
160  paramError(
161  "p_diffusion_kernel",
162  "The kernel with the given name could not be found or multiple instances were identified.");
163  _p_diffusion_kernel = dynamic_cast<LinearFVAnisotropicDiffusion *>(flux_kernel[0]);
164  if (!_p_diffusion_kernel)
165  paramError("p_diffusion_kernel",
166  "The provided diffusion kernel should of type LinearFVAnisotropicDiffusion!");
167 
168  // We fetch the body forces kernel to ensure that the face flux correction
169  // is accurate.
170 
171  // Check if components match the dimension.
172 
173  if (!_body_force_kernel_names.empty())
174  {
175  if (_body_force_kernel_names.size() != _dim)
176  paramError("body_force_kernel_names",
177  "The dimension of the body force vector does not match the problem dimension.");
178 
179  _body_force_kernels.resize(_dim);
180 
181  for (const auto dim_i : make_range(_dim))
182  for (const auto & force_name : _body_force_kernel_names[dim_i])
183  {
184  std::vector<LinearFVElementalKernel *> temp_storage;
185  auto base_query_force = _fe_problem.theWarehouse()
186  .query()
187  .template condition<AttribThread>(_tid)
188  .template condition<AttribSysNum>(_vel[dim_i]->sys().number())
189  .template condition<AttribSystem>("LinearFVElementalKernel")
190  .template condition<AttribName>(force_name)
191  .queryInto(temp_storage);
192  if (temp_storage.size() != 1)
193  paramError("body_force_kernel_names",
194  "The kernel with the given name: " + force_name +
195  " could not be found or multiple instances were identified.");
196  _body_force_kernels[dim_i].push_back(temp_storage[0]);
197  }
198  }
199 }
200 
201 void
203 {
204  // We cache the cell volumes into a petsc vector for corrections here so we can use
205  // the optimized petsc operations for the normalization
207  for (const auto & elem_info : _fe_problem.mesh().elemInfoVector())
208  // We have to check this because the variable might not be defined on the given
209  // block
210  if (hasBlocks(elem_info->subdomain_id()))
211  {
212  const auto elem_dof = elem_info->dofIndices()[_global_pressure_system_number][0];
213  _cell_volumes->set(elem_dof, elem_info->volume() * elem_info->coordFactor());
214  }
215 
216  _cell_volumes->close();
217 
218  _flow_face_info.clear();
219  for (auto & fi : _fe_problem.mesh().faceInfo())
220  if (hasBlocks(fi->elemPtr()->subdomain_id()) ||
221  (fi->neighborPtr() && hasBlocks(fi->neighborPtr()->subdomain_id())))
222  _flow_face_info.push_back(fi);
223 }
224 
225 void
227 {
228  for (const auto & pair : _HbyA_flux)
229  _HbyA_flux[pair.first] = 0;
230 
231  for (const auto & pair : _Ainv)
232  _Ainv[pair.first] = 0;
233 }
234 
235 void
237 {
238  using namespace Moose::FV;
239 
240  const auto time_arg = Moose::currentState();
241 
242  // We loop through the faces and compute the resulting face fluxes from the
243  // initial conditions for velocity
244  for (auto & fi : _flow_face_info)
245  {
246  RealVectorValue density_times_velocity;
247 
248  // On internal face we do a regular interpolation with geometric weights
249  if (_vel[0]->isInternalFace(*fi))
250  {
251  const auto & elem_info = *fi->elemInfo();
252  const auto & neighbor_info = *fi->neighborInfo();
253 
254  Real elem_rho = _rho(makeElemArg(fi->elemPtr()), time_arg);
255  Real neighbor_rho = _rho(makeElemArg(fi->neighborPtr()), time_arg);
256 
257  for (const auto dim_i : index_range(_vel))
258  interpolate(InterpMethod::Average,
259  density_times_velocity(dim_i),
260  _vel[dim_i]->getElemValue(elem_info, time_arg) * elem_rho,
261  _vel[dim_i]->getElemValue(neighbor_info, time_arg) * neighbor_rho,
262  *fi,
263  true);
264  }
265  // On the boundary, we just take the boundary values
266  else
267  {
268  const bool elem_is_fluid = hasBlocks(fi->elemPtr()->subdomain_id());
269  const Elem * const boundary_elem = elem_is_fluid ? fi->elemPtr() : fi->neighborPtr();
270 
271  // We need this multiplier in case the face is an internal face and
272  const Real boundary_normal_multiplier = elem_is_fluid ? 1.0 : -1.0;
273  const Moose::FaceArg boundary_face{
274  fi, Moose::FV::LimiterType::CentralDifference, true, false, boundary_elem, nullptr};
275 
276  const Real face_rho = _rho(boundary_face, time_arg);
277  for (const auto dim_i : index_range(_vel))
278  density_times_velocity(dim_i) = boundary_normal_multiplier * face_rho *
279  raw_value((*_vel[dim_i])(boundary_face, time_arg));
280  }
281 
282  _face_mass_flux[fi->id()] = density_times_velocity * fi->normal();
283  }
284 }
285 
286 Real
288 {
289  return _face_mass_flux.evaluate(&fi);
290 }
291 
292 Real
294 {
295  const Moose::FaceArg face_arg{&fi,
297  /*elem_is_upwind=*/true,
298  /*correct_skewness=*/false,
299  &fi.elem(),
300  /*state_limiter*/ nullptr};
301  const Real face_rho = _rho(face_arg, Moose::currentState());
302  return libmesh_map_find(_face_mass_flux, fi.id()) / face_rho;
303 }
304 
305 Real
307  const FaceInfo & fi,
308  const Moose::StateArg & time,
309  const THREAD_ID /*tid*/,
310  bool libmesh_dbg_var(subtract_mesh_velocity)) const
311 {
312  mooseAssert(!subtract_mesh_velocity, "RhieChowMassFlux does not support moving meshes yet!");
313 
315  mooseError("Interpolation methods other than Rhie-Chow are not supported!");
316  if (time.state != Moose::currentState().state)
317  mooseError("Older interpolation times are not supported!");
318 
319  return getVolumetricFaceFlux(fi);
320 }
321 
322 void
324 {
325  using namespace Moose::FV;
326 
327  const auto time_arg = Moose::currentState();
328 
329  // Petsc vector reader to make the repeated reading from the vector faster
331 
332  // We loop through the faces and compute the face fluxes using the pressure gradient
333  // and the momentum matrix/right hand side
334  for (auto & fi : _flow_face_info)
335  {
336  // Making sure the kernel knows which face we are on
338 
339  // We are setting this to 1.0 because we don't want to multiply the kernel contributions
340  // with the surface area yet. The surface area will be factored in in the advection kernels.
342 
343  Real p_grad_flux = 0.0;
344  if (_p->isInternalFace(*fi))
345  {
346  const auto & elem_info = *fi->elemInfo();
347  const auto & neighbor_info = *fi->neighborInfo();
348 
349  // Fetching the dof indices for the pressure variable
350  const auto elem_dof = elem_info.dofIndices()[_global_pressure_system_number][0];
351  const auto neighbor_dof = neighbor_info.dofIndices()[_global_pressure_system_number][0];
352 
353  // Fetching the values of the pressure for the element and the neighbor
354  const auto p_elem_value = p_reader(elem_dof);
355  const auto p_neighbor_value = p_reader(neighbor_dof);
356 
357  // Compute the elem matrix contributions for the face
358  const auto elem_matrix_contribution = _p_diffusion_kernel->computeElemMatrixContribution();
359  const auto neighbor_matrix_contribution =
361  const auto elem_rhs_contribution =
363 
364  // Compute the face flux from the matrix and right hand side contributions
365  p_grad_flux = (p_neighbor_value * neighbor_matrix_contribution +
366  p_elem_value * elem_matrix_contribution) -
367  elem_rhs_contribution;
368  }
369  else if (auto * bc_pointer = _p->getBoundaryCondition(*fi->boundaryIDs().begin()))
370  {
371  mooseAssert(fi->boundaryIDs().size() == 1, "We should only have one boundary on every face.");
372 
373  bc_pointer->setupFaceData(
374  fi, fi->faceType(std::make_pair(_p->number(), _global_pressure_system_number)));
375 
376  const ElemInfo & elem_info =
377  hasBlocks(fi->elemPtr()->subdomain_id()) ? *fi->elemInfo() : *fi->neighborInfo();
378  const auto p_elem_value = _p->getElemValue(elem_info, time_arg);
379  const auto matrix_contribution =
381  const auto rhs_contribution =
383 
384  // On the boundary, only the element side has a contribution
385  p_grad_flux = (p_elem_value * matrix_contribution - rhs_contribution);
386  }
387  // Compute the new face flux
388  _face_mass_flux[fi->id()] = -_HbyA_flux[fi->id()] + p_grad_flux;
389  }
390 }
391 
392 void
394 {
395  auto & pressure_gradient = _pressure_system->gradientContainer();
396 
397  // We set the dof value in the solution vector the same logic applies:
398  // u_C = -(H/A)_C - (1/A)_C*grad(p)_C where C is the cell index
399  for (const auto system_i : index_range(_momentum_implicit_systems))
400  {
401  auto working_vector = _Ainv_raw[system_i]->clone();
402  working_vector->pointwise_mult(*working_vector, *pressure_gradient[system_i]);
403  working_vector->add(*_HbyA_raw[system_i]);
404  working_vector->scale(-1.0);
405  (*_momentum_implicit_systems[system_i]->solution) = *working_vector;
406  _momentum_implicit_systems[system_i]->update();
407  _momentum_systems[system_i]->setSolution(
408  *_momentum_implicit_systems[system_i]->current_local_solution);
409  }
410 }
411 
412 void
414 {
415  // We loop through the faces and populate the coupling fields (face H/A and 1/H)
416  // with 0s for now. Pressure corrector solves will always come after the
417  // momentum source so we expect these fields to change before the actual solve.
418  for (auto & fi : _fe_problem.mesh().faceInfo())
419  {
420  _Ainv[fi->id()];
421  _HbyA_flux[fi->id()];
422  }
423 }
424 
425 void
427  const std::vector<std::unique_ptr<NumericVector<Number>>> & raw_hbya,
428  const std::vector<std::unique_ptr<NumericVector<Number>>> & raw_Ainv)
429 {
430  // We have the raw H/A and 1/A vectors in a petsc format. This function
431  // will create face functors from them
432  using namespace Moose::FV;
433  const auto time_arg = Moose::currentState();
434 
435  // Create the petsc vector readers for faster repeated access
436  std::vector<PetscVectorReader> hbya_reader;
437  for (const auto dim_i : index_range(raw_hbya))
438  hbya_reader.emplace_back(*raw_hbya[dim_i]);
439 
440  std::vector<PetscVectorReader> ainv_reader;
441  for (const auto dim_i : index_range(raw_Ainv))
442  ainv_reader.emplace_back(*raw_Ainv[dim_i]);
443 
444  // We loop through the faces and populate the coupling fields (face H/A and 1/H)
445  for (auto & fi : _flow_face_info)
446  {
447  Real face_rho = 0;
448  RealVectorValue face_hbya;
449 
450  // We do the lookup in advance
451  auto & Ainv = _Ainv[fi->id()];
452 
453  // If it is internal, we just interpolate (using geometric weights) to the face
454  if (_vel[0]->isInternalFace(*fi))
455  {
456  // Get the dof indices for the element and the neighbor
457  const auto & elem_info = *fi->elemInfo();
458  const auto & neighbor_info = *fi->neighborInfo();
459  const auto elem_dof = elem_info.dofIndices()[_global_momentum_system_numbers[0]][0];
460  const auto neighbor_dof = neighbor_info.dofIndices()[_global_momentum_system_numbers[0]][0];
461 
462  // Get the density values for the element and neighbor. We need this multiplication to make
463  // the coupling fields mass fluxes.
464  const Real elem_rho = _rho(makeElemArg(fi->elemPtr()), time_arg);
465  const Real neighbor_rho = _rho(makeElemArg(fi->neighborPtr()), time_arg);
466 
467  // Now we do the interpolation to the face
468  interpolate(Moose::FV::InterpMethod::Average, face_rho, elem_rho, neighbor_rho, *fi, true);
469  for (const auto dim_i : index_range(raw_hbya))
470  {
472  face_hbya(dim_i),
473  hbya_reader[dim_i](elem_dof),
474  hbya_reader[dim_i](neighbor_dof),
475  *fi,
476  true);
477  interpolate(InterpMethod::Average,
478  Ainv(dim_i),
479  elem_rho * ainv_reader[dim_i](elem_dof),
480  neighbor_rho * ainv_reader[dim_i](neighbor_dof),
481  *fi,
482  true);
483  }
484  }
485  else
486  {
487  const bool elem_is_fluid = hasBlocks(fi->elemPtr()->subdomain_id());
488 
489  // We need this multiplier in case the face is an internal face and
490  const Real boundary_normal_multiplier = elem_is_fluid ? 1.0 : -1.0;
491 
492  const ElemInfo & elem_info = elem_is_fluid ? *fi->elemInfo() : *fi->neighborInfo();
493  const auto elem_dof = elem_info.dofIndices()[_global_momentum_system_numbers[0]][0];
494 
495  // If it is a Dirichlet BC, we use the dirichlet value the make sure the face flux
496  // is consistent
497  if (_vel[0]->isDirichletBoundaryFace(*fi))
498  {
499  const Moose::FaceArg boundary_face{
500  fi, Moose::FV::LimiterType::CentralDifference, true, false, elem_info.elem(), nullptr};
501  face_rho = _rho(boundary_face, Moose::currentState());
502 
503  for (const auto dim_i : make_range(_dim))
504  {
505 
506  face_hbya(dim_i) =
507  -MetaPhysicL::raw_value((*_vel[dim_i])(boundary_face, Moose::currentState()));
508 
509  if (!_body_force_kernel_names.empty())
510  for (const auto & force_kernel : _body_force_kernels[dim_i])
511  {
512  force_kernel->setCurrentElemInfo(&elem_info);
513  face_hbya(dim_i) -= force_kernel->computeRightHandSideContribution() *
514  ainv_reader[dim_i](elem_dof) /
515  elem_info.volume(); // zero-term expansion
516  }
517  face_hbya(dim_i) *= boundary_normal_multiplier;
518  }
519  }
520  // Otherwise we just do a one-term expansion (so we just use the element value)
521  else
522  {
523  const auto elem_dof = elem_info.dofIndices()[_global_momentum_system_numbers[0]][0];
524 
525  face_rho = _rho(makeElemArg(elem_info.elem()), time_arg);
526  for (const auto dim_i : make_range(_dim))
527  face_hbya(dim_i) = boundary_normal_multiplier * hbya_reader[dim_i](elem_dof);
528  }
529 
530  // We just do a one-term expansion for 1/A no matter what
531  const Real elem_rho = _rho(makeElemArg(elem_info.elem()), time_arg);
532  for (const auto dim_i : index_range(raw_Ainv))
533  Ainv(dim_i) = elem_rho * ainv_reader[dim_i](elem_dof);
534  }
535  // Lastly, we populate the face flux resulted by H/A
536  _HbyA_flux[fi->id()] = face_hbya * fi->normal() * face_rho;
537  }
538 }
539 
540 void
541 RhieChowMassFlux::computeHbyA(const bool with_updated_pressure, bool verbose)
542 {
543  if (verbose)
544  {
545  _console << "************************************" << std::endl;
546  _console << "Computing HbyA" << std::endl;
547  _console << "************************************" << std::endl;
548  }
550  "The momentum system shall be linked before calling this function!");
551 
552  auto & pressure_gradient = selectPressureGradient(with_updated_pressure);
553 
554  _HbyA_raw.clear();
555  _Ainv_raw.clear();
556  for (auto system_i : index_range(_momentum_systems))
557  {
558  LinearImplicitSystem * momentum_system = _momentum_implicit_systems[system_i];
559 
560  NumericVector<Number> & rhs = *(momentum_system->rhs);
561  NumericVector<Number> & current_local_solution = *(momentum_system->current_local_solution);
562  NumericVector<Number> & solution = *(momentum_system->solution);
563  PetscMatrix<Number> * mmat = dynamic_cast<PetscMatrix<Number> *>(momentum_system->matrix);
564  mooseAssert(mmat,
565  "The matrices used in the segregated INSFVRhieChow objects need to be convertable "
566  "to PetscMatrix!");
567 
568  if (verbose)
569  {
570  _console << "Matrix in rc object" << std::endl;
571  mmat->print();
572  }
573 
574  // First, we extract the diagonal and we will hold on to it for a little while
575  _Ainv_raw.push_back(current_local_solution.zero_clone());
576  NumericVector<Number> & Ainv = *(_Ainv_raw.back());
577 
578  mmat->get_diagonal(Ainv);
579 
580  if (verbose)
581  {
582  _console << "Velocity solution in H(u)" << std::endl;
583  solution.print();
584  }
585 
586  // Time to create H(u) = M_{offdiag} * u - b_{nonpressure}
587  _HbyA_raw.push_back(current_local_solution.zero_clone());
588  NumericVector<Number> & HbyA = *(_HbyA_raw.back());
589 
590  // We start with the matrix product part, we will do
591  // M*u - A*u for 2 reasons:
592  // 1, We assume A*u petsc operation is faster than setting the matrix diagonal to 0
593  // 2, In PISO loops we need to reuse the matrix so we can't just set the diagonals to 0
594 
595  // We create a working vector to ease some of the operations, we initialize its values
596  // with the current solution values to have something for the A*u term
597  auto working_vector = momentum_system->current_local_solution->zero_clone();
598  PetscVector<Number> * working_vector_petsc =
599  dynamic_cast<PetscVector<Number> *>(working_vector.get());
600  mooseAssert(working_vector_petsc,
601  "The vectors used in the RhieChowMassFlux objects need to be convertable "
602  "to PetscVectors!");
603 
604  mmat->vector_mult(HbyA, solution);
605  working_vector_petsc->pointwise_mult(Ainv, solution);
606  HbyA.add(-1.0, *working_vector_petsc);
607 
608  if (verbose)
609  {
610  _console << " H(u)" << std::endl;
611  HbyA.print();
612  }
613 
614  // We continue by adding the momentum right hand side contributions
615  HbyA.add(-1.0, rhs);
616 
617  // Unfortunately, the pressure forces are included in the momentum RHS
618  // so we have to correct them back
619  working_vector_petsc->pointwise_mult(*pressure_gradient[system_i], *_cell_volumes);
620  HbyA.add(-1.0, *working_vector_petsc);
621 
622  if (verbose)
623  {
624  _console << "total RHS" << std::endl;
625  rhs.print();
626  _console << "pressure RHS" << std::endl;
627  pressure_gradient[system_i]->print();
628  _console << " H(u)-rhs-relaxation_source" << std::endl;
629  HbyA.print();
630  }
631 
632  // It is time to create element-wise 1/A-s based on the the diagonal of the momentum matrix
633  *working_vector_petsc = 1.0;
634  Ainv.pointwise_divide(*working_vector_petsc, Ainv);
635 
636  // Create 1/A*(H(u)-RHS)
637  HbyA.pointwise_mult(HbyA, Ainv);
638 
639  if (verbose)
640  {
641  _console << " (H(u)-rhs)/A" << std::endl;
642  HbyA.print();
643  }
644 
645  if (_pressure_projection_method == "consistent")
646  {
647 
648  // Consistent Corrections to SIMPLE
649  // 1. Ainv_old = 1/a_p <- Ainv = 1/(a_p + \sum_n a_n)
650  // 2. H(u) <- H(u*) + H(u') = H(u*) - (Ainv - Ainv_old) * grad(p) * Vc
651 
652  if (verbose)
653  _console << "Performing SIMPLEC projection." << std::endl;
654 
655  // Lambda function to calculate the sum of diagonal and neighbor coefficients
656  auto get_row_sum = [mmat](NumericVector<Number> & sum_vector)
657  {
658  // Ensure the sum_vector is zeroed out
659  sum_vector.zero();
660 
661  // Local row size
662  const auto local_size = mmat->local_m();
663 
664  for (const auto row_i : make_range(local_size))
665  {
666  // Get all non-zero components of the row of the matrix
667  const auto global_index = mmat->row_start() + row_i;
668  std::vector<numeric_index_type> indices;
669  std::vector<Real> values;
670  mmat->get_row(global_index, indices, values);
671 
672  // Sum row elements (no absolute values)
673  const Real row_sum = std::accumulate(values.cbegin(), values.cend(), 0.0);
674 
675  // Add the sum of diagonal and elements to the sum_vector
676  sum_vector.add(global_index, row_sum);
677  }
678  sum_vector.close();
679  };
680 
681  // Create a temporary vector to store the sum of diagonal and neighbor coefficients
682  auto row_sum = current_local_solution.zero_clone();
683  get_row_sum(*row_sum);
684 
685  // Create vector with new inverse projection matrix
686  auto Ainv_full = current_local_solution.zero_clone();
687  *working_vector_petsc = 1.0;
688  Ainv_full->pointwise_divide(*working_vector_petsc, *row_sum);
689  const auto Ainv_full_old = Ainv_full->clone();
690 
691  // Correct HbyA
692  Ainv_full->add(-1.0, Ainv);
693  working_vector_petsc->pointwise_mult(*Ainv_full, *pressure_gradient[system_i]);
694  working_vector_petsc->pointwise_mult(*working_vector_petsc, *_cell_volumes);
695  HbyA.add(-1.0, *working_vector_petsc);
696 
697  // Correct Ainv
698  Ainv = *Ainv_full_old;
699  }
700 
701  Ainv.pointwise_mult(Ainv, *_cell_volumes);
702  }
703 
704  // We fill the 1/A and H/A functors
706 
707  if (verbose)
708  {
709  _console << "************************************" << std::endl;
710  _console << "DONE Computing HbyA " << std::endl;
711  _console << "************************************" << std::endl;
712  }
713 }
714 
715 std::vector<std::unique_ptr<NumericVector<Number>>> &
716 RhieChowMassFlux::selectPressureGradient(const bool updated_pressure)
717 {
718  if (updated_pressure)
719  {
720  _grad_p_current.clear();
721  for (const auto & component : _pressure_system->gradientContainer())
722  _grad_p_current.push_back(component->clone());
723  }
724 
725  return _grad_p_current;
726 }
std::vector< LinearSystem * > _momentum_systems
Pointers to the linear system(s) in moose corresponding to the momentum equation(s) ...
const MooseEnum _pressure_projection_method
Enumerator for the method used for pressure projection.
virtual void initialize() override
void setupMeshInformation()
Compute the cell volumes on the mesh.
User object responsible for determining the face fluxes using the Rhie-Chow interpolation in a segreg...
unsigned int n_threads()
A functor whose evaluation relies on querying a map where the keys are face info ids and the values c...
const std::set< BoundaryID > & boundaryIDs() const
virtual numeric_index_type local_m() const final
void paramError(const std::string &param, Args... args) const
T & getMesh(MooseMesh &mesh)
function to cast mesh
Definition: SCM.h:35
void checkBlocks(const VarType &var) const
Check the block consistency between the passed in var and us.
const std::vector< const ElemInfo *> & elemInfoVector() const
std::vector< libMesh::LinearImplicitSystem * > _momentum_implicit_systems
Pointers to the momentum equation implicit system(s) from libmesh.
unsigned int number() const
const std::vector< std::unique_ptr< NumericVector< Number > > > & gradientContainer() const
Real getMassFlux(const FaceInfo &fi) const
Get the face velocity times density (used in advection terms)
void vector_mult(NumericVector< T > &dest, const NumericVector< T > &arg) const
virtual Real computeElemMatrixContribution() override
static const std::string component
Definition: NS.h:153
const Elem & elem() const
virtual std::unique_ptr< NumericVector< T > > zero_clone() const=0
const ElemInfo * neighborInfo() const
const ExecFlagType EXEC_NONE
const Elem * elem() const
registerMooseObject("NavierStokesApp", RhieChowMassFlux)
void computeFaceMassFlux()
Update the values of the face velocities in the containers.
void addFunctor(const std::string &name, const Moose::FunctorBase< T > &functor, const THREAD_ID tid)
MeshBase & mesh
static const std::string density
Definition: NS.h:33
auto raw_value(const Eigen::Map< T > &in)
virtual void setupFaceData(const FaceInfo *face_info)
NumericVector< Number > * rhs
void addAvailableFlags(const ExecFlagType &flag, Args... flags)
const ElemInfo * elemInfo() const
std::vector< std::unique_ptr< NumericVector< Number > > > _Ainv_raw
We hold on to the cell-based 1/A vectors so that we can easily reconstruct the cell velocities as wel...
const LinearSystem * _pressure_system
Pointer to the pressure system.
LinearFVBoundaryCondition * getBoundaryCondition(const BoundaryID bd_id) const
FaceCenteredMapFunctor< RealVectorValue, std::unordered_map< dof_id_type, RealVectorValue > > _Ainv
A map functor from faces to $(1/A)_f$.
The following methods are specializations for using the Parallel::packed_range_* routines for a vecto...
std::vector< unsigned int > _momentum_system_numbers
Numbers of the momentum system(s)
virtual void initialSetup() override
virtual void meshChanged() override
virtual void pointwise_divide(const NumericVector< T > &vec1, const NumericVector< T > &vec2) override
virtual Real computeBoundaryMatrixContribution(const LinearFVBoundaryCondition &bc) override
MooseApp & getMooseApp() const
std::vector< unsigned int > _global_momentum_system_numbers
Global numbers of the momentum system(s)
static InputParameters validParams()
SubProblem & _subproblem
Moose::ElemArg makeElemArg(const Elem *elem, bool correct_skewnewss=false) const
bool isInternalFace(const FaceInfo &) const
void computeHbyA(const bool with_updated_pressure, const bool verbose)
Computes the inverse of the diagonal (1/A) of the system matrix plus the H/A components for the press...
const std::vector< const FaceInfo *> & faceInfo() const
ValueType evaluate(const FaceInfo *const fi) const
Evaluate the face functor using a FaceInfo argument.
virtual void pointwise_mult(const NumericVector< T > &vec1, const NumericVector< T > &vec2) override
const std::string & name() const
std::vector< std::vector< std::string > > _body_force_kernel_names
Vector of body force term names.
FaceCenteredMapFunctor< Real, std::unordered_map< dof_id_type, Real > > _HbyA_flux
A map functor from faces to $HbyA_{ij} = (A_{offdiag}*{(predicted~velocity)} - {Source})_{ij}/A_{ij}$...
const Elem * neighborPtr() const
virtual const NumericVector< Number > *const & currentSolution() const override final
std::vector< std::vector< LinearFVElementalKernel * > > _body_force_kernels
Pointer to the body force terms.
TheWarehouse & theWarehouse() const
std::vector< const MooseLinearVariableFVReal * > _vel
The thread 0 copy of the x-velocity variable.
const MooseLinearVariableFVReal *const _p
The thread 0 copy of the pressure variable.
unsigned int _global_pressure_system_number
Global number of the pressure system.
RhieChowMassFlux(const InputParameters &params)
void linkMomentumPressureSystems(const std::vector< LinearSystem *> &momentum_systems, const LinearSystem &pressure_system, const std::vector< unsigned int > &momentum_system_numbers)
Update the momentum system-related information.
const Moose::Functor< Real > & _rho
Functor describing the density of the fluid.
static InputParameters validParams()
virtual Real computeElemRightHandSideContribution() override
std::unique_ptr< NumericVector< Number > > solution
void computeCellVelocity()
Update the cell values of the velocity variables.
virtual Real computeNeighborMatrixContribution() override
Real getVolumetricFaceFlux(const FaceInfo &fi) const
Get the volumetric face flux (used in advection terms)
void setCurrentFaceArea(const Real area)
virtual void print(std::ostream &os=libMesh::out) const
virtual Real computeBoundaryRHSContribution(const LinearFVBoundaryCondition &bc) override
const Point & normal() const
unsigned int number() const
virtual const MooseVariableFieldBase & getVariable(const THREAD_ID tid, const std::string &var_name, Moose::VarKindType expected_var_type=Moose::VarKindType::VAR_ANY, Moose::VarFieldType expected_var_field_type=Moose::VarFieldType::VAR_FIELD_ANY) const=0
virtual void get_row(numeric_index_type i, std::vector< numeric_index_type > &indices, std::vector< T > &values) const override
std::vector< std::unique_ptr< NumericVector< Number > > > & selectPressureGradient(const bool updated_pressure)
Select the right pressure gradient field and return a reference to the container. ...
virtual void pointwise_mult(const NumericVector< T > &vec1, const NumericVector< T > &vec2)=0
const Elem * elemPtr() const
const std::vector< std::vector< dof_id_type > > & dofIndices() const
virtual void get_diagonal(NumericVector< T > &dest) const override
FaceCenteredMapFunctor< Real, std::unordered_map< dof_id_type, Real > > & _face_mass_flux
A map functor from faces to mass fluxes which are used in the advection terms.
std::vector< std::unique_ptr< NumericVector< Number > > > _grad_p_current
for a PISO iteration we need to hold on to the original pressure gradient field.
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real
subdomain_id_type subdomain_id() const
FEProblemBase & _fe_problem
SparseMatrix< Number > * matrix
Query query()
Real getElemValue(const ElemInfo &elem_info, const StateArg &state) const
static const std::string pressure
Definition: NS.h:56
const THREAD_ID _tid
IntRange< T > make_range(T beg, T end)
virtual MooseMesh & mesh() override
dof_id_type id() const
void mooseError(Args &&... args) const
virtual numeric_index_type row_start() const override
std::unique_ptr< NumericVector< Number > > current_local_solution
static InputParameters validParams()
const ConsoleStream _console
std::vector< const FaceInfo * > _flow_face_info
The subset of the FaceInfo objects that actually cover the subdomains which the flow field is defined...
bool hasBlocks(const SubdomainName &name) const
void populateCouplingFunctors(const std::vector< std::unique_ptr< NumericVector< Number >>> &raw_hbya, const std::vector< std::unique_ptr< NumericVector< Number >>> &raw_Ainv)
Populate the face values of the H/A and 1/A fields.
virtual void add(const numeric_index_type i, const T value)=0
void interpolate(InterpMethod m, T &result, const T2 &value1, const T3 &value2, const FaceInfo &fi, const bool one_is_elem)
StateArg currentState()
LinearFVAnisotropicDiffusion * _p_diffusion_kernel
Pointer to the pressure diffusion term in the pressure Poisson equation.
auto index_range(const T &sizable)
void print(std::ostream &os=libMesh::out, const bool sparse=false) const
Real volume() const
std::vector< std::unique_ptr< NumericVector< Number > > > _HbyA_raw
We hold on to the cell-based HbyA vectors so that we can easily reconstruct the cell velocities as we...
virtual void pointwise_divide(const NumericVector< T > &vec1, const NumericVector< T > &vec2)=0
void initCouplingField()
Initialize the coupling fields (HbyA and Ainv)
unsigned int state
virtual System & system() override
unsigned int THREAD_ID
uint8_t dof_id_type
void initFaceMassFlux()
Initialize the container for face velocities.
VarFaceNeighbors faceType(const std::pair< unsigned int, unsigned int > &var_sys) const
std::unique_ptr< NumericVector< Number > > _cell_volumes
We will hold a vector of cell volumes to make sure we can do volume corrections rapidly.
const unsigned int _dim
The dimension of the mesh, e.g. 3 for hexes and tets, 2 for quads and tris.