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

Open-Sn / opensn / 22292778382

23 Feb 2026 01:09AM UTC coverage: 74.123% (-0.03%) from 74.156%
22292778382

push

github

web-flow
Merge pull request #946 from wdhawkins/additive_options

Refactor `LBSProblem` options

14 of 17 new or added lines in 1 file covered. (82.35%)

11 existing lines in 2 files now uncovered.

19997 of 26978 relevant lines covered (74.12%)

67096470.26 hits per line

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

81.84
/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/lbs_problem/iterative_methods/wgs_context.h"
6
#include "modules/linear_boltzmann_solvers/lbs_problem/iterative_methods/ags_linear_solver.h"
7
#include "modules/linear_boltzmann_solvers/lbs_problem/point_source/point_source.h"
8
#include "modules/linear_boltzmann_solvers/lbs_problem/groupset/lbs_groupset.h"
9
#include "framework/math/spatial_discretization/finite_element/piecewise_linear/piecewise_linear_discontinuous.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 "caliper/cali.h"
19
#include <algorithm>
20
#include <iomanip>
21
#include <fstream>
22
#include <cstring>
23
#include <cassert>
24
#include <memory>
25
#include <stdexcept>
26
#include <sys/stat.h>
27

28
namespace opensn
29
{
30

31
LBSProblem::LBSProblem(std::string name, std::shared_ptr<MeshContinuum> grid)
×
32
  : Problem(std::move(name)), grid_(std::move(grid)), use_gpus_(false)
×
33
{
34
}
×
35

36
InputParameters
37
LBSProblem::GetInputParameters()
574✔
38
{
39
  InputParameters params = Problem::GetInputParameters();
574✔
40

41
  params.ChangeExistingParamToOptional("name", "LBSProblem");
1,148✔
42

43
  params.AddRequiredParameter<std::shared_ptr<MeshContinuum>>("mesh", "Mesh");
1,148✔
44

45
  params.AddRequiredParameter<unsigned int>("num_groups",
1,148✔
46
                                            "The total number of groups within the solver");
47

48
  params.AddRequiredParameterArray("groupsets",
1,148✔
49
                                   "An array of blocks each specifying the input parameters for a "
50
                                   "<TT>LBSGroupset</TT>.");
51
  params.LinkParameterToBlock("groupsets", "LBSGroupset");
1,148✔
52

53
  params.AddRequiredParameterArray("xs_map",
1,148✔
54
                                   "Cross-section map from block IDs to cross-section objects.");
55

56
  params.AddOptionalParameterArray<std::shared_ptr<VolumetricSource>>(
1,148✔
57
    "volumetric_sources", {}, "An array of handles to volumetric sources.");
58

59
  params.AddOptionalParameterArray<std::shared_ptr<PointSource>>(
1,148✔
60
    "point_sources", {}, "An array of point sources.");
61

62
  params.AddOptionalParameterBlock(
1,148✔
63
    "options", ParameterBlock(), "Block of options. See <TT>OptionsBlock</TT>.");
1,148✔
64
  params.LinkParameterToBlock("options", "OptionsBlock");
1,148✔
65

66
  params.AddOptionalParameter("use_gpus", false, "Offload the sweep computation to GPUs.");
1,148✔
67

68
  return params;
574✔
69
}
×
70

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

88
  // Initialize options
89
  if (params.IsParameterValid("options"))
574✔
90
  {
91
    auto options_params = LBSProblem::GetOptionsBlock();
346✔
92
    options_params.AssignParameters(params.GetParam("options"));
348✔
93
    SetOptions(options_params);
344✔
94
  }
346✔
95

96
  // Set geometry type
97
  geometry_type_ = grid_->GetGeometryType();
572✔
98
  if (geometry_type_ == GeometryType::INVALID)
572✔
99
    throw std::runtime_error(GetName() + ": Invalid geometry type.");
×
100

101
  InitializeGroupsets(params);
572✔
102
  InitializeSources(params);
572✔
103
  InitializeXSmapAndDensities(params);
572✔
104
  InitializeMaterials();
572✔
105
}
592✔
106

107
LBSOptions&
108
LBSProblem::GetOptions()
167,251✔
109
{
110
  return options_;
167,251✔
111
}
112

113
const LBSOptions&
114
LBSProblem::GetOptions() const
682,559,520✔
115
{
116
  return options_;
682,559,520✔
117
}
118

119
double
120
LBSProblem::GetTime() const
421,872✔
121
{
122
  return time_;
421,872✔
123
}
124

125
void
126
LBSProblem::SetTime(double time)
5,564✔
127
{
128
  time_ = time;
5,564✔
129
}
5,564✔
130

131
void
132
LBSProblem::SetTimeStep(double dt)
1,800✔
133
{
134
  if (dt <= 0.0)
1,800✔
135
    throw std::runtime_error(GetName() + " dt must be greater than zero.");
×
136
  dt_ = dt;
1,800✔
137
}
1,800✔
138

139
double
140
LBSProblem::GetTimeStep() const
2,147,483,647✔
141
{
142
  return dt_;
2,147,483,647✔
143
}
144

145
void
146
LBSProblem::SetTheta(double theta)
264✔
147
{
148
  if (theta <= 0.0 or theta > 1.0)
264✔
149
    throw std::runtime_error(GetName() + " theta must be in (0.0, 1.0].");
×
150
  theta_ = theta;
264✔
151
}
264✔
152

153
double
154
LBSProblem::GetTheta() const
2,147,483,647✔
155
{
156
  return theta_;
2,147,483,647✔
157
}
158

159
GeometryType
160
LBSProblem::GetGeometryType() const
4✔
161
{
162
  return geometry_type_;
4✔
163
}
164

165
unsigned int
166
LBSProblem::GetNumMoments() const
525,809✔
167
{
168
  return num_moments_;
525,809✔
169
}
170

171
unsigned int
172
LBSProblem::GetMaxCellDOFCount() const
787✔
173
{
174
  return max_cell_dof_count_;
787✔
175
}
176

177
unsigned int
178
LBSProblem::GetMinCellDOFCount() const
787✔
179
{
180
  return min_cell_dof_count_;
787✔
181
}
182

183
bool
184
LBSProblem::UseGPUs() const
1,099✔
185
{
186
  return use_gpus_;
1,099✔
187
}
188

189
unsigned int
190
LBSProblem::GetNumGroups() const
818,722✔
191
{
192
  return num_groups_;
818,722✔
193
}
194

195
unsigned int
196
LBSProblem::GetScatteringOrder() const
4✔
197
{
198
  return scattering_order_;
4✔
199
}
200

201
unsigned int
202
LBSProblem::GetNumPrecursors() const
×
203
{
204
  return num_precursors_;
×
205
}
206

207
unsigned int
208
LBSProblem::GetMaxPrecursorsPerMaterial() const
9,550✔
209
{
210
  return max_precursors_per_material_;
9,550✔
211
}
212

213
std::vector<LBSGroupset>&
214
LBSProblem::GetGroupsets()
21,377,230✔
215
{
216
  return groupsets_;
21,377,230✔
217
}
218

219
const std::vector<LBSGroupset>&
220
LBSProblem::GetGroupsets() const
×
221
{
222
  return groupsets_;
×
223
}
224

225
void
226
LBSProblem::AddPointSource(std::shared_ptr<PointSource> point_source)
×
227
{
228
  point_sources_.push_back(point_source);
×
229
  if (discretization_)
×
230
    point_sources_.back()->Initialize(*this);
×
231
}
×
232

233
void
234
LBSProblem::ClearPointSources()
×
235
{
236
  point_sources_.clear();
×
237
}
×
238

239
const std::vector<std::shared_ptr<PointSource>>&
240
LBSProblem::GetPointSources() const
146,244✔
241
{
242
  return point_sources_;
146,244✔
243
}
244

245
void
246
LBSProblem::AddVolumetricSource(std::shared_ptr<VolumetricSource> volumetric_source)
16✔
247
{
248
  volumetric_sources_.push_back(volumetric_source);
16✔
249
  if (discretization_)
16✔
250
    volumetric_sources_.back()->Initialize(*this);
16✔
251
}
16✔
252

253
void
254
LBSProblem::ClearVolumetricSources()
12✔
255
{
256
  volumetric_sources_.clear();
12✔
257
}
12✔
258

259
const std::vector<std::shared_ptr<VolumetricSource>>&
260
LBSProblem::GetVolumetricSources() const
146,244✔
261
{
262
  return volumetric_sources_;
146,244✔
263
}
264

265
const BlockID2XSMap&
266
LBSProblem::GetBlockID2XSMap() const
19,266✔
267
{
268
  return block_id_to_xs_map_;
19,266✔
269
}
270

271
void
272
LBSProblem::SetBlockID2XSMap(const BlockID2XSMap& xs_map)
168✔
273
{
274
  block_id_to_xs_map_ = xs_map;
168✔
275
  InitializeMaterials();
168✔
276
  ResetGPUCarriers();
168✔
277
  InitializeGPUExtras();
168✔
278
}
168✔
279

280
std::shared_ptr<MeshContinuum>
281
LBSProblem::GetGrid() const
749,611✔
282
{
283
  return grid_;
749,611✔
284
}
285

286
const SpatialDiscretization&
287
LBSProblem::GetSpatialDiscretization() const
238,368✔
288
{
289
  return *discretization_;
238,368✔
290
}
291

292
const std::vector<UnitCellMatrices>&
293
LBSProblem::GetUnitCellMatrices() const
20,092✔
294
{
295
  return unit_cell_matrices_;
20,092✔
296
}
297

298
const std::map<uint64_t, UnitCellMatrices>&
299
LBSProblem::GetUnitGhostCellMatrices() const
17✔
300
{
301
  return unit_ghost_cell_matrices_;
17✔
302
}
303

304
std::vector<CellLBSView>&
305
LBSProblem::GetCellTransportViews()
301,326✔
306
{
307
  return cell_transport_views_;
301,326✔
308
}
309

310
const std::vector<CellLBSView>&
311
LBSProblem::GetCellTransportViews() const
630,984✔
312
{
313
  return cell_transport_views_;
630,984✔
314
}
315

316
const UnknownManager&
317
LBSProblem::GetUnknownManager() const
27,039✔
318
{
319
  return flux_moments_uk_man_;
27,039✔
320
}
321

322
size_t
323
LBSProblem::GetLocalNodeCount() const
3,288✔
324
{
325
  return local_node_count_;
3,288✔
326
}
327

328
size_t
329
LBSProblem::GetGlobalNodeCount() const
2,684✔
330
{
331
  return global_node_count_;
2,684✔
332
}
333

334
std::vector<double>&
335
LBSProblem::GetQMomentsLocal()
357,617✔
336
{
337
  return q_moments_local_;
357,617✔
338
}
339

340
const std::vector<double>&
341
LBSProblem::GetQMomentsLocal() const
×
342
{
343
  return q_moments_local_;
×
344
}
345

346
std::vector<double>&
347
LBSProblem::GetExtSrcMomentsLocal()
4✔
348
{
349
  return ext_src_moments_local_;
4✔
350
}
351

352
const std::vector<double>&
353
LBSProblem::GetExtSrcMomentsLocal() const
210,328✔
354
{
355
  return ext_src_moments_local_;
210,328✔
356
}
357

358
std::vector<double>&
359
LBSProblem::GetPhiOldLocal()
277,191✔
360
{
361
  return phi_old_local_;
277,191✔
362
}
363

364
const std::vector<double>&
365
LBSProblem::GetPhiOldLocal() const
×
366
{
367
  return phi_old_local_;
×
368
}
369

370
std::vector<double>&
371
LBSProblem::GetPhiNewLocal()
248,750✔
372
{
373
  return phi_new_local_;
248,750✔
374
}
375

376
const std::vector<double>&
377
LBSProblem::GetPhiNewLocal() const
×
378
{
379
  return phi_new_local_;
×
380
}
381

382
std::vector<double>&
383
LBSProblem::GetPrecursorsNewLocal()
480✔
384
{
385
  return precursor_new_local_;
480✔
386
}
387

388
const std::vector<double>&
389
LBSProblem::GetPrecursorsNewLocal() const
×
390
{
391
  return precursor_new_local_;
×
392
}
393

394
std::vector<double>&
395
LBSProblem::GetDensitiesLocal()
1,037✔
396
{
397
  return densities_local_;
1,037✔
398
}
399

400
const std::vector<double>&
401
LBSProblem::GetDensitiesLocal() const
210,328✔
402
{
403
  return densities_local_;
210,328✔
404
}
405

406
SetSourceFunction
407
LBSProblem::GetActiveSetSourceFunction() const
4,266✔
408
{
409
  return active_set_source_function_;
4,266✔
410
}
411

412
void
413
LBSProblem::SetActiveSetSourceFunction(SetSourceFunction source_function)
156✔
414
{
415
  active_set_source_function_ = std::move(source_function);
156✔
416
}
156✔
417

418
std::shared_ptr<AGSLinearSolver>
419
LBSProblem::GetAGSSolver()
2,872✔
420
{
421
  return ags_solver_;
2,872✔
422
}
423

424
std::vector<std::shared_ptr<LinearSolver>>&
425
LBSProblem::GetWGSSolvers()
2,817✔
426
{
427
  return wgs_solvers_;
2,817✔
428
}
429

430
WGSContext&
431
LBSProblem::GetWGSContext(int groupset_id)
11,520✔
432
{
433
  auto& wgs_solver = wgs_solvers_[groupset_id];
11,520✔
434
  auto raw_context = wgs_solver->GetContext();
11,520✔
435
  auto wgs_context_ptr = std::dynamic_pointer_cast<WGSContext>(raw_context);
11,520✔
436
  OpenSnLogicalErrorIf(not wgs_context_ptr, "Failed to cast WGSContext");
11,520✔
437
  return *wgs_context_ptr;
11,520✔
438
}
23,040✔
439

440
std::pair<size_t, size_t>
441
LBSProblem::GetNumPhiIterativeUnknowns()
×
442
{
443
  const auto& sdm = *discretization_;
×
444
  const size_t num_local_phi_dofs = sdm.GetNumLocalDOFs(flux_moments_uk_man_);
×
445
  const size_t num_global_phi_dofs = sdm.GetNumGlobalDOFs(flux_moments_uk_man_);
×
446

447
  return {num_local_phi_dofs, num_global_phi_dofs};
×
448
}
449

450
size_t
451
LBSProblem::MapPhiFieldFunction(unsigned int g, unsigned int m) const
28,964✔
452
{
453
  OpenSnLogicalErrorIf(phi_field_functions_local_map_.count({g, m}) == 0,
28,964✔
454
                       std::string("Failure to map phi field function g") + std::to_string(g) +
455
                         " m" + std::to_string(m));
456

457
  return phi_field_functions_local_map_.at({g, m});
28,964✔
458
}
459

460
std::shared_ptr<FieldFunctionGridBased>
461
LBSProblem::GetPowerFieldFunction() const
×
462
{
463
  OpenSnLogicalErrorIf(not options_.power_field_function_on,
×
464
                       "Called when options_.power_field_function_on == false");
465

466
  return field_functions_[power_gen_fieldfunc_local_handle_];
×
467
}
468

