• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Open-Sn / opensn / 22701806567

04 Mar 2026 02:49PM UTC coverage: 74.311% (+0.04%) from 74.268%
22701806567

push

github

web-flow
Merge pull request #957 from wdhawkins/lbs_problem_api

Refactor LBSProblem for const-correct API, reduced visibility, and unified error reporting

66 of 93 new or added lines in 17 files covered. (70.97%)

3 existing lines in 2 files now uncovered.

20009 of 26926 relevant lines covered (74.31%)

67212610.44 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

82.9
/modules/linear_boltzmann_solvers/lbs_problem/lbs_problem.cc
1
// SPDX-FileCopyrightText: 2024 The OpenSn Authors <https://open-sn.github.io/opensn/>
2
// SPDX-License-Identifier: MIT
3

4
#include "modules/linear_boltzmann_solvers/lbs_problem/lbs_problem.h"
5
#include "modules/linear_boltzmann_solvers/discrete_ordinates_problem/discrete_ordinates_problem.h"
6
#include "modules/linear_boltzmann_solvers/lbs_problem/iterative_methods/wgs_context.h"
7
#include "modules/linear_boltzmann_solvers/lbs_problem/iterative_methods/ags_linear_solver.h"
8
#include "modules/linear_boltzmann_solvers/lbs_problem/point_source/point_source.h"
9
#include "modules/linear_boltzmann_solvers/lbs_problem/groupset/lbs_groupset.h"
10
#include "framework/field_functions/field_function_grid_based.h"
11
#include "framework/materials/multi_group_xs/multi_group_xs.h"
12
#include "framework/mesh/mesh_continuum/mesh_continuum.h"
13
#include "framework/utils/hdf_utils.h"
14
#include "framework/object_factory.h"
15
#include "framework/logging/log.h"
16
#include "framework/runtime.h"
17
#include "framework/data_types/allowable_range.h"
18
#include "framework/utils/error.h"
19
#include "caliper/cali.h"
20
#include <algorithm>
21
#include <iomanip>
22
#include <fstream>
23
#include <cstring>
24
#include <cassert>
25
#include <memory>
26
#include <stdexcept>
27
#include <sys/stat.h>
28

