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

Open-Sn / opensn / 19186950716

07 Nov 2025 05:04PM UTC coverage: 74.021% (-0.004%) from 74.025%
19186950716

push

github

web-flow
Merge pull request #826 from andrsd/issue/820

Report user-friendly error message when boundary name is mispelled

3 of 5 new or added lines in 1 file covered. (60.0%)

1 existing line in 1 file now uncovered.

18358 of 24801 relevant lines covered (74.02%)

53664183.15 hits per line

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

82.51
/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 "caliper/cali.h"
18
#include <algorithm>
19
#include <iomanip>
20
#include <fstream>
21
#include <cstring>
22
#include <cassert>
23
#include <memory>
24
#include <stdexcept>
25
#include <sys/stat.h>
26

27
namespace opensn
28
{
29

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

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

40
  params.ChangeExistingParamToOptional("name", "LBSProblem");
620✔
41

42
  params.AddRequiredParameter<std::shared_ptr<MeshContinuum>>("mesh", "Mesh");
620✔
43

44
  params.AddRequiredParameter<size_t>("num_groups", "The total number of groups within the solver");
620✔
45

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

51
  params.AddRequiredParameterArray("xs_map",
620✔
52
                                   "Cross-section map from block IDs to cross-section objects.");
53

54
  params.AddOptionalParameterArray<std::shared_ptr<VolumetricSource>>(
620✔
55
    "volumetric_sources", {}, "An array of handles to volumetric sources.");
56

57
  params.AddOptionalParameterArray<std::shared_ptr<PointSource>>(
620✔
58
    "point_sources", {}, "An array of point sources.");
59

60
  params.AddOptionalParameterArray(
620✔
61
    "boundary_conditions", {}, "An array containing tables for each boundary specification.");
62
  params.LinkParameterToBlock("boundary_conditions", "BoundaryOptionsBlock");
620✔
63

64
  params.AddOptionalParameterBlock(
620✔
65
    "options", ParameterBlock(), "Block of options. See <TT>OptionsBlock</TT>.");
620✔
66
  params.LinkParameterToBlock("options", "OptionsBlock");
620✔
67

68
  params.AddOptionalParameter("use_gpus", false, "Offload the sweep computation to GPUs.");
620✔
69

70
  return params;
310✔
71
}
×
72

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

90
  // Initialize options
91
  if (params.IsParameterValid("options"))
310✔
92
  {
93
    auto options_params = LBSProblem::GetOptionsBlock();
174✔
94
    options_params.AssignParameters(params.GetParam("options"));
176✔
95
    SetOptions(options_params);
172✔
96
  }
174✔
97

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

103
  // Set boundary conditions
104
  if (params.Has("boundary_conditions"))
308✔
105
  {
106
    const auto& bcs = params.GetParam("boundary_conditions");
308✔
107
    bcs.RequireBlockTypeIs(ParameterBlockType::ARRAY);
308✔
108
    for (size_t b = 0; b < bcs.GetNumParameters(); ++b)
834✔
109
    {
110
      auto bndry_params = GetBoundaryOptionsBlock();
526✔
111
      bndry_params.AssignParameters(bcs.GetParam(b));
526✔
112
      SetBoundaryOptions(bndry_params);
526✔
113
    }
526✔
114
  }
115

116
  InitializeGroupsets(params);
308✔
117
  InitializeSources(params);
308✔
118
  InitializeXSmapAndDensities(params);
308✔
119
  InitializeMaterials();
308✔
120
}
328✔
121

122
LBSOptions&
123
LBSProblem::GetOptions()
17,302✔
124
{
125
  return options_;
17,302✔
126
}
127

128
const LBSOptions&
129
LBSProblem::GetOptions() const
473,529,530✔
130
{
131
  return options_;
473,529,530✔
132
}
133

134
GeometryType
135
LBSProblem::GetGeometryType() const
4✔
136
{
137
  return geometry_type_;
4✔
138
}
139

140
size_t
141
LBSProblem::GetNumMoments() const
129,091✔
142
{
143
  return num_moments_;
129,091✔
144
}
145

146
size_t
147
LBSProblem::GetNumGroups() const
53,032✔
148
{
149
  return num_groups_;
53,032✔
150
}
151

152
unsigned int
153
LBSProblem::GetScatteringOrder() const
4✔
154
{
155
  return scattering_order_;
4✔
156
}
157

158
size_t
159
LBSProblem::GetNumPrecursors() const
×
160
{
161
  return num_precursors_;
×
162
}
163

164
size_t
165
LBSProblem::GetMaxPrecursorsPerMaterial() const
8✔
166
{
167
  return max_precursors_per_material_;
8✔
168
}
169

170
const std::vector<LBSGroup>&
171
LBSProblem::GetGroups() const
139,094✔
172
{
173
  return groups_;
139,094✔
174
}
175

176
std::vector<LBSGroupset>&
177
LBSProblem::GetGroupsets()
8,170,827✔
178
{
179
  return groupsets_;
8,170,827✔
180
}
181

182
const std::vector<LBSGroupset>&
183
LBSProblem::GetGroupsets() const
×
184
{
185
  return groupsets_;
×
186
}
187

188
void
189
LBSProblem::AddPointSource(std::shared_ptr<PointSource> point_source)
×
190
{
191
  point_sources_.push_back(point_source);
×
192
  if (discretization_)
×
193
    point_sources_.back()->Initialize(*this);
×
194
}
×
195

196
void
197
LBSProblem::ClearPointSources()
×
198
{
199
  point_sources_.clear();
×
200
}
×
201

202
const std::vector<std::shared_ptr<PointSource>>&
203
LBSProblem::GetPointSources() const
7,444✔
204
{
205
  return point_sources_;
7,444✔
206
}
207

208
void
209
LBSProblem::AddVolumetricSource(std::shared_ptr<VolumetricSource> volumetric_source)
16✔
210
{
211
  volumetric_sources_.push_back(volumetric_source);
16✔
212
  if (discretization_)
16✔
213
    volumetric_sources_.back()->Initialize(*this);
16✔
214
}
16✔
215

216
void
217
LBSProblem::ClearVolumetricSources()
4✔
218
{
219
  volumetric_sources_.clear();
4✔
220
}
4✔
221

222
const std::vector<std::shared_ptr<VolumetricSource>>&
223
LBSProblem::GetVolumetricSources() const
7,444✔
224
{
225
  return volumetric_sources_;
7,444✔
226
}
227

228
void
229
LBSProblem::ClearBoundaries()
×
230
{
231
  boundary_preferences_.clear();
×
232
}
×
233

234
const std::map<int, std::shared_ptr<MultiGroupXS>>&
235
LBSProblem::GetMatID2XSMap() const
6,681✔
236
{
237
  return block_id_to_xs_map_;
6,681✔
238
}
239

240
std::shared_ptr<MeshContinuum>
241
LBSProblem::GetGrid() const
181,126✔
242
{
243
  return grid_;
181,126✔
244
}
245

246
const SpatialDiscretization&
247
LBSProblem::GetSpatialDiscretization() const
64,136✔
248
{
249
  return *discretization_;
64,136✔
250
}
251

252
const std::vector<UnitCellMatrices>&
253
LBSProblem::GetUnitCellMatrices() const
7,283✔
254
{
255
  return unit_cell_matrices_;
7,283✔
256
}
257

258
const std::map<uint64_t, UnitCellMatrices>&
259
LBSProblem::GetUnitGhostCellMatrices() const
17✔
260
{
261
  return unit_ghost_cell_matrices_;
17✔
262
}
263

264
const std::vector<CellLBSView>&
265
LBSProblem::GetCellTransportViews() const
190,651✔
266
{
267
  return cell_transport_views_;
190,651✔
268
}
269

270
const UnknownManager&
271
LBSProblem::GetUnknownManager() const
26,695✔
272
{
273
  return flux_moments_uk_man_;
26,695✔
274
}
275

276
size_t
277
LBSProblem::GetLocalNodeCount() const
3,064✔
278
{
279
  return local_node_count_;
3,064✔
280
}
281

282
size_t
283
LBSProblem::GetGlobalNodeCount() const
1,516✔
284
{
285
  return global_node_count_;
1,516✔
286
}
287

288
std::vector<double>&
289
LBSProblem::GetQMomentsLocal()
37,589✔
290
{
291
  return q_moments_local_;
37,589✔
292
}
293

294
const std::vector<double>&
295
LBSProblem::GetQMomentsLocal() const
×
296
{
297
  return q_moments_local_;
×
298
}
299

300
std::vector<double>&
301
LBSProblem::GetExtSrcMomentsLocal()
4✔
302
{
303
  return ext_src_moments_local_;
4✔
304
}
305

306
const std::vector<double>&
307
LBSProblem::GetExtSrcMomentsLocal() const
37,231✔
308
{
309
  return ext_src_moments_local_;
37,231✔
310
}
311

312
std::vector<double>&
313
LBSProblem::GetPhiOldLocal()
56,997✔
314
{
315
  return phi_old_local_;
56,997✔
316
}
317

318
const std::vector<double>&
319
LBSProblem::GetPhiOldLocal() const
×
320
{
321
  return phi_old_local_;
×
322
}
323

324
std::vector<double>&
325
LBSProblem::GetPhiNewLocal()
59,482✔
326
{
327
  return phi_new_local_;
59,482✔
328
}
329

330
const std::vector<double>&
331
LBSProblem::GetPhiNewLocal() const
×
332
{
333
  return phi_new_local_;
×
334
}
335

336
std::vector<double>&
337
LBSProblem::GetPrecursorsNewLocal()
16✔
338
{
339
  return precursor_new_local_;
16✔
340
}
341

342
const std::vector<double>&
343
LBSProblem::GetPrecursorsNewLocal() const
×
344
{
345
  return precursor_new_local_;
×
346
}
347

348
std::vector<double>&
349
LBSProblem::GetDensitiesLocal()
250✔
350
{
351
  return densities_local_;
250✔
352
}
353

354
const std::vector<double>&
355
LBSProblem::GetDensitiesLocal() const
37,231✔
356
{
357
  return densities_local_;
37,231✔
358
}
359

360
SetSourceFunction
361
LBSProblem::GetActiveSetSourceFunction() const
4,158✔
362
{
363
  return active_set_source_function_;
4,158✔
364
}
365

366
std::shared_ptr<AGSLinearSolver>
367
LBSProblem::GetAGSSolver()
292✔
368
{
369
  return ags_solver_;
292✔
370
}
371

372
std::vector<std::shared_ptr<LinearSolver>>&
373
LBSProblem::GetWGSSolvers()
113✔
374
{
375
  return wgs_solvers_;
113✔
376
}
377

378
WGSContext&
379
LBSProblem::GetWGSContext(int groupset_id)
11,520✔
380
{
381
  auto& wgs_solver = wgs_solvers_[groupset_id];
11,520✔
382
  auto raw_context = wgs_solver->GetContext();
11,520✔
383
  auto wgs_context_ptr = std::dynamic_pointer_cast<WGSContext>(raw_context);
11,520✔
384
  OpenSnLogicalErrorIf(not wgs_context_ptr, "Failed to cast WGSContext");
11,520✔
385
  return *wgs_context_ptr;
11,520✔
386
}
23,040✔
387

388
std::map<uint64_t, BoundaryPreference>&
389
LBSProblem::GetBoundaryPreferences()
4✔
390
{
391
  return boundary_preferences_;
4✔
392
}
393

394
std::pair<size_t, size_t>
395
LBSProblem::GetNumPhiIterativeUnknowns()
×
396
{
397
  const auto& sdm = *discretization_;
×
398
  const size_t num_local_phi_dofs = sdm.GetNumLocalDOFs(flux_moments_uk_man_);
×
399
  const size_t num_global_phi_dofs = sdm.GetNumGlobalDOFs(flux_moments_uk_man_);
×
400

401
  return {num_local_phi_dofs, num_global_phi_dofs};
×
402
}
403

404
size_t
405
LBSProblem::MapPhiFieldFunction(size_t g, size_t m) const
23,444✔
406
{
407
  OpenSnLogicalErrorIf(phi_field_functions_local_map_.count({g, m}) == 0,
23,444✔
408
                       std::string("Failure to map phi field function g") + std::to_string(g) +
409
                         " m" + std::to_string(m));
410

411
  return phi_field_functions_local_map_.at({g, m});
23,444✔
412
}
413

414
std::shared_ptr<FieldFunctionGridBased>
415
LBSProblem::GetPowerFieldFunction() const
×
416
{
417
  OpenSnLogicalErrorIf(not options_.power_field_function_on,
×
418
                       "Called when options_.power_field_function_on == false");
419

420
  return field_functions_[power_gen_fieldfunc_local_handle_];
×
421
}
422