469
InputParameters
470
LBSProblem::GetOptionsBlock()
714✔
471
{
472
  InputParameters params;
714✔
473

474
  params.SetGeneralDescription("Set options from a large list of parameters");
1,428✔
475
  params.AddOptionalParameter("max_mpi_message_size",
1,428✔
476
                              32768,
477
                              "The maximum MPI message size used during sweep initialization.");
478
  params.AddOptionalParameter(
1,428✔
479
    "restart_writes_enabled", false, "Flag that controls writing of restart dumps");
480
  params.AddOptionalParameter("write_delayed_psi_to_restart",
1,428✔
481
                              true,
482
                              "Flag that controls writing of delayed angular fluxes to restarts.");
483
  params.AddOptionalParameter(
1,428✔
484
    "read_restart_path", "", "Full path for reading restart dumps including file stem.");
485
  params.AddOptionalParameter(
1,428✔
486
    "write_restart_path", "", "Full path for writing restart dumps including file stem.");
487
  params.AddOptionalParameter("write_restart_time_interval",
1,428✔
488
                              0,
489
                              "Time interval in seconds at which restart data is to be written.");
490
  params.AddOptionalParameter(
1,428✔
491
    "use_precursors", false, "Flag for using delayed neutron precursors.");
492
  params.AddOptionalParameter("use_source_moments",
1,428✔
493
                              false,
494
                              "Flag for ignoring fixed sources and selectively using source "
495
                              "moments obtained elsewhere.");
496
  params.AddOptionalParameter(
1,428✔
497
    "save_angular_flux", false, "Flag indicating whether angular fluxes are to be stored or not.");
498
  params.AddOptionalParameter(
1,428✔
499
    "adjoint", false, "Flag for toggling whether the solver is in adjoint mode.");
500
  params.AddOptionalParameter(
1,428✔
501
    "verbose_inner_iterations", true, "Flag to control verbosity of inner iterations.");
502
  params.AddOptionalParameter(
1,428✔
503
    "verbose_outer_iterations", true, "Flag to control verbosity of across-groupset iterations.");
504
  params.AddOptionalParameter(
1,428✔
505
    "max_ags_iterations", 100, "Maximum number of across-groupset iterations.");
506
  params.AddOptionalParameter("ags_tolerance", 1.0e-6, "Across-groupset iterations tolerance.");
1,428✔
507
  params.AddOptionalParameter("ags_convergence_check",
1,428✔
508
                              "l2",
509
                              "Type of convergence check for AGS iterations. Valid values are "
510
                              "`\"l2\"` and '\"pointwise\"'");
511
  params.AddOptionalParameter(
1,428✔
512
    "verbose_ags_iterations", true, "Flag to control verbosity of across-groupset iterations.");
513
  params.AddOptionalParameter("power_field_function_on",
1,428✔
514
                              false,
515
                              "Flag to control the creation of the power generation field "
516
                              "function. If set to `true` then a field function will be created "
517
                              "with the general name <solver_name>_power_generation`.");
518
  params.AddOptionalParameter("power_default_kappa",
1,428✔
519
                              3.20435e-11,
520
                              "Default `kappa` value (Energy released per fission) to use for "
521
                              "power generation when cross sections do not have `kappa` values. "
522
                              "Default: 3.20435e-11 Joule (corresponding to 200 MeV per fission).");
523
  params.AddOptionalParameter("power_normalization",
1,428✔
524
                              -1.0,
525
                              "Power normalization factor to use. Supply a negative or zero number "
526
                              "to turn this off.");
527
  params.AddOptionalParameter("field_function_prefix_option",
1,428✔
528
                              "prefix",
529
                              "Prefix option on field function names. Default: `\"prefix\"`. Can "
530
                              "be `\"prefix\"` or `\"solver_name\"`. By default this option uses "
531
                              "the value of the `field_function_prefix` parameter. If this "
532
                              "parameter is not set, flux field functions will be exported as "
533
                              "`phi_gXXX_mYYY` where `XXX` is the zero padded 3 digit group number "
534
                              "and `YYY` is the zero padded 3 digit moment.");
535
  params.AddOptionalParameter("field_function_prefix",
1,428✔
536
                              "",
537
                              "Prefix to use on all field functions. Default: `\"\"`. By default "
538
                              "this option is empty. Ff specified, flux moments will be exported "
539
                              "as `prefix_phi_gXXX_mYYY` where `XXX` is the zero padded 3 digit "
540
                              "group number and `YYY` is the zero padded 3 digit moment. The "
541
                              "underscore after \"prefix\" is added automatically.");
542
  params.ConstrainParameterRange("ags_convergence_check",
2,142✔
543
                                 AllowableRangeList::New({"l2", "pointwise"}));
714✔
544
  params.ConstrainParameterRange("field_function_prefix_option",
2,142✔
545
                                 AllowableRangeList::New({"prefix", "solver_name"}));
714✔
546
  params.ConstrainParameterRange("max_mpi_message_size", AllowableRangeLowLimit::New(1024));
2,142✔
547
  params.ConstrainParameterRange("write_restart_time_interval", AllowableRangeLowLimit::New(0));
2,142✔
548
  params.ConstrainParameterRange("max_ags_iterations", AllowableRangeLowLimit::New(0));
2,142✔
549
  params.ConstrainParameterRange("ags_tolerance", AllowableRangeLowLimit::New(1.0e-18));
2,142✔
550
  params.ConstrainParameterRange("power_default_kappa", AllowableRangeLowLimit::New(0.0, false));
2,142✔
551

552
  return params;
714✔
553
}
×
554

555
InputParameters
556
LBSProblem::GetXSMapEntryBlock()
997✔
557
{
558
  InputParameters params;
997✔
559
  params.SetGeneralDescription("Set the cross-section map for the solver.");
1,994✔
560
  params.AddRequiredParameterArray("block_ids", "Mesh block IDs");
1,994✔
561
  params.AddRequiredParameter<std::shared_ptr<MultiGroupXS>>("xs", "Cross-section object");
1,994✔
562
  return params;
997✔
563
}
×
564

