v0.16.3
Loading...
Searching...
No Matches
Public Types | Public Member Functions | Private Member Functions | Private Attributes | List of all members
MoFEM::OperatorsTester Struct Reference

Calculate directional derivative of the right hand side and compare it with tangent matrix derivative. More...

#include "src/interfaces/OperatorsTester.hpp"

Inheritance diagram for MoFEM::OperatorsTester:
[legend]
Collaboration diagram for MoFEM::OperatorsTester:
[legend]

Public Types

using RandomFieldData = std::pair< std::string, std::array< double, 2 > >
 
using ScalarFunction = std::function< MoFEMErrorCode(Vec, PetscReal &)>
 
using VectorFunction = std::function< MoFEMErrorCode(Vec, Vec)>
 
using DirectionFunction = std::function< double(const NumeredDofEntity &dof, const std::array< double, 3 > &xyz)>
 Value of a test direction for one DOF.
 

Public Member Functions

MoFEMErrorCode query_interface (boost::typeindex::type_index type_index, UnknownInterface **iface) const
 
 OperatorsTester (const MoFEM::Core &core)
 
virtual ~OperatorsTester ()=default
 
SmartPetscObj< Vec > setRandomFields (SmartPetscObj< DM > dm, std::vector< RandomFieldData > random_fields, boost::shared_ptr< Range > ents=nullptr, RowColData r=RowColData::COL)
 Generate random fields.
 
SmartPetscObj< Vec > setDirectionFromFunction (SmartPetscObj< DM > dm, const std::vector< std::string > &fields, DirectionFunction function, boost::shared_ptr< Range > ents=nullptr, RowColData r=RowColData::COL)
 Set a direction vector from a function of the DOF and position.
 
SmartPetscObj< Vec > assembleVec (SmartPetscObj< DM > dm, std::string fe_name, boost::shared_ptr< FEMethod > pipeline, SmartPetscObj< Vec > x, SmartPetscObj< Vec > delta_x, SmartPetscObj< Vec > delta2_x, double time, double delta_t, CacheTupleWeakPtr cache_ptr)
 Assemble the right hand side vector.
 
SmartPetscObj< Mat > assembleMat (SmartPetscObj< DM > dm, std::string fe_name, boost::shared_ptr< FEMethod > pipeline, SmartPetscObj< Vec > x, SmartPetscObj< Vec > delta_x, SmartPetscObj< Vec > delta2_x, double time, double delta_t, CacheTupleWeakPtr cache_ptr)
 Assemble the left hand side vector.
 
SmartPetscObj< Vec > directionalCentralFiniteDifference (SmartPetscObj< DM > dm, std::string fe_name, boost::shared_ptr< FEMethod > pipeline, SmartPetscObj< Vec > x, SmartPetscObj< Vec > delta_x, SmartPetscObj< Vec > delta2_x, SmartPetscObj< Vec > diff_x, double time, double delta_t, double eps, CacheTupleWeakPtr cache_ptr=CacheTupleSharedPtr())
 Calculate directional directive using finite difference.
 
SmartPetscObj< Vec > checkCentralFiniteDifference (SmartPetscObj< DM > dm, std::string fe_name, boost::shared_ptr< FEMethod > pipeline_rhs, boost::shared_ptr< FEMethod > pipeline_lhs, SmartPetscObj< Vec > x, SmartPetscObj< Vec > delta_x, SmartPetscObj< Vec > delta2_x, SmartPetscObj< Vec > diff_x, double time, double delta_t, double eps, CacheTupleWeakPtr cache_ptr=CacheTupleSharedPtr())
 Check consistency between directional derivative with matrix.
 
MoFEMErrorCode checkScalarCentralFiniteDifference (Vec x, Vec direction, Vec gradient, double eps, const ScalarFunction &evaluate, PetscReal &finite_difference, PetscReal &assembled_derivative)
 
MoFEMErrorCode checkVectorCentralFiniteDifference (Vec x, Vec direction, Vec function_layout, Mat jacobian, double eps, const VectorFunction &evaluate, Vec error)
 
- Public Member Functions inherited from MoFEM::UnknownInterface
template<class IFACE >
MoFEMErrorCode registerInterface (bool error_if_registration_failed=true)
 Register interface.
 
template<class IFACE >
MoFEMErrorCode getInterface (IFACE *&iface) const
 Get interface reference to pointer of interface.
 
template<class IFACE >
MoFEMErrorCode getInterface (IFACE **const iface) const
 Get interface pointer to pointer of interface.
 
template<class IFACE , typename boost::enable_if< boost::is_pointer< IFACE >, int >::type = 0>
IFACE getInterface () const
 Get interface pointer to pointer of interface.
 
template<class IFACE , typename boost::enable_if< boost::is_reference< IFACE >, int >::type = 0>
IFACE getInterface () const
 Get reference to interface.
 
template<class IFACE >
IFACE * getInterface () const
 Function returning pointer to interface.
 
