v0.16.3
Loading...
Searching...
No Matches
dg_projection_interface.cpp
Go to the documentation of this file.
1/** \file dg_projection_interface.cpp
2 * \brief Manufactured field and tag transfer through a caller-owned DM.
3 */
4#include <MoFEM.hpp>
5#include <array>
6#include <cmath>
7#include <limits>
8#include <map>
9#include <set>
10using namespace MoFEM;
11
12namespace {
13using Projection = DGProjectionInterface;
14using FieldRequest = Projection::Request<Projection::FieldMap>;
15using FieldResult = Projection::Report<Projection::FieldReport>;
16using TagRequest = Projection::Request<Projection::TagMap>;
17using TagResult = Projection::Report<Projection::TagReport>;
20
21/// Create an affine simplex and its vertex closure for independent test meshes.
22MoFEMErrorCode simplex(moab::Interface &mb, int dim, double offset,
23 double shift, double scale, Range &cells,
24 Range &closure) {
26 std::array<EntityHandle, 4> vertices;
27 for (int v = 0; v != dim + 1; ++v) {
28 std::array<double, 3> x{offset + shift, shift, dim == 3 ? shift : 0.};
29 if (v)
30 x[v - 1] += scale;
31 CHKERR mb.create_vertex(x.data(), vertices[v]);
32 closure.insert(vertices[v]);
33 }
34 EntityHandle cell;
35 CHKERR mb.create_element(dim == 2 ? MBTRI : MBTET, vertices.data(), dim + 1,
36 cell);
37 cells.insert(cell);
38 closure.insert(cell);
39 for (int d = 1; d < dim; ++d)
40 CHKERR mb.get_adjacencies(cells, d, true, closure, moab::Interface::UNION);
42}
43
44double affine(const double *x, int component) {
45 return (component + 1) * (1. + .5 * x[0] - .7 * x[1] + .3 * x[2]);
46}
47
48MoFEMErrorCode require(bool condition, const char *message) {
50 if (!condition)
51 SETERRQ(PETSC_COMM_SELF, MOFEM_ATOM_TEST_INVALID, "%s", message);
53}
54
55/// Compare a value with its expectation; a NaN expectation requires NaN.
56MoFEMErrorCode requireValue(double value, double expected, const char *message) {
57 return require(std::isnan(expected) ? std::isnan(value)
58 : std::abs(value - expected) < 1.e-9,
59 message);
60}
61
62Projection::IntegrationRule standardRule(int order) {
63 Projection::IntegrationRule rule;
64 rule.ruleHook = [order](int, int, int) { return order; };
65 return rule;
66}
67
68/// A one-point rule at the element centroid, given by explicit points.
69template <int D> Projection::IntegrationRule centroidRule() {
70 Projection::IntegrationRule rule;
71 rule.setRuleHook = [](ForcesAndSourcesCore *fe, int, int, int) {
73 fe->gaussPts.resize(D + 1, 1, false);
74 for (int d = 0; d != D; ++d)
75 fe->gaussPts(d, 0) = 1. / (D + 1);
76 fe->gaussPts(D, 0) = 1.;
78 };
79 return rule;
80}
81
82/// Visit all local copies of cells at the given rule, outside the interface.
83template <int D>
84MoFEMErrorCode loopCells(MoFEM::Core &core, const Range &cells,
86 const Projection::IntegrationRule &rule,
87 boost::function<MoFEMErrorCode(UDO *)> work) {
89 MoFEM::Interface &field = core;
90 const std::string name = "TAG_CHECK";
91 const int build_state = core.getBuildMoFEM();
92 CHKERR field.add_finite_element(name, MF_EXCL, QUIET);
93 CHKERR field.modify_finite_element_add_field_row(name, "MEMORY");
94 CHKERR field.modify_finite_element_add_field_col(name, "MEMORY");
95 CHKERR field.modify_finite_element_add_field_data(name, "MEMORY");
96 CHKERR field.add_ents_to_finite_element_by_dim(cells, D, name);
97 CHKERR field.build_finite_elements(name, nullptr, QUIET);
98 CHKERR field.build_adjacencies(cells, QUIET);
99 CHKERR field.add_problem(name, MF_EXCL, QUIET);
100 CHKERR field.modify_problem_add_finite_element(name, name);
101 CHKERR field.modify_problem_ref_level_add_bit(name, bit);
102 CHKERR field.modify_problem_mask_ref_level_add_bit(name,
103 BitRefLevel().set());
104 auto problems = field.getInterface<ProblemsManager>();
105 CHKERR problems->buildProblem(name, true, QUIET);
107 CHKERR problems->partitionFiniteElements(name, true, 0,
108 field.get_comm_size(), QUIET);
109 const Problem *problem;
110 CHKERR field.get_problem(name, &problem);
111 auto &elements = *problem->numeredFiniteElementsPtr;
112 for (auto it = elements.begin(); it != elements.end();)
113 CHKERR require(elements.modify(it++, NumeredEntFiniteElement_change_part(
114 field.get_comm_rank())),
115 "Could not number tag check cells");
117 auto fe = boost::make_shared<Element>(field);
118 if (rule.setRuleHook) {
119 fe->getRuleHook = [](int, int, int) { return -1; };
120 fe->setRuleHook = rule.setRuleHook;
121 } else {
122 fe->getRuleHook = rule.ruleHook;
123 }
124 auto op = new UDO(NOSPACE, UDO::OPSPACE);
125 op->doWorkRhsHook = [work](DataOperator *base, int, EntityType, EntData &) {
126 return work(static_cast<UDO *>(base));
127 };
128 fe->getOpPtrVector().push_back(op);
129 CHKERR field.loop_finite_elements(name, name, *fe);
130 fe.reset();
131 CHKERR field.delete_problem(name);
132 CHKERR field.delete_finite_element(name, QUIET);
133 core.getBuildMoFEM() = build_state;
135}
136
137/// Integration-point tags: polynomial reproduction, rules, same-name and
138/// missing-data transfers, and failures that leave no private objects.
139template <int D>
140MoFEMErrorCode checkTags(MoFEM::Core &core, moab::Interface &mb,
141 DM projection_dm, const std::string &element_name,
142 const Range &source, const Range &target,
143 const Range &copy, BitRefLevel source_bit,
144 BitRefLevel target_bit, BitRefLevel copy_bit) {
146 MoFEM::Interface &field = core;
147 auto projection = field.getInterface<Projection>();
148 const auto project_tags = [&](TagRequest &request, TagResult &report) {
149 request.dm = projection_dm;
150 request.elementName = element_name;
151 return projection->project(request, report);
152 };
153 const auto nan = std::numeric_limits<double>::quiet_NaN();
154 auto make_tag = [&](const std::string &name, DataType type,
155 const double *def = nullptr) {
157 Tag th;
158 CHKERR mb.tag_get_handle(name.c_str(), def ? 1 : 0, type, th,
159 MB_TAG_CREAT | MB_TAG_EXCL | MB_TAG_VARLEN |
160 MB_TAG_SPARSE,
161 def);
163 };
164 for (const auto *name :
165 {"TAG_1", "TAG_6", "TAG_9", "TAG_10", "TAG_SAME", "TAG_LOW"})
166 CHKERR make_tag(name, MB_TYPE_DOUBLE);
167 CHKERR make_tag("TAG_NAN", MB_TYPE_DOUBLE, &nan);
168 CHKERR make_tag("TAG_INT", MB_TYPE_INTEGER);
169 Tag fixed;
170 CHKERR mb.tag_get_handle("TAG_FIXED", 2, MB_TYPE_DOUBLE, fixed,
171 MB_TAG_CREAT | MB_TAG_EXCL | MB_TAG_SPARSE);
172 const auto rule1 = standardRule(1), rule2 = standardRule(2),
173 rule3 = standardRule(3), rule4 = standardRule(4);
174 const auto centroid = centroidRule<D>();
175
176 auto fill = [&](const std::string &name, int components,
177 const Projection::IntegrationRule &rule) {
178 Tag th;
179 CHK_MOAB_THROW(mb.tag_get_handle(name.c_str(), th), "fill tag");
180 return loopCells<D>(
181 core, source, source_bit, rule, [&mb, th, components](UDO *op) {
183 const auto &coords = op->getCoordsAtGaussPts();
184 std::vector<double> values(coords.size1() * components);
185 for (size_t q = 0; q != coords.size1(); ++q)
186 for (int c = 0; c != components; ++c)
187 values[q * components + c] = affine(&coords(q, 0), c);
188 const void *data[] = {values.data()};
189 const int size = values.size();
190 const auto ent = op->getFEEntityHandle();
191 CHKERR mb.tag_set_by_ptr(th, &ent, 1, data, &size);
193 });
194 };
195 auto check = [&](const std::string &name, int components, const Range &cells,
196 BitRefLevel bit, const Projection::IntegrationRule &rule,
197 bool expect_nan) {
198 if (cells.empty())
199 return MoFEMErrorCode(0);
200 Tag th;
201 CHK_MOAB_THROW(mb.tag_get_handle(name.c_str(), th), "check tag");
202 return loopCells<D>(
203 core, cells, bit, rule, [&mb, th, components, expect_nan](UDO *op) {
205 const auto ent = op->getFEEntityHandle();
206 const double *data = nullptr;
207 int size = 0;
208 CHKERR mb.tag_get_by_ptr(th, &ent, 1, (const void **)&data, &size);
209 const auto &coords = op->getCoordsAtGaussPts();
210 CHKERR require(static_cast<size_t>(size) ==
211 coords.size1() * components,
212 "Target tag length differs from the target rule");
213 for (size_t q = 0; q != coords.size1(); ++q)
214 for (int c = 0; c != components; ++c)
215 CHKERR requireValue(
216 data[q * components + c],
217 expect_nan ? std::numeric_limits<double>::quiet_NaN()
218 : affine(&coords(q, 0), c),
219 "Projected tag differs from analytical values");
221 });
222 };
223 for (auto [name, components] :
224 {std::pair{"TAG_1", 1}, std::pair{"TAG_6", 6}, std::pair{"TAG_9", 9},
225 std::pair{"TAG_10", 10}, std::pair{"TAG_SAME", 6}})
226 CHKERR fill(name, components, rule4);
227 CHKERR fill("TAG_LOW", 1, rule1);
228
229 const auto fields_before = field.get_fields()->size();
230 Range baseline;
231 CHKERR mb.get_entities_by_handle(0, baseline);
232 auto require_no_leaks = [&]() {
234 CHKERR require(field.get_fields()->size() == fields_before,
235 "Private tag fields leaked");
236 Range after;
237 CHKERR mb.get_entities_by_handle(0, after);
238 CHKERR require(after == baseline, "Private tag entities leaked");
240 };
241 Range checked = target;
242 checked.merge(copy);
243
244 // Affine values at the source rule reproduce at a different target rule.
245 TagRequest request;
246 request.source.bit = source_bit;
247 request.target.bit = target_bit | copy_bit;
248 request.options.quadratureOrder = 6;
249 request.options.sourceRule = rule4;
250 request.options.targetRule = rule3;
251 // Components are inferred from the source tag lengths.
252 request.maps = {{{"TAG_1", "TAG_1_OUT"},
253 {"TAG_6", "TAG_6_OUT"},
254 {"TAG_9", "TAG_9_OUT"}},
255 1};
256 TagResult report;
257 CHKERR project_tags(request, report);
258 CHKERR require(report.missingPoints == 0 &&
259 report.items.size() == (target.empty() ? 0 : 3),
260 "Unexpected tag projection report");
261 for (const auto &item : report.items) {
262 CHKERR require(item.relativeMassResidual < 2.e-10,
263 "Tag mass residual is too large");
264 CHKERR require(item.sourceRelativeMassResidual < 2.e-10,
265 "Tag reconstruction residual is too large");
266 CHKERR require(item.sourceElementsWithoutData == 0,
267 "Unexpected source elements without tag data");
268 }
269 CHKERR check("TAG_1_OUT", 1, checked, target_bit | copy_bit, rule3, false);
270 CHKERR check("TAG_6_OUT", 6, checked, target_bit | copy_bit, rule3, false);
271 CHKERR check("TAG_9_OUT", 9, checked, target_bit | copy_bit, rule3, false);
272 if (!checked.empty()) {
273 Tag created;
274 int length;
275 DataType type;
276 CHKERR mb.tag_get_handle("TAG_6_OUT", created);
277 CHKERR mb.tag_get_data_type(created, type);
278 CHKERR require(type == MB_TYPE_DOUBLE &&
279 mb.tag_get_length(created, length) ==
280 MB_VARIABLE_DATA_LENGTH,
281 "Created target tag differs from its source tag");
282 }
283 CHKERR require_no_leaks();
284
285 // Explicit points from setRuleHook.
286 request.options.targetRule = centroid;
287 request.maps = {{{"TAG_6", "TAG_6_CENTRE"}}, 1};
288 CHKERR project_tags(request, report);
289 CHKERR check("TAG_6_CENTRE", 6, checked, target_bit | copy_bit, centroid,
290 false);
291
292 // Same source and target tag on the same cells, written at another rule:
293 // every source value must be read before any target value is written.
294 std::vector<Tag> tags_before, tags_after;
295 CHKERR mb.tag_get_tags(tags_before);
296 TagRequest same = request;
297 same.target.bit = source_bit;
298 same.options.targetRule = rule2;
299 same.maps = {{{"TAG_SAME", "TAG_SAME"}}, 1};
300 CHKERR project_tags(same, report);
301 CHKERR check("TAG_SAME", 6, source, source_bit, rule2, false);
302 CHKERR mb.tag_get_tags(tags_after);
303 CHKERR require(tags_before.size() == tags_after.size(),
304 "Tag projection leaked MOAB tags");
305 CHKERR require_no_leaks();
306
307 // Source cells without data take the NaN default of the source tag. With no
308 // data on any rank, the one-value default gives one component.
309 request.options.targetRule = rule3;
310 request.maps = {{{"TAG_NAN", "TAG_NAN_OUT"}}, 1};
311 CHKERR project_tags(request, report);
312 if (!target.empty())
313 CHKERR require(report.items[0].sourceElementsWithoutData > 0,
314 "Missing source tag data was not reported");
315 CHKERR check("TAG_NAN_OUT", 1, checked, target_bit | copy_bit, rule3, true);
316
317 auto reject = [&](TagRequest bad, const char *absent_target) {
319 CHKERR PetscPushErrorHandler(PetscReturnErrorHandler, nullptr);
320 const auto error = project_tags(bad, report);
321 CHKERR PetscPopErrorHandler();
322 if (!target.empty())
323 CHKERR require(error != 0, "Invalid tag projection was accepted");
324 CHKERR require_no_leaks();
325 if (absent_target) {
326 Tag th;
327 CHKERR require(mb.tag_get_handle(absent_target, th) != MB_SUCCESS,
328 "Failed tag projection left a created target tag");
329 }
331 };
332 auto bad = request;
333 bad.options.quadratureOrder = -1;
334 bad.maps = {{{"TAG_1", "TAG_NO_QUADRATURE"}}, 1};
335 CHKERR reject(bad, "TAG_NO_QUADRATURE");
336 bad = request;
337 bad.options.sourceRule = rule1; // TAG_6 holds rule-4 values.
338 bad.maps = {{{"TAG_6", "TAG_BAD_LENGTH"}}, 1};
339 CHKERR reject(bad, "TAG_BAD_LENGTH");
340 bad = request;
341 bad.maps = {{{"TAG_1", "TAG_FIXED"}}, 1};
342 CHKERR reject(bad, nullptr);
343 bad = request;
344 bad.maps = {{{"TAG_10", "TAG_BAD_COMPONENTS"}}, 1};
345 CHKERR reject(bad, "TAG_BAD_COMPONENTS");
346 bad = request;
347 bad.maps = {{{"TAG_INT", "TAG_BAD_TYPE"}}, 1};
348 CHKERR reject(bad, "TAG_BAD_TYPE");
349 bad = request;
350 bad.options.targetRule = Projection::IntegrationRule();
351 bad.maps = {{{"TAG_1", "TAG_BAD_RULE"}}, 1};
352 CHKERR reject(bad, "TAG_BAD_RULE");
353 bad = request;
354 bad.options.sourceRule = rule1; // One point cannot fit an order-1 polynomial.
355 bad.maps = {{{"TAG_LOW", "TAG_BAD_ORDER"}}, 1};
356 CHKERR reject(bad, "TAG_BAD_ORDER");
358}
359
360/// Check values at several quadrature points, not just transferred coefficients.
361template <int D>
362MoFEMErrorCode runCase(bool empty_ranks, bool shared_copies = false,
363 bool ghost_source = false) {
365 moab::Core mb;
366 auto pc = std::make_unique<ParallelComm>(&mb, PETSC_COMM_WORLD);
367 MoFEM::Core core(mb);
368 MoFEM::Interface &field = core;
369 const bool active = !empty_ranks || field.get_comm_rank() == 0;
370 const double offset = (shared_copies || ghost_source)
371 ? 0.
372 : 3. * field.get_comm_rank();
373 const double target_shift =
374 .1 + (ghost_source ? .01 * field.get_comm_rank() : 0.);
375 Range source, target, missing, copy, source_all, target_all, missing_all,
376 copy_all;
377 if (active) {
378 CHKERR simplex(mb, D, offset, 0., 1., source, source_all);
379 CHKERR simplex(mb, D, offset, target_shift, .2, target, target_all);
380 CHKERR simplex(mb, D, offset, D == 2 ? .1 : 10., .2, missing, missing_all);
381 CHKERR simplex(mb, D, offset, target_shift + .02, .05, copy, copy_all);
382 // Put target points in two distinct source cells on each active rank.
383 if (!empty_ranks && !shared_copies && !ghost_source) {
384 CHKERR simplex(mb, D, offset + 1.5, 0., 1., source, source_all);
385 CHKERR simplex(mb, D, offset + 1.5, target_shift, .2, target,
386 target_all);
387 }
388 }
389 if constexpr (D == 2) {
390 // The missing mesh is inside the source bounding box but off its plane.
391 Range vertices = source_all.subset_by_type(MBVERTEX);
392 vertices.merge(target_all.subset_by_type(MBVERTEX));
393 vertices.merge(copy_all.subset_by_type(MBVERTEX));
394 vertices.merge(missing_all.subset_by_type(MBVERTEX));
395 for (auto v : vertices) {
396 double x[3];
397 CHKERR mb.get_coords(&v, 1, x);
398 x[2] = .4 * (x[0] - offset) + .2 * x[1];
399 if (missing_all.find(v) != missing_all.end())
400 x[2] += .05;
401 CHKERR mb.set_coords(&v, 1, x);
402 }
403 }
404 if (shared_copies || ghost_source) {
406 Range all = source_all;
407 if (shared_copies) {
408 cells.merge(target);
409 cells.merge(copy);
410 cells.merge(missing);
411 all.merge(target_all);
412 all.merge(copy_all);
413 all.merge(missing_all);
414 }
415 const auto gid = mb.globalId_tag();
416 for (auto e : all) {
417 const int id = static_cast<int>(mb.id_from_handle(e));
418 CHKERR mb.tag_set_data(gid, &e, 1, &id);
419 }
420 EntityHandle part;
421 CHKERR pc->create_part(part);
422 CHKERR mb.add_entities(part, all);
423 CHKERR pc->resolve_shared_ents(0, cells, D, D);
424 // Skin resolution shares vertices/faces. Register full-dimensional copies
425 // with MOAB's remote-data API, using handles actually reported by each rank.
426 if (field.get_comm_size() > 1)
427 for (auto e : cells) {
428 unsigned long long local_handle = e;
429 std::vector<unsigned long long> remote(field.get_comm_size());
430 CHKERR MPI_Allgather(&local_handle, 1, MPI_UNSIGNED_LONG_LONG,
431 remote.data(), 1, MPI_UNSIGNED_LONG_LONG,
432 field.get_comm());
433 std::vector<int> procs;
434 std::vector<EntityHandle> handles;
435 for (int r = 0; r != field.get_comm_size(); ++r)
436 if (r != field.get_comm_rank()) {
437 procs.push_back(r);
438 handles.push_back(remote[r]);
439 }
440 CHKERR pc->update_remote_data(e, procs, handles);
441 }
442 if (shared_copies && !target.empty()) {
443 int owner;
444 CHKERR pc->get_owner(*target.begin(), owner);
445 CHKERR require(owner == 0,
446 "Fixture cell copies did not resolve to rank zero");
447 }
448 if (ghost_source && field.get_comm_rank() && !source.empty() &&
449 !target.empty()) {
450 int source_owner, target_owner;
451 CHKERR pc->get_owner(*source.begin(), source_owner);
452 CHKERR pc->get_owner(*target.begin(), target_owner);
453 CHKERR require(source_owner == 0 &&
454 target_owner == field.get_comm_rank(),
455 "Fixture did not give a rank an owned target and ghost "
456 "source");
457 }
458 }
459 const auto source_bit = BitRefLevel().set(0);
460 const auto target_bit = BitRefLevel().set(1);
461 const auto missing_bit = BitRefLevel().set(2);
462 const auto copy_bit = BitRefLevel().set(3);
463 auto bits = field.getInterface<BitRefManager>();
464 CHKERR bits->setBitRefLevel(source_all, source_bit, false);
465 CHKERR bits->setBitRefLevel(target_all, target_bit, false);
466 CHKERR bits->setBitRefLevel(missing_all, missing_bit, false);
467 CHKERR bits->setBitRefLevel(copy_all, copy_bit, false);
468 Range target_support = target;
469 target_support.merge(missing);
470 target_support.merge(copy);
471 for (int n : {1, 3, 5, 6}) {
472 const auto source_name = "SOURCE_" + std::to_string(n);
473 const auto target_name = "TARGET_" + std::to_string(n);
474 CHKERR field.add_field(source_name, H1, AINSWORTH_LEGENDRE_BASE, n);
475 CHKERR field.add_ents_to_field_by_dim(source, D, source_name);
476 CHKERR field.set_field_order(source_all, source_name, 1);
477 CHKERR field.add_field(target_name, L2, AINSWORTH_LEGENDRE_BASE, n);
478 CHKERR field.add_ents_to_field_by_dim(target_support, D, target_name);
479 CHKERR field.set_field_order(target_support, target_name, 2);
480 CHKERR field.set_field_order(copy, target_name, 1);
481 }
482 CHKERR field.add_field("MEMORY", L2, AINSWORTH_LEGENDRE_BASE, 6);
483 Range memory_support = source;
484 memory_support.merge(target_support);
485 CHKERR field.add_ents_to_field_by_dim(memory_support, D, "MEMORY");
486 CHKERR field.set_field_order(source, "MEMORY", 0);
487 CHKERR field.set_field_order(target_support, "MEMORY", 1);
488 CHKERR field.build_fields();
489 for (int n : {1, 3, 5, 6}) {
490 CHKERR field.getInterface<FieldBlas>()->fieldLambdaOnEntities(
491 [&](boost::shared_ptr<FieldEntity> entity) {
493 if (entity->getEntType() == MBVERTEX) {
494 double x[3];
495 const auto e = entity->getEnt();
496 CHKERR mb.get_coords(&e, 1, x);
497 auto values = entity->getEntFieldData();
498 for (int c = 0; c != n; ++c)
499 values[c] = affine(x, c);
500 }
502 },
503 "SOURCE_" + std::to_string(n));
504 CHKERR field.getInterface<FieldBlas>()->setField(
505 -99., "TARGET_" + std::to_string(n));
506 }
507 CHKERR field.getInterface<FieldBlas>()->setField(-99., "MEMORY");
508 CHKERR field.getInterface<FieldBlas>()->fieldLambdaOnEntities(
509 [&](boost::shared_ptr<FieldEntity> entity) {
510 auto values = entity->getEntFieldData();
511 for (int c = 0; c != 6; ++c)
512 values[c] = 7. * (c + 1);
513 return MoFEMErrorCode(0);
514 },
515 "MEMORY", &source);
516 FieldRequest request;
517 request.source.bit = source_bit;
518 request.target.bit = target_bit | copy_bit;
519 request.options.quadratureOrder = 6;
520 for (int n : {1, 3, 5, 6})
521 request.maps.push_back(
522 {"SOURCE_" + std::to_string(n), "TARGET_" + std::to_string(n)});
523 request.maps.push_back({"MEMORY", "MEMORY"});
524 // The caller owns the element, its fields, and the parent DM.
525 const std::string app_name = "APPLICATION";
526 CHKERR field.add_finite_element(app_name);
527 std::set<std::string> projection_fields{"MEMORY"};
528 for (int n : {1, 3, 5, 6}) {
529 projection_fields.insert("SOURCE_" + std::to_string(n));
530 projection_fields.insert("TARGET_" + std::to_string(n));
531 }
532 for (const auto &name : projection_fields) {
533 CHKERR field.modify_finite_element_add_field_row(app_name, name);
534 CHKERR field.modify_finite_element_add_field_col(app_name, name);
535 CHKERR field.modify_finite_element_add_field_data(app_name, name);
536 }
537 Range all_cells = source;
538 all_cells.merge(target_support);
539 CHKERR field.add_ents_to_finite_element_by_dim(all_cells, D, app_name);
540 CHKERR field.build_finite_elements(app_name);
541 CHKERR field.build_adjacencies(all_cells);
542 CHKERR DMRegister_MoFEM("DMMOFEM");
543 auto app_dm = createDM(field.get_comm(), "DMMOFEM");
544 CHKERR DMMoFEMCreateMoFEM(app_dm, &field, app_name.c_str(),
545 source_bit | target_bit | missing_bit | copy_bit);
546 CHKERR DMMoFEMSetDestroyProblem(app_dm, PETSC_TRUE);
547 CHKERR DMMoFEMSetIsPartitioned(app_dm, PETSC_TRUE);
548 CHKERR DMMoFEMAddElement(app_dm, app_name);
549 CHKERR DMSetUp(app_dm);
550 request.dm = app_dm;
551 request.elementName = app_name;
552 auto projection = field.getInterface<Projection>();
553 auto app_solution = createDMVector(app_dm);
554 CHKERR DMoFEMMeshToLocalVector(app_dm, app_solution, INSERT_VALUES,
555 SCATTER_FORWARD);
556 auto app_before = vectorDuplicate(app_solution);
557 CHKERR VecCopy(app_solution, app_before);
558
559 const auto fe_count = field.get_finite_elements()->size();
560 const auto ent_fe_count = field.get_ents_finite_elements()->size();
561 const int build_state = core.getBuildMoFEM();
562
563 Range baseline;
564 CHKERR mb.get_entities_by_handle(0, baseline);
565 FieldResult report;
566 for (int repeat = 0; repeat != 3; ++repeat) {
567 CHKERR projection->project(request, report);
568 CHKERR require(report.missingPoints == 0, "Unexpected missing points");
569 CHKERR require(
570 report.targetElements == target.size() + copy.size(),
571 "Wrong local target count");
572 for (const auto &r : report.items)
573 CHKERR require(r.relativeMassResidual < 2.e-10,
574 "Field mass residual is too large");
575 CHKERR require(field.get_finite_elements()->size() == fe_count,
576 "Private FE definitions leaked");
577 CHKERR require(field.get_ents_finite_elements()->size() == ent_fe_count,
578 "Private entity FE records leaked");
579 CHKERR require(core.getBuildMoFEM() == build_state,
580 "Projection changed the database build state");
581 Range after;
582 CHKERR mb.get_entities_by_handle(0, after);
583 CHKERR require(after == baseline, "Private mesh entities leaked");
584 }
585 // Transfer the resulting nonconstant L2 polynomial to another mesh level.
586 auto roundtrip = request;
587 roundtrip.source.bit = target_bit;
588 roundtrip.target.bit = copy_bit;
589 for (auto &[source_name, target_name] : roundtrip.maps)
590 source_name = target_name;
591 CHKERR projection->project(roundtrip, report);
592 // Genuine source/target DOF overlap is safe because sampling precedes publication.
593 FieldRequest identity;
594 identity.dm = app_dm;
595 identity.elementName = app_name;
596 identity.source.bit = source_bit;
597 identity.target.bit = source_bit;
598 identity.options.quadratureOrder = 6;
599 identity.maps = {{"MEMORY", "MEMORY"}};
600 CHKERR projection->project(identity, report);
601 // Independently evaluate target polynomials using normal FE field operators.
602 // A NaN expectation requires a NaN value.
603 using Expected = boost::function<double(const double *, int, bool)>;
604 auto check_fields = [&](const Range &cells, BitRefLevel bit,
605 Expected expected) {
607 const std::string name = "CHECK_PROJECTION";
608 const int build_state = core.getBuildMoFEM();
609 CHKERR field.add_finite_element(name);
610 for (const auto &[source_name, target_name] : request.maps) {
611 CHKERR field.modify_finite_element_add_field_row(name, target_name);
612 CHKERR field.modify_finite_element_add_field_col(name, target_name);
613 CHKERR field.modify_finite_element_add_field_data(name, target_name);
614 }
615 CHKERR field.add_ents_to_finite_element_by_dim(cells, D, name);
616 CHKERR field.build_finite_elements(name);
617 CHKERR field.build_adjacencies(cells);
618 auto dm = createDM(field.get_comm(), "DMMOFEM");
619 CHKERR DMMoFEMCreateMoFEM(dm, &field, name.c_str(), bit);
620 CHKERR DMMoFEMSetDestroyProblem(dm, PETSC_TRUE);
621 CHKERR DMMoFEMSetIsPartitioned(dm, PETSC_TRUE);
623 CHKERR DMSetUp(dm);
624 const Problem *check_problem;
625 CHKERR DMMoFEMGetProblemPtr(dm, &check_problem);
626 auto &check_elements = *check_problem->numeredFiniteElementsPtr;
627 for (auto it = check_elements.begin(); it != check_elements.end();)
628 CHKERR require(
629 check_elements.modify(
630 it++, NumeredEntFiniteElement_change_part(field.get_comm_rank())),
631 "Could not number verification cells");
633 auto fe = boost::make_shared<Element>(field);
634 fe->getRuleHook = [](int, int, int) { return 7; };
635 auto add_check = [&]<int N>(std::string target_name, bool constant) {
636 auto values = boost::make_shared<MatrixDouble>();
637 fe->getOpPtrVector().push_back(
638 new OpCalculateVectorFieldValues<N>(target_name, values));
639 auto check = new UDO(NOSPACE, UDO::OPSPACE);
640 check->doWorkRhsHook = [values, constant, expected](
641 DataOperator *base, int, EntityType,
642 EntData &) {
644 auto op = static_cast<UDO *>(base);
645 const auto &coords = op->getCoordsAtGaussPts();
646 for (size_t q = 0; q != coords.size1(); ++q)
647 for (int c = 0; c != N; ++c)
648 CHKERR requireValue((*values)(q, c),
649 expected(&coords(q, 0), c, constant),
650 "Projected field differs from analytical "
651 "values");
653 };
654 fe->getOpPtrVector().push_back(check);
655 };
656 add_check.template operator()<1>("TARGET_1", false);
657 add_check.template operator()<3>("TARGET_3", false);
658 add_check.template operator()<5>("TARGET_5", false);
659 add_check.template operator()<6>("TARGET_6", false);
660 add_check.template operator()<6>("MEMORY", true);
662 fe.reset();
663 dm.reset();
664 CHKERR field.delete_finite_element(name);
665 core.getBuildMoFEM() = build_state;
667 };
668 const Expected analytical = [](const double *x, int c, bool constant) {
669 return constant ? 7. * (c + 1) : affine(x, c);
670 };
671 Range checked = target;
672 checked.merge(copy);
673 CHKERR check_fields(checked, target_bit | copy_bit, analytical);
674 auto reject = [&](FieldRequest bad) {
676 CHKERR PetscPushErrorHandler(PetscReturnErrorHandler, nullptr);
677 const auto error = projection->project(bad, report);
678 CHKERR PetscPopErrorHandler();
679 CHKERR require(error != 0, "Invalid projection request was accepted");
680 CHKERR require(field.get_ents_finite_elements()->size() == ent_fe_count,
681 "Private entity FE records leaked");
682 Range after;
683 CHKERR mb.get_entities_by_handle(0, after);
684 CHKERR require(after == baseline,
685 "Failed projection leaked private entities");
687 };
688 auto bad = request;
689 bad.options.quadratureOrder = -1;
690 CHKERR reject(bad);
691 bad = request;
692 bad.maps[0].first = "DOES_NOT_EXIST";
693 CHKERR reject(bad);
694 bad = request;
695 bad.maps.push_back(bad.maps[0]);
696 CHKERR reject(bad);
697 bad = request;
698 bad.maps[0].second = "SOURCE_1";
699 CHKERR reject(bad);
700 bad = request;
701 bad.source.bit.reset();
702 CHKERR reject(bad);
703 bad = request;
704 bad.maps.clear();
705 CHKERR reject(bad);
706 bad = request;
707 bad.maps.resize(1);
708 bad.maps[0].second = "TARGET_3";
709 CHKERR reject(bad);
710 // The original source coefficients and unrelated target mesh remain intact.
711 for (int n : {1, 3, 5, 6})
713 [&](boost::shared_ptr<FieldEntity> entity) {
715 if (entity->getEntType() == MBVERTEX) {
716 double x[3];
717 const auto e = entity->getEnt();
718 CHKERR mb.get_coords(&e, 1, x);
719 const auto values = entity->getEntFieldData();
720 for (int c = 0; c != n; ++c)
721 CHKERR require(values[c] == affine(x, c),
722 "Source coefficients changed");
723 }
725 },
726 "SOURCE_" + std::to_string(n));
727 // Failed requests must not write any field, including a later field map.
728 for (const auto &[source_name, target_name] : request.maps)
729 CHKERR field.getInterface<FieldBlas>()->fieldLambdaOnEntities(
730 [&](boost::shared_ptr<FieldEntity> entity) {
732 for (double value : entity->getEntFieldData())
733 CHKERR require(value == -99.,
734 "Failed projection modified target data");
736 },
737 target_name, &missing);
738 // Uncovered points take the empty value; covered cells are unaffected.
739 for (double empty : {.25, std::numeric_limits<double>::quiet_NaN()}) {
740 auto partial = request;
741 partial.target.bit = target_bit | missing_bit;
742 partial.options.emptyValue = empty;
743 CHKERR projection->project(partial, report);
744 if (active)
745 CHKERR require(report.missingPoints > 0 &&
746 report.missingPoints < report.sampledPoints,
747 "Uncovered points were not counted");
748 else
749 CHKERR require(report.sampledPoints == 0 && report.items.empty(),
750 "Empty rank returned a nonlocal report");
751 CHKERR check_fields(target, target_bit, analytical);
752 CHKERR check_fields(missing, missing_bit,
753 [empty](const double *, int, bool) { return empty; });
754 }
755 if (field.get_comm_size() > 1) {
756 auto differing_options = request;
757 if (field.get_comm_rank()) {
758 differing_options.options.quadratureOrder = 10;
759 differing_options.options.emptyValue = 1.;
760 }
761 CHKERR projection->project(differing_options, report);
762 CHKERR check_fields(target, target_bit, analytical);
763 CHKERR projection->project(request, report);
764 CHKERR check_fields(target, target_bit, analytical);
765 }
766 PetscBool app_unchanged;
767 CHKERR VecEqual(app_solution, app_before, &app_unchanged);
768 CHKERR require(app_unchanged, "Application vector changed during projection");
769 CHKERR require(field.check_finite_element(app_name) &&
770 field.check_problem(app_name),
771 "Application FE/problem was removed");
772 app_before.reset();
773 app_solution.reset();
774 const int tag_build_state = core.getBuildMoFEM();
775 const std::string tag_element = "TAG_PROJECTION";
776 CHKERR field.add_finite_element(tag_element);
777 CHKERR field.add_ents_to_finite_element_by_dim(all_cells, D, tag_element);
778 CHKERR field.build_finite_elements(tag_element);
779 CHKERR field.build_adjacencies(all_cells);
780 auto tag_dm = createDM(field.get_comm(), "DMMOFEM");
781 CHKERR DMMoFEMCreateMoFEM(tag_dm, &field, tag_element.c_str(),
782 source_bit | target_bit | missing_bit | copy_bit);
783 CHKERR DMMoFEMSetDestroyProblem(tag_dm, PETSC_TRUE);
784 CHKERR DMMoFEMSetIsPartitioned(tag_dm, PETSC_TRUE);
785 CHKERR DMMoFEMAddElement(tag_dm, tag_element);
786 CHKERR DMSetUp(tag_dm);
787 CHKERR checkTags<D>(core, mb, tag_dm, tag_element, source, target, copy,
788 source_bit, target_bit, copy_bit);
789 tag_dm.reset();
790 CHKERR field.delete_finite_element(tag_element);
791 core.getBuildMoFEM() = tag_build_state;
792 auto source_only = request;
793 source_only.target.bit = BitRefLevel().set(4);
794 // A rank can carry target-level closure entities without a target cell.
795 if (!source.empty()) {
796 const auto edges = source_all.subset_by_dimension(1);
797 Range closure_only;
798 closure_only.insert(*edges.begin());
799 CHKERR bits->setBitRefLevel(closure_only, source_only.target.bit, false);
800 }
801 CHKERR projection->project(source_only, report);
802 CHKERR require(report.targetElements == 0 && report.items.empty(),
803 "Empty target returned field results");
804 TagRequest source_only_tags;
805 source_only_tags.dm = app_dm;
806 source_only_tags.elementName = app_name;
807 source_only_tags.source.bit = source_bit;
808 source_only_tags.target.bit = source_only.target.bit;
809 source_only_tags.options.quadratureOrder = 6;
810 source_only_tags.options.sourceRule = standardRule(4);
811 source_only_tags.options.targetRule = standardRule(3);
812 source_only_tags.maps = {{{"TAG_1", "TAG_1_OUT"}}, 1};
813 TagResult source_only_report;
814 CHKERR projection->project(source_only_tags, source_only_report);
815 CHKERR require(source_only_report.targetElements == 0 &&
816 source_only_report.items.empty(),
817 "Empty target returned tag results");
818 auto no_source = request;
819 no_source.source.bit = source_only.target.bit;
820 no_source.options.emptyValue = .25;
821 CHKERR projection->project(no_source, report);
822 if (active)
823 CHKERR require(report.sampledPoints > 0 &&
824 report.missingPoints == report.sampledPoints,
825 "Empty source did not mark every target point missing");
826 CHKERR check_fields(target, target_bit,
827 [](const double *, int, bool) { return .25; });
828 app_dm.reset();
829 CHKERR field.delete_finite_element(app_name);
830 CHKERR MPI_Barrier(field.get_comm());
831 MOFEM_LOG("WORLD", Sev::inform)
832 << "DG projection interface " << D << "D, empty ranks=" << empty_ranks
833 << ", shared copies=" << shared_copies
834 << ", ghost source=" << ghost_source << ": PASS";
836}
837} // namespace
838
839int main(int argc, char **argv) {
840 MoFEM::Core::Initialize(&argc, &argv, nullptr,
841 "DGProjectionInterface atom tests");
842 try {
843 CHKERR runCase<2>(false);
844 CHKERR runCase<3>(false);
845 CHKERR runCase<2>(true);
846 CHKERR runCase<3>(true);
847 CHKERR runCase<2>(false, true);
848 CHKERR runCase<3>(false, true);
849 CHKERR runCase<2>(false, false, true);
850 CHKERR runCase<3>(false, false, true);
851 }
854 return 0;
855}
CGALInterfaceImpl & owner
Report & report
std::vector< int > created
std::vector< int > source
std::vector< int > size
double length
WorkMesh base
std::vector< int > vertices
bool fixed
bool closure
The face (f0, f1, w) closes a corner at f0 or f1.
std::vector< Cell > cells
bool active
moab::Interface & mb
int components
Inferred from the source tag length.
const Field * target
ProjectedField & field
std::vector< double > empty
One value per component.
std::string type
It it
Definition Schur.cpp:2568
SmartPetscObj< Vec > work
SmartPetscObj< Vec > values
boost::shared_ptr< ConstrainMatrixCtx > projection
std::string name
int main()
@ QUIET
#define CATCH_ERRORS
Catch errors.
@ MF_EXCL
@ AINSWORTH_LEGENDRE_BASE
Ainsworth Cole (Legendre) approx. base .
Definition definitions.h:60
@ L2
field with C-1 continuity
Definition definitions.h:88
@ H1
continuous field
Definition definitions.h:85
@ NOSPACE
Definition definitions.h:83
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
#define CHK_MOAB_THROW(err, msg)
Check error code of MoAB function and throw MoFEM exception.
@ MOFEM_ATOM_TEST_INVALID
Definition definitions.h:40
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define CHKERR
Inline error check.
constexpr int order
PetscErrorCode DMMoFEMSetIsPartitioned(DM dm, PetscBool is_partitioned)
Definition DMMoFEM.cpp:1199
PetscErrorCode DMMoFEMAddElement(DM dm, std::string fe_name)
add element to dm
Definition DMMoFEM.cpp:574
PetscErrorCode DMMoFEMCreateMoFEM(DM dm, MoFEM::Interface *m_field_ptr, const char problem_name[], const MoFEM::BitRefLevel bit_level, const MoFEM::BitRefLevel bit_mask=MoFEM::BitRefLevel().set())
Must be called by user to set MoFEM data structures.
Definition DMMoFEM.cpp:143
PetscErrorCode DMMoFEMGetProblemPtr(DM dm, const MoFEM::Problem **problem_ptr)
Get pointer to problem data structure.
Definition DMMoFEM.cpp:451
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 DMRegister_MoFEM(const char sname[])
Register MoFEM problem.
Definition DMMoFEM.cpp:43
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 createDMVector(DM dm, RowColData rc=RowColData::COL)
Get smart vector from DM.
Definition DMMoFEM.hpp:1279
MoFEMErrorCode setBitRefLevel(const Range &ents, const BitRefLevel bit, const bool only_tets=true, int verb=0, Range *adj_ents_ptr=nullptr) const
Add entities to database and set bit ref level.
#define MOFEM_LOG(channel, severity)
Log.
MoFEMErrorCode buildProblem(const std::string name, const bool square_matrix, int verb=VERBOSE)
build problem data structures
auto bit
set bit
const double c
speed of light (cm/ns)
double D
const double v
phase velocity of light in medium (cm/ns)
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
std::bitset< BITREFLEVEL_SIZE > BitRefLevel
Bit structure attached to each entity identifying to what mesh entity is attached.
Definition Types.hpp:40
implementation of Data Operators for Forces and Sources
Definition Common.hpp:10
PetscErrorCode DMMoFEMSetDestroyProblem(DM dm, PetscBool destroy_problem)
Definition DMMoFEM.cpp:463
SmartPetscObj< Vec > vectorDuplicate(Vec vec)
Create duplicate vector of smart vector.
auto createDM(MPI_Comm comm, const std::string dm_type_name)
Creates smart DM object.
float offset
Definition sdf_python.py:3
int r
Definition sdf.py:205
double scale
Definition plastic.cpp:124
double q
const int N
Definition speed_test.cpp:3
Managing BitRefLevels.
Core (interface) class.
Definition Core.hpp:83
static MoFEMErrorCode Initialize(int *argc, char ***args, const char file[], const char help[])
Initializes the MoFEM database PETSc, MOAB and MPI.
Definition Core.cpp:68
int & getBuildMoFEM() const
Get flags/semaphores for different stages.
Definition Core.hpp:230
static MoFEMErrorCode Finalize()
Checks for options to be called at the conclusion of the program.
Definition Core.cpp:123
base operator to do operations at Gauss Pt. level
Deprecated interface functions.
Data on single entity (This is passed as argument to DataOperator::doWork)
Basic algebra on fields.
Definition FieldBlas.hpp:21
MoFEMErrorCode fieldLambdaOnEntities(OneFieldFunctionOnEntities lambda, const std::string field_name, Range *ents_ptr=nullptr)
field lambda
Definition FieldBlas.cpp:50
Struct keeps handle to entity in the field.
structure to get information from mofem into EntitiesFieldData
MatrixDouble gaussPts
Matrix of integration points.
boost::ptr_deque< UserDataOperator > & getOpPtrVector()
Use to push back operator for row operator.
GaussHookFun setRuleHook
Set function to calculate integration rule.
RuleHookFun getRuleHook
Hook to get rule.
Specialization for MatrixDouble vector field values calculation.
Template struct for dimension-specific finite element types.
keeps basic data about problem
boost::shared_ptr< NumeredEntFiniteElement_multiIndex > numeredFiniteElementsPtr
store finite elements
Problem manager is used to build and partition problems.
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.