423
InputParameters
424
LBSProblem::GetOptionsBlock()
370✔
425
{
426
  InputParameters params;
370✔
427

428
  params.SetGeneralDescription("Set options from a large list of parameters");
740✔
429
  params.AddOptionalParameter("max_mpi_message_size",
740✔
430
                              32768,
431
                              "The maximum MPI message size used during sweep initialization.");
432
  params.AddOptionalParameter(
740✔
433
    "restart_writes_enabled", false, "Flag that controls writing of restart dumps");
434
  params.AddOptionalParameter("write_delayed_psi_to_restart",
740✔
435
                              true,
436
                              "Flag that controls writing of delayed angular fluxes to restarts.");
437
  params.AddOptionalParameter(
740✔
438
    "read_restart_path", "", "Full path for reading restart dumps including file stem.");
439
  params.AddOptionalParameter(
740✔
440
    "write_restart_path", "", "Full path for writing restart dumps including file stem.");
441
  params.AddOptionalParameter("write_restart_time_interval",
740✔
442
                              0,
443
                              "Time interval in seconds at which restart data is to be written.");
444
  params.AddOptionalParameter(
740✔
445
    "use_precursors", false, "Flag for using delayed neutron precursors.");
446
  params.AddOptionalParameter("use_source_moments",
740✔
447
                              false,
448
                              "Flag for ignoring fixed sources and selectively using source "
449
                              "moments obtained elsewhere.");
450
  params.AddOptionalParameter(
740✔
451
    "save_angular_flux", false, "Flag indicating whether angular fluxes are to be stored or not.");
452
  params.AddOptionalParameter(
740✔
453
    "adjoint", false, "Flag for toggling whether the solver is in adjoint mode.");
454
  params.AddOptionalParameter(
740✔
455
    "verbose_inner_iterations", true, "Flag to control verbosity of inner iterations.");
456
  params.AddOptionalParameter(
740✔
457
    "verbose_outer_iterations", true, "Flag to control verbosity of across-groupset iterations.");
458
  params.AddOptionalParameter(
740✔
459
    "max_ags_iterations", 100, "Maximum number of across-groupset iterations.");
460
  params.AddOptionalParameter("ags_tolerance", 1.0e-6, "Across-groupset iterations tolerance.");
740✔
461
  params.AddOptionalParameter("ags_convergence_check",
740✔
462
                              "l2",
463
                              "Type of convergence check for AGS iterations. Valid values are "
464
                              "`\"l2\"` and '\"pointwise\"'");
465
  params.AddOptionalParameter(
740✔
466
    "verbose_ags_iterations", true, "Flag to control verbosity of across-groupset iterations.");
467
  params.AddOptionalParameter("power_field_function_on",
740✔
468
                              false,
469
                              "Flag to control the creation of the power generation field "
470
                              "function. If set to `true` then a field function will be created "
471
                              "with the general name <solver_name>_power_generation`.");
472
  params.AddOptionalParameter("power_default_kappa",
740✔
473
                              3.20435e-11,
474
                              "Default `kappa` value (Energy released per fission) to use for "
475
                              "power generation when cross sections do not have `kappa` values. "
476
                              "Default: 3.20435e-11 Joule (corresponding to 200 MeV per fission).");
477
  params.AddOptionalParameter("power_normalization",
740✔
478
                              -1.0,
479
                              "Power normalization factor to use. Supply a negative or zero number "
480
                              "to turn this off.");
481
  params.AddOptionalParameter("field_function_prefix_option",
740✔
482
                              "prefix",
483
                              "Prefix option on field function names. Default: `\"prefix\"`. Can "
484
                              "be `\"prefix\"` or `\"solver_name\"`. By default this option uses "
485
                              "the value of the `field_function_prefix` parameter. If this "
486
                              "parameter is not set, flux field functions will be exported as "
487
                              "`phi_gXXX_mYYY` where `XXX` is the zero padded 3 digit group number "
488
                              "and `YYY` is the zero padded 3 digit moment.");
489
  params.AddOptionalParameter("field_function_prefix",
740✔
490
                              "",
491
                              "Prefix to use on all field functions. Default: `\"\"`. By default "
492
                              "this option is empty. Ff specified, flux moments will be exported "
493
                              "as `prefix_phi_gXXX_mYYY` where `XXX` is the zero padded 3 digit "
494
                              "group number and `YYY` is the zero padded 3 digit moment. The "
495
                              "underscore after \"prefix\" is added automatically.");
496
  params.ConstrainParameterRange("ags_convergence_check",
1,110✔
497
                                 AllowableRangeList::New({"l2", "pointwise"}));
370✔
498
  params.ConstrainParameterRange("field_function_prefix_option",
1,110✔
499
                                 AllowableRangeList::New({"prefix", "solver_name"}));
370✔
500

501
  return params;
370✔
502
}
×
503

504
InputParameters
505
LBSProblem::GetBoundaryOptionsBlock()
526✔
506
{
507
  InputParameters params;
526✔
508

509
  params.SetGeneralDescription("Set options for boundary conditions.");
1,052✔
510
  params.AddRequiredParameter<std::string>("name",
1,052✔
511
                                           "Boundary name that identifies the specific boundary");
512
  params.AddRequiredParameter<std::string>("type", "Boundary type specification.");
1,052✔
513
  params.AddOptionalParameterArray<double>("group_strength",
1,052✔
514
                                           {},
515
                                           "Required only if \"type\" is \"isotropic\". An array "
516
                                           "of isotropic strength per group");
517
  params.AddOptionalParameter(
1,052✔
518
    "function_name", "", "Text name of the function to be called for this boundary condition.");
519
  params.ConstrainParameterRange("type",
1,578✔
520
                                 AllowableRangeList::New({"vacuum", "isotropic", "reflecting"}));
526✔
521

522
  return params;
526✔
523
}
×
524

525
InputParameters
526
LBSProblem::GetXSMapEntryBlock()
557✔
527
{
528
  InputParameters params;
557✔
529
  params.SetGeneralDescription("Set the cross-section map for the solver.");
1,114✔
530
  params.AddRequiredParameterArray("block_ids", "Mesh block IDs");
1,114✔
531
  params.AddRequiredParameter<std::shared_ptr<MultiGroupXS>>("xs", "Cross-section object");
1,114✔
532
  return params;
557✔
533
}
×
534

535
void
536
LBSProblem::SetOptions(const InputParameters& input)
184✔
537
{
538
  auto params = LBSProblem::GetOptionsBlock();
184✔
539
  params.AssignParameters(input);
184✔
540

541
  // Handle order insensitive options
542
  for (size_t p = 0; p < params.GetNumParameters(); ++p)
4,048✔
543
  {
544
    const auto& spec = params.GetParam(p);
3,864✔
545

546
    if (spec.GetName() == "max_mpi_message_size")
3,864✔
547
      options_.max_mpi_message_size = spec.GetValue<int>();
184✔
548

549
    else if (spec.GetName() == "restart_writes_enabled")
3,680✔
550
      options_.restart_writes_enabled = spec.GetValue<bool>();
184✔
551

552
    else if (spec.GetName() == "write_delayed_psi_to_restart")
3,496✔
553
      options_.write_delayed_psi_to_restart = spec.GetValue<bool>();
184✔
554

555
    else if (spec.GetName() == "read_restart_path")
3,312✔
556
    {
557
      options_.read_restart_path = spec.GetValue<std::string>();
184✔
558
      if (not options_.read_restart_path.empty())
184✔
559
        options_.read_restart_path += std::to_string(opensn::mpi_comm.rank()) + ".restart.h5";
36✔
560
    }
561

562
    else if (spec.GetName() == "write_restart_path")
3,128✔
563
    {
564
      options_.write_restart_path = spec.GetValue<std::string>();
184✔
565
      if (not options_.write_restart_path.empty())
184✔
566
        options_.write_restart_path += std::to_string(opensn::mpi_comm.rank()) + ".restart.h5";
×
567
    }
568

569
    else if (spec.GetName() == "write_restart_time_interval")
2,944✔
570
      options_.write_restart_time_interval = std::chrono::seconds(spec.GetValue<int>());
184✔
571

572
    else if (spec.GetName() == "use_precursors")
2,760✔
573
      options_.use_precursors = spec.GetValue<bool>();
184✔
574

575
    else if (spec.GetName() == "use_source_moments")
2,576✔
576
      options_.use_src_moments = spec.GetValue<bool>();
184✔
577

578
    else if (spec.GetName() == "save_angular_flux")
2,392✔
579
      options_.save_angular_flux = spec.GetValue<bool>();
184✔
580

581
    else if (spec.GetName() == "verbose_inner_iterations")
2,208✔
582
      options_.verbose_inner_iterations = spec.GetValue<bool>();
184✔
583

584
    else if (spec.GetName() == "max_ags_iterations")
2,024✔
585
      options_.max_ags_iterations = spec.GetValue<int>();
184✔
586

587
    else if (spec.GetName() == "ags_tolerance")
1,840✔
588
      options_.ags_tolerance = spec.GetValue<double>();
184✔
589

590
    else if (spec.GetName() == "ags_convergence_check")
1,656✔
591
    {
592
      auto check = spec.GetValue<std::string>();
184✔
593
      if (check == "pointwise")
184✔
594
        options_.ags_pointwise_convergence = true;
×
595
    }
184✔
596

597
    else if (spec.GetName() == "verbose_ags_iterations")
1,472✔
598
      options_.verbose_ags_iterations = spec.GetValue<bool>();
184✔
599

600
    else if (spec.GetName() == "verbose_outer_iterations")
1,288✔
601
      options_.verbose_outer_iterations = spec.GetValue<bool>();
184✔
602

603
    else if (spec.GetName() == "power_field_function_on")
1,104✔
604
      options_.power_field_function_on = spec.GetValue<bool>();
184✔
605

606
    else if (spec.GetName() == "power_default_kappa")
920✔
607
      options_.power_default_kappa = spec.GetValue<double>();
184✔
608

609
    else if (spec.GetName() == "power_normalization")
736✔
610
      options_.power_normalization = spec.GetValue<double>();
184✔
611

612
    else if (spec.GetName() == "field_function_prefix_option")
552✔
613
    {
614
      options_.field_function_prefix_option = spec.GetValue<std::string>();
184✔
615
    }
616

617
    else if (spec.GetName() == "field_function_prefix")
368✔
618
      options_.field_function_prefix = spec.GetValue<std::string>();
184✔
619
  } // for p
620

621
  if (options_.restart_writes_enabled)
184✔
622
  {
623
    // Create restart directory if necessary
624
    auto dir = options_.write_restart_path.parent_path();
×
625
    if (opensn::mpi_comm.rank() == 0)
×
626
    {
627
      if (not std::filesystem::exists(dir))
×
628
      {
629
        if (not std::filesystem::create_directories(dir))
×
630
          throw std::runtime_error(GetName() + ": Failed to create restart directory " +
×
631
                                   dir.string());
×
632
      }
633
      else if (not std::filesystem::is_directory(dir))
×
634
        throw std::runtime_error(GetName() + ": Restart path exists but is not a directory " +
×
635
                                 dir.string());
×
636
    }
637
    opensn::mpi_comm.barrier();
×
638
    UpdateRestartWriteTime();
×
639
  }
×
640
}
184✔
641

642
void
643
LBSProblem::SetBoundaryOptions(const InputParameters& params)
526✔
644
{
645
  const auto boundary_name = params.GetParamValue<std::string>("name");
526✔
646
  const auto bndry_type = params.GetParamValue<std::string>("type");
526✔
647

648
  auto grid = GetGrid();
526✔
649
  const auto bnd_map = grid->GetBoundaryIDMap();
526✔
650
  const auto bnd_name_map = grid->GetBoundaryNameMap();
526✔
651
  auto it = bnd_name_map.find(boundary_name);
526✔
652
  if (it == bnd_name_map.end())
526✔
NEW
653
    throw std::runtime_error(std::format("Could not find the specified boundary '{}' - please "
×
654
                                         "check that the 'name' parameter is spelled correctly.",
NEW
655
                                         boundary_name));
×
656
  const auto bid = it->second;
526✔
657
  const std::map<std::string, LBSBoundaryType> type_list = {
526✔
658
    {"vacuum", LBSBoundaryType::VACUUM},
526✔
659
    {"isotropic", LBSBoundaryType::ISOTROPIC},
526✔
660
    {"reflecting", LBSBoundaryType::REFLECTING}};
2,104✔
661

662
  const auto type = type_list.at(bndry_type);
526✔
663
  switch (type)
526✔
664
  {
665
    case LBSBoundaryType::VACUUM:
430✔
666
    case LBSBoundaryType::REFLECTING:
430✔
667
    {
430✔
668
      boundary_preferences_[bid] = {type};
430✔
669
      break;
430✔
670
    }
671
    case LBSBoundaryType::ISOTROPIC:
96✔
672
    {
96✔
673
      OpenSnInvalidArgumentIf(not params.Has("group_strength"),
96✔
674
                              "Boundary conditions with type=\"isotropic\" require parameter "
675
                              "\"group_strength\"");
676

677
      params.RequireParameterBlockTypeIs("group_strength", ParameterBlockType::ARRAY);
96✔
678
      const auto group_strength = params.GetParamVectorValue<double>("group_strength");
96✔
679
      boundary_preferences_[bid] = {type, group_strength};
96✔
680
      break;
96✔
681
    }
96✔
682
    case LBSBoundaryType::ARBITRARY:
×
683
    {
×
684
      throw std::runtime_error(GetName() +
×
685
                               ": Arbitrary boundary conditions are not currently supported");
×
686
      break;
526✔
687
    }
688
  }
689
}
2,104✔
690