565
void
566
LBSProblem::SetOptions(const InputParameters& input)
356✔
567
{
568
  auto params = LBSProblem::GetOptionsBlock();
356✔
569
  params.AssignParameters(input);
356✔
570
  const auto& params_at_assignment = input.GetParametersAtAssignment();
356✔
571
  const auto& specified_params = params_at_assignment.GetNumParameters() > 0
356✔
572
                                   ? params_at_assignment
356✔
573
                                   : static_cast<const ParameterBlock&>(input);
356✔
574

575
  // Apply only options explicitly specified by the caller.
576
  for (const auto& spec : specified_params.GetParameters())
1,311✔
577
  {
578
    if (spec.GetName() == "max_mpi_message_size")
955✔
UNCOV
579
      options_.max_mpi_message_size = spec.GetValue<int>();
×
580

581
    else if (spec.GetName() == "restart_writes_enabled")
955✔
UNCOV
582
      options_.restart_writes_enabled = spec.GetValue<bool>();
×
583

584
    else if (spec.GetName() == "write_delayed_psi_to_restart")
955✔
UNCOV
585
      options_.write_delayed_psi_to_restart = spec.GetValue<bool>();
×
586

587
    else if (spec.GetName() == "read_restart_path")
955✔
588
    {
589
      options_.read_restart_path = spec.GetValue<std::string>();
12✔
590
      if (not options_.read_restart_path.empty())
12✔
591
        options_.read_restart_path += std::to_string(opensn::mpi_comm.rank()) + ".restart.h5";
36✔
592
    }
593

594
    else if (spec.GetName() == "write_restart_path")
943✔
595
    {
UNCOV
596
      options_.write_restart_path = spec.GetValue<std::string>();
×
UNCOV
597
      if (not options_.write_restart_path.empty())
×
598
        options_.write_restart_path += std::to_string(opensn::mpi_comm.rank()) + ".restart.h5";
×
599
    }
600

601
    else if (spec.GetName() == "write_restart_time_interval")
943✔
UNCOV
602
      options_.write_restart_time_interval = std::chrono::seconds(spec.GetValue<int>());
×
603

604
    else if (spec.GetName() == "use_precursors")
943✔
605
      options_.use_precursors = spec.GetValue<bool>();
120✔
606

607
    else if (spec.GetName() == "use_source_moments")
823✔
608
      options_.use_src_moments = spec.GetValue<bool>();
4✔
609

610
    else if (spec.GetName() == "save_angular_flux")
819✔
611
      options_.save_angular_flux = spec.GetValue<bool>();
198✔
612

613
    else if (spec.GetName() == "verbose_inner_iterations")
621✔
614
      options_.verbose_inner_iterations = spec.GetValue<bool>();
207✔
615

616
    else if (spec.GetName() == "max_ags_iterations")
414✔
617
      options_.max_ags_iterations = spec.GetValue<int>();
50✔
618

619
    else if (spec.GetName() == "ags_tolerance")
364✔
620
      options_.ags_tolerance = spec.GetValue<double>();
8✔
621

622
    else if (spec.GetName() == "ags_convergence_check")
356✔
623
    {
UNCOV
624
      auto check = spec.GetValue<std::string>();
×
NEW
625
      options_.ags_pointwise_convergence = (check == "pointwise");
×
626
    }
×
627

628
    else if (spec.GetName() == "verbose_ags_iterations")
356✔
629
      options_.verbose_ags_iterations = spec.GetValue<bool>();
124✔
630

631
    else if (spec.GetName() == "verbose_outer_iterations")
232✔
632
      options_.verbose_outer_iterations = spec.GetValue<bool>();
183✔
633

634
    else if (spec.GetName() == "power_field_function_on")
49✔
635
      options_.power_field_function_on = spec.GetValue<bool>();
4✔
636

637
    else if (spec.GetName() == "power_default_kappa")
45✔
638
      options_.power_default_kappa = spec.GetValue<double>();
12✔
639

640
    else if (spec.GetName() == "power_normalization")
33✔
641
      options_.power_normalization = spec.GetValue<double>();
12✔
642

643
    else if (spec.GetName() == "field_function_prefix_option")
21✔
644
    {
UNCOV
645
      options_.field_function_prefix_option = spec.GetValue<std::string>();
×
646
    }
647

648
    else if (spec.GetName() == "field_function_prefix")
21✔
649
      options_.field_function_prefix = spec.GetValue<std::string>();
1✔
650

651
    else if (spec.GetName() == "adjoint")
20✔
652
      options_.adjoint = spec.GetValue<bool>();
20✔
653

654
  } // for specified options
655

656
  OpenSnInvalidArgumentIf(options_.write_restart_time_interval > std::chrono::seconds(0) and
356✔
657
                            not options_.restart_writes_enabled,
658
                          GetName() + ": `write_restart_time_interval>0` requires "
659
                                      "`restart_writes_enabled=true`.");
660

661
  OpenSnInvalidArgumentIf(options_.write_restart_time_interval > std::chrono::seconds(0) and
356✔
662
                            options_.write_restart_time_interval < std::chrono::seconds(30),
663
                          GetName() + ": `write_restart_time_interval` must be 0 (disabled) "
664
                                      "or at least 30 seconds.");
665

666
  OpenSnInvalidArgumentIf(options_.restart_writes_enabled and options_.write_restart_path.empty(),
356✔
667
                          GetName() + ": `restart_writes_enabled=true` requires a non-empty "
668
                                      "`write_restart_path`.");
669

670
  OpenSnInvalidArgumentIf(not options_.field_function_prefix.empty() and
356✔
671
                            options_.field_function_prefix_option != "prefix",
672
                          GetName() + ": non-empty `field_function_prefix` requires "
673
                                      "`field_function_prefix_option=\"prefix\"`.");
674

675
  if (options_.restart_writes_enabled)
356✔
676
  {
NEW
677
    const auto dir = options_.write_restart_path.parent_path();
×
678

679
    // Create restart directory if necessary.
680
    // If dir is empty, write path resolves relative to the working directory.
NEW
681
    if ((not dir.empty()) and opensn::mpi_comm.rank() == 0)
×
682
    {
683
      if (not std::filesystem::exists(dir))
×
684
      {
685
        if (not std::filesystem::create_directories(dir))
×
686
          throw std::runtime_error(GetName() + ": Failed to create restart directory " +
×
687
                                   dir.string());
×
688
      }
689
      else if (not std::filesystem::is_directory(dir))
×
690
        throw std::runtime_error(GetName() + ": Restart path exists but is not a directory " +
×
691
                                 dir.string());
×
692
    }
693
    opensn::mpi_comm.barrier();
×
694
    UpdateRestartWriteTime();
×
695
  }
×
696
}
356✔
697

698
void
699
LBSProblem::Initialize()
572✔
700
{
701
  CALI_CXX_MARK_SCOPE("LBSProblem::Initialize");
572✔
702

703
  PrintSimHeader();
572✔
704
  mpi_comm.barrier();
572✔
705

706
  InitializeSpatialDiscretization();
572✔
707
  InitializeParrays();
572✔
708
  InitializeBoundaries();
572✔
709
  InitializeGPUExtras();
572✔
710
  SetAdjoint(options_.adjoint);
572✔
711

712
  // Initialize point sources
713
  for (auto& point_source : point_sources_)
581✔
714
    point_source->Initialize(*this);
9✔
715

716
  // Initialize volumetric sources
717
  for (auto& volumetric_source : volumetric_sources_)
1,051✔
718
    volumetric_source->Initialize(*this);
479✔
719
}
572✔
720

721
void
722
LBSProblem::PrintSimHeader()
×
723
{
724
  if (opensn::mpi_comm.rank() == 0)
×
725
  {
726
    std::stringstream outstr;
×
727
    outstr << "\n"
×
728
           << "Initializing " << GetName() << "\n\n"
×
729
           << "Scattering order    : " << scattering_order_ << "\n"
×
730
           << "Number of moments   : " << num_moments_ << "\n"
×
731
           << "Number of groups    : " << num_groups_ << "\n"
×
732
           << "Number of groupsets : " << groupsets_.size() << "\n\n";
×
733

734
    for (const auto& groupset : groupsets_)
×
735
    {
736
      outstr << "***** Groupset " << groupset.id << " *****\n"
×
737
             << "Groups:\n";
×
738
      const auto n_gs_groups = groupset.GetNumGroups();
×
739
      constexpr int groups_per_line = 12;
740
      for (size_t i = 0; i < n_gs_groups; ++i)
×
741
      {
742
        outstr << std::setw(5) << groupset.first_group + i << ' ';
×
743
        if ((i + 1) % groups_per_line == 0)
×
744
          outstr << '\n';
×
745
      }
746
      if (n_gs_groups > 0 && n_gs_groups % groups_per_line != 0)
×
747
        outstr << '\n';
×
748
    }
749

750
    log.Log() << outstr.str() << '\n';
×
751
  }
×
752
}
×
753

754
void
755
LBSProblem::InitializeSources(const InputParameters& params)
572✔
756
{
757
  if (params.Has("volumetric_sources"))
572✔
758
  {
759
    const auto& vol_srcs = params.GetParam("volumetric_sources");
572✔
760
    vol_srcs.RequireBlockTypeIs(ParameterBlockType::ARRAY);
572✔
761
    for (const auto& src : vol_srcs)
1,051✔
762
      volumetric_sources_.push_back(src.GetValue<std::shared_ptr<VolumetricSource>>());
958✔
763
  }
764

765
  if (params.Has("point_sources"))
572✔
766
  {
767
    const auto& pt_srcs = params.GetParam("point_sources");
572✔
768
    pt_srcs.RequireBlockTypeIs(ParameterBlockType::ARRAY);
572✔
769
    for (const auto& src : pt_srcs)
581✔
770
      point_sources_.push_back(src.GetValue<std::shared_ptr<PointSource>>());
18✔
771
  }
772
}
572✔
773

774
void
775
LBSProblem::InitializeGroupsets(const InputParameters& params)
572✔
776
{
777
  // Initialize groups
778
  if (num_groups_ == 0)
572✔
779
    throw std::invalid_argument(GetName() + ": Number of groups must be > 0");
×
780

781
  // Initialize groupsets
782
  const auto& groupsets_array = params.GetParam("groupsets");
572✔
783
  const size_t num_gs = groupsets_array.GetNumParameters();
572✔
784
  if (num_gs == 0)
572✔
785
    throw std::invalid_argument(GetName() + ": At least one groupset must be specified");
×
786
  for (size_t gs = 0; gs < num_gs; ++gs)
1,203✔
787
  {
788
    const auto& groupset_params = groupsets_array.GetParam(gs);
631✔
789
    InputParameters gs_input_params = LBSGroupset::GetInputParameters();
631✔
790
    gs_input_params.SetObjectType("LBSProblem:LBSGroupset");
631✔
791
    gs_input_params.AssignParameters(groupset_params);
631✔
792
    groupsets_.emplace_back(gs_input_params, gs, *this);
631✔
793
    if (groupsets_.back().GetNumGroups() == 0)
631✔
794
    {
795
      std::stringstream oss;
×
796
      oss << GetName() << ": No groups added to groupset " << groupsets_.back().id;
×
797
      throw std::runtime_error(oss.str());
×
798
    }
×
799
  }
631✔
800
}
572✔
801

802
void
803
LBSProblem::InitializeXSmapAndDensities(const InputParameters& params)
572✔
804
{
805
  // Build XS map
806
  const auto& xs_array = params.GetParam("xs_map");
572✔
807
  const size_t num_xs = xs_array.GetNumParameters();
572✔
808
  for (size_t i = 0; i < num_xs; ++i)
1,401✔
809
  {
810
    const auto& item_params = xs_array.GetParam(i);
829✔
811
    InputParameters xs_entry_pars = GetXSMapEntryBlock();
829✔
812
    xs_entry_pars.AssignParameters(item_params);
829✔
813

814
    const auto& block_ids_param = xs_entry_pars.GetParam("block_ids");
829✔
815
    block_ids_param.RequireBlockTypeIs(ParameterBlockType::ARRAY);
829✔
816
    const auto& block_ids = block_ids_param.GetVectorValue<unsigned int>();
829✔
817
    auto xs = xs_entry_pars.GetSharedPtrParam<MultiGroupXS>("xs");
829✔
818
    for (const auto& block_id : block_ids)
1,766✔
819
      block_id_to_xs_map_[block_id] = xs;
937✔
820
  }
829✔
821

822
  // Assign placeholder unit densities
823
  densities_local_.assign(grid_->local_cells.size(), 1.0);
572✔
824
}
572✔
825

826
void
827
LBSProblem::InitializeMaterials()
752✔
828
{
829
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeMaterials");
752✔
830

831
  log.Log0Verbose1() << "Initializing Materials";
1,504✔
832

833
  // Create set of material ids locally relevant
834
  int invalid_mat_cell_count = 0;
752✔
835
  std::set<unsigned int> unique_block_ids;
752✔
836
  for (auto& cell : grid_->local_cells)
597,625✔
837
  {
838
    unique_block_ids.insert(cell.block_id);
596,873✔
839
    if (cell.block_id == std::numeric_limits<unsigned int>::max() or
596,873✔
840
        (block_id_to_xs_map_.find(cell.block_id) == block_id_to_xs_map_.end()))
596,873✔
841
      ++invalid_mat_cell_count;
×
842
  }
843
  const auto& ghost_cell_ids = grid_->cells.GetGhostGlobalIDs();
752✔
844
  for (uint64_t cell_id : ghost_cell_ids)
98,849✔
845
  {
846
    const auto& cell = grid_->cells[cell_id];
98,097✔
847
    unique_block_ids.insert(cell.block_id);
98,097✔
848
    if (cell.block_id == std::numeric_limits<unsigned int>::max() or
98,097✔
849
        (block_id_to_xs_map_.find(cell.block_id) == block_id_to_xs_map_.end()))
98,097✔
850
      ++invalid_mat_cell_count;
×
851
  }
852
  OpenSnLogicalErrorIf(invalid_mat_cell_count > 0,
752✔
853
                       std::to_string(invalid_mat_cell_count) +
854
                         " cells encountered with an invalid material id.");
855

856
  // Get ready for processing
857
  for (const auto& [blk_id, mat] : block_id_to_xs_map_)
1,885✔
858
  {
859
    mat->SetAdjointMode(options_.adjoint);
1,133✔
860

861
    OpenSnLogicalErrorIf(mat->GetNumGroups() < num_groups_,
1,133✔
862
                         "Cross-sections for block \"" + std::to_string(blk_id) +
863
                           "\" have fewer groups (" + std::to_string(mat->GetNumGroups()) +
864
                           ") than the simulation (" + std::to_string(num_groups_) + "). " +
865
                           "Cross-sections must have at least as many groups as the simulation.");
866
  }
867

868
  // Initialize precursor properties
869
  num_precursors_ = 0;
752✔
870
  max_precursors_per_material_ = 0;
752✔
871
  for (const auto& mat_id_xs : block_id_to_xs_map_)
1,885✔
872
  {
873
    const auto& xs = mat_id_xs.second;
1,133✔
874
    num_precursors_ += xs->GetNumPrecursors();
1,133✔
875
    max_precursors_per_material_ = std::max(xs->GetNumPrecursors(), max_precursors_per_material_);
1,133✔
876
  }
877

878
  // if no precursors, turn off precursors
879
  if (num_precursors_ == 0)
752✔
880
    options_.use_precursors = false;
556✔
881

882
  // check compatibility when precursors are on
883
  if (options_.use_precursors)
752✔
884
  {
885
    for (const auto& [mat_id, xs] : block_id_to_xs_map_)
352✔
886
    {
887
      OpenSnLogicalErrorIf(xs->IsFissionable() and num_precursors_ == 0,
176✔
888
                           "Incompatible cross-section data encountered for material id " +
889
                             std::to_string(mat_id) + ". When delayed neutron data is present " +
890
                             "for one fissionable matrial, it must be present for all fissionable "
891
                             "materials.");
892
    }
893
  }
894

895
  // Update transport views if available
896
  if (grid_->local_cells.size() == cell_transport_views_.size())
752✔
897
    for (const auto& cell : grid_->local_cells)
25,168✔
898
    {
899
      const auto& xs_ptr = block_id_to_xs_map_[cell.block_id];
24,988✔
900
      auto& transport_view = cell_transport_views_[cell.local_id];
24,988✔
901
      transport_view.ReassignXS(*xs_ptr);
24,988✔
902
    }
903

904
  mpi_comm.barrier();
752✔
905
}
752✔
906

907
void
908
LBSProblem::InitializeSpatialDiscretization()
492✔
909
{
910
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeSpatialDiscretization");
492✔
911

912
  log.Log() << "Initializing spatial discretization.\n";
984✔
913
  discretization_ = PieceWiseLinearDiscontinuous::New(grid_);
492✔
914

915
  ComputeUnitIntegrals();
492✔
916
}
492✔
917