virtual ~UnknownInterface ()=default
 

Private Member Functions

std::pair< SmartPetscObj< Vec >, SmartPetscObj< Vec > > setPipelineX (boost::shared_ptr< FEMethod > pipeline, SmartPetscObj< Vec > x, SmartPetscObj< Vec > delta_x, SmartPetscObj< Vec > delta2_x, double delta_t)
 Set vectors, x, x_t, and x_tt to finite element instance.
 

Private Attributes

MoFEM::Core & cOre
 

Additional Inherited Members

- Static Public Member Functions inherited from MoFEM::UnknownInterface
static MoFEMErrorCode getLibVersion (Version &version)
 Get library version.
 
static MoFEMErrorCode getFileVersion (moab::Interface &moab, Version &version)
 Get database major version.
 
static MoFEMErrorCode setFileVersion (moab::Interface &moab, Version version=Version(MoFEM_VERSION_MAJOR, MoFEM_VERSION_MINOR, MoFEM_VERSION_BUILD))
 Get database major version.
 
static MoFEMErrorCode getInterfaceVersion (Version &version)
 Get database major version.
 

Detailed Description

Calculate directional derivative of the right hand side and compare it with tangent matrix derivative.

Examples
mofem/atom_tests/operators_tester_direction.cpp, mofem/atom_tests/operators_tests.cpp, mofem/atom_tests/tensor_divergence_operator.cpp, mofem/tutorials/adv-0_plasticity/plastic.cpp, mofem/tutorials/adv-3_level_set/level_set.cpp, and mofem/tutorials/vec-7_shape_optimisation/adjoint.cpp.

Definition at line 21 of file OperatorsTester.hpp.

Member Typedef Documentation

◆ DirectionFunction

using MoFEM::OperatorsTester::DirectionFunction = std::function<double( const NumeredDofEntity &dof, const std::array<double, 3> &xyz)>

Value of a test direction for one DOF.

The DOF gives the entity, field, coefficient index and order; xyz is the centroid of the entity's corner vertices (zero for meshsets).

Definition at line 64 of file OperatorsTester.hpp.

◆ RandomFieldData

using MoFEM::OperatorsTester::RandomFieldData = std::pair<std::string, std::array<double, 2> >

Definition at line 29 of file OperatorsTester.hpp.

◆ ScalarFunction

using MoFEM::OperatorsTester::ScalarFunction = std::function<MoFEMErrorCode(Vec, PetscReal &)>

Definition at line 30 of file OperatorsTester.hpp.

◆ VectorFunction

using MoFEM::OperatorsTester::VectorFunction = std::function<MoFEMErrorCode(Vec, Vec)>

Definition at line 32 of file OperatorsTester.hpp.

Constructor & Destructor Documentation

◆ OperatorsTester()

MoFEM::OperatorsTester::OperatorsTester ( const MoFEM::Core &  core)

Definition at line 13 of file OperatorsTester.cpp.

14 : cOre(const_cast<Core &>(core)) {}
CoreTmp< 0 > Core
Definition Core.hpp:1161

◆ ~OperatorsTester()

virtual MoFEM::OperatorsTester::~OperatorsTester ( )
virtualdefault

Member Function Documentation

◆ assembleMat()

SmartPetscObj< Mat > MoFEM::OperatorsTester::assembleMat ( SmartPetscObj< DM >  dm,
std::string  fe_name,
boost::shared_ptr< FEMethod >  pipeline,
SmartPetscObj< Vec >  x,
SmartPetscObj< Vec >  delta_x,
SmartPetscObj< Vec >  delta2_x,
double  time,
double  delta_t,
CacheTupleWeakPtr  cache_ptr 
)

Assemble the left hand side vector.

Parameters
dm
fe_name// fe name
pipeline// pipeline, i.e. fe instance
x// problem (dm) vector
delta_x// vector for x rate, can be null, i.e, SmartPetscObj<Vec>()
delta2_x// vector for x second rate, i.e. acceleration
time// time
delta_t// time increment
cache_ptr// finite element data cache, can be null
Returns
SmartPetscObj<Vec>

Definition at line 237 of file OperatorsTester.cpp.

