16using Projection = DGProjectionInterface;
17using UDO = ForcesAndSourcesCore::UserDataOperator;
18using EntData = EntitiesFieldData::EntData;
19using FieldRequest = Projection::Request<Projection::FieldMap>;
20using FieldResult = Projection::Report<Projection::FieldReport>;
21using TagRequest = Projection::Request<Projection::TagMap>;
22using TagResult = Projection::Report<Projection::TagReport>;
33struct ProjectedField {
38 boost::make_shared<MatrixDouble>();
59 boost::make_shared<MatrixDouble>();
66 std::map<EntityHandle, std::vector<double>>
staged;
67 std::map<EntityHandle, std::pair<bool, std::vector<double>>>
previous;
73bool sourceTagData(moab::Interface &
mb,
Tag tag, EntityHandle ent,
74 const double *def,
int def_size,
size_t expected,
75 const double *&data,
int &
size) {
78 if (
mb.tag_get_by_ptr(
tag, &ent, 1, (
const void **)&data, &
size) !=
82 const bool is_default =
83 def && (data == def ||
84 (
static_cast<size_t>(
size) != expected &&
size == def_size &&
85 std::equal(data, data +
size, def, [](
double a,
double b) {
86 return a == b || (std::isnan(
a) && std::isnan(b));
92 return std::all_of(
values.data().begin(),
values.data().end(),
93 [](
double value) { return std::isfinite(value); });
102 const auto weights = gauss_pts.size1() - 1;
103 for (
size_t q = 0;
q != weighted.size1(); ++
q)
104 for (
size_t c = 0;
c != weighted.size2(); ++
c)
105 weighted(
q,
c) *= gauss_pts(weights,
q);
108 for (
size_t i = 0;
i != lower.size1(); ++
i)
109 for (
size_t j =
i + 1;
j != lower.size2(); ++
j)
113 return static_cast<double>(norm_frobenius(
residual)) /
114 std::max(
static_cast<double>(norm_frobenius(rhs)),
115 std::numeric_limits<double>::min());
119struct OpElementMass : OpBaseDerivativesBase {
122 OpElementMass(
Interface &m_field, ProjectedField &
f,
123 boost::shared_ptr<MatrixDouble> mass,
124 boost::shared_ptr<EntitiesFieldData> basis)
125 : OpBaseDerivativesBase(mass, basis,
f.
target->getApproxBase(),
L2),
131 field.target->getBitNumber(), getFEEntityHandle());
132 const auto it = entities.find(uid);
133 if (
it == entities.end())
135 "Target field entity is missing");
137 CHKERR calculateBase([&]() {
return field.targetEntity->getMaxOrder(); });
145struct OpReconstructionMass : OpBaseDerivativesBase {
148 boost::shared_ptr<MatrixDouble> mass,
149 boost::shared_ptr<EntitiesFieldData> basis)
154 auto &ent_data = dataL2->dataOnEntities[getFEType()][0];
155 const auto &
n = ent_data.getN(
base);
156 auto &mass = *baseMassPtr;
157 const auto nb =
n.size2();
158 mass.resize(
nb,
nb,
false);
160 auto t_w = getFTensor0IntegrationWeight();
161 auto t_row_base = ent_data.getFTensor0N();
162 for (
size_t gg = 0; gg !=
n.size1(); ++gg) {
163 const double alpha = t_w;
164 for (
size_t rr = 0; rr !=
nb; ++rr) {
165 auto a_mat_ptr = &mass(rr, 0);
166 auto t_col_base = ent_data.getFTensor0N(gg, 0);
167 for (
size_t cc = 0; cc <= rr; ++cc) {
168 *a_mat_ptr += alpha * (t_row_base * t_col_base);
179 for (
size_t i = 0;
i !=
nb && !singular; ++
i)
180 largest = std::max(largest, mass(
i,
i));
181 for (
size_t i = 0;
i !=
nb && !singular; ++
i)
182 singular = !std::isfinite(mass(
i,
i)) || !(mass(
i,
i) > 1.e-6 * largest);
185 "Source integration rule cannot determine the order-%d tag "
193struct OpTagBasis : OpBaseDerivativesBase {
195 OpTagBasis(
int o, boost::shared_ptr<EntitiesFieldData> basis)
196 : OpBaseDerivativesBase(boost::make_shared<
MatrixDouble>(), basis,
206template <
typename FE>
207MoFEMErrorCode loopSelectedCells(DM dm,
const std::string &element,
208 const boost::shared_ptr<FE> &fe,
211 return cells.find(method->numeredEntFiniteElementPtr->getEnt()) !=
218struct DGProjectionInterfaceImpl final : DGProjectionInterface {
222 explicit DGProjectionInterfaceImpl(
const Core &core)
225 UnknownInterface **iface)
const override {
226 *iface =
const_cast<DGProjectionInterfaceImpl *
>(
this);
233 const auto error =
work();
235 SETERRQ(PETSC_COMM_SELF, error,
"DG projection: %s failed",
name);
239 MoFEMErrorCode project(
const FieldRequest &, FieldResult &)
override;
244 const int build_state =
mCore.getBuildMoFEM();
245 const auto error =
work();
246 mCore.getBuildMoFEM() = build_state;
254 const std::vector<SamplePolicy> &,
257 const std::vector<SamplePolicy> &,
Range &,
Range &,
258 std::vector<ProjectedField> &,
int &);
259 MoFEMErrorCode createSubDM(DM,
const std::string &,
const MeshLevel &,
260 const MeshLevel &,
const std::string &,
261 SmartPetscObj<DM> &);
264 const std::string &,
const Range &,
265 std::vector<ProjectedField> &,
bool, FieldResult &);
266 MoFEMErrorCode validateTags(
const TagRequest &, std::vector<ProjectedTag> &);
269 const std::vector<ProjectedTag> &,
273 std::vector<ProjectedTag> &);
277 std::vector<ProjectedTag> &);
279 MoFEMErrorCode projectTagsImpl(
const TagRequest &, DM,
const std::string &,
281 std::vector<ProjectedTag> &,
bool,
285 std::vector<ProjectedTag> &);
304 const MeshLevel &source_level,
const MeshLevel &target_level,
Range &
source,
309 CHKERR phase(
"mesh selection", [&]() {
311 for (
const auto *level : {&source_level, &target_level})
312 if (!level->bit.any() || (level->bit & level->mask) != level->bit)
314 "Invalid mesh selectors");
316 source_level.bit, source_level.mask,
source);
318 target_level.bit, target_level.mask,
target);
324 dimension = target_dim;
338 const FieldRequest &request,
const std::vector<SamplePolicy> &policies,
343 CHKERR phase(
"request validation", [&]() {
345 if (request.maps.empty() || policies.size() != request.maps.size())
347 "Invalid field maps");
348 if (request.options.quadratureOrder < 0)
350 "DG projection requires a caller-supplied quadrature order");
351 std::set<std::string> destinations;
352 for (
size_t m = 0;
m != request.maps.size(); ++
m) {
353 const auto &[source_name, target_name] = request.maps[
m];
354 if (source_name.empty() || target_name.empty() ||
355 !destinations.insert(target_name).second ||
358 "Missing field or duplicate projection destination");
359 ProjectedField
field;
362 field.policy = policies[
m];
364 if ((
field.source->getSpace() !=
H1 &&
field.source->getSpace() !=
L2) ||
365 field.target->getSpace() !=
L2)
367 "DG projection supports H1/L2 sources and L2 targets");
370 "Source/target component counts differ");
371 if (components < 1 || components > 9)
373 "DG projection supports 1 through 9 components");
376 "Empty value does not match the component count");
377 fields.push_back(std::move(
field));
387 const MeshLevel &
target,
const std::string &element,
388 SmartPetscObj<DM> &subdm) {
400 const Problem *problem;
402 auto &elements = *problem->numeredFiniteElementsPtr;
403 for (
auto it = elements.begin();
it != elements.end();) {
404 if (!elements.modify(
407 "Could not assign local projection FE ownership");
416 boost::shared_ptr<MatrixDouble>
values) {
418 return new OpCalculateVectorFieldValues<N>(
name,
values,
419 SmartPetscObj<Vec>());
426template <
typename FE>
427void installRule(FE &fe,
const Projection::IntegrationRule &rule) {
428 if (rule.setRuleHook) {
429 fe.getRuleHook = [](
int,
int,
int) {
return -1; };
430 fe.setRuleHook = rule.setRuleHook;
432 fe.getRuleHook = rule.ruleHook;
439 const FieldRequest &request, DM projection_dm,
440 const std::string &problem_name,
const Range &target_cells,
441 std::vector<ProjectedField> &fields,
bool has_source, FieldResult &
report) {
443 using Element =
typename PipelineManager::ElementsAndOpsByDim<D>::DomainEle;
445 auto target_fe = boost::make_shared<Element>(
mField);
446 target_fe->getRuleHook =
448 auto collect =
new UDO(
NOSPACE, UDO::OPSPACE);
449 collect->doWorkRhsHook = [&](DataOperator *
base,
int, EntityType,
EntData &) {
451 auto op =
static_cast<UDO *
>(
base);
452 const auto &coords = op->getCoordsAtGaussPts();
453 points.offsets.emplace(op->getFEEntityHandle(),
points.coordinates.size());
454 for (
size_t gg = 0; gg != coords.size1(); ++gg)
455 points.coordinates.push_back(
456 {coords(gg, 0), coords(gg, 1), coords(gg, 2)});
459 target_fe->getOpPtrVector().push_back(collect);
460 CHKERR phase(
"target quadrature", [&]() {
461 return loopSelectedCells(projection_dm, request.elementName, target_fe,
467 auto search = evaluator->getData<
Element>();
468 auto located_coordinates = boost::make_shared<MatrixDouble>();
469 double source_scale = 0.;
470 auto cache = boost::make_shared<CacheTuple>();
472 const bool search_source = has_source && !
points.coordinates.empty();
473 CHKERR phase(
"source search", [&]() {
477 CHKERR evaluator->buildTree<
D>(search, request.elementName, request.source.bit,
478 request.source.mask);
479 double lower[3], upper[3];
481 CHKERR search->treePtr->get_info(search->rooTreeSet, lower, upper, depth);
482 for (
int d = 0;
d != 3; ++
d)
483 source_scale = std::hypot(source_scale, upper[
d] - lower[
d]);
485 search->feMethodPtr->getRuleHook = [](
int,
int,
int) {
return -1; };
486 auto locate_check =
new UDO(
NOSPACE, UDO::OPSPACE);
487 locate_check->doWorkRhsHook = [located_coordinates](DataOperator *
base,
int,
489 *located_coordinates =
static_cast<UDO *
>(
base)->getCoordsAtGaussPts();
492 search->feMethodPtr->getOpPtrVector().push_back(locate_check);
493 for (
auto &
field : fields) {
495 field.source->getNbOfCoeffs(),
false);
496 search->feMethodPtr->getOpPtrVector().push_back(
497 valuesOperator(
field.source->getNbOfCoeffs(),
field.source->getName(),
498 field.sourceValues));
502 unsigned long long missing = 0;
503 CHKERR phase(
"source sampling", [&]() {
505 std::vector<char> sampled(
points.coordinates.size(),
false);
506 for (
size_t q = 0;
q !=
points.coordinates.size(); ++
q) {
507 for (
auto &
field : fields)
508 for (size_t
c = 0;
c !=
field.samples.size2(); ++
c)
512 CHKERR evaluator->evalFEAtPoints<
D>(
513 points.coordinates, 1.e-10, problem_name, request.elementName,
515 request.source.mask, cache,
516 [&](
const std::vector<size_t> &indices) {
518 if (located_coordinates->size1() != indices.size() ||
519 located_coordinates->size2() != 3)
521 "Invalid located-point coordinates");
522 for (
size_t row = 0;
row != indices.size(); ++
row) {
523 const auto q = indices[
row];
524 const auto &x =
points.coordinates[
q];
525 const moab::CartVect
back(&(*located_coordinates)(
row, 0));
526 const moab::CartVect query(x.data());
527 double coordinate_scale = 0.;
528 for (
double value : x)
529 coordinate_scale =
std::max(coordinate_scale,
std::abs(value));
530 const double physical_tolerance = std::max(
531 1.e-10 * source_scale,
532 64 * std::numeric_limits<double>::epsilon() *
534 if (!std::isfinite((
back - query).
length()) ||
537 for (
auto &
field : fields) {
539 if (
values.size1() != indices.size() ||
542 "Inconsistent source sample layout");
543 for (
size_t c = 0;
c !=
values.size2(); ++
c) {
544 if (
field.policy.finiteSource &&
547 "Nonfinite source field value");
556 for (
auto valid : sampled)
561 report.missingPoints = missing;
562 target_fe->getOpPtrVector().clear();
563 for (
auto &
field : fields) {
564 auto mass = boost::make_shared<MatrixDouble>();
565 auto basis = boost::make_shared<EntitiesFieldData>(MBENTITYSET);
566 auto values = boost::make_shared<MatrixDouble>();
567 auto coefficients = boost::make_shared<MatrixDouble>();
568 auto load =
new UDO(
NOSPACE, UDO::OPSPACE);
572 auto op =
static_cast<UDO *
>(
base);
573 const auto offset =
points.offsets.at(op->getFEEntityHandle());
574 const auto count = op->getGaussPts().size2();
575 values->resize(count,
field.samples.size2(),
false);
576 for (
size_t q = 0;
q != count; ++
q)
577 for (
size_t c = 0;
c !=
values->size2(); ++
c)
581 target_fe->getOpPtrVector().push_back(load);
582 target_fe->getOpPtrVector().push_back(
584 target_fe->getOpPtrVector().push_back(
new OpDGProjectionCoefficients(
585 values, coefficients, mass, basis,
field.target->getApproxBase(),
L2));
586 auto store =
new UDO(
NOSPACE, UDO::OPSPACE);
587 store->doWorkRhsHook = [&
field,
values, coefficients, mass, basis](
590 auto op =
static_cast<UDO *
>(
base);
591 auto destination =
field.targetEntity->getEntFieldData();
592 if (coefficients->data().size() != destination.size())
594 "Target coefficient layout mismatch");
595 if (allFinite(*
values) && allFinite(*coefficients)) {
596 const auto &
n = basis->dataOnEntities[op->getFEType()][0].getN(
597 field.target->getApproxBase());
599 std::max(
field.residual, massSolveResidual(
n, op->getGaussPts(),
603 std::copy(coefficients->data().begin(), coefficients->data().end(),
604 destination.begin());
607 target_fe->getOpPtrVector().push_back(store);
609 CHKERR phase(
"local projection", [&]() {
610 return loopSelectedCells(projection_dm, request.elementName, target_fe,
613 for (
const auto &
field : fields)
620DGProjectionInterfaceImpl::transferFields(
const FieldRequest &request,
621 const std::vector<SamplePolicy> &policies,
626 std::vector<ProjectedField> fields;
629 if (!request.dm || request.elementName.empty() ||
632 "Projection requires a MoFEM DM and existing finite element");
633 std::string problem_name;
634 CHKERR reserveProblemName(problem_name);
635 SmartPetscObj<DM> projection_dm;
636 CHKERR createSubDM(request.dm, problem_name, request.source, request.target,
637 request.elementName, projection_dm);
640 CHKERR projectImpl<2>(request, projection_dm, problem_name,
target,
643 CHKERR projectImpl<3>(request, projection_dm, problem_name,
target,
649MoFEMErrorCode DGProjectionInterfaceImpl::project(
const FieldRequest &request,
652 std::vector<SamplePolicy> policies;
653 for (
const auto &[source_name, target_name] : request.maps) {
658 request.options.emptyValue);
659 policies.push_back(
policy);
661 CHKERR preservingBuildState(
662 [&]() {
return transferFields(request, policies,
report); });
668DGProjectionInterfaceImpl::validateTags(
const TagRequest &request,
669 std::vector<ProjectedTag> &tags) {
672 CHKERR phase(
"tag request validation", [&]() {
674 const auto has_rule = [](
const IntegrationRule &rule) {
675 return static_cast<bool>(rule.ruleHook) ||
676 static_cast<bool>(rule.setRuleHook);
678 const auto &[pairs,
order] = request.maps;
679 if (pairs.empty() || request.options.quadratureOrder < 0)
681 "Tag projection requires maps and a quadrature order");
684 "Negative tag projection order");
685 if (!has_rule(request.options.sourceRule) ||
686 !has_rule(request.options.targetRule))
688 "Tag projection requires source and target integration rules");
690 const auto describe = [&](
Tag tag) {
694 if (
type != MB_TYPE_DOUBLE)
696 "Projected tags must hold doubles");
699 std::set<std::string> destinations;
700 for (
const auto &[source_name, target_name] : pairs) {
701 if (source_name.empty() || target_name.empty() ||
702 !destinations.insert(target_name).second)
704 "Missing tag name or duplicate projection destination");
706 tag.sourceName = source_name;
707 tag.targetName = target_name;
709 if (
mb.tag_get_handle(source_name.c_str(),
tag.source) != MB_SUCCESS)
711 source_name.c_str());
713 const bool target_exists =
714 mb.tag_get_handle(target_name.c_str(),
tag.target) == MB_SUCCESS;
719 tags.push_back(std::move(
tag));
731 const TagRequest &request, DM projection_dm,
const Range &source_cells,
732 const std::vector<ProjectedTag> &tags, std::vector<int> &local) {
734 using Element =
typename PipelineManager::ElementsAndOpsByDim<D>::DomainEle;
736 std::vector<const double *> defaults(tags.size(),
nullptr);
737 std::vector<int> default_sizes(tags.size(), 0);
738 std::vector<int> fixed_lengths(tags.size(), -1);
739 for (
size_t t = 0;
t != tags.size(); ++
t) {
741 if (
mb.tag_get_length(tags[
t].source,
length) != MB_VARIABLE_DATA_LENGTH)
743 const void *def =
nullptr;
744 if (
mb.tag_get_default_value(tags[
t].source, def, default_sizes[
t]) ==
746 defaults[
t] =
static_cast<const double *
>(def);
748 auto fe = boost::make_shared<Element>(
mField);
749 installRule(*fe, request.options.sourceRule);
750 auto count =
new UDO(
NOSPACE, UDO::OPSPACE);
751 count->doWorkRhsHook = [&](DataOperator *
base,
int, EntityType,
EntData &) {
752 auto op =
static_cast<UDO *
>(
base);
753 const auto ent = op->getFEEntityHandle();
754 const int points = op->getGaussPts().size2();
755 for (
size_t t = 0;
t != tags.size(); ++
t) {
756 const double *data =
nullptr;
757 int size = fixed_lengths[
t];
760 default_sizes[
t], 0, data,
size)))
767 fe->getOpPtrVector().push_back(count);
768 CHKERR loopSelectedCells(projection_dm, request.elementName, fe,
778 const TagRequest &request, DM projection_dm,
const Range &source_cells,
779 const Range &target_cells,
int dimension, std::vector<ProjectedTag> &tags) {
782 const auto n = tags.size();
783 std::vector<int> local(
n, 0);
784 const auto error = phase(
"tag component inference", [&]() {
786 return localTagComponents<2>(request, projection_dm, source_cells, tags,
789 return localTagComponents<3>(request, projection_dm, source_cells, tags,
797 constexpr int no_data = std::numeric_limits<int>::min();
798 std::vector<int> send(2 *
n + 1), global(2 *
n + 1);
799 for (
size_t t = 0;
t !=
n; ++
t) {
801 send[
n +
t] = local[
t] ? -local[
t] : no_data;
803 send[2 *
n] = !target_cells.empty();
805 CHKERR PetscObjectGetComm((PetscObject)projection_dm, &
comm);
806 CHKERR MPI_Allreduce(send.data(), global.data(), send.size(), MPI_INT,
811 for (
size_t t = 0;
t !=
n; ++
t) {
813 if (global[
n +
t] == no_data) {
814 const void *def =
nullptr;
816 if (
mb.tag_get_default_value(
tag.source, def, def_size) != MB_SUCCESS ||
819 "Tag %s has no source data and no default value; its "
820 "components cannot be inferred",
821 tag.sourceName.c_str());
822 tag.components = def_size;
824 const int lowest = -global[
n +
t];
827 "Tag component inference failed on another rank");
828 if (lowest < 0 || lowest != global[
t])
830 "Tag %s lengths are not one multiple of the source rule "
831 "points on every element",
832 tag.sourceName.c_str());
833 tag.components = lowest;
835 if (
tag.components < 1 ||
tag.components > 9)
837 "Tag %s has %d components; tag projection supports 1 through 9",
838 tag.sourceName.c_str(),
tag.components);
846 const TagRequest &request, DM projection_dm,
const Range &source_cells,
847 std::vector<ProjectedTag> &tags) {
849 using Element =
typename PipelineManager::ElementsAndOpsByDim<D>::DomainEle;
851 auto fe = boost::make_shared<Element>(
mField);
852 installRule(*fe, request.options.sourceRule);
853 for (
auto &
tag : tags) {
855 auto values = boost::make_shared<MatrixDouble>();
856 auto coefficients = boost::make_shared<MatrixDouble>();
857 auto mass = boost::make_shared<MatrixDouble>();
858 auto basis = boost::make_shared<EntitiesFieldData>(MBENTITYSET);
860 const void *def =
nullptr;
862 if (
mb.tag_get_default_value(
tag.source, def, def_size) != MB_SUCCESS)
864 auto read =
new UDO(
NOSPACE, UDO::OPSPACE);
866 def_size](DataOperator *
base,
int, EntityType,
869 auto op =
static_cast<UDO *
>(
base);
870 const auto ent = op->getFEEntityHandle();
871 const auto points = op->getGaussPts().size2();
873 const double *data =
nullptr;
875 if (!sourceTagData(
mb,
tag.source, ent,
static_cast<const double *
>(def),
885 "Tag %s holds %d values; the source rule has %zu points of "
888 std::copy(data, data +
size,
values->data().begin());
889 if (
tag.policy.finiteSource && !allFinite(*
values))
891 tag.sourceName.c_str());
894 fe->getOpPtrVector().push_back(read);
895 fe->getOpPtrVector().push_back(
896 new OpReconstructionMass(
tag.order, tagBase, mass, basis));
897 fe->getOpPtrVector().push_back(
new OpDGProjectionCoefficients(
899 auto store =
new UDO(
NOSPACE, UDO::OPSPACE);
900 store->doWorkRhsHook = [&
tag,
values, coefficients, mass,
901 basis](DataOperator *
base,
int, EntityType,
904 auto op =
static_cast<UDO *
>(
base);
905 tag.sourceCoefficients[op->getFEEntityHandle()] = *coefficients;
908 if (!allFinite(*coefficients))
910 "Nonfinite tag reconstruction coefficient");
912 basis->dataOnEntities[op->getFEType()][0].getN(tagBase);
914 std::max(
tag.sourceResidual,
915 massSolveResidual(
n, op->getGaussPts(), *
values, *mass,
919 fe->getOpPtrVector().push_back(store);
921 CHKERR phase(
"tag reconstruction", [&]() {
922 return loopSelectedCells(projection_dm, request.elementName, fe,
931 const TagRequest &request, DM projection_dm,
const std::string &problem_name,
932 const Range &target_cells, std::vector<ProjectedTag> &tags,
933 bool has_source, TagResult &
report) {
935 using Element =
typename PipelineManager::ElementsAndOpsByDim<D>::DomainEle;
937 auto target_fe = boost::make_shared<Element>(
mField);
938 target_fe->getRuleHook =
940 auto collect =
new UDO(
NOSPACE, UDO::OPSPACE);
941 collect->doWorkRhsHook = [&
points](DataOperator *
base,
int, EntityType,
944 auto op =
static_cast<UDO *
>(
base);
945 const auto &coords = op->getCoordsAtGaussPts();
946 points.offsets.emplace(op->getFEEntityHandle(),
points.coordinates.size());
947 for (
size_t q = 0;
q != coords.size1(); ++
q)
948 points.coordinates.push_back(
949 {coords(
q, 0), coords(
q, 1), coords(
q, 2)});
952 target_fe->getOpPtrVector().push_back(collect);
953 CHKERR phase(
"tag target quadrature", [&]() {
954 return loopSelectedCells(projection_dm, request.elementName, target_fe,
961 auto search = evaluator->getData<
Element>();
962 auto located_coordinates = boost::make_shared<MatrixDouble>();
963 auto cache = boost::make_shared<CacheTuple>();
964 double source_scale = 0.;
965 const bool search_source = has_source && !
points.coordinates.empty();
966 CHKERR phase(
"tag source search", [&]() {
970 CHKERR evaluator->buildTree<
D>(search, request.elementName,
971 request.source.bit, request.source.mask);
972 double lower[3], upper[3];
974 CHKERR search->treePtr->get_info(search->rooTreeSet, lower, upper, depth);
975 for (
int d = 0;
d != 3; ++
d)
976 source_scale = std::hypot(source_scale, upper[
d] - lower[
d]);
978 search->feMethodPtr->getRuleHook = [](
int,
int,
int) {
return -1; };
979 auto locate =
new UDO(
NOSPACE, UDO::OPSPACE);
980 locate->doWorkRhsHook = [located_coordinates](DataOperator *
base,
int,
982 *located_coordinates =
static_cast<UDO *
>(
base)->getCoordsAtGaussPts();
985 search->feMethodPtr->getOpPtrVector().push_back(locate);
986 for (
auto &
tag : tags) {
987 tag.samples.resize(
points.coordinates.size(),
tag.components,
989 auto coefficients = boost::make_shared<MatrixDouble>();
990 auto basis = boost::make_shared<EntitiesFieldData>(MBENTITYSET);
991 auto load =
new UDO(
NOSPACE, UDO::OPSPACE);
992 load->doWorkRhsHook = [&
tag, coefficients](DataOperator *
base,
int,
995 const auto ent =
static_cast<UDO *
>(
base)->getFEEntityHandle();
996 const auto it =
tag.sourceCoefficients.find(ent);
997 if (
it ==
tag.sourceCoefficients.end())
999 "Source tag coefficients are missing");
1000 *coefficients =
it->second;
1003 search->feMethodPtr->getOpPtrVector().push_back(load);
1004 search->feMethodPtr->getOpPtrVector().push_back(
1005 new OpTagBasis(
tag.order, basis));
1006 search->feMethodPtr->getOpPtrVector().push_back(
1007 new OpDGProjectionEvaluation(
tag.sourceValues, coefficients, basis,
1013 unsigned long long missing = 0;
1014 CHKERR phase(
"tag source sampling", [&]() {
1016 std::vector<char> sampled(
points.coordinates.size(),
false);
1017 for (
size_t q = 0;
q !=
points.coordinates.size(); ++
q) {
1018 for (
auto &
tag : tags)
1019 for (size_t
c = 0;
c !=
tag.samples.size2(); ++
c)
1020 tag.samples(
q,
c) =
tag.policy.empty[
c];
1023 CHKERR evaluator->evalFEAtPoints<
D>(
1024 points.coordinates, 1.e-10, problem_name, request.elementName,
1026 request.source.mask, cache,
1027 [&](
const std::vector<size_t> &indices) {
1029 if (located_coordinates->size1() != indices.size() ||
1030 located_coordinates->size2() != 3)
1032 "Invalid located tag point");
1033 for (
size_t row = 0;
row != indices.size(); ++
row) {
1034 const auto q = indices[
row];
1035 const auto &x =
points.coordinates[
q];
1036 const moab::CartVect
back(&(*located_coordinates)(
row, 0));
1037 const moab::CartVect query(x.data());
1038 double coordinate_scale = 0.;
1039 for (
double value : x)
1040 coordinate_scale =
std::max(coordinate_scale,
std::abs(value));
1042 1.e-10 * source_scale,
1043 64 * std::numeric_limits<double>::epsilon() *
1045 if (!std::isfinite((
back - query).
length()) ||
1048 for (
auto &
tag : tags) {
1050 if (
values.size1() != indices.size() ||
1052 static_cast<size_t>(
tag.components))
1054 "Inconsistent reconstructed tag values");
1055 for (
size_t c = 0;
c !=
values.size2(); ++
c)
1063 for (
auto valid : sampled)
1068 report.missingPoints = missing;
1070 target_fe->getOpPtrVector().clear();
1071 for (
auto &
tag : tags) {
1072 auto values = boost::make_shared<MatrixDouble>();
1073 auto coefficients = boost::make_shared<MatrixDouble>();
1074 auto mass = boost::make_shared<MatrixDouble>();
1075 auto basis = boost::make_shared<EntitiesFieldData>(MBENTITYSET);
1076 auto load =
new UDO(
NOSPACE, UDO::OPSPACE);
1080 auto op =
static_cast<UDO *
>(
base);
1081 const auto offset =
points.offsets.at(op->getFEEntityHandle());
1082 const auto count = op->getGaussPts().size2();
1083 values->resize(count,
tag.components,
false);
1084 for (
size_t q = 0;
q != count; ++
q)
1085 for (
size_t c = 0;
c !=
values->size2(); ++
c)
1089 target_fe->getOpPtrVector().push_back(load);
1090 target_fe->getOpPtrVector().push_back(
1091 new OpReconstructionMass(
tag.order, tagBase, mass, basis));
1092 target_fe->getOpPtrVector().push_back(
new OpDGProjectionCoefficients(
1094 auto store =
new UDO(
NOSPACE, UDO::OPSPACE);
1095 store->doWorkRhsHook = [&
tag,
values, coefficients, mass,
1096 basis](DataOperator *
base,
int, EntityType,
1099 auto op =
static_cast<UDO *
>(
base);
1100 tag.targetCoefficients[op->getFEEntityHandle()] = *coefficients;
1101 if (allFinite(*
values) && allFinite(*coefficients)) {
1102 const auto &
n = basis->dataOnEntities[op->getFEType()][0].getN(tagBase);
1103 tag.targetResidual =
1104 std::max(
tag.targetResidual,
1105 massSolveResidual(
n, op->getGaussPts(), *
values, *mass,
1110 target_fe->getOpPtrVector().push_back(store);
1112 CHKERR phase(
"tag local projection", [&]() {
1113 return loopSelectedCells(projection_dm, request.elementName, target_fe,
1123 const TagRequest &request, DM projection_dm,
const Range &target_cells,
1124 std::vector<ProjectedTag> &tags) {
1126 using Element =
typename PipelineManager::ElementsAndOpsByDim<D>::DomainEle;
1127 auto fe = boost::make_shared<Element>(
mField);
1128 installRule(*fe, request.options.targetRule);
1129 for (
auto &
tag : tags) {
1130 auto values = boost::make_shared<MatrixDouble>();
1131 auto coefficients = boost::make_shared<MatrixDouble>();
1132 auto basis = boost::make_shared<EntitiesFieldData>(MBENTITYSET);
1133 auto load =
new UDO(
NOSPACE, UDO::OPSPACE);
1134 load->doWorkRhsHook = [&
tag, coefficients](DataOperator *
base,
int,
1137 const auto ent =
static_cast<UDO *
>(
base)->getFEEntityHandle();
1138 const auto it =
tag.targetCoefficients.find(ent);
1139 if (
it ==
tag.targetCoefficients.end())
1141 "Target tag coefficients are missing");
1142 *coefficients =
it->second;
1145 fe->getOpPtrVector().push_back(load);
1146 fe->getOpPtrVector().push_back(
new OpTagBasis(
tag.order, basis));
1147 fe->getOpPtrVector().push_back(
new OpDGProjectionEvaluation(
1149 auto stage =
new UDO(
NOSPACE, UDO::OPSPACE);
1153 auto op =
static_cast<UDO *
>(
base);
1154 const auto points = op->getGaussPts().size2();
1156 values->size2() !=
static_cast<size_t>(
tag.components))
1158 "Inconsistent target tag value layout");
1159 if (
tag.targetLength >= 0 &&
1160 static_cast<size_t>(
tag.targetLength) !=
values->data().size())
1162 "Fixed-length tag %s holds %d values; the target rule needs "
1164 tag.targetName.c_str(),
tag.targetLength,
1166 tag.staged[op->getFEEntityHandle()].assign(
values->data().begin(),
1170 fe->getOpPtrVector().push_back(stage);
1172 CHKERR phase(
"tag evaluation", [&]() {
1173 return loopSelectedCells(projection_dm, request.elementName, fe,
1182DGProjectionInterfaceImpl::publishTags(std::vector<ProjectedTag> &tags,
1183 const Range &target_copies) {
1186 const auto set_values = [&](
const ProjectedTag &
tag, EntityHandle ent,
1187 const std::vector<double> &
values) {
1189 if (
tag.targetLength >= 0) {
1192 const void *data[] = {
values.data()};
1198 const auto restore = [&]() {
1199 return phase(
"tag publication rollback", [&]() {
1201 for (
auto &
tag : tags)
1211 auto error = phase(
"tag publication", [&]() {
1213 for (
auto &
tag : tags)
1214 for (auto ent : target_copies) {
1215 const double *data =
nullptr;
1219 (
const void **)&data,
1220 &
size) == MB_SUCCESS &&
1225 for (
auto &
tag : tags)
1226 for (auto ent : target_copies)
1238MoFEMErrorCode DGProjectionInterfaceImpl::transferTags(
const TagRequest &request,
1242 if (!request.dm || request.elementName.empty() ||
1243 !
mField.check_finite_element(request.elementName))
1245 "Tag projection requires a MoFEM DM and existing finite element");
1250 std::vector<ProjectedTag> tags;
1251 CHKERR validateTags(request, tags);
1252 std::string problem_name;
1253 CHKERR reserveProblemName(problem_name);
1254 SmartPetscObj<DM> projection_dm;
1255 CHKERR createSubDM(request.dm, problem_name, request.source, request.target,
1256 request.elementName, projection_dm);
1261 const auto execute = [&]() {
1265 CHKERR phase(
"target tag preparation", [&]() {
1267 for (
auto &
tag : tags) {
1268 const void *def =
nullptr;
1274 const bool variable =
1275 mb.tag_get_length(
tag.source,
length) == MB_VARIABLE_DATA_LENGTH;
1276 const bool has_default =
1277 mb.tag_get_default_value(
tag.source, def, def_size) ==
1280 unsigned flags = MB_TAG_CREAT | MB_TAG_EXCL | storage;
1282 flags |= MB_TAG_VARLEN;
1284 variable ? (has_default ? def_size : 0)
1287 has_default ? def : nullptr);
1291 if (
mb.tag_get_length(
tag.target,
length) != MB_VARIABLE_DATA_LENGTH)
1294 tag.policy.empty.assign(
components, request.options.emptyValue);
1297 if (
mb.tag_get_default_value(
tag.target, def, def_size) == MB_SUCCESS &&
1298 def && def_size > 0) {
1299 const auto *
values =
static_cast<const double *
>(def);
1303 tag.policy.finiteSource =
1304 std::all_of(
tag.policy.empty.begin(),
tag.policy.empty.end(),
1305 [](
double value) { return std::isfinite(value); });
1310 CHKERR reconstructTags<2>(request, projection_dm,
source, tags);
1312 CHKERR reconstructTags<3>(request, projection_dm,
source, tags);
1315 CHKERR projectTagsImpl<2>(request, projection_dm, problem_name,
1318 CHKERR projectTagsImpl<3>(request, projection_dm, problem_name,
1322 CHKERR evaluateTags<2>(request, projection_dm,
target, tags);
1324 CHKERR evaluateTags<3>(request, projection_dm,
target, tags);
1327 for (
size_t t = 0;
t != tags.size(); ++
t) {
1329 item.targetTag = tags[
t].targetName;
1330 item.relativeMassResidual = tags[
t].targetResidual;
1331 item.sourceRelativeMassResidual = tags[
t].sourceResidual;
1332 item.sourceElementsWithoutData = tags[
t].withoutData;
1333 report.items.push_back(item);
1337 const auto error = execute();
1339 for (
auto &
tag : tags)
1346MoFEMErrorCode DGProjectionInterfaceImpl::project(
const TagRequest &request,
1349 CHKERR preservingBuildState([&]() {
return transferTags(request,
report); });
1356createInterface<DGProjectionInterface>(
const Core &core) {
1357 return new DGProjectionInterfaceImpl(core);
MoFEM::Interface & mField
std::vector< int > created
std::vector< int > source
const std::vector< Vec > * points
Vec t
Removal: the ring edge.
std::vector< int > parent
bool back
Slid back beyond the node along its edge.
std::vector< Cell > cells
std::map< EntityHandle, size_t > offsets
boost::shared_ptr< FieldEntity > targetEntity
int components
Inferred from the source tag length.
unsigned long long withoutData
unsigned long long sequence
std::map< EntityHandle, MatrixDouble > targetCoefficients
std::map< EntityHandle, std::pair< bool, std::vector< double > > > previous
boost::shared_ptr< MatrixDouble > sourceValues
int targetLength
Values held by a fixed-length target tag.
std::vector< double > empty
One value per component.
bool finiteSource
Reject nonfinite source values.
std::vector< std::array< double, 3 > > coordinates
std::map< EntityHandle, std::vector< double > > staged
std::map< EntityHandle, MatrixDouble > sourceCoefficients
std::vector< FieldBitNumber > row
SmartPetscObj< Vec > work
SmartPetscObj< Vec > values
size_t cholesky_decompose(const MATRIX &A, TRIA &L)
decompose the symmetric positive definit matrix A into product L L^T.
FieldApproximationBase
approximation base
@ AINSWORTH_LEGENDRE_BASE
Ainsworth Cole (Legendre) approx. base .
#define MoFEMFunctionReturnHot(a)
Last executable line of each PETSc function used for error handling. Replaces return()
@ L2
field with C-1 continuity
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
@ MOFEM_OPERATION_UNSUCCESSFUL
@ MOFEM_DATA_INCONSISTENCY
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define CHKERR
Inline error check.
#define THROW_MESSAGE(msg)
Throw MoFEM exception.
PetscErrorCode DMMoFEMCreateSubDM(DM subdm, DM dm, const char problem_name[])
Must be called by user to set Sub DM MoFEM data structures.
PetscErrorCode DMMoFEMAddElement(DM dm, std::string fe_name)
add element to dm
PetscErrorCode DMMoFEMSetSquareProblem(DM dm, PetscBool square_problem)
set squared problem
PetscErrorCode DMMoFEMGetProblemPtr(DM dm, const MoFEM::Problem **problem_ptr)
Get pointer to problem data structure.
PetscErrorCode DMoFEMLoopFiniteElements(DM dm, const char fe_name[], MoFEM::FEMethod *method, CacheTupleWeakPtr cache_ptr=CacheTupleSharedPtr())
Executes FEMethod for finite elements in DM.
virtual const FieldEntity_multiIndex * get_field_ents() const =0
Get the field ents object.
virtual const Field * get_field_structure(const std::string &name, enum MoFEMTypes bh=MF_EXIST) const =0
get field structure
virtual bool check_field(const std::string &name) const =0
check if field is in database
virtual MoFEMErrorCode modify_problem_mask_ref_level_set_bit(const std::string &name_problem, const BitRefLevel &bit)=0
set dof mask ref level for problem
virtual MoFEMErrorCode modify_problem_ref_level_set_bit(const std::string &name_problem, const BitRefLevel &bit)=0
set ref level for problem
virtual bool check_problem(const std::string name)=0
check if problem exist
FTensor::Index< 'i', SPACE_DIM > i
const double c
speed of light (cm/ns)
FTensor::Index< 'j', 3 > j
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
UBlasMatrix< double > MatrixDouble
implementation of Data Operators for Forces and Sources
auto type_from_handle(const EntityHandle h)
get type from entity handle
auto dimension_from_handle(const EntityHandle h)
get entity dimension form handle
DeprecatedCoreInterface Interface
auto createDM(MPI_Comm comm, const std::string dm_type_name)
Creates smart DM object.
FTensor::Index< 'm', 3 > m
virtual int get_comm_size() const =0
virtual moab::Interface & get_moab()=0
virtual MoFEMErrorCode cache_problem_entities(const std::string prb_name, CacheTupleWeakPtr cache_ptr)=0
Cache variables.
virtual bool check_finite_element(const std::string &name) const =0
Check if finite element is in database.
virtual int get_comm_rank() const =0
Data on single entity (This is passed as argument to DataOperator::doWork)
UId getLocalUniqueIdCalculate()
Get the Local Unique Id Calculate object.
FieldCoefficientsNumber getNbOfCoeffs() const
Get number of field coefficients per DOF.
MoFEMErrorCode getInterface(IFACE *&iface) const
Get interface reference to pointer of interface.
Volume finite element base.