23#include "libmesh/enum_to_string.h"
24#include "libmesh/mesh_tools.h"
25#include "libmesh/parallel_sync.h"
26#include "libmesh/remote_elem.h"
27#include "libmesh/periodic_boundary.h"
28#include "libmesh/periodic_boundaries.h"
38 params.addRangeCheckedParam<Real>(
"ray_distance",
39 std::numeric_limits<Real>::max(),
41 "The maximum distance all Rays can travel");
43 params.addParam<
bool>(
44 "tolerate_failure",
false,
"Whether or not to tolerate a ray tracing failure");
46 MooseEnum work_buffers(
"lifo circular",
"circular");
47 params.addParam<
MooseEnum>(
"work_buffer_type", work_buffers,
"The work buffer type to use");
49 params.addParam<
bool>(
50 "ray_kernel_coverage_check",
true,
"Whether or not to perform coverage checks on RayKernels");
51 params.addParam<
bool>(
"warn_non_planar",
53 "Whether or not to produce a warning if any element faces are non-planar.");
55 params.addParam<
bool>(
56 "always_cache_traces",
58 "Whether or not to cache the Ray traces on every execution, primarily for use in output. "
59 "Warning: this can get expensive very quick with a large number of rays!");
60 params.addParam<
bool>(
"data_on_cache_traces",
62 "Whether or not to also cache the Ray's data when caching its traces");
63 params.addParam<
bool>(
"aux_data_on_cache_traces",
65 "Whether or not to also cache the Ray's aux data when caching its traces");
66 params.addParam<
bool>(
67 "segments_on_cache_traces",
69 "Whether or not to cache individual segments when trace caching is enabled. If false, we "
70 "will instead cache a segment for each part of the trace where the direction is the same. "
71 "This minimizes the number of segments requied to represent the Ray's path, but removes the "
72 "ability to show Ray field data on each segment through an element.");
74 params.addParam<
bool>(
"use_internal_sidesets",
76 "Whether or not to use internal sidesets for RayBCs in ray tracing");
78 params.addParam<
bool>(
"warn_subdomain_hmax",
80 "Whether or not to warn if the approximated hmax (constant on subdomain) "
81 "varies significantly for an element");
83 params.addParam<
bool>(
86 "Whether or not to verify the generated Rays. This includes checking their "
87 "starting information and the uniqueness of Rays before and after execution. This is also "
88 "used by derived studies for more specific verification.");
89 params.addParam<
bool>(
"verify_trace_intersections",
91 "Whether or not to verify the trace intersections in devel and dbg modes. "
92 "Trace intersections are not verified regardless of this parameter in "
93 "optimized modes (opt, oprof).");
95 params.addParam<
bool>(
"allow_other_flags_with_prekernels",
97 "Whether or not to allow the list of execution flags to have PRE_KERNELS "
98 "mixed with other flags. If this parameter is not set then if PRE_KERNELS "
99 "is provided it must be the only execution flag.");
104 params.addParamNamesToGroup(
105 "always_cache_traces data_on_cache_traces aux_data_on_cache_traces segments_on_cache_traces",
107 params.addParamNamesToGroup(
"warn_non_planar warn_subdomain_hmax",
"Tracing Warnings");
108 params.addParamNamesToGroup(
"ray_kernel_coverage_check verify_rays verify_trace_intersections",
109 "Checks and verifications");
112 params.addPrivateParam<
bool>(
"_use_ray_registration",
true);
114 params.addPrivateParam<
bool>(
"_bank_rays_on_completion",
true);
116 params.addPrivateParam<
bool>(
"_ray_dependent_subdomain_setup",
true);
119 params.addRelationshipManager(
"ElementPointNeighborLayers",
120 Moose::RelationshipManagerType::GEOMETRIC |
121 Moose::RelationshipManagerType::ALGEBRAIC,
123 { rm_params.
set<
unsigned short>(
"layers") = 1; });
130 _mesh(_fe_problem.
mesh()),
134 _ray_kernel_coverage_check(getParam<bool>(
"ray_kernel_coverage_check")),
135 _warn_non_planar(getParam<bool>(
"warn_non_planar")),
136 _use_ray_registration(getParam<bool>(
"_use_ray_registration")),
137 _use_internal_sidesets(getParam<bool>(
"use_internal_sidesets")),
138 _tolerate_failure(getParam<bool>(
"tolerate_failure")),
139 _bank_rays_on_completion(getParam<bool>(
"_bank_rays_on_completion")),
140 _ray_dependent_subdomain_setup(getParam<bool>(
"_ray_dependent_subdomain_setup")),
142 _always_cache_traces(getParam<bool>(
"always_cache_traces")),
143 _data_on_cache_traces(getParam<bool>(
"data_on_cache_traces")),
144 _aux_data_on_cache_traces(getParam<bool>(
"aux_data_on_cache_traces")),
145 _segments_on_cache_traces(getParam<bool>(
"segments_on_cache_traces")),
146 _ray_max_distance(getParam<Real>(
"ray_distance")),
147 _verify_rays(getParam<bool>(
"verify_rays")),
149 _verify_trace_intersections(getParam<bool>(
"verify_trace_intersections")),
152 _threaded_elem_side_builders(
libMesh::n_threads()),
155 declareRestartableData<
std::unordered_map<
std::string,
RayID>>(
"registered_ray_map")),
156 _reverse_registered_ray_map(
157 declareRestartableData<
std::vector<
std::string>>(
"reverse_registered_ray_map")),
159 _threaded_cached_traces(
libMesh::n_threads()),
161 _num_cached(
libMesh::n_threads(), 0),
163 _has_non_planar_sides(true),
164 _has_same_level_active_elems(sameLevelActiveElems()),
166 _b_box(MeshTools::create_nodal_bounding_box(_mesh.getMesh())),
167 _domain_max_length(1.01 * (_b_box.max() - _b_box.min()).norm()),
168 _total_volume(computeTotalVolume()),
170 _threaded_cache_ray_kernel(
libMesh::n_threads()),
171 _threaded_cache_ray_bc(
libMesh::n_threads()),
172 _threaded_ray_object_registration(
libMesh::n_threads()),
173 _threaded_current_ray_kernels(
libMesh::n_threads()),
174 _threaded_trace_ray(
libMesh::n_threads()),
175 _threaded_fe_face(
libMesh::n_threads()),
176 _threaded_q_face(
libMesh::n_threads()),
177 _threaded_cached_normals(
libMesh::n_threads()),
178 _threaded_next_ray_id(
libMesh::n_threads()),
182 _local_trace_ray_results(
TraceRay::FAILED_TRACES + 1, 0),
184 _called_initial_setup(false),
186 _elem_index_helper(_mesh.getMesh(),
name() +
"_elem_index")
196 FEBase::build(
_mesh.
dimension(), FEType(CONSTANT, MONOMIAL).set_p_refinement(
false));
205 if (!getParam<bool>(
"allow_other_flags_with_prekernels") &&
_execute_enum.
size() > 1)
207 "PRE_KERNELS cannot be mixed with any other execution flag.\nThat is, you cannot "
209 "mix RayKernels that contribute to the Jacobian/residual with those that do not.");
212 mooseError(
"Execution on residual and Jacobian evaluation (execute_on = PRE_KERNELS)\n",
213 "is not supported for an eigenvalue solve.");
258 std::vector<RayKernelBase *> ray_kernels;
260 for (
const auto & rkb : ray_kernels)
262 mooseError(
"This study has RayKernel objects that contribute to residuals and Jacobians.",
263 "\nIn this case, the study must use the execute_on = PRE_KERNELS");
274 mooseAssert(
_num_cached[tid] == 0,
"Cached residuals/Jacobians not empty");
277 rto->residualSetup();
284 mooseAssert(
_num_cached[tid] == 0,
"Cached residuals/Jacobians not empty");
287 rto->jacobianSetup();
294 rto->timestepSetup();
308 trace_ray->meshChanged();
323 std::vector<RayKernelBase *> ray_kernels;
326 std::set<SubdomainID> ray_kernel_blocks;
327 for (
const auto & rk : ray_kernels)
328 ray_kernel_blocks.insert(rk->blockIDs().begin(), rk->blockIDs().end());
330 std::set<SubdomainID> missing;
333 ray_kernel_blocks.begin(),
334 ray_kernel_blocks.end(),
335 std::inserter(missing, missing.begin()));
339 std::ostringstream error;
340 error <<
"Subdomains { ";
341 std::copy(missing.begin(), missing.end(), std::ostream_iterator<SubdomainID>(error,
" "));
342 error <<
"} do not have RayKernels defined!";
352 std::vector<RayTracingObject *> ray_tracing_objects;
364 for (
const auto & rto : rtos)
365 for (
const auto & dep_name : rto->getRequestedItems())
368 for (
const auto & rto_search : rtos)
369 if (rto_search->name() == dep_name)
376 rto->paramError(
"depends_on",
"The ", rto->getBase(),
" '", dep_name,
"' does not exist");
389 Utility::enum_to_string(elem->type()),
390 " is not supported in ray tracing with adaptivity");
394 Utility::enum_to_string(elem->type()),
395 " is not supported in ray tracing");
403 std::vector<const RayBoundaryConditionBase *> rbc_ptrs;
405 std::vector<const PeriodicRayBC *> prbc_ptrs;
406 for (
const auto rbc_ptr : rbc_ptrs)
407 if (
const auto prbc_ptr =
dynamic_cast<const PeriodicRayBC *
>(rbc_ptr))
408 prbc_ptrs.push_back(prbc_ptr);
409 if (prbc_ptrs.empty())
413 std::map<boundary_id_type,
416 std::unordered_set<dof_id_type>>>
418 for (
const auto prbc_ptr : prbc_ptrs)
420 for (
const auto & [bid, pb] : prbc_ptr->getPeriodicBoundaries())
422 const auto [it, inserted] = boundary_map.emplace(
423 std::piecewise_construct,
425 std::forward_as_tuple(prbc_ptr, pb.get(), std::unordered_set<dof_id_type>()));
427 prbc_ptr->mooseError(
"The periodic boundary '",
429 "' has been defined in both ",
430 prbc_ptr->typeAndName(),
432 std::get<0>(it->second)->typeAndName());
443 const auto & sideset_map =
_mesh.
getMesh().get_boundary_info().get_sideset_map();
444 for (
const auto & [elem, side_bid_pair] : sideset_map)
446 const auto [side, bid] = side_bid_pair;
447 if (
auto it = boundary_map.find(bid); it != boundary_map.end())
448 for (
const auto n : elem->nodes_on_side(side))
449 std::get<2>(it->second).insert(elem->node_ref(n).id());
453 for (
auto & bid_tuple_pair : boundary_map)
457 std::map<std::pair<boundary_id_type, boundary_id_type>,
458 std::pair<const PeriodicRayBC *, const PeriodicRayBC *>>
460 for (
auto it = boundary_map.begin(); it != boundary_map.end(); ++it)
462 const auto & [bid, tup] = *it;
463 const auto [prbc_ptr, pb, node_ids] = tup;
465 for (
auto other_it = std::next(it); other_it != boundary_map.end(); ++other_it)
467 const auto & [other_bid, other_tup] = *other_it;
470 if (pb->pairedboundary == other_bid)
473 const auto other_prbc_ptr = std::get<0>(other_tup);
474 const auto & other_node_ids = std::get<2>(other_tup);
475 for (
const auto node_id : node_ids)
476 if (other_node_ids.count(node_id))
478 if (!warn_boundaries.count(std::make_pair(other_bid, bid)))
479 warn_boundaries.emplace(std::make_pair(bid, other_bid),
480 std::make_pair(prbc_ptr, other_prbc_ptr));
486 if (warn_boundaries.size())
488 std::ostringstream oss;
489 oss << warn_boundaries.size()
490 <<
" ray tracing periodic boundaries were found to be neighbors:\n\n";
491 for (
const auto & [bids_pair, prbc_ptrs_pair] : warn_boundaries)
493 const auto [bid, paired_bid] = bids_pair;
494 const auto [prbc_ptr, paired_prbc_ptr] = prbc_ptrs_pair;
497 << paired_prbc_ptr->typeAndName() <<
")\n";
499 oss <<
"\nThe periodic propagation of rays at points where two or more periodic"
500 <<
"\nboundaries meet is not fully supported with a distributed mesh."
501 <<
"\n\nIf you encounter trace failures, you should use a replicated mesh.";
529 Elem * elem = bnd_elem->_elem;
530 const unsigned int side = bnd_elem->_side;
531 const auto bnd_id = bnd_elem->_bnd_id;
534 const Elem *
const neighbor = elem->neighbor_ptr(side);
535 if (!neighbor || neighbor == remote_elem)
539 std::vector<RayBoundaryConditionBase *> result;
544 if (neighbor->subdomain_id() == elem->subdomain_id())
545 mooseError(
"RayBCs exist on internal sidesets that are not bounded by a different",
546 "\nsubdomain on each side.",
547 "\n\nIn order to use RayBCs on internal sidesets, said sidesets must have",
548 "\na different subdomain on each side.");
559 entry.resize(elem->n_sides(), std::vector<BoundaryID>());
562 entry[side].push_back(bnd_id);
566 mooseError(
"RayBCs are defined on internal sidesets, but the study is not set to use ",
567 "internal sidesets during tracing.",
568 "\n\nSet the parameter use_internal_sidesets = true to enable this capability.");
585 for (
const Elem * elem :
_mesh.
getMesh().active_element_ptr_range())
589 entry.resize(elem->n_sides(), 0);
591 for (
const auto s : elem->side_index_range())
593 const auto & side =
elemSide(*elem, s);
594 if (side.n_vertices() < 4)
597 if (!side.has_affine_map())
605 "Ray tracing on non-planar faces is an approximation and may fail.\n\n",
606 "Use at your own risk! You can disable this warning by setting the\n",
607 "parameter 'warn_non_planar' to false.");
627 entry = std::max(entry, elem->hmax());
633 if (getParam<bool>(
"warn_subdomain_hmax"))
635 const auto warn_prefix =
type() +
" '" +
name() +
"': ";
636 const auto warn_suffix =
637 "\n\nRay tracing uses an approximate element size for each subdomain to scale the\n"
638 "tolerances used in computing ray intersections. This warning suggests that the\n"
639 "approximate element size is not a good approximation. This is likely due to poor\n"
640 "element aspect ratios.\n\n"
641 "This warning is only output for the first element affected.\n"
642 "To disable this warning, set warn_subdomain_hmax = false.\n";
646 const auto hmin = elem->hmin();
647 const auto hmax = elem->hmax();
650 const auto hmax_rel = hmax / max_hmax;
651 if (hmax_rel < 1.e-2 || hmax_rel > 1.e2)
653 "Element hmax varies significantly from subdomain hmax.\n",
655 "First element affected:\n",
658 const auto h_rel = max_hmax / hmin;
661 "Element hmin varies significantly from subdomain hmax.\n",
663 "First element affected:\n",
677 entry.resize(num_rays);
686 std::vector<std::string> all_ray_names;
689 all_ray_names.push_back(pair.first);
691 for (
auto & rto : rtos)
694 const auto & ray_names = rto->parameters().get<std::vector<std::string>>(
"rays");
696 const auto tid = rto->parameters().get<
THREAD_ID>(
"_tid");
700 for (
const auto & ray_name : (ray_names.empty() ? all_ray_names : ray_names))
705 "rays",
"Supplied ray '", ray_name,
"' is not a registered Ray in ",
typeAndName());
706 registration[id].insert(rto);
713 for (
const auto & rto : rtos)
714 if (rto->parameters().get<std::vector<std::string>>(
"rays").size())
717 "Rays cannot be supplied when the study does not require Ray registration.\n\n",
719 " does not require Ray registration.");
726 std::set<std::string> vars_to_be_zeroed;
727 std::vector<RayKernelBase *> ray_kernels;
729 for (
auto & rk : ray_kernels)
736 std::vector<std::string> vars_to_be_zeroed_vec(vars_to_be_zeroed.begin(),
737 vars_to_be_zeroed.end());
751 std::set<MooseVariableFEBase *> needed_moose_vars;
752 std::unordered_set<unsigned int> needed_mat_props;
758 rkb->subdomainSetup();
760 const auto & mv_deps = rkb->getMooseVariableDependencies();
761 needed_moose_vars.insert(mv_deps.begin(), mv_deps.end());
763 const auto & mp_deps = rkb->getMatPropDependencies();
764 needed_mat_props.insert(mp_deps.begin(), mp_deps.end());
768 for (
auto & var : needed_moose_vars)
769 if (var->kind() == Moose::VarKindType::VAR_AUXILIARY)
778 const Elem * elem,
const Point & start,
const Point & end,
const Real length,
THREAD_ID tid)
780 mooseAssert(MooseUtils::absoluteFuzzyEqual((start - end).norm(), length),
"Invalid length");
792 if (rk->needSegmentReinit())
802 std::vector<Point> points;
803 std::vector<Real> weights;
816 std::vector<Point> & points,
817 std::vector<Real> & weights)
const
822 const Point diff = end - start;
823 const Point sum = end + start;
824 mooseAssert(MooseUtils::absoluteFuzzyEqual(length, diff.norm()),
"Invalid length");
846 "Values should only be cached when computing Jacobian/residual");
855 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
866 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
876 TIME_SECTION(
"executeStudy", 2,
"Executing Study");
904 rto->preExecuteStudy();
921 auto generation_start_time = std::chrono::steady_clock::now();
923 TIME_SECTION(
"generateRays", 2,
"Generating Rays");
927 _generation_time = std::chrono::steady_clock::now() - generation_start_time;
936 "after generateRays()");
941 "after generateRays()");
947 TIME_SECTION(
"propagateRays", 2,
"Propagating Rays");
949 const auto propagation_start_time = std::chrono::steady_clock::now();
963 "after tracing completed");
971 "after tracing completed");
1002 type(),
" '",
name(),
"': ", failures,
" ray tracing failures were tolerated.\n");
1012 std::size_t num_entries = 0;
1030 "Should not have cached values without Jacobian/residual computation");
1053 rto->postExecuteStudy();
1080 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1083 mooseError(
"Cannot register Ray ", (aux ?
"aux " :
""),
"data after initialSetup()");
1086 const auto find = map.find(
name);
1087 if (find != map.end())
1088 return find->second;
1091 if (other_map.find(
name) != other_map.end())
1092 mooseError(
"Cannot register Ray aux data with name ",
1095 (aux ?
"(non-aux)" :
"aux"),
1096 " data already exists with said name.");
1099 map.emplace(
name, map.size());
1103 vector.push_back(
name);
1105 return map.size() - 1;
1108std::vector<RayDataIndex>
1111 std::vector<RayDataIndex> indices(names.size());
1112 for (std::size_t i = 0; i < names.size(); ++i)
1120 const bool graceful)
const
1122 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1125 const auto find = map.find(
name);
1126 if (find != map.end())
1127 return find->second;
1133 if (other_map.find(
name) != other_map.end())
1136 "' was not found.\n\n",
1138 (aux ?
"non-aux" :
"aux"),
1139 " data with said name was found.\n",
1140 "Did you mean to use ",
1141 (aux ?
"getRayDataIndex()/getRayDataIndices()?"
1142 :
"getRayAuxDataIndex()/getRayAuxDataIndices()"),
1145 mooseError(
"Unknown Ray ", (aux ?
"aux " :
""),
"data with name ",
name);
1148std::vector<RayDataIndex>
1151 const bool graceful)
const
1153 std::vector<RayDataIndex> indices(names.size());
1154 for (std::size_t i = 0; i < names.size(); ++i)
1162 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1165 mooseError(
"Unknown Ray ", aux ?
"aux " :
"",
"data with index ", index);
1175std::vector<RayDataIndex>
1187std::vector<RayDataIndex>
1189 const bool graceful )
const
1206std::vector<RayDataIndex>
1214 const bool graceful )
const
1219std::vector<RayDataIndex>
1221 const bool graceful )
const
1235 std::vector<RayKernelBase *> result;
1237 return result.size();
1248 mooseError(
"Should not call getRayKernels() before initialSetup()");
1253 .condition<AttribSystem>(
"RayKernel")
1276 std::vector<RayKernelBase *> rkbs;
1284 for (
auto rkb : rkbs)
1285 if (ray_id_rtos.count(rkb))
1286 result.push_back(rkb);
1300 mooseError(
"Should not call getRayBCs() before initialSetup()");
1305 .condition<AttribSystem>(
"RayBoundaryCondition")
1315 const std::vector<TraceRayBndElement> & bnd_elems,
1322 if (bnd_elems.size() == 1)
1323 getRayBCs(result, bnd_elems[0].bnd_id, tid);
1326 std::vector<BoundaryID> bnd_ids(bnd_elems.size());
1327 for (MooseIndex(bnd_elems.size()) i = 0; i < bnd_elems.size(); ++i)
1328 bnd_ids[i] = bnd_elems[i].bnd_id;
1336 std::vector<RayBoundaryConditionBase *> rbcs;
1337 if (bnd_elems.size() == 1)
1338 getRayBCs(rbcs, bnd_elems[0].bnd_id, tid);
1341 std::vector<BoundaryID> bnd_ids(bnd_elems.size());
1342 for (MooseIndex(bnd_elems.size()) i = 0; i < bnd_elems.size(); ++i)
1343 bnd_ids[i] = bnd_elems[i].bnd_id;
1353 for (
auto rbc : rbcs)
1354 if (ray_id_rtos.count(rbc))
1355 result.push_back(rbc);
1359std::vector<RayTracingObject *>
1362 std::vector<RayTracingObject *> result;
1367const std::vector<std::shared_ptr<Ray>> &
1371 mooseError(
"The Ray bank is not available because the private parameter "
1372 "'_bank_rays_on_completion' is set to false.");
1374 mooseError(
"Cannot get the Ray bank during generation or propagation.");
1384 std::shared_ptr<Ray> ray;
1385 for (
const std::shared_ptr<Ray> & possible_ray :
rayBank())
1386 if (possible_ray->id() == ray_id)
1393 unsigned int have_ray = ray ? 1 : 0;
1396 mooseError(
"Could not find a Ray with the ID ", ray_id,
" in the Ray banks.");
1399 mooseAssert(have_ray == 1,
"Multiple rays with the same ID were found in the Ray banks");
1407 const bool aux)
const
1412 Real value = ray ? (aux ? ray->auxData(index) : ray->data(index)) : 0;
1432 libmesh_parallel_only(
comm());
1434 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1437 mooseError(
"Cannot use registerRay() with Ray registration disabled");
1441 libmesh_parallel_only(
comm());
1456 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1459 mooseError(
"Should not use registeredRayID() with Ray registration disabled");
1463 return search->second;
1468 mooseError(
"Attempted to obtain ID of registered Ray ",
1470 ", but a Ray with said name is not registered.");
1476 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1479 mooseError(
"Should not use registeredRayName() with Ray registration disabled");
1484 mooseError(
"Attempted to obtain name of registered Ray with ID ",
1486 ", but a Ray with said ID is not registered.");
1494 volume += elem->volume();
1499const std::vector<std::vector<BoundaryID>> &
1505 "Internal sideset map not initialized");
1523 const std::vector<std::shared_ptr<Ray>>::const_iterator end,
1525 const std::string & error_suffix)
const
1530 std::set<RayID> local_rays;
1531 for (
const std::shared_ptr<Ray> & ray : as_range(begin, end))
1533 mooseAssert(ray,
"Null ray");
1537 if (!local_rays.insert(ray->id()).second)
1539 for (
const std::shared_ptr<Ray> & other_ray : as_range(begin, end))
1540 if (ray.get() != other_ray.get() && ray->id() == other_ray->id())
1547 "\n\nOffending Ray information:\n\n",
1550 other_ray->getInfo());
1558 std::map<processor_id_type, std::vector<RayID>> send_ids;
1559 if (local_rays.size())
1560 send_ids.emplace(std::piecewise_construct,
1561 std::forward_as_tuple(0),
1562 std::forward_as_tuple(local_rays.begin(), local_rays.end()));
1566 std::map<RayID, processor_id_type> global_map;
1569 const auto check_ids =
1570 [
this, &global_map, &error_suffix](processor_id_type pid,
const std::vector<RayID> & ids)
1572 for (
const RayID id : ids)
1574 const auto emplace_pair = global_map.emplace(
id, pid);
1577 if (!emplace_pair.second)
1580 " exists on ranks ",
1581 emplace_pair.first->second,
1589 Parallel::push_parallel_vector_data(
_communicator, send_ids, check_ids);
1595 const std::vector<std::shared_ptr<Ray>>::const_iterator end,
1596 const std::string & error_suffix)
1598 std::set<const Ray *> rays;
1599 for (
const std::shared_ptr<Ray> & ray : as_range(begin, end))
1600 if (!rays.insert(ray.get()).second)
1601 mooseError(
"Multiple shared_ptrs were found that point to the same Ray ",
1603 "\n\nOffending Ray:\n",
1611 mooseAssert(ray,
"Null ray");
1612 mooseAssert(ray->shouldContinue(),
"Ray is not continuing");
1622 for (
const std::shared_ptr<Ray> & ray : rays)
1624 mooseAssert(ray,
"Null ray");
1625 mooseAssert(ray->shouldContinue(),
"Ray is not continuing");
1637 mooseAssert(ray,
"Null ray");
1647 mooseError(
"Can only reserve in Ray buffer during generateRays()");
1655 std::unordered_map<std::pair<const Elem *, unsigned short>, Point> & cache =
1659 const auto elem_side_pair = std::make_pair(elem, side);
1660 const auto search = cache.find(elem_side_pair);
1663 if (search == cache.end())
1667 cache.emplace(elem_side_pair, normal);
1672 return search->second;
1678 unsigned int min_level = std::numeric_limits<unsigned int>::max();
1679 unsigned int max_level = std::numeric_limits<unsigned int>::min();
1683 const auto level = elem->level();
1684 min_level = std::min(level, min_level);
1685 max_level = std::max(level, max_level);
1691 return min_level == max_level;
1699 mooseError(
"Subdomain ", subdomain_id,
" not found in subdomain hmax map");
1700 return find->second;
1706 Real bbox_volume = 1;
1710 return MooseUtils::absoluteFuzzyEqual(bbox_volume,
totalVolume(), TOLERANCE);
1716 libmesh_parallel_only(
comm());
1718 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1721 "Cannot be reset during generation or propagation");
1742 libmesh_parallel_only(
comm());
1744 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1747 "Cannot be reset during generation or propagation");
1760 const unsigned short side,
1761 const Point & direction,
1765 const auto dot = normal * direction;
1802 libmesh_parallel_only(
comm());
boundary_id_type BoundaryID
subdomain_id_type SubdomainID
const ExecFlagType EXEC_PRE_KERNELS
unsigned int RayDataIndex
Type for the index into the data and aux data on a Ray.
unsigned long int RayID
Type for a Ray's ID.
float RayData
Type for a Ray's data.
void modifyArbitraryWeights(const std::vector< Real > &weights)
Attribute for the RayTracingStudy a RayTracingObject is associated with.
MooseVariableFE< Real > & variable()
Gets the variable this AuxRayKernel contributes to.
libMesh::dof_id_type getIndex(const libMesh::Elem *elem) const
Get the index associated with the element elem.
void initialize(const libMesh::SimpleRange< libMesh::MeshBase::element_iterator > elems)
Initializes the indices in a contiguous manner for the given element range.
libMesh::dof_id_type maxIndex() const
Gets the maximum index generated using this object.
void addAvailableFlags(const ExecFlagType &flag, Args... flags)
virtual void reinitElemPhys(const Elem *elem, const std::vector< Point > &phys_points_in_elem, const THREAD_ID tid) override
virtual void cacheResidual(const THREAD_ID tid) override
virtual void addCachedResidual(const THREAD_ID tid) override
AuxiliarySystem & getAuxiliarySystem()
virtual void addCachedJacobian(const THREAD_ID tid) override
virtual void cacheJacobian(const THREAD_ID tid) override
virtual void setCurrentSubdomainID(const Elem *elem, const THREAD_ID tid) override
void reinitMaterials(SubdomainID blk_id, const THREAD_ID tid, bool swap_stateful=true)
virtual void prepare(const Elem *elem, const THREAD_ID tid) override
void clearActiveMaterialProperties(const THREAD_ID tid)
virtual void clearActiveElementalMooseVariables(const THREAD_ID tid) override
void prepareMaterials(const std::unordered_set< unsigned int > &consumer_needed_mat_props, const SubdomainID blk_id, const THREAD_ID tid)
virtual void setActiveElementalMooseVariables(const std::set< MooseVariableFEBase * > &moose_vars, const THREAD_ID tid) override
virtual Assembly & assembly(const THREAD_ID tid, const unsigned int sys_num) override
TheWarehouse & theWarehouse() const
const bool & currentlyComputingResidual() const
virtual void subdomainSetup(SubdomainID subdomain, const THREAD_ID tid)
Adaptivity & adaptivity()
virtual const SystemBase & getSystemBase(const unsigned int sys_num) const
bool hasActiveMaterialProperties(const THREAD_ID tid) const
static InputParameters validParams()
const std::string & type() const
std::string typeAndName() const
const std::string & name() const
void paramError(const std::string ¶m, Args... args) const
void mooseError(Args &&... args) const
void mooseWarning(Args &&... args) const
virtual unsigned int dimension() const
virtual bool isDistributedMesh() const
const std::set< SubdomainID > & meshSubdomains() const
std::string getBoundaryString(const BoundaryID boundary_id) const
const libMesh::ConstElemRange * getActiveLocalElementRange()
libMesh::StoredRange< MooseMesh::const_bnd_elem_iterator, const BndElement * > * getBoundaryElementRange()
bool isValueSet(const std::string &value) const
unsigned int size() const
static InputParameters validParams()
RayBC that enforces periodic boundaries.
Base object for the RayKernel syntax.
Base class for a ray kernel that contributes to the residual and/or Jacobian.
Key that is used for restricting access to moveRayToBufferDuringTrace() and acquireRayDuringTrace().
unsigned int _ending_max_intersections
Max number of intersections for Rays that finished on this processor.
bool _has_same_level_active_elems
Whether or not the mesh has active elements of the same level.
void moveRayToBufferDuringTrace(std::shared_ptr< Ray > &ray, const THREAD_ID tid, const AcquireMoveDuringTraceKey &)
INTERNAL method for moving a Ray into the buffer during tracing.
void traceableMeshChecks()
Check for if all of the element types in the mesh are supported by ray tracing.
std::vector< TheWarehouse::QueryCache< AttribSubdomains > > _threaded_cache_ray_kernel
Threaded cached subdomain query for RayKernelBase objects pertaining to this study.
std::shared_ptr< Ray > acquireCopiedRay(const Ray &ray)
Acquires a Ray that that is copied from another Ray within generateRays().
std::vector< TheWarehouse::QueryCache< AttribBoundaries > > _threaded_cache_ray_bc
Threaded cached boundary query for RayBC objects pertaining to this study.
void verifyDependenciesExist(const std::vector< RayTracingObject * > &rtos)
Verifies that the dependencies exist for a set of RayTracingObjects.
const bool _use_internal_sidesets
Whether or not to use the internal sidesets in ray tracing.
std::vector< RayTracingObject * > getRayTracingObjects()
Gets all of the currently active RayTracingObjects.
std::unordered_map< std::string, RayDataIndex > _ray_aux_data_map
The map from Ray aux data names to index.
RayDataIndex registerRayAuxData(const std::string &name)
Register a value to be filled in the aux data on a Ray with a given name.
const std::vector< RayKernelBase * > & currentRayKernels(THREAD_ID tid) const
Gets the current RayKernels for a thread, which are set in segmentSubdomainSetup()
std::vector< unsigned long long int > _local_trace_ray_results
Cumulative results on this processor from the threaded TraceRay objects.
bool sideIsIncoming(const Elem *const elem, const unsigned short side, const Point &direction, const THREAD_ID tid)
Whether or not side is incoming on element elem in direction direction.
void resetUniqueRayIDs()
Resets the generation of unique RayIDs via generateUniqueRayID() to the beginning of the range.
Real _ending_distance
Total distance traveled by Rays that end on this processor.
std::shared_ptr< Ray > acquireRegisteredRay(const std::string &name)
Acquires a Ray with a given name within generateRays().
const bool _tolerate_failure
Whether or not to tolerate a Ray Tracing failure.
std::chrono::steady_clock::duration _generation_time
Threads::spin_mutex _spin_mutex
Spin mutex object for locks.
std::vector< std::string > _ray_aux_data_names
The names for each Ray aux data entry.
void getRayKernels(std::vector< RayKernelBase * > &result, SubdomainID id, THREAD_ID tid)
Fills the active RayKernels associated with this study and a block into result.
void verifyUniqueRays(const std::vector< std::shared_ptr< Ray > >::const_iterator begin, const std::vector< std::shared_ptr< Ray > >::const_iterator end, const std::string &error_suffix)
Verifies that the Rays in the given range are unique.
std::size_t rayDataSize() const
The registered size of values in the Ray data.
RayDataIndex registerRayData(const std::string &name)
Register a value to be filled in the data on a Ray with a given name.
TraceData & initThreadedCachedTrace(const std::shared_ptr< Ray > &ray, THREAD_ID tid)
Initialize a Ray in the threaded cached trace map to be filled with segments.
std::vector< std::vector< std::vector< BoundaryID > > > _internal_sidesets_map
Internal sideset data, if internal sidesets exist (indexed with getLocalElemIndex())
std::vector< std::shared_ptr< Ray > > _ray_bank
Cumulative Ray bank - stored only when _bank_rays_on_completion.
void nonPlanarSideSetup()
Sets up the caching of whether or not each element side is non-planar, which is stored in _non_planar...
std::chrono::steady_clock::duration _propagation_time
virtual void initialSetup() override
bool sameLevelActiveElems() const
Determine whether or not the mesh currently has active elements that are all the same level.
const libMesh::Elem & elemSide(const libMesh::Elem &elem, const unsigned int s, const THREAD_ID tid=0)
Get an element's side pointer without excessive memory allocation.
std::set< BoundaryID > _internal_sidesets
The BoundaryIDs on the local mesh that have internal RayBCs.
bool _has_non_planar_sides
Whether or not the local mesh has elements with non-planar sides.
unsigned int _ending_max_processor_crossings
Max number of total processor crossings for Rays that finished on this processor.
std::vector< std::unique_ptr< libMesh::QBase > > _threaded_q_face
Face quadrature used for computing face normals for each thread.
const bool _use_ray_registration
Whether or not to use Ray registration.
RayTracingStudy(const InputParameters ¶meters)
static InputParameters validParams()
bool currentlyGenerating() const
Whether or not the study is generating.
MooseMesh & _mesh
The Mesh.
std::shared_ptr< Ray > getBankedRay(const RayID ray_id) const
Gets the Ray with the ID ray_id from the Ray bank.
void subdomainHMaxSetup()
Caches the hmax for all elements in each subdomain.
void localElemIndexSetup()
Sets up the _elem_index_helper, which is used for obtaining a contiguous index for all elements that ...
RayID registerRay(const std::string &name)
Registers a Ray with a given name.
std::vector< std::string > _ray_data_names
The names for each Ray data entry.
unsigned long long int _total_intersections
Total number of Ray/element intersections.
std::shared_ptr< Ray > acquireRayDuringTrace(const THREAD_ID tid, const AcquireMoveDuringTraceKey &)
INTERNAL methods for acquiring a Ray during a trace in RayKernels and RayBCs.
Real _total_distance
Total distance traveled by all Rays.
unsigned long long int _ending_processor_crossings
Total number of processor crossings for Rays that finished on this processor.
std::vector< std::unordered_map< std::pair< const Elem *, unsigned short >, Point > > _threaded_cached_normals
Threaded cache for side normals that have been computed already during tracing.
RayID _replicated_next_ray_id
Storage for the next available replicated RayID, obtained via generateReplicatedRayID()
void resetReplicatedRayIDs()
Resets the generation of unique replicated RayIDs accessed via generateReplicatedRayID().
const std::string & getRayAuxDataName(const RayDataIndex index) const
Gets the name associated with a registered value in the Ray aux data.
const std::string & getRayDataNameInternal(const RayDataIndex index, const bool aux) const
Internal method for getting the name of Ray data or Ray aux data.
virtual void segmentSubdomainSetup(const SubdomainID subdomain, const THREAD_ID tid, const RayID ray_id)
Setup for on subdomain change or subdomain AND ray change during ray tracing.
virtual void preExecuteStudy()
Entry point before study execution.
RayData getBankedRayData(const RayID ray_id, const RayDataIndex index) const
Gets the data value for a banked ray with a given ID.
virtual void residualSetup() override
std::vector< TraceData > _cached_traces
Storage for the cached traces.
unsigned int _max_trajectory_changes
Max number of trajectory changes for a single Ray.
virtual void reinitSegment(const Elem *elem, const Point &start, const Point &end, const Real length, THREAD_ID tid)
Reinitialize objects for a Ray segment for ray tracing.
virtual void generateRays()=0
Subclasses should override this to determine how to generate Rays.
std::vector< RayDataIndex > getRayAuxDataIndices(const std::vector< std::string > &names, const bool graceful=false) const
Gets the indices associated with registered values in the Ray aux data.
const bool _bank_rays_on_completion
Whether or not to bank rays on completion.
std::vector< std::vector< RayKernelBase * > > _threaded_current_ray_kernels
The current RayKernel objects for each thread.
std::vector< RayID > _threaded_next_ray_id
Storage for the next available unique RayID, obtained via generateUniqueRayID()
const std::unique_ptr< ParallelRayStudy > _parallel_ray_study
The study that used is to actually execute (trace) the Rays.
Real computeTotalVolume()
Helper function for computing the total domain volume.
std::unordered_map< std::string, RayID > & _registered_ray_map
Map from registered Ray name to ID.
RayDataIndex registerRayDataInternal(const std::string &name, const bool aux)
Internal method for registering Ray data or Ray aux data with a name.
virtual void postOnSegment(const THREAD_ID tid, const std::shared_ptr< Ray > &ray)
Called at the end of a Ray segment.
libMesh::BoundingBox _loose_b_box
Loose nodal bounding box for the domain.
void internalSidesetSetup()
Does the setup for internal sidesets.
virtual void buildSegmentQuadrature(const Point &start, const Point &end, const Real length, std::vector< Point > &points, std::vector< Real > &weights) const
Builds quadrature points for a given segment using the _segment_qrule.
unsigned long long int _ending_intersections
Total number of Ray/element intersections for Rays that finished on this processor.
std::shared_ptr< Ray > acquireReplicatedRay()
Acquire a Ray from the pool of Rays within generateRays() in a replicated fashion.
virtual void execute() override
Executes the study (generates and propagates Rays)
virtual void postExecuteStudy()
Entry point after study execution.
unsigned int _max_intersections
Max number of intersections for a single Ray.
bool isRectangularDomain() const
Whether or not the domain is rectangular (if it is prefectly encompassed by its bounding box)
std::shared_ptr< Ray > acquireUnsizedRay()
Acquire a Ray from the pool of Rays within generateRays(), without resizing the data (sizes the data ...
void registeredRaySetup()
Sets up the maps from Ray to associated RayTracingObjects if _use_ray_registration.
RayDataIndex getRayDataIndex(const std::string &name, const bool graceful=false) const
Gets the index associated with a registered value in the Ray data.
const bool _ray_kernel_coverage_check
Whether or not to perform coverage checks on RayKernels.
std::unique_ptr< libMesh::QBase > _segment_qrule
Quadrature rule for laying points across a 1D ray segment.
virtual void jacobianSetup() override
void moveRayToBuffer(std::shared_ptr< Ray > &ray)
Moves a ray to the buffer to be traced during generateRays().
const std::string & registeredRayName(const RayID ray_id) const
Gets the name of a registered ray.
void reserveRayBuffer(const std::size_t size)
Reserve size entires in the Ray buffer.
void verifyUniqueRayIDs(const std::vector< std::shared_ptr< Ray > >::const_iterator begin, const std::vector< std::shared_ptr< Ray > >::const_iterator end, const bool global, const std::string &error_suffix) const
Verifies that the Rays in the given range have unique Ray IDs.
std::unordered_map< SubdomainID, Real > _subdomain_hmax
The cached hmax for all elements in a subdomain.
bool verifyRays() const
Whether or not to verify if Rays have valid information before being traced.
RayID registeredRayID(const std::string &name, const bool graceful=false) const
Gets the ID of a registered ray.
virtual const Point & getSideNormal(const Elem *elem, const unsigned short side, const THREAD_ID tid)
Get the outward normal for a given element side.
virtual void meshChanged() override
unsigned long long int _total_processor_crossings
Total number of processor crossings.
std::vector< std::vector< TraceData > > _threaded_cached_traces
The threaded storage for cached traces.
std::vector< std::shared_ptr< TraceRay > > _threaded_trace_ray
The TraceRay objects for each thread (they do the physical tracing)
RayID generateReplicatedRayID()
Generates a Ray ID that is replicated across all processors.
ElemIndexHelper _elem_index_helper
Helper for defining a local contiguous index for each element.
std::shared_ptr< Ray > acquireRay()
User APIs for constructing Rays within the RayTracingStudy.
Real totalVolume() const
Get the current total volume of the domain.
const std::string & getRayDataName(const RayDataIndex index) const
Gets the name associated with a registered value in the Ray data.
std::chrono::steady_clock::duration _execution_time
std::size_t rayAuxDataSize() const
The registered size of values in the Ray aux data.
virtual void timestepSetup() override
RayData getBankedRayAuxData(const RayID ray_id, const RayDataIndex index) const
Gets the data value for a banked ray with a given ID.
std::unordered_map< std::string, RayDataIndex > _ray_data_map
The map from Ray data names to index.
const std::vector< std::shared_ptr< Ray > > & rayBank() const
Get the Ray bank.
std::vector< std::vector< std::set< const RayTracingObject * > > > _threaded_ray_object_registration
Threaded storage for all of the RayTracingObjects associated with a single Ray.
virtual RayID generateUniqueRayID(const THREAD_ID tid)
Generates a unique RayID to be used for a Ray.
std::vector< std::vector< unsigned short > > _non_planar_sides
Non planar side data, which is for quick checking if an elem side is non-planar We use unsigned short...
void coverageChecks()
Perform coverage checks (coverage of RayMaterials and RayKernels, if enabled)
const std::set< BoundaryID > & getInternalSidesets() const
Gets the internal sidesets (that have RayBCs) within the local domain.
virtual bool shouldCacheTrace(const std::shared_ptr< Ray > &) const
Virtual that allows for selection in if a Ray should be cached or not (only used when _cache_traces).
Real subdomainHmax(const SubdomainID subdomain_id) const
Get the cached hmax for all elements in a subdomain.
unsigned int _ending_max_trajectory_changes
Max number of trajectory changes for Rays that finished on this processor.
RayDataIndex getRayDataIndexInternal(const std::string &name, const bool aux, const bool graceful) const
Internal method for getting the index of Ray data or Ray aux data.
bool hasInternalSidesets() const
Whether or not the local mesh has internal sidesets that have RayBCs on them.
RayDataIndex getRayAuxDataIndex(const std::string &name, const bool graceful=false) const
Gets the index associated with a registered value in the Ray aux data.
libMesh::BoundingBox _b_box
Nodal bounding box for the domain.
void getRayBCs(std::vector< RayBoundaryConditionBase * > &result, BoundaryID id, THREAD_ID tid)
Fills the active RayBCs associated with this study and a boundary into result.
std::vector< RayDataIndex > getRayDataIndices(const std::vector< std::string > &names, const bool graceful=false) const
Gets the indices associated with registered values in the Ray data.
std::vector< RayDataIndex > getRayDataIndicesInternal(const std::vector< std::string > &names, const bool aux, const bool graceful) const
Internal method for getting the indicies of Ray data or Ray aux data.
void moveRaysToBuffer(std::vector< std::shared_ptr< Ray > > &rays)
Moves rays to the buffer to be traced during generateRays().
void dependencyChecks()
Perform checks to see if the listed dependencies in the RayTracingObjects exist.
const processor_id_type _pid
The rank of this processor (this actually takes time to lookup - so just do it once)
virtual void onCompleteRay(const std::shared_ptr< Ray > &ray)
Entry point for acting on a ray when it is completed (shouldContinue() == false)
std::vector< std::unique_ptr< libMesh::FEBase > > _threaded_fe_face
Face FE used for computing face normals for each thread.
bool _called_initial_setup
Whether or not we've called initial setup - used to stop from late registration.
RayData getBankedRayDataInternal(const RayID ray_id, const RayDataIndex index, const bool aux) const
Internal method for getting the value (replicated across all processors) in a Ray's data or aux data ...
std::vector< std::string > & _reverse_registered_ray_map
Map from registered Ray ID to name.
void periodicBoundaryChecks()
Check for overlapping PeriodicRayBC boundaries and check for cases in which ghosting may not be suffi...
bool hasRayKernels(const THREAD_ID tid)
Whether or not there are currently any active RayKernel objects.
void executeStudy()
Method for executing the study so that it can be called out of the standard UO execute()
unsigned int _max_processor_crossings
Max number of processor crossings for all Rays.
std::chrono::steady_clock::time_point _execution_start_time
Timing.
std::vector< std::size_t > _num_cached
Number of currently cached objects for Jacobian/residual for each thread.
bool currentlyPropagating() const
Whether or not the study is propagating (tracing Rays)
void zeroAuxVariables()
Zero the AuxVariables that the registered AuxRayKernels contribute to.
const bool _warn_non_planar
Whether not to warn if non-planar faces are found.
Class that is used as a parameter to the public constructors/reset methods.
Basic datastructure for a ray that will traverse the mesh.
static const RayDataIndex INVALID_RAY_DATA_INDEX
Invalid index into a Ray's data.
static const RayID INVALID_RAY_ID
Invalid Ray ID.
const ExecFlagEnum & _execute_enum
const bool & currentlyComputingJacobian() const
virtual bool hasActiveElementalMooseVariables(const THREAD_ID tid) const
virtual void zeroVariables(std::vector< std::string > &vars_to_be_zeroed)
unsigned int number() const
NumericVector< Number > & solution()
virtual libMesh::Order getMinQuadratureOrder()
void max(const T &r, T &o, Request &req) const
processor_id_type size() const
void min(const T &r, T &o, Request &req) const
void set_union(T &data, const unsigned int root_id) const
Traces Rays through the mesh on a single processor.
FEProblemBase & _fe_problem
const Point & max() const
void scale(const Real factor)
const Point & min() const
const Parallel::Communicator & _communicator
const Parallel::Communicator & comm() const
processor_id_type n_processors() const
const SubdomainID ANY_BLOCK_ID
std::string stringify(const T &t)
The following methods are specializations for using the Parallel::packed_range_* routines for a vecto...
Data structure that stores information for output of a partial trace of a Ray on a processor.