241 {
242 auto m = createDMMatrix(dm);
243
244 pipeline->data_ctx =
246 pipeline->A = m;
247 pipeline->B = m;
248
249 pipeline->ts_t = time;
250
251 pipeline->ts_dt = delta_t;
252 pipeline->ts_a = 1. / delta_t;
253 pipeline->ts_aa = 1. / pow(delta_t, 2);
254
255 pipeline->ksp_ctx = KspMethod::KSPContext::CTX_OPERATORS;
258
259 auto [v, a] = setPipelineX(pipeline, x, delta_x, delta2_x, delta_t);
260 std::ignore = a;
261 std::ignore = v;
262
264 DMoFEMMeshToLocalVector(dm, x, INSERT_VALUES, SCATTER_REVERSE),
265 "loc to vec");
266 CHK_THROW_MESSAGE(DMoFEMLoopFiniteElements(dm, fe_name, pipeline, cache_ptr),
267 "Run assemble pipeline");
268 CHK_THROW_MESSAGE(MatAssemblyBegin(m, MAT_FINAL_ASSEMBLY), "Asmb mat");
269 CHK_THROW_MESSAGE(MatAssemblyEnd(m, MAT_FINAL_ASSEMBLY), "Asmb mat");
270
271 auto get_norm = [](auto m) {
272 double fnorm;
273 MatNorm(m, NORM_1, &fnorm);
274 return fnorm;
275 };
276 MOFEM_LOG_CHANNEL("WORLD");
277 MOFEM_TAG_AND_LOG_C("WORLD", Sev::noisy, "OpTester", "Matrix norm %3.4e",
278 get_norm(m));
279
280 return m;
281}
#define MOFEM_TAG_AND_LOG_C(channel, severity, tag, format,...)
Tag and log in channel.
constexpr double a
#define CHK_THROW_MESSAGE(err, msg)
Check and throw MoFEM exception.
PetscErrorCode DMoFEMMeshToLocalVector(DM dm, Vec l, InsertMode mode, ScatterMode scatter_mode, RowColData rc=RowColData::COL)
set local (or ghosted) vector values on mesh for partition only
Definition DMMoFEM.cpp:600
PetscErrorCode DMoFEMLoopFiniteElements(DM dm, const char fe_name[], MoFEM::FEMethod *method, CacheTupleWeakPtr cache_ptr=CacheTupleSharedPtr())
Executes FEMethod for finite elements in DM.
Definition DMMoFEM.cpp:662
auto createDMMatrix(DM dm)
Get smart matrix from DM.
Definition DMMoFEM.hpp:1236
#define MOFEM_LOG_CHANNEL(channel)
Set and reset channel.
const double v
phase velocity of light in medium (cm/ns)
FTensor::Index< 'm', 3 > m
@ CTX_OPERATORS
Setting up linear operators.
std::pair< SmartPetscObj< Vec >, SmartPetscObj< Vec > > setPipelineX(boost::shared_ptr< FEMethod > pipeline, SmartPetscObj< Vec > x, SmartPetscObj< Vec > delta_x, SmartPetscObj< Vec > delta2_x, double delta_t)
Set vectors, x, x_t, and x_tt to finite element instance.
static constexpr Switches CtxSetA
Jacobian matrix switch.
static constexpr Switches CtxSetB
Preconditioner matrix switch.
static constexpr Switches CtxSetTime
Time value switch.
@ CTX_SNESSETJACOBIAN
Setting up Jacobian matrix computation.
@ CTX_TSSETIJACOBIAN
Setting up implicit Jacobian.

◆ assembleVec()

SmartPetscObj< Vec > MoFEM::OperatorsTester::assembleVec ( SmartPetscObj< DM >  dm,
std::string  fe_name,
boost::shared_ptr< FEMethod >  pipeline,
SmartPetscObj< Vec >  x,
SmartPetscObj< Vec >  delta_x,
SmartPetscObj< Vec >  delta2_x,
double  time,
double  delta_t,
CacheTupleWeakPtr  cache_ptr 
)

Assemble the right hand side vector.

Parameters
dm
fe_name// fe name
pipeline// pipeline, i.e. fe instance
x// problem (dm) vector
delta_x// vector for x rate, can be null, i.e, SmartPetscObj<Vec>()
delta2_x// vector for x second rate, i.e. acceleration
time// time
delta_t// time increment
cache_ptr// finite element data cache, can be null
Returns
SmartPetscObj<Vec>

Definition at line 187 of file OperatorsTester.cpp.