29
namespace opensn
30
{
31

32
InputParameters
33
LBSProblem::GetInputParameters()
583✔
34
{
35
  InputParameters params = Problem::GetInputParameters();
583✔
36

37
  params.ChangeExistingParamToOptional("name", "LBSProblem");
1,166✔
38

39
  params.AddRequiredParameter<std::shared_ptr<MeshContinuum>>("mesh", "Mesh");
1,166✔
40

41
  params.AddRequiredParameter<unsigned int>("num_groups",
1,166✔
42
                                            "The total number of groups within the solver");
43

44
  params.AddRequiredParameterArray("groupsets",
1,166✔
45
                                   "An array of blocks each specifying the input parameters for a "
46
                                   "<TT>LBSGroupset</TT>.");
47
  params.LinkParameterToBlock("groupsets", "LBSGroupset");
1,166✔
48

49
  params.AddRequiredParameterArray("xs_map",
1,166✔
50
                                   "Cross-section map from block IDs to cross-section objects.");
51

52
  params.AddOptionalParameterArray<std::shared_ptr<VolumetricSource>>(
1,166✔
53
    "volumetric_sources", {}, "An array of handles to volumetric sources.");
54

55
  params.AddOptionalParameterArray<std::shared_ptr<PointSource>>(
1,166✔
56
    "point_sources", {}, "An array of point sources.");
57

58
  params.AddOptionalParameterBlock(
1,166✔
59
    "options", ParameterBlock(), "Block of options. See <TT>OptionsBlock</TT>.");
1,166✔
60
  params.LinkParameterToBlock("options", "OptionsBlock");
1,166✔
61

62
  params.AddOptionalParameter("use_gpus", false, "Offload the sweep computation to GPUs.");
1,166✔
63

64
  return params;
583✔
65
}
×
66

67
LBSProblem::LBSProblem(const InputParameters& params)
583✔
68
  : Problem(params),
69
    num_groups_(params.GetParamValue<unsigned int>("num_groups")),
583✔
70
    grid_(params.GetSharedPtrParam<MeshContinuum>("mesh")),
583✔
71
    use_gpus_(params.GetParamValue<bool>("use_gpus"))
1,749✔
72
{
73
  // Check system for GPU acceleration
74
  if (use_gpus_)
583✔
75
  {
76
#ifdef __OPENSN_WITH_GPU__
77
    CheckCapableDevices();
78
#else
NEW
79
    OpenSnInvalidArgument(
×
80
      GetName() + ": GPU support was requested, but OpenSn was built without CUDA enabled.");
81
#endif // __OPENSN_WITH_GPU__
82
  }
83

84
  // Initialize options
85
  if (params.IsParameterValid("options"))
583✔
86
  {
87
    auto options_params = LBSProblem::GetOptionsBlock();
355✔
88
    options_params.AssignParameters(params.GetParam("options"));
357✔
89
    ParseOptions(options_params);
353✔
90
  }
355✔
91
  applied_adjoint_ = options_.adjoint;
581✔
92
  applied_save_angular_flux_ = options_.save_angular_flux;
581✔
93

94
  // Set geometry type
95
  geometry_type_ = grid_->GetGeometryType();
581✔
96
  OpenSnInvalidArgumentIf(geometry_type_ == GeometryType::INVALID,
581✔
97
                          GetName() + ": Invalid geometry type.");
98

99
  InitializeGroupsets(params);
581✔
100
  InitializeSources(params);
581✔
101
  InitializeXSmapAndDensities(params);
581✔
102
  InitializeMaterials();
581✔
103
}
601✔
104

105
const LBSOptions&
106
LBSProblem::GetOptions() const
685,756,282✔
107
{
108
  return options_;
685,756,282✔
109
}
110

111
double
112
LBSProblem::GetTime() const
442,052✔
113
{
114
  return time_;
442,052✔
115
}
116

117
void
118
LBSProblem::SetTime(double time)
5,660✔
119
{
120
  time_ = time;
5,660✔
121
}
5,660✔
122

123
void
124
LBSProblem::SetTimeStep(double dt)
1,808✔
125
{
126
  OpenSnInvalidArgumentIf(dt <= 0.0, GetName() + ": dt must be greater than zero.");
1,808✔
127
  dt_ = dt;
1,808✔
128
}
1,808✔
129

130
double
131
LBSProblem::GetTimeStep() const
2,147,483,647✔
132
{
133
  return dt_;
2,147,483,647✔
134
}
135

136
void
137
LBSProblem::SetTheta(double theta)
272✔
138
{
139
  OpenSnInvalidArgumentIf(theta <= 0.0 or theta > 1.0,
272✔
140
                          GetName() + ": theta must be in (0.0, 1.0].");
141
  theta_ = theta;
272✔
142
}
272✔
143

144
double
145
LBSProblem::GetTheta() const
2,147,483,647✔
146
{
147
  return theta_;
2,147,483,647✔
148
}
149

150
bool
151
LBSProblem::IsTimeDependent() const
×
152
{
153
  return false;
×
154
}
155

156
void
157
LBSProblem::SetTimeDependentMode()
×
158
{
NEW
159
  OpenSnLogicalError(GetName() + ": Time-dependent mode is not supported for this problem type.");
×
160
}
161

162
void
163
LBSProblem::SetSteadyStateMode()
×
164
{
165
  // Steady-state is the default for problem types without time-dependent support.
166
}
×
167

168
GeometryType
169
LBSProblem::GetGeometryType() const
4✔
170
{
171
  return geometry_type_;
4✔
172
}
173

174
unsigned int
175
LBSProblem::GetNumMoments() const
546,746✔
176
{
177
  return num_moments_;
546,746✔
178
}
179

180
unsigned int
181
LBSProblem::GetMaxCellDOFCount() const
744✔
182
{
183
  return max_cell_dof_count_;
744✔
184
}
185

186
unsigned int
187
LBSProblem::GetMinCellDOFCount() const
744✔
188
{
189
  return min_cell_dof_count_;
744✔
190
}
191

192
bool
193
LBSProblem::UseGPUs() const
1,056✔
194
{
195
  return use_gpus_;
1,056✔
196
}
197

198
unsigned int
199
LBSProblem::GetNumGroups() const
849,040✔
200
{
201
  return num_groups_;
849,040✔
202
}
203

204
unsigned int
205
LBSProblem::GetScatteringOrder() const
4✔
206
{
207
  return scattering_order_;
4✔
208
}
209

210
unsigned int
211
LBSProblem::GetNumPrecursors() const
×
212
{
213
  return num_precursors_;
×
214
}
215

216
unsigned int
217
LBSProblem::GetMaxPrecursorsPerMaterial() const
9,550✔
218
{
219
  return max_precursors_per_material_;
9,550✔
220
}
221

222
const std::vector<LBSGroupset>&
223
LBSProblem::GetGroupsets() const
28,092✔
224
{
225
  return groupsets_;
28,092✔
226
}
227

228
LBSGroupset&
229
LBSProblem::GetGroupset(size_t groupset_id)
22,578,778✔
230
{
231
  return groupsets_.at(groupset_id);
22,578,778✔
232
}
233

234
const LBSGroupset&
NEW
235
LBSProblem::GetGroupset(size_t groupset_id) const
×
236
{
NEW
237
  return groupsets_.at(groupset_id);
×
238
}
239

240
size_t
241
LBSProblem::GetNumGroupsets() const
67✔
242
{
243
  return groupsets_.size();
67✔
244
}
245

246
void
247
LBSProblem::AddPointSource(std::shared_ptr<PointSource> point_source)
×
248
{
249
  point_sources_.push_back(point_source);
×
250
  if (initialized_)
×
251
    point_sources_.back()->Initialize(*this);
×
252
}
×
253

254
void
255
LBSProblem::ClearPointSources()
×
256
{
257
  point_sources_.clear();
×
258
}
×
259

260
const std::vector<std::shared_ptr<PointSource>>&
261
LBSProblem::GetPointSources() const
155,868✔
262
{
263
  return point_sources_;
155,868✔
264
}
265

266
void
267
LBSProblem::AddVolumetricSource(std::shared_ptr<VolumetricSource> volumetric_source)
24✔
268
{
269
  volumetric_sources_.push_back(volumetric_source);
24✔
270
  if (initialized_)
24✔
271
    volumetric_sources_.back()->Initialize(*this);
24✔
272
}
24✔
273

274
void
275
LBSProblem::ClearVolumetricSources()
12✔
276
{
277
  volumetric_sources_.clear();
12✔
278
}
12✔
279

280
const std::vector<std::shared_ptr<VolumetricSource>>&
281
LBSProblem::GetVolumetricSources() const
155,868✔
282
{
283
  return volumetric_sources_;
155,868✔
284
}
285

286
const BlockID2XSMap&
287
LBSProblem::GetBlockID2XSMap() const
19,271✔
288
{
289
  return block_id_to_xs_map_;
19,271✔
290
}
291

292
void
293
LBSProblem::SetBlockID2XSMap(const BlockID2XSMap& xs_map)
172✔
294
{
295
  block_id_to_xs_map_ = xs_map;
172✔
296
  InitializeMaterials();
172✔
297
  ResetGPUCarriers();
172✔
298
  InitializeGPUExtras();
172✔
299
}
172✔
300

301
std::shared_ptr<MeshContinuum>
302
LBSProblem::GetGrid() const
780,731✔
303
{
304
  return grid_;
780,731✔
305
}
306

307
const SpatialDiscretization&
308
LBSProblem::GetSpatialDiscretization() const
248,348✔
309
{
310
  return *discretization_;
248,348✔
311
}
312

313
const std::vector<UnitCellMatrices>&
314
LBSProblem::GetUnitCellMatrices() const
20,237✔
315
{
316
  return unit_cell_matrices_;
20,237✔
317
}
318

319
const std::map<uint64_t, UnitCellMatrices>&
320
LBSProblem::GetUnitGhostCellMatrices() const
17✔
321
{
322
  return unit_ghost_cell_matrices_;
17✔
323
}
324

325
std::vector<CellLBSView>&
326
LBSProblem::GetCellTransportViews()
312,393✔
327
{
328
  return cell_transport_views_;
312,393✔
329
}
330

331
const std::vector<CellLBSView>&
332
LBSProblem::GetCellTransportViews() const
661,038✔
333
{
334
  return cell_transport_views_;
661,038✔
335
}
336

337
const UnknownManager&
338
LBSProblem::GetUnknownManager() const
27,044✔
339
{
340
  return flux_moments_uk_man_;
27,044✔
341
}
342

343
size_t
344
LBSProblem::GetLocalNodeCount() const
3,288✔
345
{
346
  return local_node_count_;
3,288✔
347
}
348

349
size_t
350
LBSProblem::GetGlobalNodeCount() const
2,684✔
351
{
352
  return global_node_count_;
2,684✔
353
}
354

355
std::vector<double>&
356
LBSProblem::GetQMomentsLocal()
377,261✔
357
{
358
  return q_moments_local_;
377,261✔
359
}
360

361
const std::vector<double>&
362
LBSProblem::GetQMomentsLocal() const
×
363
{
364
  return q_moments_local_;
×
365
}
366

367
std::vector<double>&
368
LBSProblem::GetExtSrcMomentsLocal()
4✔
369
{
370
  return ext_src_moments_local_;
4✔
371
}
372

373
const std::vector<double>&
374
LBSProblem::GetExtSrcMomentsLocal() const
220,346✔
375
{
376
  return ext_src_moments_local_;
220,346✔
377
}
378

379
std::vector<double>&
380
LBSProblem::GetPhiOldLocal()
287,829✔
381
{
382
  return phi_old_local_;
287,829✔
383
}
384

385
const std::vector<double>&
386
LBSProblem::GetPhiOldLocal() const
×
387
{
388
  return phi_old_local_;
×
389
}
390

391
std::vector<double>&
392
LBSProblem::GetPhiNewLocal()
259,656✔
393
{
394
  return phi_new_local_;
259,656✔
395
}
396

397
const std::vector<double>&
398
LBSProblem::GetPhiNewLocal() const
×
399
{
400
  return phi_new_local_;
×
401
}
402

403
std::vector<double>&
404
LBSProblem::GetPrecursorsNewLocal()
436✔
405
{
406
  return precursor_new_local_;
436✔
407
}
408

409
const std::vector<double>&
410
LBSProblem::GetPrecursorsNewLocal() const
×
411
{
412
  return precursor_new_local_;
×
413
}
414

415
std::vector<double>&
416
LBSProblem::GetDensitiesLocal()
994✔
417
{
418
  return densities_local_;
994✔
419
}
420

421
const std::vector<double>&
422
LBSProblem::GetDensitiesLocal() const
220,346✔
423
{
424
  return densities_local_;
220,346✔
425
}
426

427
SetSourceFunction
428
LBSProblem::GetActiveSetSourceFunction() const
4,397✔
429
{
430
  return active_set_source_function_;
4,397✔
431
}
432

433
void
434
LBSProblem::SetActiveSetSourceFunction(SetSourceFunction source_function)
104✔
435
{
436
  active_set_source_function_ = std::move(source_function);
104✔
437
}
104✔
438

439
std::shared_ptr<AGSLinearSolver>
440
LBSProblem::GetAGSSolver() const
2,936✔
441
{
442
  return ags_solver_;
2,936✔
443
}
444

445
std::shared_ptr<LinearSolver>
446
LBSProblem::GetWGSSolver(size_t groupset_id) const
2,821✔
447
{
448
  return wgs_solvers_.at(groupset_id);
2,821✔
449
}
450

451
size_t
452
LBSProblem::GetNumWGSSolvers() const
5,324✔
453
{
454
  return wgs_solvers_.size();
5,324✔
455
}
456

457
WGSContext&
458
LBSProblem::GetWGSContext(int groupset_id)
11,901✔
459
{
460
  auto& wgs_solver = wgs_solvers_[groupset_id];
11,901✔
461
  auto raw_context = wgs_solver->GetContext();
11,901✔
462
  auto wgs_context_ptr = std::dynamic_pointer_cast<WGSContext>(raw_context);
11,901✔
463
  OpenSnLogicalErrorIf(not wgs_context_ptr,
11,901✔
464
                       GetName() + ": Failed to cast solver context to WGSContext.");
465
  return *wgs_context_ptr;
11,901✔
466
}
23,802✔
467

468
std::pair<size_t, size_t>
469
LBSProblem::GetNumPhiIterativeUnknowns()
×
470
{
471
  const auto& sdm = *discretization_;
×
472
  const size_t num_local_phi_dofs = sdm.GetNumLocalDOFs(flux_moments_uk_man_);
×
473
  const size_t num_global_phi_dofs = sdm.GetNumGlobalDOFs(flux_moments_uk_man_);
×
474

475
  return {num_local_phi_dofs, num_global_phi_dofs};
×
476
}
477

478
std::shared_ptr<FieldFunctionGridBased>
479
LBSProblem::GetScalarFluxFieldFunction(unsigned int g, unsigned int m) const
28,985✔
480
{
481
  OpenSnLogicalErrorIf(g >= num_groups_, GetName() + ": Group index out of range.");
28,985✔
482
  OpenSnLogicalErrorIf(m >= num_moments_, GetName() + ": Moment index out of range.");
28,985✔
483

484
  const auto map_it = phi_field_functions_local_map_.find({g, m});
28,985✔
485
  OpenSnLogicalErrorIf(map_it == phi_field_functions_local_map_.end(),
28,985✔
486
                       GetName() + ": Failed to map phi field function for g=" + std::to_string(g) +
487
                         ", m=" + std::to_string(m) + ".");
488

489
  return field_functions_.at(map_it->second);
57,970✔
490
}
491

492
std::shared_ptr<FieldFunctionGridBased>
493
LBSProblem::GetPowerFieldFunction() const
1✔
494
{
495
  OpenSnLogicalErrorIf(not options_.power_field_function_on,
1✔
496
                       GetName() + ": GetPowerFieldFunction called with "
497
                                   "options_.power_field_function_on=false.");
498

499
  return field_functions_[power_gen_fieldfunc_local_handle_];
2✔
500
}
501

502
InputParameters
503
LBSProblem::GetOptionsBlock()
732✔
504
{
505
  InputParameters params;
732✔
506

507
  params.SetGeneralDescription("Set options from a large list of parameters");
1,464✔
508
  params.AddOptionalParameter("max_mpi_message_size",
1,464✔
509
                              32768,
510
                              "The maximum MPI message size used during sweep initialization.");
511
  params.AddOptionalParameter(
1,464✔
512
    "restart_writes_enabled", false, "Flag that controls writing of restart dumps");
513
  params.AddOptionalParameter("write_delayed_psi_to_restart",
1,464✔
514
                              true,
515
                              "Flag that controls writing of delayed angular fluxes to restarts.");
516
  params.AddOptionalParameter(
1,464✔
517
    "read_restart_path", "", "Full path for reading restart dumps including file stem.");
518
  params.AddOptionalParameter(
1,464✔
519
    "write_restart_path", "", "Full path for writing restart dumps including file stem.");
520
  params.AddOptionalParameter("write_restart_time_interval",
1,464✔
521
                              0,
522
                              "Time interval in seconds at which restart data is to be written.");
523
  params.AddOptionalParameter(
1,464✔
524
    "use_precursors", false, "Flag for using delayed neutron precursors.");
525
  params.AddOptionalParameter("use_source_moments",
1,464✔
526
                              false,
527
                              "Flag for ignoring fixed sources and selectively using source "
528
                              "moments obtained elsewhere.");
529
  params.AddOptionalParameter(
1,464✔
530
    "save_angular_flux", false, "Flag indicating whether angular fluxes are to be stored or not.");
531
  params.AddOptionalParameter(
1,464✔
532
    "adjoint", false, "Flag for toggling whether the solver is in adjoint mode.");
533
  params.AddOptionalParameter(
1,464✔
534
    "verbose_inner_iterations", true, "Flag to control verbosity of inner iterations.");
535
  params.AddOptionalParameter(
1,464✔
536
    "verbose_outer_iterations", true, "Flag to control verbosity of across-groupset iterations.");
537
  params.AddOptionalParameter(
1,464✔
538
    "max_ags_iterations", 100, "Maximum number of across-groupset iterations.");
539
  params.AddOptionalParameter("ags_tolerance", 1.0e-6, "Across-groupset iterations tolerance.");
1,464✔
540
  params.AddOptionalParameter("ags_convergence_check",
1,464✔
541
                              "l2",
542
                              "Type of convergence check for AGS iterations. Valid values are "
543
                              "`\"l2\"` and '\"pointwise\"'");
544
  params.AddOptionalParameter(
1,464✔
545
    "verbose_ags_iterations", true, "Flag to control verbosity of across-groupset iterations.");
546
  params.AddOptionalParameter("power_field_function_on",
1,464✔
547
                              false,
548
                              "Flag to control the creation of the power generation field "
549
                              "function. If set to `true` then a field function will be created "
550
                              "with the general name <solver_name>_power_generation`.");
551
  params.AddOptionalParameter("power_default_kappa",
1,464✔
552
                              3.20435e-11,
553
                              "Default `kappa` value (Energy released per fission) to use for "
554
                              "power generation when cross sections do not have `kappa` values. "
555
                              "Default: 3.20435e-11 Joule (corresponding to 200 MeV per fission).");
556
  params.AddOptionalParameter("power_normalization",
1,464✔
557
                              -1.0,
558
                              "Power normalization factor to use. Supply a negative or zero number "
559
                              "to turn this off.");
560
  params.AddOptionalParameter("field_function_prefix_option",
1,464✔
561
                              "prefix",
562
                              "Prefix option on field function names. Default: `\"prefix\"`. Can "
563
                              "be `\"prefix\"` or `\"solver_name\"`. By default this option uses "
564
                              "the value of the `field_function_prefix` parameter. If this "
565
                              "parameter is not set, flux field functions will be exported as "
566
                              "`phi_gXXX_mYYY` where `XXX` is the zero padded 3 digit group number "
567
                              "and `YYY` is the zero padded 3 digit moment.");
568
  params.AddOptionalParameter("field_function_prefix",
1,464✔
569
                              "",
570
                              "Prefix to use on all field functions. Default: `\"\"`. By default "
571
                              "this option is empty. Ff specified, flux moments will be exported "
572
                              "as `prefix_phi_gXXX_mYYY` where `XXX` is the zero padded 3 digit "
573
                              "group number and `YYY` is the zero padded 3 digit moment. The "
574
                              "underscore after \"prefix\" is added automatically.");
575
  params.ConstrainParameterRange("ags_convergence_check",
2,196✔
576
                                 AllowableRangeList::New({"l2", "pointwise"}));
732✔
577
  params.ConstrainParameterRange("field_function_prefix_option",
2,196✔
578
                                 AllowableRangeList::New({"prefix", "solver_name"}));
732✔
579
  params.ConstrainParameterRange("max_mpi_message_size", AllowableRangeLowLimit::New(1024));
2,196✔
580
  params.ConstrainParameterRange("write_restart_time_interval", AllowableRangeLowLimit::New(0));
2,196✔
581
  params.ConstrainParameterRange("max_ags_iterations", AllowableRangeLowLimit::New(0));
2,196✔
582
  params.ConstrainParameterRange("ags_tolerance", AllowableRangeLowLimit::New(1.0e-18));
2,196✔
583
  params.ConstrainParameterRange("power_default_kappa", AllowableRangeLowLimit::New(0.0, false));
2,196✔
584

585
  return params;
732✔
586
}
×
587

588
InputParameters
589
LBSProblem::GetXSMapEntryBlock()
1,010✔
590
{
591
  InputParameters params;
1,010✔
592
  params.SetGeneralDescription("Set the cross-section map for the solver.");
2,020✔
593
  params.AddRequiredParameterArray("block_ids", "Mesh block IDs");
2,020✔
594
  params.AddRequiredParameter<std::shared_ptr<MultiGroupXS>>("xs", "Cross-section object");
2,020✔
595
  return params;
1,010✔
596
}
×
597

598
void
599
LBSProblem::SetOptions(const InputParameters& input)
12✔
600
{
601
  ParseOptions(input);
12✔
602
  ApplyOptions();
12✔
603
}
12✔
604

605
void
606
LBSProblem::ParseOptions(const InputParameters& input)
365✔
607
{
608
  auto params = LBSProblem::GetOptionsBlock();
365✔
609
  params.AssignParameters(input);
365✔
610
  const auto& params_at_assignment = input.GetParametersAtAssignment();
365✔
611
  const auto& specified_params = params_at_assignment.GetNumParameters() > 0
365✔
612
                                   ? params_at_assignment
365✔
613
                                   : static_cast<const ParameterBlock&>(input);
365✔
614

615
  // Apply only options explicitly specified by the caller.
616
  for (const auto& spec : specified_params.GetParameters())
1,357✔
617
  {
618
    if (spec.GetName() == "max_mpi_message_size")
992✔
619
      options_.max_mpi_message_size = spec.GetValue<int>();
×
620

621
    else if (spec.GetName() == "restart_writes_enabled")
992✔
622
      options_.restart_writes_enabled = spec.GetValue<bool>();
×
623

624
    else if (spec.GetName() == "write_delayed_psi_to_restart")
992✔
625
      options_.write_delayed_psi_to_restart = spec.GetValue<bool>();
×
626

627
    else if (spec.GetName() == "read_restart_path")
992✔
628
    {
629
      options_.read_restart_path = spec.GetValue<std::string>();
12✔
630
      if (not options_.read_restart_path.empty())
12✔
631
        options_.read_restart_path += std::to_string(opensn::mpi_comm.rank()) + ".restart.h5";
36✔
632
    }
633

634
    else if (spec.GetName() == "write_restart_path")
980✔
635
    {
636
      options_.write_restart_path = spec.GetValue<std::string>();
×
637
      if (not options_.write_restart_path.empty())
×
638
        options_.write_restart_path += std::to_string(opensn::mpi_comm.rank()) + ".restart.h5";
×
639
    }
640

641
    else if (spec.GetName() == "write_restart_time_interval")
980✔
642
      options_.write_restart_time_interval = std::chrono::seconds(spec.GetValue<int>());
×
643

644
    else if (spec.GetName() == "use_precursors")
980✔
645
      options_.use_precursors = spec.GetValue<bool>();
124✔
646

647
    else if (spec.GetName() == "use_source_moments")
856✔
648
      options_.use_src_moments = spec.GetValue<bool>();
4✔
649

650
    else if (spec.GetName() == "save_angular_flux")
852✔
651
      options_.save_angular_flux = spec.GetValue<bool>();
202✔
652

653
    else if (spec.GetName() == "verbose_inner_iterations")
650✔
654
      options_.verbose_inner_iterations = spec.GetValue<bool>();
216✔
655

656
    else if (spec.GetName() == "max_ags_iterations")
434✔
657
      options_.max_ags_iterations = spec.GetValue<int>();
50✔
658

659
    else if (spec.GetName() == "ags_tolerance")
384✔
660
      options_.ags_tolerance = spec.GetValue<double>();
8✔
661

662
    else if (spec.GetName() == "ags_convergence_check")
376✔
663
    {
664
      auto check = spec.GetValue<std::string>();
×
665
      options_.ags_pointwise_convergence = (check == "pointwise");
×
666
    }
×
667

668
    else if (spec.GetName() == "verbose_ags_iterations")
376✔
669
      options_.verbose_ags_iterations = spec.GetValue<bool>();
132✔
670

671
    else if (spec.GetName() == "verbose_outer_iterations")
244✔
672
      options_.verbose_outer_iterations = spec.GetValue<bool>();
192✔
673

674
    else if (spec.GetName() == "power_field_function_on")
52✔
675
      options_.power_field_function_on = spec.GetValue<bool>();
5✔
676

677
    else if (spec.GetName() == "power_default_kappa")
47✔
678
      options_.power_default_kappa = spec.GetValue<double>();
13✔
679

680
    else if (spec.GetName() == "power_normalization")
34✔
681
      options_.power_normalization = spec.GetValue<double>();
13✔
682

683
    else if (spec.GetName() == "field_function_prefix_option")
21✔
684
    {
685
      options_.field_function_prefix_option = spec.GetValue<std::string>();
×
686
    }
687

688
    else if (spec.GetName() == "field_function_prefix")
21✔
689
      options_.field_function_prefix = spec.GetValue<std::string>();
1✔
690

691
    else if (spec.GetName() == "adjoint")
20✔
692
      options_.adjoint = spec.GetValue<bool>();
20✔
693

694
  } // for specified options
695

696
  OpenSnInvalidArgumentIf(options_.write_restart_time_interval > std::chrono::seconds(0) and
365✔
697
                            not options_.restart_writes_enabled,
698
                          GetName() + ": `write_restart_time_interval>0` requires "
699
                                      "`restart_writes_enabled=true`.");
700

701
  OpenSnInvalidArgumentIf(options_.write_restart_time_interval > std::chrono::seconds(0) and
365✔
702
                            options_.write_restart_time_interval < std::chrono::seconds(30),
703
                          GetName() + ": `write_restart_time_interval` must be 0 (disabled) "
704
                                      "or at least 30 seconds.");
705

706
  OpenSnInvalidArgumentIf(options_.restart_writes_enabled and options_.write_restart_path.empty(),
365✔
707
                          GetName() + ": `restart_writes_enabled=true` requires a non-empty "
708
                                      "`write_restart_path`.");
709

710
  OpenSnInvalidArgumentIf(not options_.field_function_prefix.empty() and
365✔
711
                            options_.field_function_prefix_option != "prefix",
712
                          GetName() + ": non-empty `field_function_prefix` requires "
713
                                      "`field_function_prefix_option=\"prefix\"`.");
714

715
  if (options_.restart_writes_enabled)
365✔
716
  {
717
    const auto dir = options_.write_restart_path.parent_path();
×
718

719
    // Create restart directory if necessary.
720
    // If dir is empty, write path resolves relative to the working directory.
721
    if ((not dir.empty()) and opensn::mpi_comm.rank() == 0)
×
722
    {
723
      if (not std::filesystem::exists(dir))
×
724
      {
NEW
725
        OpenSnLogicalErrorIf(not std::filesystem::create_directories(dir),
×
726
                             GetName() + ": Failed to create restart directory " + dir.string());
727
      }
728
      else
NEW
729
        OpenSnLogicalErrorIf(not std::filesystem::is_directory(dir),
×
730
                             GetName() + ": Restart path exists but is not a directory " +
731
                               dir.string());
732
    }
733
    opensn::mpi_comm.barrier();
×
734
    UpdateRestartWriteTime();
×
735
  }
×
736
}
365✔
737

738
void
739
LBSProblem::ApplyOptions()
12✔
740
{
741
  if (not initialized_)
12✔
742
    return;
743

744
  if (options_.adjoint != applied_adjoint_)
12✔
745
    SetAdjoint(options_.adjoint);
4✔
746

747
  if (options_.save_angular_flux != applied_save_angular_flux_)
12✔
748
    SetSaveAngularFlux(options_.save_angular_flux);
×
749
}
750

751
void
752
LBSProblem::BuildRuntime()
581✔
753
{
754
  CALI_CXX_MARK_SCOPE("LBSProblem::BuildRuntime");
581✔
755
  if (initialized_)
581✔
756
    return;
×
757

758
  PrintSimHeader();
581✔
759
  mpi_comm.barrier();
581✔
760

761
  InitializeRuntimeCore();
581✔
762
  ValidateRuntimeModeConfiguration();
581✔
763
  InitializeSources();
581✔
764

765
  initialized_ = true;
581✔
766
}
581✔
767

768
void
769
LBSProblem::InitializeRuntimeCore()
581✔
770
{
771
  InitializeSpatialDiscretization();
581✔
772
  InitializeParrays();
581✔
773
  InitializeBoundaries();
581✔
774
  InitializeGPUExtras();
581✔
775
}
581✔
776

777
void
778
LBSProblem::ValidateRuntimeModeConfiguration() const
581✔
779
{
780
  if (options_.adjoint)
581✔
781
    if (const auto* do_problem = dynamic_cast<const DiscreteOrdinatesProblem*>(this);
16✔
782
        do_problem and do_problem->IsTimeDependent())
16✔
NEW
783
      OpenSnInvalidArgument(GetName() + ": Time-dependent adjoint problems are not supported.");
×
784
}
581✔
785

786
void
787
LBSProblem::InitializeSources()
581✔
788
{
789
  // Initialize point sources
790
  for (auto& point_source : point_sources_)
590✔
791
    point_source->Initialize(*this);
9✔
792

793
  // Initialize volumetric sources
794
  for (auto& volumetric_source : volumetric_sources_)
1,064✔
795
    volumetric_source->Initialize(*this);
483✔
796
}
581✔
797

798
void
799
LBSProblem::PrintSimHeader()
×
800
{
801
  if (opensn::mpi_comm.rank() == 0)
×
802
  {
803
    std::stringstream outstr;
×
804
    outstr << "\n"
×
805
           << "Initializing " << GetName() << "\n\n"
×
806
           << "Scattering order    : " << scattering_order_ << "\n"
×
807
           << "Number of moments   : " << num_moments_ << "\n"
×
808
           << "Number of groups    : " << num_groups_ << "\n"
×
809
           << "Number of groupsets : " << groupsets_.size() << "\n\n";
×
810

811
    for (const auto& groupset : groupsets_)
×
812
    {
813
      outstr << "***** Groupset " << groupset.id << " *****\n"
×
814
             << "Groups:\n";
×
815
      const auto n_gs_groups = groupset.GetNumGroups();
×
816
      constexpr int groups_per_line = 12;
817
      for (size_t i = 0; i < n_gs_groups; ++i)
×
818
      {
819
        outstr << std::setw(5) << groupset.first_group + i << ' ';
×
820
        if ((i + 1) % groups_per_line == 0)
×
821
          outstr << '\n';
×
822
      }
823
      if (n_gs_groups > 0 && n_gs_groups % groups_per_line != 0)
×
824
        outstr << '\n';
×
825
    }
826

827
    log.Log() << outstr.str() << '\n';
×
828
  }
×
829
}
×
830

831
void
832
LBSProblem::InitializeSources(const InputParameters& params)
581✔
833
{
834
  if (params.Has("volumetric_sources"))
581✔
835
  {
836
    const auto& vol_srcs = params.GetParam("volumetric_sources");
581✔
837
    vol_srcs.RequireBlockTypeIs(ParameterBlockType::ARRAY);
581✔
838
    for (const auto& src : vol_srcs)
1,064✔
839
      volumetric_sources_.push_back(src.GetValue<std::shared_ptr<VolumetricSource>>());
966✔
840
  }
841

842
  if (params.Has("point_sources"))
581✔
843
  {
844
    const auto& pt_srcs = params.GetParam("point_sources");
581✔
845
    pt_srcs.RequireBlockTypeIs(ParameterBlockType::ARRAY);
581✔
846
    for (const auto& src : pt_srcs)
590✔
847
      point_sources_.push_back(src.GetValue<std::shared_ptr<PointSource>>());
18✔
848
  }
849
}
581✔
850

851
void
852
LBSProblem::InitializeGroupsets(const InputParameters& params)
581✔
853
{
854
  // Initialize groups
855
  OpenSnInvalidArgumentIf(num_groups_ == 0, GetName() + ": Number of groups must be > 0.");
581✔
856

857
  // Initialize groupsets
858
  const auto& groupsets_array = params.GetParam("groupsets");
581✔
859
  const size_t num_gs = groupsets_array.GetNumParameters();
581✔
860
  OpenSnInvalidArgumentIf(num_gs == 0, GetName() + ": At least one groupset must be specified.");
581✔
861
  for (size_t gs = 0; gs < num_gs; ++gs)
1,221✔
862
  {
863
    const auto& groupset_params = groupsets_array.GetParam(gs);
640✔
864
    InputParameters gs_input_params = LBSGroupset::GetInputParameters();
640✔
865
    gs_input_params.SetObjectType("LBSProblem:LBSGroupset");
640✔
866
    gs_input_params.AssignParameters(groupset_params);
640✔
867
    groupsets_.emplace_back(gs_input_params, gs, *this);
640✔
868
    if (groupsets_.back().GetNumGroups() == 0)
640✔
869
    {
870
      std::stringstream oss;
×
871
      oss << GetName() << ": No groups added to groupset " << groupsets_.back().id;
×
NEW
872
      OpenSnInvalidArgument(oss.str());
×
873
    }
×
874
  }
640✔
875
}
581✔
876

877
void
878
LBSProblem::InitializeXSmapAndDensities(const InputParameters& params)
581✔
879
{
880
  // Build XS map
881
  const auto& xs_array = params.GetParam("xs_map");
581✔
882
  const size_t num_xs = xs_array.GetNumParameters();
581✔
883
  for (size_t i = 0; i < num_xs; ++i)
1,419✔
884
  {
885
    const auto& item_params = xs_array.GetParam(i);
838✔
886
    InputParameters xs_entry_pars = GetXSMapEntryBlock();
838✔
887
    xs_entry_pars.AssignParameters(item_params);
838✔
888

889
    const auto& block_ids_param = xs_entry_pars.GetParam("block_ids");
838✔
890
    block_ids_param.RequireBlockTypeIs(ParameterBlockType::ARRAY);
838✔
891
    const auto& block_ids = block_ids_param.GetVectorValue<unsigned int>();
838✔
892
    auto xs = xs_entry_pars.GetSharedPtrParam<MultiGroupXS>("xs");
838✔
893
    for (const auto& block_id : block_ids)
1,784✔
894
      block_id_to_xs_map_[block_id] = xs;
946✔
895
  }
838✔
896

897
  // Assign placeholder unit densities
898
  densities_local_.assign(grid_->local_cells.size(), 1.0);
581✔
899
}
581✔
900

901
void
902
LBSProblem::InitializeMaterials()
777✔
903
{
904
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeMaterials");
777✔
905

906
  log.Log0Verbose1() << "Initializing Materials";
1,554✔
907

908
  // Create set of material ids locally relevant
909
  int invalid_mat_cell_count = 0;
777✔
910
  std::set<unsigned int> unique_block_ids;
777✔
911
  for (auto& cell : grid_->local_cells)
601,420✔
912
  {
913
    unique_block_ids.insert(cell.block_id);
600,643✔
914
    if (cell.block_id == std::numeric_limits<unsigned int>::max() or
600,643✔
915
        (block_id_to_xs_map_.find(cell.block_id) == block_id_to_xs_map_.end()))
600,643✔
916
      ++invalid_mat_cell_count;
×
917
  }
918
  const auto& ghost_cell_ids = grid_->cells.GetGhostGlobalIDs();
777✔
919
  for (uint64_t cell_id : ghost_cell_ids)
99,448✔
920
  {
921
    const auto& cell = grid_->cells[cell_id];
98,671✔
922
    unique_block_ids.insert(cell.block_id);
98,671✔
923
    if (cell.block_id == std::numeric_limits<unsigned int>::max() or
98,671✔
924
        (block_id_to_xs_map_.find(cell.block_id) == block_id_to_xs_map_.end()))
98,671✔
925
      ++invalid_mat_cell_count;
×
926
  }
927
  OpenSnLogicalErrorIf(invalid_mat_cell_count > 0,
777✔
928
                       std::to_string(invalid_mat_cell_count) +
929
                         " cells encountered with an invalid material id.");
930

931
  // Get ready for processing
932
  for (const auto& [blk_id, mat] : block_id_to_xs_map_)
1,943✔
933
  {
934
    mat->SetAdjointMode(options_.adjoint);
1,166✔
935

936
    OpenSnLogicalErrorIf(mat->GetNumGroups() < num_groups_,
1,166✔
937
                         "Cross-sections for block \"" + std::to_string(blk_id) +
938
                           "\" have fewer groups (" + std::to_string(mat->GetNumGroups()) +
939
                           ") than the simulation (" + std::to_string(num_groups_) + "). " +
940
                           "Cross-sections must have at least as many groups as the simulation.");
941
  }
942

943
  // Initialize precursor properties
944
  num_precursors_ = 0;
777✔
945
  max_precursors_per_material_ = 0;
777✔
946
  for (const auto& mat_id_xs : block_id_to_xs_map_)
1,943✔
947
  {
948
    const auto& xs = mat_id_xs.second;
1,166✔
949
    num_precursors_ += xs->GetNumPrecursors();
1,166✔
950
    max_precursors_per_material_ = std::max(xs->GetNumPrecursors(), max_precursors_per_material_);
1,166✔
951
  }
952

953
  // if no precursors, turn off precursors
954
  if (num_precursors_ == 0)
777✔
955
    options_.use_precursors = false;
580✔
956

957
  // check compatibility when precursors are on
958
  if (options_.use_precursors)
777✔
959
  {
960
    for (const auto& [mat_id, xs] : block_id_to_xs_map_)
352✔
961
    {
962
      OpenSnLogicalErrorIf(xs->IsFissionable() and num_precursors_ == 0,
176✔
963
                           "Incompatible cross-section data encountered for material id " +
964
                             std::to_string(mat_id) + ". When delayed neutron data is present " +
965
                             "for one fissionable matrial, it must be present for all fissionable "
966
                             "materials.");
967
    }
968
  }
969

970
  // Update transport views if available
971
  if (grid_->local_cells.size() == cell_transport_views_.size())
777✔
972
    for (const auto& cell : grid_->local_cells)
27,976✔
973
    {
974
      const auto& xs_ptr = block_id_to_xs_map_[cell.block_id];
27,780✔
975
      auto& transport_view = cell_transport_views_[cell.local_id];
27,780✔
976
      transport_view.ReassignXS(*xs_ptr);
27,780✔
977
    }
978

979
  mpi_comm.barrier();
777✔
980
}
777✔
981

982
void
983
LBSProblem::InitializeSpatialDiscretization()
501✔
984
{
985
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeSpatialDiscretization");
501✔
986

987
  OpenSnLogicalErrorIf(not discretization_,
501✔
988
                       GetName() + ": Missing spatial discretization. Construct the problem "
989
                                   "through its factory Create(...) entry point.");
990
  log.Log() << "Initializing spatial discretization metadata.\n";
1,002✔
991

992
  ComputeUnitIntegrals();
501✔
993
}
501✔
994

995
void
996
LBSProblem::ComputeUnitIntegrals()
581✔
997
{
998
  CALI_CXX_MARK_SCOPE("LBSProblem::ComputeUnitIntegrals");
581✔
999

1000
  log.Log() << "Computing unit integrals.\n";
1,162✔
1001
  const auto& sdm = *discretization_;
581✔
1002

1003
  const size_t num_local_cells = grid_->local_cells.size();
581✔
1004
  unit_cell_matrices_.resize(num_local_cells);
581✔
1005

1006
  for (const auto& cell : grid_->local_cells)
573,444✔
1007
    unit_cell_matrices_[cell.local_id] =
572,863✔
1008
      ComputeUnitCellIntegrals(sdm, cell, grid_->GetCoordinateSystem());
572,863✔
1009

1010
  const auto ghost_ids = grid_->cells.GetGhostGlobalIDs();
581✔
1011
  for (auto ghost_id : ghost_ids)
90,410✔
1012
    unit_ghost_cell_matrices_[ghost_id] =
89,829✔
1013
      ComputeUnitCellIntegrals(sdm, grid_->cells[ghost_id], grid_->GetCoordinateSystem());
179,658✔
1014

1015
  // Assessing global unit cell matrix storage
1016
  std::array<size_t, 2> num_local_ucms = {unit_cell_matrices_.size(),
581✔
1017
                                          unit_ghost_cell_matrices_.size()};
581✔
1018
  std::array<size_t, 2> num_global_ucms = {0, 0};
581✔
1019

1020
  mpi_comm.all_reduce(num_local_ucms.data(), 2, num_global_ucms.data(), mpi::op::sum<size_t>());
581✔
1021

1022
  opensn::mpi_comm.barrier();
581✔
1023
  log.Log() << "Ghost cell unit cell-matrix ratio: "
581✔
1024
            << (double)num_global_ucms[1] * 100 / (double)num_global_ucms[0] << "%";
1,162✔
1025
  log.Log() << "Cell matrices computed.";
1,162✔
1026
}
581✔
1027

1028
void
1029
LBSProblem::InitializeParrays()
581✔
1030
{
1031
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeParrays");
581✔
1032

1033
  log.Log() << "Initializing parallel arrays."
1,162✔
1034
            << " G=" << num_groups_ << " M=" << num_moments_ << std::endl;
581✔
1035

1036
  // Initialize unknown
1037
  // structure
1038
  flux_moments_uk_man_.unknowns.clear();
581✔
1039
  for (unsigned int m = 0; m < num_moments_; ++m)
1,736✔
1040
  {
1041
    flux_moments_uk_man_.AddUnknown(UnknownType::VECTOR_N, num_groups_);
1,155✔
1042
    flux_moments_uk_man_.unknowns.back().name = "m" + std::to_string(m);
1,155✔
1043
  }
1044

1045
  // Compute local # of dof
1046
  local_node_count_ = discretization_->GetNumLocalNodes();
581✔
1047
  global_node_count_ = discretization_->GetNumGlobalNodes();
581✔
1048

1049
  // Compute num of unknowns
1050
  size_t local_unknown_count = local_node_count_ * num_groups_ * num_moments_;
581✔
1051

1052
  log.LogAllVerbose1() << "LBS Number of phi unknowns: " << local_unknown_count;
1,162✔
1053

1054
  // Size local vectors
1055
  q_moments_local_.assign(local_unknown_count, 0.0);
581✔
1056
  phi_old_local_.assign(local_unknown_count, 0.0);
581✔
1057
  phi_new_local_.assign(local_unknown_count, 0.0);
581✔
1058

1059
  // Setup precursor vector
1060
  if (options_.use_precursors)
581✔
1061
  {
1062
    size_t num_precursor_dofs = grid_->local_cells.size() * max_precursors_per_material_;
60✔
1063
    precursor_new_local_.assign(num_precursor_dofs, 0.0);
60✔
1064
  }
1065

1066
  // Initialize transport views
1067
  // Transport views act as a data structure to store information
1068
  // related to the transport simulation. The most prominent function
1069
  // here is that it holds the means to know where a given cell's
1070
  // transport quantities are located in the unknown vectors (i.e. phi)
1071
  //
1072
  // Also, for a given cell, within a given sweep chunk,
1073
  // we need to solve a matrix which square size is the
1074
  // amount of nodes on the cell. max_cell_dof_count is
1075
  // initialized here.
1076
  //
1077
  size_t block_MG_counter = 0; // Counts the strides of moment and group
581✔
1078

1079
  const Vector3 ihat(1.0, 0.0, 0.0);
581✔
1080
  const Vector3 jhat(0.0, 1.0, 0.0);
581✔
1081
  const Vector3 khat(0.0, 0.0, 1.0);
581✔
1082

1083
  min_cell_dof_count_ = std::numeric_limits<unsigned int>::max();
581✔
1084
  max_cell_dof_count_ = 0;
581✔
1085
  cell_transport_views_.clear();
581✔
1086
  cell_transport_views_.reserve(grid_->local_cells.size());
581✔
1087
  for (auto& cell : grid_->local_cells)
573,444✔
1088
  {
1089
    size_t num_nodes = discretization_->GetCellNumNodes(cell);
572,863✔
1090

1091
    // compute cell volumes
1092
    double cell_volume = 0.0;
572,863✔
1093
    const auto& IntV_shapeI = unit_cell_matrices_[cell.local_id].intV_shapeI;
572,863✔
1094
    for (size_t i = 0; i < num_nodes; ++i)
3,971,827✔
1095
      cell_volume += IntV_shapeI(i);
3,398,964✔
1096

1097
    size_t cell_phi_address = block_MG_counter;
572,863✔
1098

1099
    const size_t num_faces = cell.faces.size();
572,863✔
1100
    std::vector<bool> face_local_flags(num_faces, true);
572,863✔
1101
    std::vector<int> face_locality(num_faces, opensn::mpi_comm.rank());
572,863✔
1102
    std::vector<const Cell*> neighbor_cell_ptrs(num_faces, nullptr);
572,863✔
1103
    bool cell_on_boundary = false;
572,863✔
1104
    int f = 0;
572,863✔
1105
    for (auto& face : cell.faces)
3,404,219✔
1106
    {
1107
      if (not face.has_neighbor)
2,831,356✔
1108
      {
1109
        cell_on_boundary = true;
91,778✔
1110
        face_local_flags[f] = false;
91,778✔
1111
        face_locality[f] = -1;
91,778✔
1112
      } // if bndry
1113
      else
1114
      {
1115
        const int neighbor_partition = face.GetNeighborPartitionID(grid_.get());
2,739,578✔
1116
        face_local_flags[f] = (neighbor_partition == opensn::mpi_comm.rank());
2,739,578✔
1117
        face_locality[f] = neighbor_partition;
2,739,578✔
1118
        neighbor_cell_ptrs[f] = &grid_->cells[face.neighbor_id];
2,739,578✔
1119
      }
1120

1121
      ++f;
2,831,356✔
1122
    } // for f
1123

1124
    max_cell_dof_count_ = std::max(max_cell_dof_count_, static_cast<unsigned int>(num_nodes));
572,863✔
1125
    min_cell_dof_count_ = std::min(min_cell_dof_count_, static_cast<unsigned int>(num_nodes));
572,863✔
1126
    cell_transport_views_.emplace_back(cell_phi_address,
1,145,726✔
1127
                                       num_nodes,
1128
                                       num_groups_,
572,863✔
1129
                                       num_moments_,
572,863✔
1130
                                       num_faces,
1131
                                       *block_id_to_xs_map_[cell.block_id],
572,863✔
1132
                                       cell_volume,
1133
                                       face_local_flags,
1134
                                       face_locality,
1135
                                       neighbor_cell_ptrs,
1136
                                       cell_on_boundary);
1137
    block_MG_counter += num_nodes * num_groups_ * num_moments_;
572,863✔
1138
  } // for local cell
572,863✔
1139

1140
  // Populate grid nodal mappings
1141
  // This is used in the Flux Data Structures (FLUDS)
1142
  grid_nodal_mappings_.clear();
581✔
1143
  grid_nodal_mappings_.reserve(grid_->local_cells.size());
581✔
1144
  for (auto& cell : grid_->local_cells)
573,444✔
1145
  {
1146
    CellFaceNodalMapping cell_nodal_mapping;
572,863✔
1147
    cell_nodal_mapping.reserve(cell.faces.size());
572,863✔
1148

1149
    for (auto& face : cell.faces)
3,404,219✔
1150
    {
1151
      std::vector<short> face_node_mapping;
2,831,356✔
1152
      std::vector<short> cell_node_mapping;
2,831,356✔
1153
      int adj_face_idx = -1;
2,831,356✔
1154

1155
      if (face.has_neighbor)
2,831,356✔
1156
      {
1157
        grid_->FindAssociatedVertices(face, face_node_mapping);
2,739,578✔
1158
        grid_->FindAssociatedCellVertices(face, cell_node_mapping);
2,739,578✔
1159
        adj_face_idx = face.GetNeighborAdjacentFaceIndex(grid_.get());
2,739,578✔
1160
      }
1161

1162
      cell_nodal_mapping.emplace_back(adj_face_idx, face_node_mapping, cell_node_mapping);
2,831,356✔
1163
    } // for f
2,831,356✔
1164

1165
    grid_nodal_mappings_.push_back(cell_nodal_mapping);
572,863✔
1166
  } // for local cell
572,863✔
1167

1168
  // Get grid localized communicator set
1169
  grid_local_comm_set_ = grid_->MakeMPILocalCommunicatorSet();
581✔
1170

1171
  // Initialize Field Functions
1172
  InitializeFieldFunctions();
581✔
1173

1174
  opensn::mpi_comm.barrier();
581✔
1175
  log.Log() << "Done with parallel arrays." << std::endl;
1,162✔
1176
}
581✔
1177

1178
void
1179
LBSProblem::InitializeFieldFunctions()
581✔
1180
{
1181
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeFieldFunctions");
581✔
1182

1183
  if (not field_functions_.empty())
581✔
1184
    return;
×
1185

1186
  // Initialize Field Functions for flux moments
1187
  phi_field_functions_local_map_.clear();
581✔
1188

1189
  for (unsigned int g = 0; g < num_groups_; ++g)
23,251✔
1190
  {
1191
    for (unsigned int m = 0; m < num_moments_; ++m)
100,658✔
1192
    {
1193
      std::string prefix;
77,988✔
1194
      if (options_.field_function_prefix_option == "prefix")
77,988✔
1195
      {
1196
        prefix = options_.field_function_prefix;
77,988✔
1197
        if (not prefix.empty())
77,988✔
1198
          prefix += "_";
1✔
1199
      }
1200
      if (options_.field_function_prefix_option == "solver_name")
77,988✔
1201
        prefix = GetName() + "_";
×
1202

1203
      std::ostringstream oss;
77,988✔
1204
      oss << prefix << "phi_g" << std::setw(3) << std::setfill('0') << static_cast<int>(g) << "_m"
77,988✔
1205
          << std::setw(2) << std::setfill('0') << static_cast<int>(m);
77,988✔
1206
      const std::string name = oss.str();
77,988✔
1207

1208
      auto group_ff = std::make_shared<FieldFunctionGridBased>(
77,988✔
1209
        name, discretization_, Unknown(UnknownType::SCALAR));
77,988✔
1210

1211
      field_function_stack.push_back(group_ff);
155,976✔
1212
      field_functions_.push_back(group_ff);
77,988✔
1213

1214
      phi_field_functions_local_map_[{g, m}] = field_functions_.size() - 1;
77,988✔
1215
    } // for m
77,988✔
1216
  } // for g
1217

1218
  // Initialize power generation field function
1219
  if (options_.power_field_function_on)
581✔
1220
  {
1221
    std::string prefix;
5✔
1222
    if (options_.field_function_prefix_option == "prefix")
5✔
1223
    {
1224
      prefix = options_.field_function_prefix;
5✔
1225
      if (not prefix.empty())
5✔
1226
        prefix += "_";
×
1227
    }
1228
    if (options_.field_function_prefix_option == "solver_name")
5✔
1229
      prefix = GetName() + "_";
×
1230

1231
    auto power_ff = std::make_shared<FieldFunctionGridBased>(
5✔
1232
      prefix + "power_generation", discretization_, Unknown(UnknownType::SCALAR));
10✔
1233

1234
    field_function_stack.push_back(power_ff);
10✔
1235
    field_functions_.push_back(power_ff);
5✔
1236

1237
    power_gen_fieldfunc_local_handle_ = field_functions_.size() - 1;
5✔
1238
  }
5✔
1239
}
581✔
1240

1241
void
1242
LBSProblem::InitializeSolverSchemes()
685✔
1243
{
1244
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeSolverSchemes");
685✔
1245
  InitializeWGSSolvers();
685✔
1246

1247
  ags_solver_ = std::make_shared<AGSLinearSolver>(*this, wgs_solvers_);
685✔
1248
  if (groupsets_.size() == 1)
685✔
1249
  {
1250
    ags_solver_->SetMaxIterations(1);
630✔
1251
    ags_solver_->SetVerbosity(false);
630✔
1252
  }
1253
  else
1254
  {
1255
    ags_solver_->SetMaxIterations(options_.max_ags_iterations);
55✔
1256
    ags_solver_->SetVerbosity(options_.verbose_ags_iterations);
55✔
1257
  }
1258
  ags_solver_->SetTolerance(options_.ags_tolerance);
685✔
1259
}
685✔
1260

1261
#ifndef __OPENSN_WITH_GPU__
1262
void
1263
LBSProblem::InitializeGPUExtras()
753✔
1264
{
1265
}
753✔
1266

1267
void
1268
LBSProblem::ResetGPUCarriers()
741✔
1269
{
1270
}
741✔
1271

1272
void
1273
LBSProblem::CheckCapableDevices()
×
1274
{
1275
}
×
1276
#endif // __OPENSN_WITH_GPU__
1277

1278
std::vector<double>
1279
LBSProblem::MakeSourceMomentsFromPhi()
4✔
1280
{
1281
  CALI_CXX_MARK_SCOPE("LBSProblem::MakeSourceMomentsFromPhi");
4✔
1282

1283
  size_t num_local_dofs = discretization_->GetNumLocalDOFs(flux_moments_uk_man_);
4✔
1284

1285
  std::vector<double> source_moments(num_local_dofs, 0.0);
4✔
1286
  for (auto& groupset : groupsets_)
8✔
1287
  {
1288
    active_set_source_function_(groupset,
4✔
1289
                                source_moments,
1290
                                phi_new_local_,
4✔
1291
                                APPLY_AGS_SCATTER_SOURCES | APPLY_WGS_SCATTER_SOURCES |
1292
                                  APPLY_AGS_FISSION_SOURCES | APPLY_WGS_FISSION_SOURCES);
4✔
1293
  }
1294

1295
  return source_moments;
4✔
1296
}
4✔
1297

1298
void
1299
LBSProblem::UpdateFieldFunctions()
2,805✔
1300
{
1301
  CALI_CXX_MARK_SCOPE("LBSProblem::UpdateFieldFunctions");
2,805✔
1302

1303
  const auto& sdm = *discretization_;
2,805✔
1304
  const auto& phi_uk_man = flux_moments_uk_man_;
2,805✔
1305

1306
  // Update flux moments
1307
  for (const auto& [g_and_m, ff_index] : phi_field_functions_local_map_)
87,841✔
1308
  {
1309
    const auto g = g_and_m.first;
85,036✔
1310
    const auto m = g_and_m.second;
85,036✔
1311

1312
    std::vector<double> data_vector_local(local_node_count_, 0.0);
85,036✔
1313

1314
    for (const auto& cell : grid_->local_cells)
24,450,775✔
1315
    {
1316
      const auto& cell_mapping = sdm.GetCellMapping(cell);
24,365,739✔
1317
      const size_t num_nodes = cell_mapping.GetNumNodes();
24,365,739✔
1318

1319
      for (size_t i = 0; i < num_nodes; ++i)
164,663,059✔
1320
      {
1321
        const auto imapA = sdm.MapDOFLocal(cell, i, phi_uk_man, m, g);
140,297,320✔
1322
        const auto imapB = sdm.MapDOFLocal(cell, i);
140,297,320✔
1323

1324
        data_vector_local[imapB] = phi_new_local_[imapA];
140,297,320✔
1325
      } // for node
1326
    } // for cell
1327

1328
    auto& ff_ptr = field_functions_.at(ff_index);
85,036✔
1329
    ff_ptr->UpdateFieldVector(data_vector_local);
85,036✔
1330
  }
85,036✔
1331

1332
  // Update power generation and scalar flux
1333
  if (options_.power_field_function_on)
2,805✔
1334
  {
1335
    std::vector<double> data_vector_power_local(local_node_count_, 0.0);
5✔
1336

1337
    double local_total_power = 0.0;
5✔
1338
    for (const auto& cell : grid_->local_cells)
83,319✔
1339
    {
1340
      const auto& cell_mapping = sdm.GetCellMapping(cell);
83,314✔
1341
      const size_t num_nodes = cell_mapping.GetNumNodes();
83,314✔
1342

1343
      const auto& Vi = unit_cell_matrices_[cell.local_id].intV_shapeI;
83,314✔
1344

1345
      const auto& xs = block_id_to_xs_map_.at(cell.block_id);
83,314✔
1346

1347
      if (not xs->IsFissionable())
83,314✔
1348
        continue;
56,360✔
1349

1350
      for (size_t i = 0; i < num_nodes; ++i)
134,670✔
1351
      {
1352
        const auto imapA = sdm.MapDOFLocal(cell, i);
107,716✔
1353
        const auto imapB = sdm.MapDOFLocal(cell, i, phi_uk_man, 0, 0);
107,716✔
1354

1355
        double nodal_power = 0.0;
1356
        for (unsigned int g = 0; g < num_groups_; ++g)
861,128✔
1357
        {
1358
          const double sigma_fg = xs->GetSigmaFission()[g];
753,412✔
1359
          // const double kappa_g = xs->Kappa()[g];
1360
          const double kappa_g = options_.power_default_kappa;
753,412✔
1361

1362
          nodal_power += kappa_g * sigma_fg * phi_new_local_[imapB + g];
753,412✔
1363
        } // for g
1364

1365
        data_vector_power_local[imapA] = nodal_power;
107,716✔
1366
        local_total_power += nodal_power * Vi(i);
107,716✔
1367
      } // for node
1368
    } // for cell
1369

1370
    double scale_factor = 1.0;
5✔
1371
    if (options_.power_normalization > 0.0)
5✔
1372
    {
1373
      double global_total_power = 0.0;
5✔
1374
      mpi_comm.all_reduce(local_total_power, global_total_power, mpi::op::sum<double>());
5✔
1375
      scale_factor = options_.power_normalization / global_total_power;
5✔
1376
      Scale(data_vector_power_local, scale_factor);
5✔
1377
    }
1378

1379
    const size_t ff_index = power_gen_fieldfunc_local_handle_;
5✔
1380

1381
    auto& ff_ptr = field_functions_.at(ff_index);
5✔
1382
    ff_ptr->UpdateFieldVector(data_vector_power_local);
5✔
1383

1384
    // scale scalar flux if neccessary
1385
    if (scale_factor != 1.0)
5✔
1386
    {
1387
      for (unsigned int g = 0; g < num_groups_; ++g)
34✔
1388
      {
1389
        const size_t phi_ff_index = phi_field_functions_local_map_.at({g, size_t{0}});
29✔
1390
        auto& phi_ff_ptr = field_functions_.at(phi_ff_index);
29✔
1391
        const auto& phi_vec = phi_ff_ptr->GetLocalFieldVector();
29✔
1392
        std::vector<double> phi_scaled(phi_vec.begin(), phi_vec.end());
29✔
1393
        Scale(phi_scaled, scale_factor);
29✔
1394
        phi_ff_ptr->UpdateFieldVector(phi_scaled);
29✔
1395
      }
29✔
1396
    }
1397
  } // if power enabled
5✔
1398
}
2,805✔
1399

1400
void
1401
LBSProblem::SetPhiFromFieldFunctions(PhiSTLOption which_phi,
×
1402
                                     const std::vector<unsigned int>& m_indices,
1403
                                     const std::vector<unsigned int>& g_indices)
1404
{
1405
  CALI_CXX_MARK_SCOPE("LBSProblem::SetPhiFromFieldFunctions");
×
1406

1407
  std::vector<unsigned int> m_ids_to_copy = m_indices;
×
1408
  std::vector<unsigned int> g_ids_to_copy = g_indices;
×
1409
  if (m_indices.empty())
×
1410
    for (unsigned int m = 0; m < num_moments_; ++m)
×
1411
      m_ids_to_copy.push_back(m);
×
1412
  if (g_ids_to_copy.empty())
×
1413
    for (unsigned int g = 0; g < num_groups_; ++g)
×
1414
      g_ids_to_copy.push_back(g);
×
1415

1416
  const auto& sdm = *discretization_;
×
1417
  const auto& phi_uk_man = flux_moments_uk_man_;
×
1418

1419
  for (const auto m : m_ids_to_copy)
×
1420
  {
1421
    for (const auto g : g_ids_to_copy)
×
1422
    {
1423
      const size_t ff_index = phi_field_functions_local_map_.at({g, m});
×
1424
      const auto& ff_ptr = field_functions_.at(ff_index);
×
1425
      const auto& ff_data = ff_ptr->GetLocalFieldVector();
×
1426

1427
      for (const auto& cell : grid_->local_cells)
×
1428
      {
1429
        const auto& cell_mapping = sdm.GetCellMapping(cell);
×
1430
        const size_t num_nodes = cell_mapping.GetNumNodes();
×
1431

1432
        for (size_t i = 0; i < num_nodes; ++i)
×
1433
        {
1434
          const auto imapA = sdm.MapDOFLocal(cell, i);
×
1435
          const auto imapB = sdm.MapDOFLocal(cell, i, phi_uk_man, m, g);
×
1436

1437
          if (which_phi == PhiSTLOption::PHI_OLD)
×
1438
            phi_old_local_[imapB] = ff_data[imapA];
×
1439
          else if (which_phi == PhiSTLOption::PHI_NEW)
×
1440
            phi_new_local_[imapB] = ff_data[imapA];
×
1441
        } // for node
1442
      } // for cell
1443
    } // for g
1444
  } // for m
1445
}
×
1446

1447
LBSProblem::~LBSProblem()
569✔
1448
{
1449
  ResetGPUCarriers();
1450
}
2,845✔
1451

569✔
1452
void
1453
LBSProblem::SetSaveAngularFlux(bool save)
48✔
1454
{
1455
  options_.save_angular_flux = save;
48✔
1456
  if (initialized_)
48✔
1457
    applied_save_angular_flux_ = save;
4✔
1458
}
48✔
1459

1460
void
1461
LBSProblem::ZeroPhi()
×
1462
{
1463
  phi_old_local_.assign(phi_old_local_.size(), 0.0);
×
1464
  phi_new_local_.assign(phi_new_local_.size(), 0.0);
×
1465
}
×
1466

1467
void
1468
LBSProblem::SetAdjoint(bool adjoint)
24✔
1469
{
1470
  OpenSnLogicalErrorIf(
24✔
1471
    not initialized_, GetName() + ": Problem must be fully constructed before calling SetAdjoint.");
1472

1473
  if (adjoint)
24✔
1474
    if (const auto* do_problem = dynamic_cast<const DiscreteOrdinatesProblem*>(this);
20✔
1475
        do_problem and do_problem->IsTimeDependent())
20✔
NEW
1476
      OpenSnInvalidArgument(GetName() + ": Time-dependent adjoint problems are not supported.");
×
1477

1478
  options_.adjoint = adjoint;
24✔
1479

1480
  if (adjoint != applied_adjoint_)
24✔
1481
  {
1482
    // Reinitialize materials to obtain the proper forward/adjoint cross sections.
1483
    InitializeMaterials();
24✔
1484

1485
    // Forward and adjoint sources are fundamentally different.
1486
    point_sources_.clear();
24✔
1487
    volumetric_sources_.clear();
24✔
1488
    ClearBoundaries();
24✔
1489

1490
    // Reset all solution vectors.
1491
    phi_old_local_.assign(phi_old_local_.size(), 0.0);
24✔
1492
    phi_new_local_.assign(phi_new_local_.size(), 0.0);
24✔
1493
    ZeroPsi();
24✔
1494
    precursor_new_local_.assign(precursor_new_local_.size(), 0.0);
24✔
1495

1496
    applied_adjoint_ = adjoint;
24✔
1497
  }
1498
}
24✔
1499

1500
bool
1501
LBSProblem::IsAdjoint() const
×
1502
{
1503
  return options_.adjoint;
×
1504
}
1505

1506
} // namespace opensn
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc