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