191 {
192
193 pipeline->data_ctx = PetscData::CtxSetF | PetscData::CtxSetTime;
194 auto f = createDMVector(dm);
195 pipeline->f = f;
196 pipeline->ts_t = time;
197 pipeline->ts_dt = delta_t;
198
199 pipeline->ksp_ctx = KspMethod::KSPContext::CTX_SETFUNCTION;
202
203 auto [v, a] = setPipelineX(pipeline, x, delta_x, delta2_x, delta_t);
204 std::ignore = a;
205 std::ignore = v;
206
208 DMoFEMMeshToLocalVector(dm, x, INSERT_VALUES, SCATTER_REVERSE),
209 "loc to vec");
210 CHK_THROW_MESSAGE(DMoFEMLoopFiniteElements(dm, fe_name, pipeline, cache_ptr),
211 "Run assemble pipeline");
212 CHK_THROW_MESSAGE(VecAssemblyBegin(f), "Asmb vector");
213 CHK_THROW_MESSAGE(VecAssemblyEnd(f), "Asmb vector");
214
215 CHK_THROW_MESSAGE(VecGhostUpdateBegin(f, ADD_VALUES, SCATTER_REVERSE),
216 "Update vec");
217 CHK_THROW_MESSAGE(VecGhostUpdateEnd(f, ADD_VALUES, SCATTER_REVERSE),
218 "Update vec");
219 CHK_THROW_MESSAGE(VecGhostUpdateBegin(f, INSERT_VALUES, SCATTER_FORWARD),
220 "Update vec");
221 CHK_THROW_MESSAGE(VecGhostUpdateEnd(f, INSERT_VALUES, SCATTER_FORWARD),
222 "Update vec");
223
224 auto get_norm = [](auto f) {
225 double fnorm;
226 VecNorm(f, NORM_2, &fnorm);
227 return fnorm;
228 };
229 MOFEM_LOG_CHANNEL("WORLD");
230 MOFEM_TAG_AND_LOG_C("WORLD", Sev::noisy, "OpTester", "Vec norm %3.4e",
231 get_norm(f));
232
233 return f;
234}
auto createDMVector(DM dm, RowColData rc=RowColData::COL)
Get smart vector from DM.
Definition DMMoFEM.hpp:1279
@ CTX_SETFUNCTION
Setting up the linear system function.
static constexpr Switches CtxSetF
Residual vector switch.
@ CTX_SNESSETFUNCTION
Setting up nonlinear function evaluation.
@ CTX_TSSETIFUNCTION
Setting up implicit function.

◆ checkCentralFiniteDifference()

SmartPetscObj< Vec > MoFEM::OperatorsTester::checkCentralFiniteDifference ( SmartPetscObj< DM >  dm,
std::string  fe_name,
boost::shared_ptr< FEMethod >  pipeline_rhs,
boost::shared_ptr< FEMethod >  pipeline_lhs,
SmartPetscObj< Vec >  x,
SmartPetscObj< Vec >  delta_x,
SmartPetscObj< Vec >  delta2_x,
SmartPetscObj< Vec >  diff_x,
double  time,
double  delta_t,
double  eps,
CacheTupleWeakPtr  cache_ptr = CacheTupleSharedPtr() 
)

Check consistency between directional derivative with matrix.

Parameters
dm
fe_name
pipeline_rhs
pipeline_lhs
x
delta_x
delta2_x
diff_x
time
delta_t
eps
cache_ptr
Returns
SmartPetscObj<Vec>

Definition at line 340 of file OperatorsTester.cpp.

346 {
347
349 dm, fe_name, pipeline_rhs, x, delta_x, delta2_x, diff_x, time, delta_t,
350 eps, cache_ptr);
351
352 auto m = assembleMat(dm, fe_name, pipeline_lhs, x, delta_x, delta2_x, time,
353 delta_t, cache_ptr);
354
355 auto fm = vectorDuplicate(fd_diff);
356 CHK_THROW_MESSAGE(MatMult(m, diff_x, fm), "Mat mult");
357 CHK_THROW_MESSAGE(VecAXPY(fd_diff, -1., fm), "Add");
358
359 return fd_diff;
360}
static const double eps
SmartPetscObj< Vec > vectorDuplicate(Vec vec)
Create duplicate vector of smart vector.
SmartPetscObj< Mat > assembleMat(SmartPetscObj< DM > dm, std::string fe_name, boost::shared_ptr< FEMethod > pipeline, SmartPetscObj< Vec > x, SmartPetscObj< Vec > delta_x, SmartPetscObj< Vec > delta2_x, double time, double delta_t, CacheTupleWeakPtr cache_ptr)
Assemble the left hand side vector.
SmartPetscObj< Vec > directionalCentralFiniteDifference(SmartPetscObj< DM > dm, std::string fe_name, boost::shared_ptr< FEMethod > pipeline, SmartPetscObj< Vec > x, SmartPetscObj< Vec > delta_x, SmartPetscObj< Vec > delta2_x, SmartPetscObj< Vec > diff_x, double time, double delta_t, double eps, CacheTupleWeakPtr cache_ptr=CacheTupleSharedPtr())
Calculate directional directive using finite difference.

◆ checkScalarCentralFiniteDifference()

MoFEMErrorCode MoFEM::OperatorsTester::checkScalarCentralFiniteDifference ( Vec  x,
Vec  direction,
Vec  gradient,
double  eps,
const ScalarFunction &  evaluate,
PetscReal &  finite_difference,
PetscReal &  assembled_derivative 
)

Check a scalar function derivative against gradient dot direction.

Definition at line 362 of file OperatorsTester.cpp.

