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")
204 if (!getParam<bool>(
"allow_other_flags_with_prekernels") &&
_execute_enum.
size() > 1)
206 "PRE_KERNELS cannot be mixed with any other execution flag.\nThat is, you cannot "
208 "mix RayKernels that contribute to the Jacobian/residual with those that do not.");
211 mooseError(
"Execution on residual and Jacobian evaluation (execute_on = PRE_KERNELS)\n",
212 "is not supported for an eigenvalue solve.");
257 std::vector<RayKernelBase *> ray_kernels;
259 for (
const auto & rkb : ray_kernels)
261 mooseError(
"This study has RayKernel objects that contribute to residuals and Jacobians.",
262 "\nIn this case, the study must use the execute_on = PRE_KERNELS");
273 mooseAssert(
_num_cached[tid] == 0,
"Cached residuals/Jacobians not empty");
276 rto->residualSetup();
283 mooseAssert(
_num_cached[tid] == 0,
"Cached residuals/Jacobians not empty");
286 rto->jacobianSetup();
293 rto->timestepSetup();
307 trace_ray->meshChanged();
322 std::vector<RayKernelBase *> ray_kernels;
325 std::set<SubdomainID> ray_kernel_blocks;
326 for (
const auto & rk : ray_kernels)
327 ray_kernel_blocks.insert(rk->blockIDs().begin(), rk->blockIDs().end());
329 std::set<SubdomainID> missing;
332 ray_kernel_blocks.begin(),
333 ray_kernel_blocks.end(),
334 std::inserter(missing, missing.begin()));
338 std::ostringstream error;
339 error <<
"Subdomains { ";
340 std::copy(missing.begin(), missing.end(), std::ostream_iterator<SubdomainID>(error,
" "));
341 error <<
"} do not have RayKernels defined!";
351 std::vector<RayTracingObject *> ray_tracing_objects;
363 for (
const auto & rto : rtos)
364 for (
const auto & dep_name : rto->getRequestedItems())
367 for (
const auto & rto_search : rtos)
368 if (rto_search->name() == dep_name)
375 rto->paramError(
"depends_on",
"The ", rto->getBase(),
" '", dep_name,
"' does not exist");
388 Utility::enum_to_string(elem->type()),
389 " is not supported in ray tracing with adaptivity");
393 Utility::enum_to_string(elem->type()),
394 " is not supported in ray tracing");
402 std::vector<const RayBoundaryConditionBase *> rbc_ptrs;
404 std::vector<const PeriodicRayBC *> prbc_ptrs;
405 for (
const auto rbc_ptr : rbc_ptrs)
406 if (
const auto prbc_ptr =
dynamic_cast<const PeriodicRayBC *
>(rbc_ptr))
407 prbc_ptrs.push_back(prbc_ptr);
408 if (prbc_ptrs.empty())
412 std::map<boundary_id_type,
415 std::unordered_set<dof_id_type>>>
417 for (
const auto prbc_ptr : prbc_ptrs)
419 for (
const auto & [bid, pb] : prbc_ptr->getPeriodicBoundaries())
421 const auto [it, inserted] = boundary_map.emplace(
422 std::piecewise_construct,
424 std::forward_as_tuple(prbc_ptr, pb.get(), std::unordered_set<dof_id_type>()));
426 prbc_ptr->mooseError(
"The periodic boundary '",
428 "' has been defined in both ",
429 prbc_ptr->typeAndName(),
431 std::get<0>(it->second)->typeAndName());
442 const auto & sideset_map =
_mesh.
getMesh().get_boundary_info().get_sideset_map();
443 for (
const auto & [elem, side_bid_pair] : sideset_map)
445 const auto [side, bid] = side_bid_pair;
446 if (
auto it = boundary_map.find(bid); it != boundary_map.end())
447 for (
const auto n : elem->nodes_on_side(side))
448 std::get<2>(it->second).insert(elem->node_ref(n).id());
452 for (
auto & bid_tuple_pair : boundary_map)
456 std::map<std::pair<boundary_id_type, boundary_id_type>,
457 std::pair<const PeriodicRayBC *, const PeriodicRayBC *>>
459 for (
auto it = boundary_map.begin(); it != boundary_map.end(); ++it)
461 const auto & [bid, tup] = *it;
462 const auto [prbc_ptr, pb, node_ids] = tup;
464 for (
auto other_it = std::next(it); other_it != boundary_map.end(); ++other_it)
466 const auto & [other_bid, other_tup] = *other_it;
469 if (pb->pairedboundary == other_bid)
472 const auto other_prbc_ptr = std::get<0>(other_tup);
473 const auto & other_node_ids = std::get<2>(other_tup);
474 for (
const auto node_id : node_ids)
475 if (other_node_ids.count(node_id))
477 if (!warn_boundaries.count(std::make_pair(other_bid, bid)))
478 warn_boundaries.emplace(std::make_pair(bid, other_bid),
479 std::make_pair(prbc_ptr, other_prbc_ptr));
485 if (warn_boundaries.size())
487 std::ostringstream oss;
488 oss << warn_boundaries.size()
489 <<
" ray tracing periodic boundaries were found to be neighbors:\n\n";
490 for (
const auto & [bids_pair, prbc_ptrs_pair] : warn_boundaries)
492 const auto [bid, paired_bid] = bids_pair;
493 const auto [prbc_ptr, paired_prbc_ptr] = prbc_ptrs_pair;
496 << paired_prbc_ptr->typeAndName() <<
")\n";
498 oss <<
"\nThe periodic propagation of rays at points where two or more periodic"
499 <<
"\nboundaries meet is not fully supported with a distributed mesh."
500 <<
"\n\nIf you encounter trace failures, you should use a replicated mesh.";
528 Elem * elem = bnd_elem->_elem;
529 const unsigned int side = bnd_elem->_side;
530 const auto bnd_id = bnd_elem->_bnd_id;
533 const Elem *
const neighbor = elem->neighbor_ptr(side);
534 if (!neighbor || neighbor == remote_elem)
538 std::vector<RayBoundaryConditionBase *> result;
543 if (neighbor->subdomain_id() == elem->subdomain_id())
544 mooseError(
"RayBCs exist on internal sidesets that are not bounded by a different",
545 "\nsubdomain on each side.",
546 "\n\nIn order to use RayBCs on internal sidesets, said sidesets must have",
547 "\na different subdomain on each side.");
558 entry.resize(elem->n_sides(), std::vector<BoundaryID>());
561 entry[side].push_back(bnd_id);
565 mooseError(
"RayBCs are defined on internal sidesets, but the study is not set to use ",
566 "internal sidesets during tracing.",
567 "\n\nSet the parameter use_internal_sidesets = true to enable this capability.");
584 for (
const Elem * elem :
_mesh.
getMesh().active_element_ptr_range())
588 entry.resize(elem->n_sides(), 0);
590 for (
const auto s : elem->side_index_range())
592 const auto & side =
elemSide(*elem, s);
593 if (side.n_vertices() < 4)
596 if (!side.has_affine_map())
604 "Ray tracing on non-planar faces is an approximation and may fail.\n\n",
605 "Use at your own risk! You can disable this warning by setting the\n",
606 "parameter 'warn_non_planar' to false.");
626 entry = std::max(entry, elem->hmax());
632 if (getParam<bool>(
"warn_subdomain_hmax"))
634 const auto warn_prefix =
type() +
" '" +
name() +
"': ";
635 const auto warn_suffix =
636 "\n\nRay tracing uses an approximate element size for each subdomain to scale the\n"
637 "tolerances used in computing ray intersections. This warning suggests that the\n"
638 "approximate element size is not a good approximation. This is likely due to poor\n"
639 "element aspect ratios.\n\n"
640 "This warning is only output for the first element affected.\n"
641 "To disable this warning, set warn_subdomain_hmax = false.\n";
645 const auto hmin = elem->hmin();
646 const auto hmax = elem->hmax();
649 const auto hmax_rel = hmax / max_hmax;
650 if (hmax_rel < 1.e-2 || hmax_rel > 1.e2)
652 "Element hmax varies significantly from subdomain hmax.\n",
654 "First element affected:\n",
657 const auto h_rel = max_hmax / hmin;
660 "Element hmin varies significantly from subdomain hmax.\n",
662 "First element affected:\n",
676 entry.resize(num_rays);
685 std::vector<std::string> all_ray_names;
688 all_ray_names.push_back(pair.first);
690 for (
auto & rto : rtos)
693 const auto & ray_names = rto->parameters().get<std::vector<std::string>>(
"rays");
695 const auto tid = rto->parameters().get<
THREAD_ID>(
"_tid");
699 for (
const auto & ray_name : (ray_names.empty() ? all_ray_names : ray_names))
704 "rays",
"Supplied ray '", ray_name,
"' is not a registered Ray in ",
typeAndName());
705 registration[id].insert(rto);
712 for (
const auto & rto : rtos)
713 if (rto->parameters().get<std::vector<std::string>>(
"rays").size())
716 "Rays cannot be supplied when the study does not require Ray registration.\n\n",
718 " does not require Ray registration.");
725 std::set<std::string> vars_to_be_zeroed;
726 std::vector<RayKernelBase *> ray_kernels;
728 for (
auto & rk : ray_kernels)
735 std::vector<std::string> vars_to_be_zeroed_vec(vars_to_be_zeroed.begin(),
736 vars_to_be_zeroed.end());
750 std::set<MooseVariableFEBase *> needed_moose_vars;
751 std::unordered_set<unsigned int> needed_mat_props;
757 rkb->subdomainSetup();
759 const auto & mv_deps = rkb->getMooseVariableDependencies();
760 needed_moose_vars.insert(mv_deps.begin(), mv_deps.end());
762 const auto & mp_deps = rkb->getMatPropDependencies();
763 needed_mat_props.insert(mp_deps.begin(), mp_deps.end());
767 for (
auto & var : needed_moose_vars)
768 if (var->kind() == Moose::VarKindType::VAR_AUXILIARY)
777 const Elem * elem,
const Point & start,
const Point & end,
const Real length,
THREAD_ID tid)
779 mooseAssert(MooseUtils::absoluteFuzzyEqual((start - end).norm(), length),
"Invalid length");
791 if (rk->needSegmentReinit())
801 std::vector<Point> points;
802 std::vector<Real> weights;
815 std::vector<Point> & points,
816 std::vector<Real> & weights)
const
821 const Point diff = end - start;
822 const Point sum = end + start;
823 mooseAssert(MooseUtils::absoluteFuzzyEqual(length, diff.norm()),
"Invalid length");
845 "Values should only be cached when computing Jacobian/residual");
854 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
865 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
875 TIME_SECTION(
"executeStudy", 2,
"Executing Study");
903 rto->preExecuteStudy();
920 auto generation_start_time = std::chrono::steady_clock::now();
922 TIME_SECTION(
"generateRays", 2,
"Generating Rays");
926 _generation_time = std::chrono::steady_clock::now() - generation_start_time;
935 "after generateRays()");
940 "after generateRays()");
946 TIME_SECTION(
"propagateRays", 2,
"Propagating Rays");
948 const auto propagation_start_time = std::chrono::steady_clock::now();
962 "after tracing completed");
970 "after tracing completed");
1001 type(),
" '",
name(),
"': ", failures,
" ray tracing failures were tolerated.\n");
1011 std::size_t num_entries = 0;
1029 "Should not have cached values without Jacobian/residual computation");
1052 rto->postExecuteStudy();
1079 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1082 mooseError(
"Cannot register Ray ", (aux ?
"aux " :
""),
"data after initialSetup()");
1085 const auto find = map.find(
name);
1086 if (find != map.end())
1087 return find->second;
1090 if (other_map.find(
name) != other_map.end())
1091 mooseError(
"Cannot register Ray aux data with name ",
1094 (aux ?
"(non-aux)" :
"aux"),
1095 " data already exists with said name.");
1098 map.emplace(
name, map.size());
1102 vector.push_back(
name);
1104 return map.size() - 1;
1107std::vector<RayDataIndex>
1110 std::vector<RayDataIndex> indices(names.size());
1111 for (std::size_t i = 0; i < names.size(); ++i)
1119 const bool graceful)
const
1121 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1124 const auto find = map.find(
name);
1125 if (find != map.end())
1126 return find->second;
1132 if (other_map.find(
name) != other_map.end())
1135 "' was not found.\n\n",
1137 (aux ?
"non-aux" :
"aux"),
1138 " data with said name was found.\n",
1139 "Did you mean to use ",
1140 (aux ?
"getRayDataIndex()/getRayDataIndices()?"
1141 :
"getRayAuxDataIndex()/getRayAuxDataIndices()"),
1144 mooseError(
"Unknown Ray ", (aux ?
"aux " :
""),
"data with name ",
name);
1147std::vector<RayDataIndex>
1150 const bool graceful)
const
1152 std::vector<RayDataIndex> indices(names.size());
1153 for (std::size_t i = 0; i < names.size(); ++i)
1161 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1164 mooseError(
"Unknown Ray ", aux ?
"aux " :
"",
"data with index ", index);
1174std::vector<RayDataIndex>
1186std::vector<RayDataIndex>
1188 const bool graceful )
const
1205std::vector<RayDataIndex>
1213 const bool graceful )
const
1218std::vector<RayDataIndex>
1220 const bool graceful )
const
1234 std::vector<RayKernelBase *> result;
1236 return result.size();
1247 mooseError(
"Should not call getRayKernels() before initialSetup()");
1252 .condition<AttribSystem>(
"RayKernel")
1275 std::vector<RayKernelBase *> rkbs;
1283 for (
auto rkb : rkbs)
1284 if (ray_id_rtos.count(rkb))
1285 result.push_back(rkb);
1299 mooseError(
"Should not call getRayBCs() before initialSetup()");
1304 .condition<AttribSystem>(
"RayBoundaryCondition")
1314 const std::vector<TraceRayBndElement> & bnd_elems,
1321 if (bnd_elems.size() == 1)
1322 getRayBCs(result, bnd_elems[0].bnd_id, tid);
1325 std::vector<BoundaryID> bnd_ids(bnd_elems.size());
1326 for (MooseIndex(bnd_elems.size()) i = 0; i < bnd_elems.size(); ++i)
1327 bnd_ids[i] = bnd_elems[i].bnd_id;
1335 std::vector<RayBoundaryConditionBase *> rbcs;
1336 if (bnd_elems.size() == 1)
1337 getRayBCs(rbcs, bnd_elems[0].bnd_id, tid);
1340 std::vector<BoundaryID> bnd_ids(bnd_elems.size());
1341 for (MooseIndex(bnd_elems.size()) i = 0; i < bnd_elems.size(); ++i)
1342 bnd_ids[i] = bnd_elems[i].bnd_id;
1352 for (
auto rbc : rbcs)
1353 if (ray_id_rtos.count(rbc))
1354 result.push_back(rbc);
1358std::vector<RayTracingObject *>
1361 std::vector<RayTracingObject *> result;
1366const std::vector<std::shared_ptr<Ray>> &
1370 mooseError(
"The Ray bank is not available because the private parameter "
1371 "'_bank_rays_on_completion' is set to false.");
1373 mooseError(
"Cannot get the Ray bank during generation or propagation.");
1383 std::shared_ptr<Ray> ray;
1384 for (
const std::shared_ptr<Ray> & possible_ray :
rayBank())
1385 if (possible_ray->id() == ray_id)
1392 unsigned int have_ray = ray ? 1 : 0;
1395 mooseError(
"Could not find a Ray with the ID ", ray_id,
" in the Ray banks.");
1398 mooseAssert(have_ray == 1,
"Multiple rays with the same ID were found in the Ray banks");
1406 const bool aux)
const
1411 Real value = ray ? (aux ? ray->auxData(index) : ray->data(index)) : 0;
1431 libmesh_parallel_only(
comm());
1433 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1436 mooseError(
"Cannot use registerRay() with Ray registration disabled");
1440 libmesh_parallel_only(
comm());
1455 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1458 mooseError(
"Should not use registeredRayID() with Ray registration disabled");
1462 return search->second;
1467 mooseError(
"Attempted to obtain ID of registered Ray ",
1469 ", but a Ray with said name is not registered.");
1475 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1478 mooseError(
"Should not use registeredRayName() with Ray registration disabled");
1483 mooseError(
"Attempted to obtain name of registered Ray with ID ",
1485 ", but a Ray with said ID is not registered.");
1493 volume += elem->volume();
1498const std::vector<std::vector<BoundaryID>> &
1504 "Internal sideset map not initialized");
1522 const std::vector<std::shared_ptr<Ray>>::const_iterator end,
1524 const std::string & error_suffix)
const
1529 std::set<RayID> local_rays;
1530 for (
const std::shared_ptr<Ray> & ray : as_range(begin, end))
1532 mooseAssert(ray,
"Null ray");
1536 if (!local_rays.insert(ray->id()).second)
1538 for (
const std::shared_ptr<Ray> & other_ray : as_range(begin, end))
1539 if (ray.get() != other_ray.get() && ray->id() == other_ray->id())
1546 "\n\nOffending Ray information:\n\n",
1549 other_ray->getInfo());
1557 std::map<processor_id_type, std::vector<RayID>> send_ids;
1558 if (local_rays.size())
1559 send_ids.emplace(std::piecewise_construct,
1560 std::forward_as_tuple(0),
1561 std::forward_as_tuple(local_rays.begin(), local_rays.end()));
1565 std::map<RayID, processor_id_type> global_map;
1568 const auto check_ids =
1569 [
this, &global_map, &error_suffix](processor_id_type pid,
const std::vector<RayID> & ids)
1571 for (
const RayID id : ids)
1573 const auto emplace_pair = global_map.emplace(
id, pid);
1576 if (!emplace_pair.second)
1579 " exists on ranks ",
1580 emplace_pair.first->second,
1588 Parallel::push_parallel_vector_data(
_communicator, send_ids, check_ids);
1594 const std::vector<std::shared_ptr<Ray>>::const_iterator end,
1595 const std::string & error_suffix)
1597 std::set<const Ray *> rays;
1598 for (
const std::shared_ptr<Ray> & ray : as_range(begin, end))
1599 if (!rays.insert(ray.get()).second)
1600 mooseError(
"Multiple shared_ptrs were found that point to the same Ray ",
1602 "\n\nOffending Ray:\n",
1610 mooseAssert(ray,
"Null ray");
1611 mooseAssert(ray->shouldContinue(),
"Ray is not continuing");
1621 for (
const std::shared_ptr<Ray> & ray : rays)
1623 mooseAssert(ray,
"Null ray");
1624 mooseAssert(ray->shouldContinue(),
"Ray is not continuing");
1636 mooseAssert(ray,
"Null ray");
1646 mooseError(
"Can only reserve in Ray buffer during generateRays()");
1654 std::unordered_map<std::pair<const Elem *, unsigned short>, Point> & cache =
1658 const auto elem_side_pair = std::make_pair(elem, side);
1659 const auto search = cache.find(elem_side_pair);
1662 if (search == cache.end())
1666 cache.emplace(elem_side_pair, normal);
1671 return search->second;
1677 unsigned int min_level = std::numeric_limits<unsigned int>::max();
1678 unsigned int max_level = std::numeric_limits<unsigned int>::min();
1682 const auto level = elem->level();
1683 min_level = std::min(level, min_level);
1684 max_level = std::max(level, max_level);
1690 return min_level == max_level;
1698 mooseError(
"Subdomain ", subdomain_id,
" not found in subdomain hmax map");
1699 return find->second;
1705 Real bbox_volume = 1;
1709 return MooseUtils::absoluteFuzzyEqual(bbox_volume,
totalVolume(), TOLERANCE);
1715 libmesh_parallel_only(
comm());
1717 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1720 "Cannot be reset during generation or propagation");
1741 libmesh_parallel_only(
comm());
1743 Threads::spin_mutex::scoped_lock lock(
_spin_mutex);
1746 "Cannot be reset during generation or propagation");
1759 const unsigned short side,
1760 const Point & direction,
1764 const auto dot = normal * direction;
1801 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.