918
void
919
LBSProblem::ComputeUnitIntegrals()
572✔
920
{
921
  CALI_CXX_MARK_SCOPE("LBSProblem::ComputeUnitIntegrals");
572✔
922

923
  log.Log() << "Computing unit integrals.\n";
1,144✔
924
  const auto& sdm = *discretization_;
572✔
925

926
  const size_t num_local_cells = grid_->local_cells.size();
572✔
927
  unit_cell_matrices_.resize(num_local_cells);
572✔
928

929
  for (const auto& cell : grid_->local_cells)
572,457✔
930
    unit_cell_matrices_[cell.local_id] =
571,885✔
931
      ComputeUnitCellIntegrals(sdm, cell, grid_->GetCoordinateSystem());
571,885✔
932

933
  const auto ghost_ids = grid_->cells.GetGhostGlobalIDs();
572✔
934
  for (auto ghost_id : ghost_ids)
90,185✔
935
    unit_ghost_cell_matrices_[ghost_id] =
89,613✔
936
      ComputeUnitCellIntegrals(sdm, grid_->cells[ghost_id], grid_->GetCoordinateSystem());
179,226✔
937

938
  // Assessing global unit cell matrix storage
939
  std::array<size_t, 2> num_local_ucms = {unit_cell_matrices_.size(),
572✔
940
                                          unit_ghost_cell_matrices_.size()};
572✔
941
  std::array<size_t, 2> num_global_ucms = {0, 0};
572✔
942

943
  mpi_comm.all_reduce(num_local_ucms.data(), 2, num_global_ucms.data(), mpi::op::sum<size_t>());
572✔
944

945
  opensn::mpi_comm.barrier();
572✔
946
  log.Log() << "Ghost cell unit cell-matrix ratio: "
572✔
947
            << (double)num_global_ucms[1] * 100 / (double)num_global_ucms[0] << "%";
1,144✔
948
  log.Log() << "Cell matrices computed.";
1,144✔
949
}
572✔
950

951
void
952
LBSProblem::InitializeParrays()
572✔
953
{
954
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeParrays");
572✔
955

956
  log.Log() << "Initializing parallel arrays."
1,144✔
957
            << " G=" << num_groups_ << " M=" << num_moments_ << std::endl;
572✔
958

959
  // Initialize unknown
960
  // structure
961
  flux_moments_uk_man_.unknowns.clear();
572✔
962
  for (unsigned int m = 0; m < num_moments_; ++m)
1,718✔
963
  {
964
    flux_moments_uk_man_.AddUnknown(UnknownType::VECTOR_N, num_groups_);
1,146✔
965
    flux_moments_uk_man_.unknowns.back().name = "m" + std::to_string(m);
1,146✔
966
  }
967

968
  // Compute local # of dof
969
  local_node_count_ = discretization_->GetNumLocalNodes();
572✔
970
  global_node_count_ = discretization_->GetNumGlobalNodes();
572✔
971

972
  // Compute num of unknowns
973
  size_t local_unknown_count = local_node_count_ * num_groups_ * num_moments_;
572✔
974

975
  log.LogAllVerbose1() << "LBS Number of phi unknowns: " << local_unknown_count;
1,144✔
976

977
  // Size local vectors
978
  q_moments_local_.assign(local_unknown_count, 0.0);
572✔
979
  phi_old_local_.assign(local_unknown_count, 0.0);
572✔
980
  phi_new_local_.assign(local_unknown_count, 0.0);
572✔
981

982
  // Setup precursor vector
983
  if (options_.use_precursors)
572✔
984
  {
985
    size_t num_precursor_dofs = grid_->local_cells.size() * max_precursors_per_material_;
60✔
986
    precursor_new_local_.assign(num_precursor_dofs, 0.0);
60✔
987
  }
988

989
  // Initialize transport views
990
  // Transport views act as a data structure to store information
991
  // related to the transport simulation. The most prominent function
992
  // here is that it holds the means to know where a given cell's
993
  // transport quantities are located in the unknown vectors (i.e. phi)
994
  //
995
  // Also, for a given cell, within a given sweep chunk,
996
  // we need to solve a matrix which square size is the
997
  // amount of nodes on the cell. max_cell_dof_count is
998
  // initialized here.
999
  //
1000
  size_t block_MG_counter = 0; // Counts the strides of moment and group
572✔
1001

1002
  const Vector3 ihat(1.0, 0.0, 0.0);
572✔
1003
  const Vector3 jhat(0.0, 1.0, 0.0);
572✔
1004
  const Vector3 khat(0.0, 0.0, 1.0);
572✔
1005

1006
  min_cell_dof_count_ = std::numeric_limits<unsigned int>::max();
572✔
1007
  max_cell_dof_count_ = 0;
572✔
1008
  cell_transport_views_.clear();
572✔
1009
  cell_transport_views_.reserve(grid_->local_cells.size());
572✔
1010
  for (auto& cell : grid_->local_cells)
572,457✔
1011
  {
1012
    size_t num_nodes = discretization_->GetCellNumNodes(cell);
571,885✔
1013

1014
    // compute cell volumes
1015
    double cell_volume = 0.0;
571,885✔
1016
    const auto& IntV_shapeI = unit_cell_matrices_[cell.local_id].intV_shapeI;
571,885✔
1017
    for (size_t i = 0; i < num_nodes; ++i)
3,966,781✔
1018
      cell_volume += IntV_shapeI(i);
3,394,896✔
1019

1020
    size_t cell_phi_address = block_MG_counter;
571,885✔
1021

1022
    const size_t num_faces = cell.faces.size();
571,885✔
1023
    std::vector<bool> face_local_flags(num_faces, true);
571,885✔
1024
    std::vector<int> face_locality(num_faces, opensn::mpi_comm.rank());
571,885✔
1025
    std::vector<const Cell*> neighbor_cell_ptrs(num_faces, nullptr);
571,885✔
1026
    bool cell_on_boundary = false;
571,885✔
1027
    int f = 0;
571,885✔
1028
    for (auto& face : cell.faces)
3,399,301✔
1029
    {
1030
      if (not face.has_neighbor)
2,827,416✔
1031
      {
1032
        cell_on_boundary = true;
91,560✔
1033
        face_local_flags[f] = false;
91,560✔
1034
        face_locality[f] = -1;
91,560✔
1035
      } // if bndry
1036
      else
1037
      {
1038
        const int neighbor_partition = face.GetNeighborPartitionID(grid_.get());
2,735,856✔
1039
        face_local_flags[f] = (neighbor_partition == opensn::mpi_comm.rank());
2,735,856✔
1040
        face_locality[f] = neighbor_partition;
2,735,856✔
1041
        neighbor_cell_ptrs[f] = &grid_->cells[face.neighbor_id];
2,735,856✔
1042
      }
1043

1044
      ++f;
2,827,416✔
1045
    } // for f
1046

1047
    max_cell_dof_count_ = std::max(max_cell_dof_count_, static_cast<unsigned int>(num_nodes));
571,885✔
1048
    min_cell_dof_count_ = std::min(min_cell_dof_count_, static_cast<unsigned int>(num_nodes));
571,885✔
1049
    cell_transport_views_.emplace_back(cell_phi_address,
1,143,770✔
1050
                                       num_nodes,
1051
                                       num_groups_,
571,885✔
1052
                                       num_moments_,
571,885✔
1053
                                       num_faces,
1054
                                       *block_id_to_xs_map_[cell.block_id],
571,885✔
1055
                                       cell_volume,
1056
                                       face_local_flags,
1057
                                       face_locality,
1058
                                       neighbor_cell_ptrs,
1059
                                       cell_on_boundary);
1060
    block_MG_counter += num_nodes * num_groups_ * num_moments_;
571,885✔
1061
  } // for local cell
571,885✔
1062

1063
  // Populate grid nodal mappings
1064
  // This is used in the Flux Data Structures (FLUDS)
1065
  grid_nodal_mappings_.clear();
572✔
1066
  grid_nodal_mappings_.reserve(grid_->local_cells.size());
572✔
1067
  for (auto& cell : grid_->local_cells)
572,457✔
1068
  {
1069
    CellFaceNodalMapping cell_nodal_mapping;
571,885✔
1070
    cell_nodal_mapping.reserve(cell.faces.size());
571,885✔
1071

1072
    for (auto& face : cell.faces)
3,399,301✔
1073
    {
1074
      std::vector<short> face_node_mapping;
2,827,416✔
1075
      std::vector<short> cell_node_mapping;
2,827,416✔
1076
      int adj_face_idx = -1;
2,827,416✔
1077

1078
      if (face.has_neighbor)
2,827,416✔
1079
      {
1080
        grid_->FindAssociatedVertices(face, face_node_mapping);
2,735,856✔
1081
        grid_->FindAssociatedCellVertices(face, cell_node_mapping);
2,735,856✔
1082
        adj_face_idx = face.GetNeighborAdjacentFaceIndex(grid_.get());
2,735,856✔
1083
      }
1084

1085
      cell_nodal_mapping.emplace_back(adj_face_idx, face_node_mapping, cell_node_mapping);
2,827,416✔
1086
    } // for f
2,827,416✔
1087

1088
    grid_nodal_mappings_.push_back(cell_nodal_mapping);
571,885✔
1089
  } // for local cell
571,885✔
1090

1091
  // Get grid localized communicator set
1092
  grid_local_comm_set_ = grid_->MakeMPILocalCommunicatorSet();
572✔
1093

1094
  // Initialize Field Functions
1095
  InitializeFieldFunctions();
572✔
1096

1097
  opensn::mpi_comm.barrier();
572✔
1098
  log.Log() << "Done with parallel arrays." << std::endl;
1,144✔
1099
}
572✔
1100

1101
void
1102
LBSProblem::InitializeFieldFunctions()
572✔
1103
{
1104
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeFieldFunctions");
572✔
1105

1106
  if (not field_functions_.empty())
572✔
1107
    return;
×
1108

1109
  // Initialize Field Functions for flux moments
1110
  phi_field_functions_local_map_.clear();
572✔
1111

1112
  for (unsigned int g = 0; g < num_groups_; ++g)
23,233✔
1113
  {
1114
    for (unsigned int m = 0; m < num_moments_; ++m)
100,640✔
1115
    {
1116
      std::string prefix;
77,979✔
1117
      if (options_.field_function_prefix_option == "prefix")
77,979✔
1118
      {
1119
        prefix = options_.field_function_prefix;
77,979✔
1120
        if (not prefix.empty())
77,979✔
1121
          prefix += "_";
1✔
1122
      }
1123
      if (options_.field_function_prefix_option == "solver_name")
77,979✔
1124
        prefix = GetName() + "_";
×
1125

1126
      std::ostringstream oss;
77,979✔
1127
      oss << prefix << "phi_g" << std::setw(3) << std::setfill('0') << static_cast<int>(g) << "_m"
77,979✔
1128
          << std::setw(2) << std::setfill('0') << static_cast<int>(m);
77,979✔
1129
      const std::string name = oss.str();
77,979✔
1130

1131
      auto group_ff = std::make_shared<FieldFunctionGridBased>(
77,979✔
1132
        name, discretization_, Unknown(UnknownType::SCALAR));
77,979✔
1133

1134
      field_function_stack.push_back(group_ff);
155,958✔
1135
      field_functions_.push_back(group_ff);
77,979✔
1136

1137
      phi_field_functions_local_map_[{g, m}] = field_functions_.size() - 1;
77,979✔
1138
    } // for m
77,979✔
1139
  } // for g
1140

1141
  // Initialize power generation field function
1142
  if (options_.power_field_function_on)
572✔
1143
  {
1144
    std::string prefix;
4✔
1145
    if (options_.field_function_prefix_option == "prefix")
4✔
1146
    {
1147
      prefix = options_.field_function_prefix;
4✔
1148
      if (not prefix.empty())
4✔
1149
        prefix += "_";
×
1150
    }
1151
    if (options_.field_function_prefix_option == "solver_name")
4✔
1152
      prefix = GetName() + "_";
×
1153

1154
    auto power_ff = std::make_shared<FieldFunctionGridBased>(
4✔
1155
      prefix + "power_generation", discretization_, Unknown(UnknownType::SCALAR));
8✔
1156

1157
    field_function_stack.push_back(power_ff);
8✔
1158
    field_functions_.push_back(power_ff);
4✔
1159

1160
    power_gen_fieldfunc_local_handle_ = field_functions_.size() - 1;
4✔
1161
  }
4✔
1162
}
572✔
1163

1164
void
1165
LBSProblem::InitializeSolverSchemes()
728✔
1166
{
1167
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeSolverSchemes");
728✔
1168
  InitializeWGSSolvers();
728✔
1169

1170
  ags_solver_ = std::make_shared<AGSLinearSolver>(*this, wgs_solvers_);
728✔
1171
  if (groupsets_.size() == 1)
728✔
1172
  {
1173
    ags_solver_->SetMaxIterations(1);
673✔
1174
    ags_solver_->SetVerbosity(false);
673✔
1175
  }
1176
  else
1177
  {
1178
    ags_solver_->SetMaxIterations(options_.max_ags_iterations);
55✔
1179
    ags_solver_->SetVerbosity(options_.verbose_ags_iterations);
55✔
1180
  }
1181
  ags_solver_->SetTolerance(options_.ags_tolerance);
728✔
1182
}
728✔
1183

1184
#ifndef __OPENSN_WITH_GPU__
1185
void
1186
LBSProblem::InitializeGPUExtras()
740✔
1187
{
1188
}
740✔
1189

1190
void
1191
LBSProblem::ResetGPUCarriers()
728✔
1192
{
1193
}
728✔
1194

1195
void
1196
LBSProblem::CheckCapableDevices()
×
1197
{
1198
}
×
1199
#endif // __OPENSN_WITH_GPU__
1200

1201
std::vector<double>
1202
LBSProblem::MakeSourceMomentsFromPhi()
4✔
1203
{
1204
  CALI_CXX_MARK_SCOPE("LBSProblem::MakeSourceMomentsFromPhi");
4✔
1205

1206
  size_t num_local_dofs = discretization_->GetNumLocalDOFs(flux_moments_uk_man_);
4✔
1207

1208
  std::vector<double> source_moments(num_local_dofs, 0.0);
4✔
1209
  for (auto& groupset : groupsets_)
8✔
1210
  {
1211
    active_set_source_function_(groupset,
4✔
1212
                                source_moments,
1213
                                phi_new_local_,
4✔
1214
                                APPLY_AGS_SCATTER_SOURCES | APPLY_WGS_SCATTER_SOURCES |
1215
                                  APPLY_AGS_FISSION_SOURCES | APPLY_WGS_FISSION_SOURCES);
4✔
1216
  }
1217

1218
  return source_moments;
4✔
1219
}
4✔
1220

1221
void
1222
LBSProblem::UpdateFieldFunctions()
2,744✔
1223
{
1224
  CALI_CXX_MARK_SCOPE("LBSProblem::UpdateFieldFunctions");
2,744✔
1225

1226
  const auto& sdm = *discretization_;
2,744✔
1227
  const auto& phi_uk_man = flux_moments_uk_man_;
2,744✔
1228

1229
  // Update flux moments
1230
  for (const auto& [g_and_m, ff_index] : phi_field_functions_local_map_)
87,719✔
1231
  {
1232
    const auto g = g_and_m.first;
84,975✔
1233
    const auto m = g_and_m.second;
84,975✔
1234

1235
    std::vector<double> data_vector_local(local_node_count_, 0.0);
84,975✔
1236

1237
    for (const auto& cell : grid_->local_cells)
24,447,304✔
1238
    {
1239
      const auto& cell_mapping = sdm.GetCellMapping(cell);
24,362,329✔
1240
      const size_t num_nodes = cell_mapping.GetNumNodes();
24,362,329✔
1241

1242
      for (size_t i = 0; i < num_nodes; ++i)
164,643,037✔
1243
      {
1244
        const auto imapA = sdm.MapDOFLocal(cell, i, phi_uk_man, m, g);
140,280,708✔
1245
        const auto imapB = sdm.MapDOFLocal(cell, i);
140,280,708✔
1246

1247
        data_vector_local[imapB] = phi_new_local_[imapA];
140,280,708✔
1248
      } // for node
1249
    } // for cell
1250

1251
    auto& ff_ptr = field_functions_.at(ff_index);
84,975✔
1252
    ff_ptr->UpdateFieldVector(data_vector_local);
84,975✔
1253
  }
84,975✔
1254

1255
  // Update power generation and scalar flux
1256
  if (options_.power_field_function_on)
2,744✔
1257
  {
1258
    std::vector<double> data_vector_power_local(local_node_count_, 0.0);
4✔
1259

1260
    double local_total_power = 0.0;
4✔
1261
    for (const auto& cell : grid_->local_cells)
83,268✔
1262
    {
1263
      const auto& cell_mapping = sdm.GetCellMapping(cell);
83,264✔
1264
      const size_t num_nodes = cell_mapping.GetNumNodes();
83,264✔
1265

1266
      const auto& Vi = unit_cell_matrices_[cell.local_id].intV_shapeI;
83,264✔
1267

1268
      const auto& xs = block_id_to_xs_map_.at(cell.block_id);
83,264✔
1269

1270
      if (not xs->IsFissionable())
83,264✔
1271
        continue;
56,360✔
1272

1273
      for (size_t i = 0; i < num_nodes; ++i)
134,520✔
1274
      {
1275
        const auto imapA = sdm.MapDOFLocal(cell, i);
107,616✔
1276
        const auto imapB = sdm.MapDOFLocal(cell, i, phi_uk_man, 0, 0);
107,616✔
1277

1278
        double nodal_power = 0.0;
1279
        for (unsigned int g = 0; g < num_groups_; ++g)
860,928✔
1280
        {
1281
          const double sigma_fg = xs->GetSigmaFission()[g];
753,312✔
1282
          // const double kappa_g = xs->Kappa()[g];
1283
          const double kappa_g = options_.power_default_kappa;
753,312✔
1284

1285
          nodal_power += kappa_g * sigma_fg * phi_new_local_[imapB + g];
753,312✔
1286
        } // for g
1287

1288
        data_vector_power_local[imapA] = nodal_power;
107,616✔
1289
        local_total_power += nodal_power * Vi(i);
107,616✔
1290
      } // for node
1291
    } // for cell
1292

1293
    double scale_factor = 1.0;
4✔
1294
    if (options_.power_normalization > 0.0)
4✔
1295
    {
1296
      double global_total_power = 0.0;
4✔
1297
      mpi_comm.all_reduce(local_total_power, global_total_power, mpi::op::sum<double>());
4✔
1298
      scale_factor = options_.power_normalization / global_total_power;
4✔
1299
      Scale(data_vector_power_local, scale_factor);
4✔
1300
    }
1301

1302
    const size_t ff_index = power_gen_fieldfunc_local_handle_;
4✔
1303

1304
    auto& ff_ptr = field_functions_.at(ff_index);
4✔
1305
    ff_ptr->UpdateFieldVector(data_vector_power_local);
4✔
1306

1307
    // scale scalar flux if neccessary
1308
    if (scale_factor != 1.0)
4✔
1309
    {
1310
      for (unsigned int g = 0; g < num_groups_; ++g)
32✔
1311
      {
1312
        const size_t phi_ff_index = phi_field_functions_local_map_.at({g, size_t{0}});
28✔
1313
        auto& phi_ff_ptr = field_functions_.at(phi_ff_index);
28✔
1314
        const auto& phi_vec = phi_ff_ptr->GetLocalFieldVector();
28✔
1315
        std::vector<double> phi_scaled(phi_vec.begin(), phi_vec.end());
28✔
1316
        Scale(phi_scaled, scale_factor);
28✔
1317
        phi_ff_ptr->UpdateFieldVector(phi_scaled);
28✔
1318
      }
28✔
1319
    }
1320
  } // if power enabled
4✔
1321
}
2,744✔
1322

1323
void
1324
LBSProblem::SetPhiFromFieldFunctions(PhiSTLOption which_phi,
×
1325
                                     const std::vector<unsigned int>& m_indices,
1326
                                     const std::vector<unsigned int>& g_indices)
1327
{
1328
  CALI_CXX_MARK_SCOPE("LBSProblem::SetPhiFromFieldFunctions");
×
1329

1330
  std::vector<unsigned int> m_ids_to_copy = m_indices;
×
1331
  std::vector<unsigned int> g_ids_to_copy = g_indices;
×
1332
  if (m_indices.empty())
×
1333
    for (unsigned int m = 0; m < num_moments_; ++m)
×
1334
      m_ids_to_copy.push_back(m);
×
1335
  if (g_ids_to_copy.empty())
×
1336
    for (unsigned int g = 0; g < num_groups_; ++g)
×
1337
      g_ids_to_copy.push_back(g);
×
1338

1339
  const auto& sdm = *discretization_;
×
1340
  const auto& phi_uk_man = flux_moments_uk_man_;
×
1341

1342
  for (const auto m : m_ids_to_copy)
×
1343
  {
1344
    for (const auto g : g_ids_to_copy)
×
1345
    {
1346
      const size_t ff_index = phi_field_functions_local_map_.at({g, m});
×
1347
      const auto& ff_ptr = field_functions_.at(ff_index);
×
1348
      const auto& ff_data = ff_ptr->GetLocalFieldVector();
×
1349

1350
      for (const auto& cell : grid_->local_cells)
×
1351
      {
1352
        const auto& cell_mapping = sdm.GetCellMapping(cell);
×
1353
        const size_t num_nodes = cell_mapping.GetNumNodes();
×
1354

1355
        for (size_t i = 0; i < num_nodes; ++i)
×
1356
        {
1357
          const auto imapA = sdm.MapDOFLocal(cell, i);
×
1358
          const auto imapB = sdm.MapDOFLocal(cell, i, phi_uk_man, m, g);
×
1359

1360
          if (which_phi == PhiSTLOption::PHI_OLD)
×
1361
            phi_old_local_[imapB] = ff_data[imapA];
×
1362
          else if (which_phi == PhiSTLOption::PHI_NEW)
×
1363
            phi_new_local_[imapB] = ff_data[imapA];
×
1364
        } // for node
1365
      } // for cell
1366
    } // for g
1367
  } // for m
1368
}
×
1369

1370
LBSProblem::~LBSProblem()
560✔
1371
{
1372
  ResetGPUCarriers();
1373
}
2,800✔
1374

560✔
1375
void
1376
LBSProblem::SetAdjoint(bool adjoint)
584✔
1377
{
1378
  if (adjoint != options_.adjoint)
584✔
1379
  {
1380
    options_.adjoint = adjoint;
12✔
1381

1382
    // If a discretization exists, the solver has already been initialized.
1383
    // Reinitialize the materials to obtain the appropriate xs and clear the
1384
    // sources to prepare for defining the adjoint problem
1385
    if (discretization_)
12✔
1386
    {
1387
      // The materials are reinitialized here to ensure that the proper cross sections
1388
      // are available to the solver. Because an adjoint solve requires volumetric or
1389
      // point sources, the material-based sources are not set within the initialize routine.
1390
      InitializeMaterials();
12✔
1391

1392
      // Forward and adjoint sources are fundamentally different, so any existing sources
1393
      // should be cleared and reset through options upon changing modes.
1394
      point_sources_.clear();
12✔
1395
      volumetric_sources_.clear();
12✔
1396
      ClearBoundaries();
12✔
1397

1398
      // Set all solutions to zero.
1399
      phi_old_local_.assign(phi_old_local_.size(), 0.0);
12✔
1400
      phi_new_local_.assign(phi_new_local_.size(), 0.0);
12✔
1401
      ZeroSolutions();
12✔
1402
      precursor_new_local_.assign(precursor_new_local_.size(), 0.0);
12✔
1403
    }
1404
  }
1405
}
584✔
1406

1407
} // 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