365 {
367 if (!(eps > 0) || !evaluate)
368 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
369 "Scalar directional-derivative test requires a positive step "
370 "and evaluator");
371 auto x_plus = vectorDuplicate(x);
372 auto x_minus = vectorDuplicate(x);
373 CHKERR VecWAXPY(x_plus, eps, direction, x);
374 CHKERR VecWAXPY(x_minus, -eps, direction, x);
375 CHKERR VecGhostUpdateBegin(x_plus, INSERT_VALUES, SCATTER_FORWARD);
376 CHKERR VecGhostUpdateEnd(x_plus, INSERT_VALUES, SCATTER_FORWARD);
377 CHKERR VecGhostUpdateBegin(x_minus, INSERT_VALUES, SCATTER_FORWARD);
378 CHKERR VecGhostUpdateEnd(x_minus, INSERT_VALUES, SCATTER_FORWARD);
379 PetscReal value_plus = 0;
380 PetscReal value_minus = 0;
381 CHKERR evaluate(x_plus, value_plus);
382 CHKERR evaluate(x_minus, value_minus);
383 finite_difference = (value_plus - value_minus) / (2 * eps);
384 PetscScalar derivative = 0;
385 CHKERR VecDot(gradient, direction, &derivative);
386 assembled_derivative = PetscRealPart(derivative);
388}
SmartPetscObj< Vec > gradient
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
@ MOFEM_INVALID_DATA
Definition definitions.h:36
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define CHKERR
Inline error check.

◆ checkVectorCentralFiniteDifference()

MoFEMErrorCode MoFEM::OperatorsTester::checkVectorCentralFiniteDifference ( Vec  x,
Vec  direction,
Vec  function_layout,
Mat  jacobian,
double  eps,
const VectorFunction &  evaluate,
Vec  error 
)

Check a vector function derivative against Jacobian times direction. The returned error is written into a vector with the function layout.

Definition at line 390 of file OperatorsTester.cpp.

392 {
394 if (!(eps > 0) || !evaluate)
395 SETERRQ(PETSC_COMM_SELF, MOFEM_INVALID_DATA,
396 "Vector directional-derivative test requires a positive step "
397 "and evaluator");
398 auto x_plus = vectorDuplicate(x);
399 auto x_minus = vectorDuplicate(x);
400 auto value_plus = vectorDuplicate(function_layout);
401 auto value_minus = vectorDuplicate(function_layout);
402 auto assembled = vectorDuplicate(function_layout);
403 CHKERR VecWAXPY(x_plus, eps, direction, x);
404 CHKERR VecWAXPY(x_minus, -eps, direction, x);
405 CHKERR VecGhostUpdateBegin(x_plus, INSERT_VALUES, SCATTER_FORWARD);
406 CHKERR VecGhostUpdateEnd(x_plus, INSERT_VALUES, SCATTER_FORWARD);
407 CHKERR VecGhostUpdateBegin(x_minus, INSERT_VALUES, SCATTER_FORWARD);
408 CHKERR VecGhostUpdateEnd(x_minus, INSERT_VALUES, SCATTER_FORWARD);
409 CHKERR evaluate(x_plus, value_plus);
410 CHKERR evaluate(x_minus, value_minus);
411 CHKERR VecCopy(value_plus, error);
412 CHKERR VecAXPY(error, -1., value_minus);
413 CHKERR VecScale(error, 1. / (2 * eps));
414 CHKERR MatMult(jacobian, direction, assembled);
415 CHKERR VecAXPY(error, -1., assembled);
417}
SmartPetscObj< Mat > jacobian

◆ directionalCentralFiniteDifference()

SmartPetscObj< Vec > MoFEM::OperatorsTester::directionalCentralFiniteDifference ( SmartPetscObj< DM >  dm,
std::string  fe_name,
boost::shared_ptr< FEMethod >  pipeline,
SmartPetscObj< Vec >  x,
SmartPetscObj< Vec >  delta_x,
SmartPetscObj< Vec >  delta2_x,
SmartPetscObj< Vec >  diff_x,
double  time,
double  delta_t,
double  eps,
CacheTupleWeakPtr  cache_ptr = CacheTupleSharedPtr() 
)

Calculate directional directive using finite difference.

Parameters
dm
fe_name
pipeline
x
delta_x
delta2_x
diff_x// direction of derivative
time
delta_t
eps
cache_ptr
Returns
SmartPetscObj<Vec>

Definition at line 283 of file OperatorsTester.cpp.

288 {
289
290 auto axpy = [&](auto v0, auto diff_v, auto eps) {
291 SmartPetscObj<Vec> v;
292 if (v0.use_count()) {
293 v = vectorDuplicate(v0);
294 CHK_THROW_MESSAGE(VecCopy(v0, v), "Cpy");
295 CHK_THROW_MESSAGE(VecAXPY(v, eps, diff_v), "Add");
296 CHK_THROW_MESSAGE(VecGhostUpdateBegin(v, INSERT_VALUES, SCATTER_FORWARD),
297 "ghost");
298 CHK_THROW_MESSAGE(VecGhostUpdateEnd(v, INSERT_VALUES, SCATTER_FORWARD),
299 "ghost");
300 }
301 return v;
302 };
303
304 auto fm1 = assembleVec(dm, fe_name, pipeline,
305 //
306 axpy(x, diff_x, -eps),
307 //
308 axpy(delta_x, diff_x, -eps),
309 //
310 axpy(delta2_x, diff_x, -eps),
311 //
312 time, delta_t, cache_ptr);
313
314 auto fp1 = assembleVec(dm, fe_name, pipeline,
315 //
316 axpy(x, diff_x, eps),
317 //
318 axpy(delta_x, diff_x, eps),
319 //
320 axpy(delta2_x, diff_x, eps),
321 //
322 time, delta_t, cache_ptr);
323
324 auto calculate_derivative = [eps](auto fm1, auto fp1) {
325 int size;
326 VecGetLocalSize(fp1, &size);
327 VecAXPY(fp1, -1, fm1);
328 double *array;
329 VecGetArray(fp1, &array);
330 for (int j = 0; j != size; ++j) {
331 array[j] /= 2 * eps;
332 }
333 VecRestoreArray(fp1, &array);
334 return fp1;
335 };
336
337 return calculate_derivative(fm1, fp1);
338}
std::vector< int > size
FTensor::Index< 'j', 3 > j
SmartPetscObj< Vec > assembleVec(SmartPetscObj< DM > dm, std::string fe_name, boost::shared_ptr< FEMethod > pipeline, SmartPetscObj< Vec > x, SmartPetscObj< Vec > delta_x, SmartPetscObj< Vec > delta2_x, double time, double delta_t, CacheTupleWeakPtr cache_ptr)
Assemble the right hand side vector.

◆ query_interface()

MoFEMErrorCode MoFEM::OperatorsTester::query_interface ( boost::typeindex::type_index  type_index,
UnknownInterface **  iface 
) const
virtual

Implements MoFEM::UnknownInterface.

Definition at line 17 of file OperatorsTester.cpp.

18 {
19 *iface = const_cast<OperatorsTester *>(this);
20 return 0;
21}
OperatorsTester(const MoFEM::Core &core)

◆ setDirectionFromFunction()

SmartPetscObj< Vec > MoFEM::OperatorsTester::setDirectionFromFunction ( SmartPetscObj< DM >  dm,
const std::vector< std::string > &  fields,
DirectionFunction  function,
boost::shared_ptr< Range >  ents = nullptr,
RowColData  r = RowColData::COL 
)

Set a direction vector from a function of the DOF and position.

Unlike setRandomFields, which draws values in local DOF order, the value of each DOF depends only on the function, the DOF and the mesh. The vector is therefore the same for any number of ranks and any DOF numbering, so derivative checks on one and several ranks test the same direction. DOFs of other fields, or outside ents when given, are zero.

auto d = opt->setDirectionFromFunction(
dm, {"FIELD"}, [](const NumeredDofEntity &dof, const auto &xyz) {
return std::sin(xyz[0] + dof.getDofCoeffIdx());
});
keeps information about indexed dofs for the problem
FieldCoefficientsNumber getDofCoeffIdx() const
Parameters
dm
fieldsfields set by the function
functionvalue for each DOF, see DirectionFunction
entsrestrict the direction to these entities, null for all
rrow or column layout
Returns
SmartPetscObj<Vec> vector with ghost values updated

Definition at line 98 of file OperatorsTester.cpp.