691
void
692
LBSProblem::Initialize()
308✔
693
{
694
  CALI_CXX_MARK_SCOPE("LBSProblem::Initialize");
308✔
695

696
  PrintSimHeader();
308✔
697
  mpi_comm.barrier();
308✔
698

699
  InitializeSpatialDiscretization();
308✔
700
  InitializeParrays();
308✔
701
  InitializeBoundaries();
308✔
702
  InitializeGPUExtras();
308✔
703
  SetAdjoint(false);
308✔
704

705
  // Initialize point sources
706
  for (auto& point_source : point_sources_)
317✔
707
    point_source->Initialize(*this);
9✔
708

709
  // Initialize volumetric sources
710
  for (auto& volumetric_source : volumetric_sources_)
635✔
711
    volumetric_source->Initialize(*this);
327✔
712
}
308✔
713

714
void
715
LBSProblem::PrintSimHeader()
×
716
{
717
  if (opensn::mpi_comm.rank() == 0)
×
718
  {
719
    std::stringstream outstr;
×
720
    outstr << "\n"
×
721
           << "Initializing " << GetName() << "\n\n"
×
722
           << "Scattering order    : " << scattering_order_ << "\n"
×
723
           << "Number of moments   : " << num_moments_ << "\n"
×
724
           << "Number of groups    : " << groups_.size() << "\n"
×
725
           << "Number of groupsets : " << groupsets_.size() << "\n\n";
×
726

727
    for (const auto& groupset : groupsets_)
×
728
    {
729
      outstr << "***** Groupset " << groupset.id << " *****\n"
×
730
             << "Groups:\n";
×
731
      const auto& groups = groupset.groups;
732
      constexpr int groups_per_line = 12;
733
      for (size_t i = 0; i < groups.size(); ++i)
×
734
      {
735
        outstr << std::setw(5) << groups[i].id << ' ';
×
736
        if ((i + 1) % groups_per_line == 0)
×
737
          outstr << '\n';
×
738
      }
739
      if (!groups.empty() && groups.size() % groups_per_line != 0)
×
740
        outstr << '\n';
×
741
    }
742

743
    log.Log() << outstr.str() << '\n';
×
744
  }
×
745
}
×
746

747
void
748
LBSProblem::InitializeSources(const InputParameters& params)
308✔
749
{
750
  if (params.Has("volumetric_sources"))
308✔
751
  {
752
    const auto& vol_srcs = params.GetParam("volumetric_sources");
308✔
753
    vol_srcs.RequireBlockTypeIs(ParameterBlockType::ARRAY);
308✔
754
    for (const auto& src : vol_srcs)
635✔
755
      volumetric_sources_.push_back(src.GetValue<std::shared_ptr<VolumetricSource>>());
654✔
756
  }
757

758
  if (params.Has("point_sources"))
308✔
759
  {
760
    const auto& pt_srcs = params.GetParam("point_sources");
308✔
761
    pt_srcs.RequireBlockTypeIs(ParameterBlockType::ARRAY);
308✔
762
    for (const auto& src : pt_srcs)
317✔
763
      point_sources_.push_back(src.GetValue<std::shared_ptr<PointSource>>());
18✔
764
  }
765
}
308✔
766

767
void
768
LBSProblem::InitializeGroupsets(const InputParameters& params)
308✔
769
{
770
  // Initialize groups
771
  if (num_groups_ == 0)
308✔
772
    throw std::invalid_argument(GetName() + ": Number of groups must be > 0");
×
773
  for (size_t g = 0; g < num_groups_; ++g)
20,653✔
774
    groups_.emplace_back(static_cast<int>(g));
20,345✔
775

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

797
void
798
LBSProblem::InitializeXSmapAndDensities(const InputParameters& params)
308✔
799
{
800
  // Build XS map
801
  const auto& xs_array = params.GetParam("xs_map");
308✔
802
  const size_t num_xs = xs_array.GetNumParameters();
308✔
803
  for (size_t i = 0; i < num_xs; ++i)
865✔
804
  {
805
    const auto& item_params = xs_array.GetParam(i);
557✔
806
    InputParameters xs_entry_pars = GetXSMapEntryBlock();
557✔
807
    xs_entry_pars.AssignParameters(item_params);
557✔
808

809
    const auto& block_ids_param = xs_entry_pars.GetParam("block_ids");
557✔
810
    block_ids_param.RequireBlockTypeIs(ParameterBlockType::ARRAY);
557✔
811
    const auto& block_ids = block_ids_param.GetVectorValue<int>();
557✔
812
    auto xs = xs_entry_pars.GetSharedPtrParam<MultiGroupXS>("xs");
557✔
813
    for (const auto& block_id : block_ids)
1,210✔
814
      block_id_to_xs_map_[block_id] = xs;
653✔
815
  }
557✔
816

817
  // Assign placeholder unit densities
818
  densities_local_.assign(grid_->local_cells.size(), 1.0);
308✔
819
}
308✔
820

821
void
822
LBSProblem::InitializeMaterials()
320✔
823
{
824
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeMaterials");
320✔
825

826
  log.Log0Verbose1() << "Initializing Materials";
640✔
827

828
  // Create set of material ids locally relevant
829
  int invalid_mat_cell_count = 0;
320✔
830
  std::set<int> unique_block_ids;
320✔
831
  for (auto& cell : grid_->local_cells)
330,604✔
832
  {
833
    unique_block_ids.insert(cell.block_id);
330,284✔
834
    if (cell.block_id < 0 or (block_id_to_xs_map_.find(cell.block_id) == block_id_to_xs_map_.end()))
330,284✔
835
      ++invalid_mat_cell_count;
×
836
  }
837
  const auto& ghost_cell_ids = grid_->cells.GetGhostGlobalIDs();
320✔
838
  for (uint64_t cell_id : ghost_cell_ids)
48,159✔
839
  {
840
    const auto& cell = grid_->cells[cell_id];
47,839✔
841
    unique_block_ids.insert(cell.block_id);
47,839✔
842
    if (cell.block_id < 0 or (block_id_to_xs_map_.find(cell.block_id) == block_id_to_xs_map_.end()))
47,839✔
843
      ++invalid_mat_cell_count;
×
844
  }
845
  OpenSnLogicalErrorIf(invalid_mat_cell_count > 0,
320✔
846
                       std::to_string(invalid_mat_cell_count) +
847
                         " cells encountered with an invalid material id.");
848

849
  // Get ready for processing
850
  for (const auto& [blk_id, mat] : block_id_to_xs_map_)
1,001✔
851
  {
852
    mat->SetAdjointMode(options_.adjoint);
681✔
853

854
    OpenSnLogicalErrorIf(mat->GetNumGroups() < groups_.size(),
681✔
855
                         "Cross-sections for block \"" + std::to_string(blk_id) +
856
                           "\" have fewer groups (" + std::to_string(mat->GetNumGroups()) +
857
                           ") than the simulation (" + std::to_string(groups_.size()) + "). " +
858
                           "Cross-sections must have at least as many groups as the simulation.");
859
  }
860

861
  // Initialize precursor properties
862
  num_precursors_ = 0;
320✔
863
  max_precursors_per_material_ = 0;
320✔
864
  for (const auto& mat_id_xs : block_id_to_xs_map_)
1,001✔
865
  {
866
    const auto& xs = mat_id_xs.second;
681✔
867
    num_precursors_ += xs->GetNumPrecursors();
681✔
868
    if (xs->GetNumPrecursors() > max_precursors_per_material_)
681✔
869
      max_precursors_per_material_ = xs->GetNumPrecursors();
8✔
870
  }
871

872
  // if no precursors, turn off precursors
873
  if (num_precursors_ == 0)
320✔
874
    options_.use_precursors = false;
312✔
875

876
  // check compatibility when precursors are on
877
  if (options_.use_precursors)
320✔
878
  {
879
    for (const auto& [mat_id, xs] : block_id_to_xs_map_)
16✔
880
    {
881
      OpenSnLogicalErrorIf(xs->IsFissionable() and num_precursors_ == 0,
8✔
882
                           "Incompatible cross-section data encountered for material id " +
883
                             std::to_string(mat_id) + ". When delayed neutron data is present " +
884
                             "for one fissionable matrial, it must be present for all fissionable "
885
                             "materials.");
886
    }
887
  }
888

889
  // Update transport views if available
890
  if (grid_->local_cells.size() == cell_transport_views_.size())
320✔
891
    for (const auto& cell : grid_->local_cells)
10,812✔
892
    {
893
      const auto& xs_ptr = block_id_to_xs_map_[cell.block_id];
10,800✔
894
      auto& transport_view = cell_transport_views_[cell.local_id];
10,800✔
895
      transport_view.ReassignXS(*xs_ptr);
10,800✔
896
    }
897

898
  mpi_comm.barrier();
320✔
899
}
320✔
900

901
void
902
LBSProblem::InitializeSpatialDiscretization()
300✔
903
{
904
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeSpatialDiscretization");
300✔
905

906
  log.Log() << "Initializing spatial discretization.\n";
600✔
907
  discretization_ = PieceWiseLinearDiscontinuous::New(grid_);
300✔
908

909
  ComputeUnitIntegrals();
300✔
910
}
300✔
911

912
void
913
LBSProblem::ComputeUnitIntegrals()
308✔
914
{
915
  CALI_CXX_MARK_SCOPE("LBSProblem::ComputeUnitIntegrals");
308✔
916

917
  log.Log() << "Computing unit integrals.\n";
616✔
918
  const auto& sdm = *discretization_;
308✔
919

920
  const size_t num_local_cells = grid_->local_cells.size();
308✔
921
  unit_cell_matrices_.resize(num_local_cells);
308✔
922

923
  for (const auto& cell : grid_->local_cells)
319,792✔
924
    unit_cell_matrices_[cell.local_id] =
319,484✔
925
      ComputeUnitCellIntegrals(sdm, cell, grid_->GetCoordinateSystem());
319,484✔
926

927
  const auto ghost_ids = grid_->cells.GetGhostGlobalIDs();
308✔
928
  for (auto ghost_id : ghost_ids)
47,391✔
929
    unit_ghost_cell_matrices_[ghost_id] =
47,083✔
930
      ComputeUnitCellIntegrals(sdm, grid_->cells[ghost_id], grid_->GetCoordinateSystem());
94,166✔
931

932
  // Assessing global unit cell matrix storage
933
  std::array<size_t, 2> num_local_ucms = {unit_cell_matrices_.size(),
308✔
934
                                          unit_ghost_cell_matrices_.size()};
308✔
935
  std::array<size_t, 2> num_global_ucms = {0, 0};
308✔
936

937
  mpi_comm.all_reduce(num_local_ucms.data(), 2, num_global_ucms.data(), mpi::op::sum<size_t>());
308✔
938

939
  opensn::mpi_comm.barrier();
308✔
940
  log.Log() << "Ghost cell unit cell-matrix ratio: "
308✔
941
            << (double)num_global_ucms[1] * 100 / (double)num_global_ucms[0] << "%";
616✔
942
  log.Log() << "Cell matrices computed.";
616✔
943
}
308✔
944

945
void
946
LBSProblem::InitializeParrays()
308✔
947
{
948
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeParrays");
308✔
949

950
  log.Log() << "Initializing parallel arrays."
616✔
951
            << " G=" << num_groups_ << " M=" << num_moments_ << std::endl;
308✔
952

953
  // Initialize unknown
954
  // structure
955
  flux_moments_uk_man_.unknowns.clear();
308✔
956
  for (size_t m = 0; m < num_moments_; ++m)
1,170✔
957
  {
958
    flux_moments_uk_man_.AddUnknown(UnknownType::VECTOR_N, groups_.size());
862✔
959
    flux_moments_uk_man_.unknowns.back().name = "m" + std::to_string(m);
862✔
960
  }
961

962
  // Compute local # of dof
963
  local_node_count_ = discretization_->GetNumLocalNodes();
308✔
964
  global_node_count_ = discretization_->GetNumGlobalNodes();
308✔
965

966
  // Compute num of unknowns
967
  size_t num_grps = groups_.size();
308✔
968
  size_t local_unknown_count = local_node_count_ * num_grps * num_moments_;
308✔
969

970
  log.LogAllVerbose1() << "LBS Number of phi unknowns: " << local_unknown_count;
616✔
971

972
  // Size local vectors
973
  q_moments_local_.assign(local_unknown_count, 0.0);
308✔
974
  phi_old_local_.assign(local_unknown_count, 0.0);
308✔
975
  phi_new_local_.assign(local_unknown_count, 0.0);
308✔
976

977
  // Setup precursor vector
978
  if (options_.use_precursors)
308✔
979
  {
980
    size_t num_precursor_dofs = grid_->local_cells.size() * max_precursors_per_material_;
8✔
981
    precursor_new_local_.assign(num_precursor_dofs, 0.0);
8✔
982
  }
983

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

997
  const Vector3 ihat(1.0, 0.0, 0.0);
308✔
998
  const Vector3 jhat(0.0, 1.0, 0.0);
308✔
999
  const Vector3 khat(0.0, 0.0, 1.0);
308✔
1000

1001
  min_cell_dof_count_ = static_cast<size_t>(-1);
308✔
1002
  max_cell_dof_count_ = 0;
308✔
1003
  cell_transport_views_.clear();
308✔
1004
  cell_transport_views_.reserve(grid_->local_cells.size());
308✔
1005
  for (auto& cell : grid_->local_cells)
319,792✔
1006
  {
1007
    size_t num_nodes = discretization_->GetCellNumNodes(cell);
319,484✔
1008

1009
    // compute cell volumes
1010
    double cell_volume = 0.0;
319,484✔
1011
    const auto& IntV_shapeI = unit_cell_matrices_[cell.local_id].intV_shapeI;
319,484✔
1012
    for (size_t i = 0; i < num_nodes; ++i)
2,708,018✔
1013
      cell_volume += IntV_shapeI(i);
2,388,534✔
1014

1015
    size_t cell_phi_address = block_MG_counter;
319,484✔
1016

1017
    const size_t num_faces = cell.faces.size();
319,484✔
1018
    std::vector<bool> face_local_flags(num_faces, true);
319,484✔
1019
    std::vector<int> face_locality(num_faces, opensn::mpi_comm.rank());
319,484✔
1020
    std::vector<const Cell*> neighbor_cell_ptrs(num_faces, nullptr);
319,484✔
1021
    bool cell_on_boundary = false;
319,484✔
1022
    int f = 0;
319,484✔
1023
    for (auto& face : cell.faces)
2,144,202✔
1024
    {
1025
      if (not face.has_neighbor)
1,824,718✔
1026
      {
1027
        cell_on_boundary = true;
60,856✔
1028
        face_local_flags[f] = false;
60,856✔
1029
        face_locality[f] = -1;
60,856✔
1030
      } // if bndry
1031
      else
1032
      {
1033
        const int neighbor_partition = face.GetNeighborPartitionID(grid_.get());
1,763,862✔
1034
        face_local_flags[f] = (neighbor_partition == opensn::mpi_comm.rank());
1,763,862✔
1035
        face_locality[f] = neighbor_partition;
1,763,862✔
1036
        neighbor_cell_ptrs[f] = &grid_->cells[face.neighbor_id];
1,763,862✔
1037
      }
1038

1039
      ++f;
1,824,718✔
1040
    } // for f
1041

1042
    max_cell_dof_count_ = std::max(max_cell_dof_count_, num_nodes);
319,484✔
1043
    min_cell_dof_count_ = std::min(min_cell_dof_count_, num_nodes);
319,484✔
1044
    cell_transport_views_.emplace_back(cell_phi_address,
638,968✔
1045
                                       num_nodes,
1046
                                       num_grps,
1047
                                       num_moments_,
319,484✔
1048
                                       num_faces,
1049
                                       *block_id_to_xs_map_[cell.block_id],
319,484✔
1050
                                       cell_volume,
1051
                                       face_local_flags,
1052
                                       face_locality,
1053
                                       neighbor_cell_ptrs,
1054
                                       cell_on_boundary);
1055
    block_MG_counter += num_nodes * num_grps * num_moments_;
319,484✔
1056
  } // for local cell
319,484✔
1057

1058
  // Populate grid nodal mappings
1059
  // This is used in the Flux Data Structures (FLUDS)
1060
  grid_nodal_mappings_.clear();
308✔
1061
  grid_nodal_mappings_.reserve(grid_->local_cells.size());
308✔
1062
  for (auto& cell : grid_->local_cells)
319,792✔
1063
  {
1064
    CellFaceNodalMapping cell_nodal_mapping;
319,484✔
1065
    cell_nodal_mapping.reserve(cell.faces.size());
319,484✔
1066

1067
    for (auto& face : cell.faces)
2,144,202✔
1068
    {
1069
      std::vector<short> face_node_mapping;
1,824,718✔
1070
      std::vector<short> cell_node_mapping;
1,824,718✔
1071
      int adj_face_idx = -1;
1,824,718✔
1072

1073
      if (face.has_neighbor)
1,824,718✔
1074
      {
1075
        grid_->FindAssociatedVertices(face, face_node_mapping);
1,763,862✔
1076
        grid_->FindAssociatedCellVertices(face, cell_node_mapping);
1,763,862✔
1077
        adj_face_idx = face.GetNeighborAdjacentFaceIndex(grid_.get());
1,763,862✔
1078
      }
1079

1080
      cell_nodal_mapping.emplace_back(adj_face_idx, face_node_mapping, cell_node_mapping);
1,824,718✔
1081
    } // for f
1,824,718✔
1082

1083
    grid_nodal_mappings_.push_back(cell_nodal_mapping);
319,484✔
1084
  } // for local cell
319,484✔
1085

1086
  // Get grid localized communicator set
1087
  grid_local_comm_set_ = grid_->MakeMPILocalCommunicatorSet();
308✔
1088

1089
  // Initialize Field Functions
1090
  InitializeFieldFunctions();
308✔
1091

1092
  opensn::mpi_comm.barrier();
308✔
1093
  log.Log() << "Done with parallel arrays." << std::endl;
616✔
1094
}
308✔
1095

1096
void
1097
LBSProblem::InitializeFieldFunctions()
308✔
1098
{
1099
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeFieldFunctions");
308✔
1100

1101
  if (not field_functions_.empty())
308✔
1102
    return;
×
1103

1104
  // Initialize Field Functions for flux moments
1105
  phi_field_functions_local_map_.clear();
308✔
1106

1107
  for (size_t g = 0; g < groups_.size(); ++g)
20,653✔
1108
  {
1109
    for (size_t m = 0; m < num_moments_; ++m)
94,304✔
1110
    {
1111
      std::string prefix;
73,959✔
1112
      if (options_.field_function_prefix_option == "prefix")
73,959✔
1113
      {
1114
        prefix = options_.field_function_prefix;
73,959✔
1115
        if (not prefix.empty())
73,959✔
1116
          prefix += "_";
1✔
1117
      }
1118
      if (options_.field_function_prefix_option == "solver_name")
73,959✔
1119
        prefix = GetName() + "_";
×
1120

1121
      char buff[100];
73,959✔
1122
      snprintf(
73,959✔
1123
        buff, 99, "%sphi_g%03d_m%02d", prefix.c_str(), static_cast<int>(g), static_cast<int>(m));
1124
      const std::string name = std::string(buff);
73,959✔
1125

1126
      auto group_ff = std::make_shared<FieldFunctionGridBased>(
73,959✔
1127
        name, discretization_, Unknown(UnknownType::SCALAR));
73,959✔
1128

1129
      field_function_stack.push_back(group_ff);
147,918✔
1130
      field_functions_.push_back(group_ff);
73,959✔
1131

1132
      phi_field_functions_local_map_[{g, m}] = field_functions_.size() - 1;
73,959✔
1133
    } // for m
73,959✔
1134
  } // for g
1135

1136
  // Initialize power generation field function
1137
  if (options_.power_field_function_on)
308✔
1138
  {
1139
    std::string prefix;
4✔
1140
    if (options_.field_function_prefix_option == "prefix")
4✔
1141
    {
1142
      prefix = options_.field_function_prefix;
4✔
1143
      if (not prefix.empty())
4✔
1144
        prefix += "_";
×
1145
    }
1146
    if (options_.field_function_prefix_option == "solver_name")
4✔
1147
      prefix = GetName() + "_";
×
1148

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

1152
    field_function_stack.push_back(power_ff);
8✔
1153
    field_functions_.push_back(power_ff);
4✔
1154

1155
    power_gen_fieldfunc_local_handle_ = field_functions_.size() - 1;
4✔
1156
  }
4✔
1157
}
308✔
1158

1159
void
1160
LBSProblem::InitializeSolverSchemes()
308✔
1161
{
1162
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeSolverSchemes");
308✔
1163

1164
  log.Log() << "Initializing WGS and AGS solvers";
616✔
1165

1166
  InitializeWGSSolvers();
308✔
1167

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

1182
#ifndef __OPENSN_USE_CUDA__
1183
void
1184
LBSProblem::InitializeGPUExtras()
308✔
1185
{
1186
}
308✔
1187

1188
void
1189
LBSProblem::ResetGPUCarriers()
304✔
1190
{
1191
}
304✔
1192

1193
void
1194
LBSProblem::CheckCapableDevices()
×
1195
{
1196
}
×
1197
#endif // __OPENSN_USE_CUDA__
1198

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

1204
  size_t num_local_dofs = discretization_->GetNumLocalDOFs(flux_moments_uk_man_);
4✔
1205

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

1216
  return source_moments;
4✔
1217
}
4✔
1218

1219
void
1220
LBSProblem::UpdateFieldFunctions()
320✔
1221
{
1222
  CALI_CXX_MARK_SCOPE("LBSProblem::UpdateFieldFunctions");
320✔
1223

1224
  const auto& sdm = *discretization_;
320✔
1225
  const auto& phi_uk_man = flux_moments_uk_man_;
320✔
1226

1227
  // Update flux moments
1228
  for (const auto& [g_and_m, ff_index] : phi_field_functions_local_map_)
74,327✔
1229
  {
1230
    const size_t g = g_and_m.first;
74,007✔
1231
    const size_t m = g_and_m.second;
74,007✔
1232

1233
    std::vector<double> data_vector_local(local_node_count_, 0.0);
74,007✔
1234

1235
    for (const auto& cell : grid_->local_cells)
18,276,384✔
1236
    {
1237
      const auto& cell_mapping = sdm.GetCellMapping(cell);
18,202,377✔
1238
      const size_t num_nodes = cell_mapping.GetNumNodes();
18,202,377✔
1239

1240
      for (size_t i = 0; i < num_nodes; ++i)
129,366,485✔
1241
      {
1242
        const auto imapA = sdm.MapDOFLocal(cell, i, phi_uk_man, m, g);
111,164,108✔
1243
        const auto imapB = sdm.MapDOFLocal(cell, i);
111,164,108✔
1244

1245
        data_vector_local[imapB] = phi_new_local_[imapA];
111,164,108✔
1246
      } // for node
1247
    } // for cell
1248

1249
    auto& ff_ptr = field_functions_.at(ff_index);
74,007✔
1250
    ff_ptr->UpdateFieldVector(data_vector_local);
74,007✔
1251
  }
74,007✔
1252

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

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

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

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

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

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

1276
        double nodal_power = 0.0;
1277
        for (size_t g = 0; g < groups_.size(); ++g)
860,928✔
1278
        {
1279
          const double sigma_fg = xs->GetSigmaFission()[g];
753,312✔
1280
          // const double kappa_g = xs->Kappa()[g];
1281
          const double kappa_g = options_.power_default_kappa;
753,312✔
1282

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

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

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

1300
    const size_t ff_index = power_gen_fieldfunc_local_handle_;
4✔
1301

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

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

1321
void
1322
LBSProblem::SetPhiFromFieldFunctions(PhiSTLOption which_phi,
×
1323
                                     const std::vector<size_t>& m_indices,
1324
                                     const std::vector<size_t>& g_indices)
1325
{
1326
  CALI_CXX_MARK_SCOPE("LBSProblem::SetPhiFromFieldFunctions");
×
1327

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

1337
  const auto& sdm = *discretization_;
×
1338
  const auto& phi_uk_man = flux_moments_uk_man_;
×
1339

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

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

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

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

1368
LBSProblem::~LBSProblem()
304✔
1369
{
1370
  ResetGPUCarriers();
1371
}
1,520✔
1372

304✔
1373
void
1374
LBSProblem::SetAdjoint(bool adjoint)
320✔
1375
{
1376
  if (adjoint != options_.adjoint)
320✔
1377
  {
1378
    options_.adjoint = adjoint;
12✔
1379

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

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

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

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