101 {
102
103 MoFEM::Interface &m_field = cOre;
104 auto &moab = m_field.get_moab();
105 if (!function)
106 THROW_MESSAGE("Direction function is empty");
107
108 auto prb_ptr = getProblemPtr(dm);
109 boost::shared_ptr<NumeredDofEntity_multiIndex> dofs;
110 switch (r) {
111 case RowColData::ROW:
112 dofs = prb_ptr->getNumeredRowDofsPtr();
113 break;
114 case RowColData::COL:
115 dofs = prb_ptr->getNumeredColDofsPtr();
116 break;
117 default:
118 THROW_MESSAGE("Invalid RowColData");
119 }
120
121 auto v = createDMVector(dm, r);
122 int size;
123 CHK_THROW_MESSAGE(VecGetLocalSize(v, &size), "Get local size");
124 double *array;
125 CHK_THROW_MESSAGE(VecGetArray(v, &array), "Get array");
126
127 // DOFs of one entity are adjacent in the index, so the centroid is
128 // computed once per entity.
129 EntityHandle last_ent = 0;
130 std::array<double, 3> xyz{0., 0., 0.};
131 auto get_centroid = [&](const EntityHandle ent) {
132 if (ent == last_ent)
133 return;
134 last_ent = ent;
135 xyz = {0., 0., 0.};
136 const auto type = type_from_handle(ent);
137 if (type == MBVERTEX) {
138 CHK_MOAB_THROW(moab.get_coords(&ent, 1, xyz.data()), "Get coords");
139 } else if (type != MBENTITYSET) {
140 const EntityHandle *conn;
141 int num_nodes;
142 CHK_MOAB_THROW(moab.get_connectivity(ent, conn, num_nodes, true),
143 "Get connectivity");
144 std::vector<double> coords(3 * num_nodes);
145 CHK_MOAB_THROW(moab.get_coords(conn, num_nodes, coords.data()),
146 "Get coords");
147 for (int n = 0; n != num_nodes; ++n)
148 for (int d = 0; d != 3; ++d)
149 xyz[d] += coords[3 * n + d] / num_nodes;
150 }
151 };
152
153 auto set_values = [&](auto lo, auto hi) {
154 for (; lo != hi; ++lo) {
155 const auto idx = (*lo)->getPetscLocalDofIdx();
156 if (idx >= 0 && idx < size) {
157 get_centroid((*lo)->getEnt());
158 array[idx] = function(**lo, xyz);
159 }
160 }
161 };
162
163 for (auto &field : fields) {
164 const auto field_id = m_field.get_field_bit_number(field);
165 if (!ents_ptr) {
166 set_values(dofs->lower_bound(FieldEntity::getLoBitNumberUId(field_id)),
167 dofs->upper_bound(FieldEntity::getHiBitNumberUId(field_id)));
168 } else {
169 for (auto pit = ents_ptr->const_pair_begin();
170 pit != ents_ptr->const_pair_end(); ++pit)
171 set_values(dofs->get<Unique_mi_tag>().lower_bound(
172 DofEntity::getLoFieldEntityUId(field_id, pit->first)),
173 dofs->get<Unique_mi_tag>().upper_bound(
174 DofEntity::getHiFieldEntityUId(field_id, pit->second)));
175 }
176 }
177
178 CHK_THROW_MESSAGE(VecRestoreArray(v, &array), "Restore array");
179 CHK_THROW_MESSAGE(VecGhostUpdateBegin(v, INSERT_VALUES, SCATTER_FORWARD),
180 "Ghost update");
181 CHK_THROW_MESSAGE(VecGhostUpdateEnd(v, INSERT_VALUES, SCATTER_FORWARD),
182 "Ghost update");
183 return v;
184}
ProjectedField & field
std::string type
@ COL
@ ROW
#define CHK_MOAB_THROW(err, msg)
Check error code of MoAB function and throw MoFEM exception.
#define THROW_MESSAGE(msg)
Throw MoFEM exception.
auto type_from_handle(const EntityHandle h)
get type from entity handle
auto getProblemPtr(DM dm)
get problem pointer from DM
Definition DMMoFEM.hpp:1224
virtual FieldBitNumber get_field_bit_number(const std::string name) const =0
get field bit number
virtual moab::Interface & get_moab()=0
Deprecated interface functions.
static UId getLoFieldEntityUId(const FieldBitNumber bit, const EntityHandle ent)
static UId getHiFieldEntityUId(const FieldBitNumber bit, const EntityHandle ent)
static UId getHiBitNumberUId(const FieldBitNumber bit_number)
static UId getLoBitNumberUId(const FieldBitNumber bit_number)

◆ setPipelineX()

std::pair< SmartPetscObj< Vec >, SmartPetscObj< Vec > > MoFEM::OperatorsTester::setPipelineX ( boost::shared_ptr< FEMethod >  pipeline,
SmartPetscObj< Vec >  x,
SmartPetscObj< Vec >  delta_x,
SmartPetscObj< Vec >  delta2_x,
double  delta_t 
)
private

Set vectors, x, x_t, and x_tt to finite element instance.

Finite element instance is a pipeline. x_t and x_tt are evaluated for given delta_x, delta2_x and delta_t.

Parameters
pipeline
x
delta_x
delta2_x
delta_t
Returns
std::pair<SmartPetscObj<Vec>, SmartPetscObj<Vec>>

Definition at line 420 of file OperatorsTester.cpp.

422 {
423
424 // Set dofs vector to finite element instance
425 pipeline->x = x;
426 pipeline->data_ctx |= PetscData::CTX_SET_X;
427
428 SmartPetscObj<Vec> x_t, x_tt;
429
430 // Set velocity dofs vector to finite element instance
431
432 if (delta_x.use_count()) {
433 x_t = vectorDuplicate(x);
434 VecCopy(delta_x, x_t);
435 VecScale(x_t, 1. / delta_t);
436 CHK_THROW_MESSAGE(VecGhostUpdateBegin(x_t, INSERT_VALUES, SCATTER_FORWARD),
437 "ghost");
438 CHK_THROW_MESSAGE(VecGhostUpdateEnd(x_t, INSERT_VALUES, SCATTER_FORWARD),
439 "ghost");
440 pipeline->x_t = x_t;
441 pipeline->data_ctx |= PetscData::CTX_SET_X_T;
442 } else {
443 pipeline->x_t = PETSC_NULLPTR;
444 }
445
446 // Set acceleration dofs vector to finite element instance
447
448 if (delta2_x.use_count()) {
449 x_tt = vectorDuplicate(x);
450 VecCopy(delta2_x, x_tt);
451 VecScale(x_tt, 1. / pow(delta_t, 2));
452 CHK_THROW_MESSAGE(VecGhostUpdateBegin(x_tt, INSERT_VALUES, SCATTER_FORWARD),
453 "ghost");
454 CHK_THROW_MESSAGE(VecGhostUpdateEnd(x_tt, INSERT_VALUES, SCATTER_FORWARD),
455 "ghost");
456 pipeline->x_tt = x_tt;
457 pipeline->data_ctx |= PetscData::CTX_SET_X_TT;
458 } else {
459 pipeline->x_tt = PETSC_NULLPTR;
460 }
461
462 return std::make_pair(x_t, x_tt);
463}
@ CTX_SET_X_T
Time derivative X_t is set.
@ CTX_SET_X
Solution vector X is set.
@ CTX_SET_X_TT
Second time derivative X_tt is set.

◆ setRandomFields()

SmartPetscObj< Vec > MoFEM::OperatorsTester::setRandomFields ( SmartPetscObj< DM >  dm,
std::vector< RandomFieldData >  random_fields,
boost::shared_ptr< Range >  ents = nullptr,
RowColData  r = RowColData::COL 
)

Generate random fields.

Example: generate random vector for DM (problem) from simple interface, where FIELD random values of DOFs are in range from -1 to 1, and FIELD2 random values are in range from 0 to 1.

auto x = opt->setRandomFields(simple->getDM(),
{{"FIELD1", {-1, 1}}, {"FIELD2", {0,1}}});
void simple(double P1[], double P2[], double P3[], double c[], const int N)
Definition acoustic.cpp:69

TODO: Set random field to specific entities, and potentially order for testing proposes to dissect error in tangent matrix.

Parameters
dm
random_fieldslook at definition RandomFieldData
Returns
SmartPetscObj<Vec> smart vector
Examples
mofem/atom_tests/tensor_divergence_operator.cpp.

Definition at line 23 of file OperatorsTester.cpp.

25 {
26
27 MoFEM::Interface &m_field = cOre;
28
29 auto prb_ptr = getProblemPtr(dm);
30 std::mt19937 rng(0x4d584431u);
31
32 auto get_random_number = [&rng](auto &range) {
33 std::uniform_real_distribution<double> dist(range[0], range[1]);
34 return dist(rng);
35 };
36
37 auto v = createDMVector(dm, r);
38 double *array;
39 CHKERR VecGetArray(v, &array);
40
41 int size;
42 CHKERR VecGetLocalSize(v, &size);
43
44 MOFEM_LOG_CHANNEL("WORLD");
45
46 for (auto &rf : random_fields) {
47 const auto field_id = m_field.get_field_bit_number(rf.first);
48 MOFEM_TAG_AND_LOG("WORLD", Sev::noisy, "OperatorsTester")
49 << "Set random field " << rf.first << " " << static_cast<int>(field_id);
50
51 auto get_numbered_dofs = [&]() {
52 switch (r) {
53 case RowColData::ROW:
54 return prb_ptr->getNumeredRowDofsPtr();
55 case RowColData::COL:
56 return prb_ptr->getNumeredColDofsPtr();
57 default:
58 throw std::runtime_error("Invalid RowColData");
59 }
60 };
61
62 if (!ents_ptr) {
63 auto lo = get_numbered_dofs()->lower_bound(
65 const auto hi = get_numbered_dofs()->upper_bound(
67 for (; lo != hi; ++lo) {
68 const auto idx = (*lo)->getPetscLocalDofIdx();
69 if (idx >= 0 && idx < size) {
70 array[idx] = get_random_number(rf.second);
71 }
72 }
73 } else {
74 for (auto pit = ents_ptr->const_pair_begin();
75 pit != ents_ptr->const_pair_end(); ++pit) {
76 auto lo = get_numbered_dofs()->get<Unique_mi_tag>().lower_bound(
77 DofEntity::getLoFieldEntityUId(field_id, pit->first));
78 auto hi = get_numbered_dofs()->get<Unique_mi_tag>().upper_bound(
79 DofEntity::getHiFieldEntityUId(field_id, pit->second));
80 for (; lo != hi; ++lo) {
81 const auto idx = (*lo)->getPetscLocalDofIdx();
82 if (idx >= 0 && idx < size) {
83 array[idx] = get_random_number(rf.second);
84 }
85 }
86 }
87 }
88 }
89
90 CHKERR VecRestoreArray(v, &array);
91
92 CHKERR VecGhostUpdateBegin(v, INSERT_VALUES, SCATTER_FORWARD);
93 CHKERR VecGhostUpdateEnd(v, INSERT_VALUES, SCATTER_FORWARD);
94
95 return v;
96};
#define MOFEM_TAG_AND_LOG(channel, severity, tag)
Tag and log in channel.

Member Data Documentation

◆ cOre

MoFEM::Core& MoFEM::OperatorsTester::cOre
private

Definition at line 202 of file OperatorsTester.hpp.


The documentation for this struct was generated from the following files: