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

Open-Sn / opensn / 21538385973

30 Jan 2026 06:38PM UTC coverage: 73.98% (-0.2%) from 74.167%
21538385973

push

github

web-flow
Merge pull request #911 from wdhawkins/solver_mode

Adding ability to switch solver mode between steady state and time dependent

36 of 46 new or added lines in 11 files covered. (78.26%)

48 existing lines in 4 files now uncovered.

18794 of 25404 relevant lines covered (73.98%)

59734997.38 hits per line

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

83.04
/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()
374✔
38
{
39
  InputParameters params = Problem::GetInputParameters();
374✔
40

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

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

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

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

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

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

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

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

65
  params.AddOptionalParameter("use_gpus", false, "Offload the sweep computation to GPUs.");
748✔
66

67
  return params;
374✔
UNCOV
68
}
×
69

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

87
  // Initialize options
88
  if (params.IsParameterValid("options"))
374✔
89
  {
90
    auto options_params = LBSProblem::GetOptionsBlock();
206✔
91
    options_params.AssignParameters(params.GetParam("options"));
208✔
92
    SetOptions(options_params);
204✔
93
  }
206✔
94

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

100
  InitializeGroupsets(params);
372✔
101
  InitializeSources(params);
372✔
102
  InitializeXSmapAndDensities(params);
372✔
103
  InitializeMaterials();
372✔
104
}
392✔
105

106
LBSOptions&
107
LBSProblem::GetOptions()
20,759✔
108
{
109
  return options_;
20,759✔
110
}
111

112
const LBSOptions&
113
LBSProblem::GetOptions() const
598,359,154✔
114
{
115
  return options_;
598,359,154✔
116
}
117

118
double
119
LBSProblem::GetTime() const
118,640✔
120
{
121
  return time_;
118,640✔
122
}
123

124
void
125
LBSProblem::SetTime(double time)
1,660✔
126
{
127
  time_ = time;
1,660✔
128
}
1,660✔
129

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

138
double
139
LBSProblem::GetTimeStep() const
2,065,145,364✔
140
{
141
  return dt_;
2,065,145,364✔
142
}
143

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

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

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

164
size_t
165
LBSProblem::GetNumMoments() const
199,221✔
166
{
167
  return num_moments_;
199,221✔
168
}
169

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

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

182
bool
183
LBSProblem::UseGPUs() const
511✔
184
{
185
  return use_gpus_;
511✔
186
}
187

188
size_t
189
LBSProblem::GetNumGroups() const
78,313✔
190
{
191
  return num_groups_;
78,313✔
192
}
193

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

200
size_t
201
LBSProblem::GetNumPrecursors() const
×
202
{
203
  return num_precursors_;
×
204
}
205

206
size_t
207
LBSProblem::GetMaxPrecursorsPerMaterial() const
8✔
208
{
209
  return max_precursors_per_material_;
8✔
210
}
211

212
const std::vector<LBSGroup>&
213
LBSProblem::GetGroups() const
206,325✔
214
{
215
  return groups_;
206,325✔
216
}
217

218
std::vector<LBSGroupset>&
219
LBSProblem::GetGroupsets()
7,312,263✔
220
{
221
  return groupsets_;
7,312,263✔
222
}
223

224
const std::vector<LBSGroupset>&
225
LBSProblem::GetGroupsets() const
×
226
{
227
  return groupsets_;
×
228
}
229

230
void
231
LBSProblem::AddPointSource(std::shared_ptr<PointSource> point_source)
×
232
{
233
  point_sources_.push_back(point_source);
×
234
  if (discretization_)
×
235
    point_sources_.back()->Initialize(*this);
×
236
}
×
237

238
void
239
LBSProblem::ClearPointSources()
×
240
{
241
  point_sources_.clear();
×
242
}
×
243

244
const std::vector<std::shared_ptr<PointSource>>&
245
LBSProblem::GetPointSources() const
8,664✔
246
{
247
  return point_sources_;
8,664✔
248
}
249

250
void
251
LBSProblem::AddVolumetricSource(std::shared_ptr<VolumetricSource> volumetric_source)
16✔
252
{
253
  volumetric_sources_.push_back(volumetric_source);
16✔
254
  if (discretization_)
16✔
255
    volumetric_sources_.back()->Initialize(*this);
16✔
256
}
16✔
257

258
void
259
LBSProblem::ClearVolumetricSources()
4✔
260
{
261
  volumetric_sources_.clear();
4✔
262
}
4✔
263

264
const std::vector<std::shared_ptr<VolumetricSource>>&
265
LBSProblem::GetVolumetricSources() const
8,664✔
266
{
267
  return volumetric_sources_;
8,664✔
268
}
269

270
const BlockID2XSMap&
271
LBSProblem::GetBlockID2XSMap() const
7,052✔
272
{
273
  return block_id_to_xs_map_;
7,052✔
274
}
275

276
void
277
LBSProblem::SetBlockID2XSMap(const BlockID2XSMap& xs_map)
8✔
278
{
279
  block_id_to_xs_map_ = xs_map;
8✔
280
  InitializeMaterials();
8✔
281
  ResetGPUCarriers();
8✔
282
  InitializeGPUExtras();
8✔
283
}
8✔
284

285
std::shared_ptr<MeshContinuum>
286
LBSProblem::GetGrid() const
270,427✔
287
{
288
  return grid_;
270,427✔
289
}
290

291
const SpatialDiscretization&
292
LBSProblem::GetSpatialDiscretization() const
86,888✔
293
{
294
  return *discretization_;
86,888✔
295
}
296

297
const std::vector<UnitCellMatrices>&
298
LBSProblem::GetUnitCellMatrices() const
7,806✔
299
{
300
  return unit_cell_matrices_;
7,806✔
301
}
302

303
const std::map<uint64_t, UnitCellMatrices>&
304
LBSProblem::GetUnitGhostCellMatrices() const
17✔
305
{
306
  return unit_ghost_cell_matrices_;
17✔
307
}
308

309
std::vector<CellLBSView>&
310
LBSProblem::GetCellTransportViews()
124,362✔
311
{
312
  return cell_transport_views_;
124,362✔
313
}
314

315
const std::vector<CellLBSView>&
316
LBSProblem::GetCellTransportViews() const
177,960✔
317
{
318
  return cell_transport_views_;
177,960✔
319
}
320

321
const UnknownManager&
322
LBSProblem::GetUnknownManager() const
26,931✔
323
{
324
  return flux_moments_uk_man_;
26,931✔
325
}
326

327
size_t
328
LBSProblem::GetLocalNodeCount() const
3,100✔
329
{
330
  return local_node_count_;
3,100✔
331
}
332

333
size_t
334
LBSProblem::GetGlobalNodeCount() const
2,428✔
335
{
336
  return global_node_count_;
2,428✔
337
}
338

339
std::vector<double>&
340
LBSProblem::GetQMomentsLocal()
63,345✔
341
{
342
  return q_moments_local_;
63,345✔
343
}
344

345
const std::vector<double>&
346
LBSProblem::GetQMomentsLocal() const
×
347
{
348
  return q_moments_local_;
×
349
}
350

351
std::vector<double>&
352
LBSProblem::GetExtSrcMomentsLocal()
4✔
353
{
354
  return ext_src_moments_local_;
4✔
355
}
356

357
const std::vector<double>&
358
LBSProblem::GetExtSrcMomentsLocal() const
59,320✔
359
{
360
  return ext_src_moments_local_;
59,320✔
361
}
362

363
std::vector<double>&
364
LBSProblem::GetPhiOldLocal()
101,987✔
365
{
366
  return phi_old_local_;
101,987✔
367
}
368

369
const std::vector<double>&
370
LBSProblem::GetPhiOldLocal() const
×
371
{
372
  return phi_old_local_;
×
373
}
374

375
std::vector<double>&
376
LBSProblem::GetPhiNewLocal()
84,074✔
377
{
378
  return phi_new_local_;
84,074✔
379
}
380

381
const std::vector<double>&
382
LBSProblem::GetPhiNewLocal() const
×
383
{
384
  return phi_new_local_;
×
385
}
386

387
std::vector<double>&
388
LBSProblem::GetPrecursorsNewLocal()
16✔
389
{
390
  return precursor_new_local_;
16✔
391
}
392

393
const std::vector<double>&
394
LBSProblem::GetPrecursorsNewLocal() const
×
395
{
396
  return precursor_new_local_;
×
397
}
398

399
std::vector<double>&
400
LBSProblem::GetDensitiesLocal()
681✔
401
{
402
  return densities_local_;
681✔
403
}
404

405
const std::vector<double>&
406
LBSProblem::GetDensitiesLocal() const
59,320✔
407
{
408
  return densities_local_;
59,320✔
409
}
410

411
SetSourceFunction
412
LBSProblem::GetActiveSetSourceFunction() const
4,158✔
413
{
414
  return active_set_source_function_;
4,158✔
415
}
416

417
std::shared_ptr<AGSLinearSolver>
418
LBSProblem::GetAGSSolver()
356✔
419
{
420
  return ags_solver_;
356✔
421
}
422

423
std::vector<std::shared_ptr<LinearSolver>>&
424
LBSProblem::GetWGSSolvers()
125✔
425
{
426
  return wgs_solvers_;
125✔
427
}
428

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

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

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

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

456
  return phi_field_functions_local_map_.at({g, m});
27,648✔
457
}
458

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

465
  return field_functions_[power_gen_fieldfunc_local_handle_];
×
466
}
467

468
InputParameters
469
LBSProblem::GetOptionsBlock()
434✔
470
{
471
  InputParameters params;
434✔
472

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

546
  return params;
434✔
547
}
×
548

549
InputParameters
550
LBSProblem::GetXSMapEntryBlock()
637✔
551
{
552
  InputParameters params;
637✔
553
  params.SetGeneralDescription("Set the cross-section map for the solver.");
1,274✔
554
  params.AddRequiredParameterArray("block_ids", "Mesh block IDs");
1,274✔
555
  params.AddRequiredParameter<std::shared_ptr<MultiGroupXS>>("xs", "Cross-section object");
1,274✔
556
  return params;
637✔
557
}
×
558

559
void
560
LBSProblem::SetOptions(const InputParameters& input)
216✔
561
{
562
  auto params = LBSProblem::GetOptionsBlock();
216✔
563
  params.AssignParameters(input);
216✔
564

565
  // Handle order insensitive options
566
  for (size_t p = 0; p < params.GetNumParameters(); ++p)
4,752✔
567
  {
568
    const auto& spec = params.GetParam(p);
4,536✔
569

570
    if (spec.GetName() == "max_mpi_message_size")
4,536✔
571
      options_.max_mpi_message_size = spec.GetValue<int>();
216✔
572

573
    else if (spec.GetName() == "restart_writes_enabled")
4,320✔
574
      options_.restart_writes_enabled = spec.GetValue<bool>();
216✔
575

576
    else if (spec.GetName() == "write_delayed_psi_to_restart")
4,104✔
577
      options_.write_delayed_psi_to_restart = spec.GetValue<bool>();
216✔
578

579
    else if (spec.GetName() == "read_restart_path")
3,888✔
580
    {
581
      options_.read_restart_path = spec.GetValue<std::string>();
216✔
582
      if (not options_.read_restart_path.empty())
216✔
583
        options_.read_restart_path += std::to_string(opensn::mpi_comm.rank()) + ".restart.h5";
36✔
584
    }
585

586
    else if (spec.GetName() == "write_restart_path")
3,672✔
587
    {
588
      options_.write_restart_path = spec.GetValue<std::string>();
216✔
589
      if (not options_.write_restart_path.empty())
216✔
590
        options_.write_restart_path += std::to_string(opensn::mpi_comm.rank()) + ".restart.h5";
×
591
    }
592

593
    else if (spec.GetName() == "write_restart_time_interval")
3,456✔
594
      options_.write_restart_time_interval = std::chrono::seconds(spec.GetValue<int>());
216✔
595

596
    else if (spec.GetName() == "use_precursors")
3,240✔
597
      options_.use_precursors = spec.GetValue<bool>();
216✔
598

599
    else if (spec.GetName() == "use_source_moments")
3,024✔
600
      options_.use_src_moments = spec.GetValue<bool>();
216✔
601

602
    else if (spec.GetName() == "save_angular_flux")
2,808✔
603
      options_.save_angular_flux = spec.GetValue<bool>();
216✔
604

605
    else if (spec.GetName() == "verbose_inner_iterations")
2,592✔
606
      options_.verbose_inner_iterations = spec.GetValue<bool>();
216✔
607

608
    else if (spec.GetName() == "max_ags_iterations")
2,376✔
609
      options_.max_ags_iterations = spec.GetValue<int>();
216✔
610

611
    else if (spec.GetName() == "ags_tolerance")
2,160✔
612
      options_.ags_tolerance = spec.GetValue<double>();
216✔
613

614
    else if (spec.GetName() == "ags_convergence_check")
1,944✔
615
    {
616
      auto check = spec.GetValue<std::string>();
216✔
617
      if (check == "pointwise")
216✔
618
        options_.ags_pointwise_convergence = true;
×
619
    }
216✔
620

621
    else if (spec.GetName() == "verbose_ags_iterations")
1,728✔
622
      options_.verbose_ags_iterations = spec.GetValue<bool>();
216✔
623

624
    else if (spec.GetName() == "verbose_outer_iterations")
1,512✔
625
      options_.verbose_outer_iterations = spec.GetValue<bool>();
216✔
626

627
    else if (spec.GetName() == "power_field_function_on")
1,296✔
628
      options_.power_field_function_on = spec.GetValue<bool>();
216✔
629

630
    else if (spec.GetName() == "power_default_kappa")
1,080✔
631
      options_.power_default_kappa = spec.GetValue<double>();
216✔
632

633
    else if (spec.GetName() == "power_normalization")
864✔
634
      options_.power_normalization = spec.GetValue<double>();
216✔
635

636
    else if (spec.GetName() == "field_function_prefix_option")
648✔
637
    {
638
      options_.field_function_prefix_option = spec.GetValue<std::string>();
216✔
639
    }
640

641
    else if (spec.GetName() == "field_function_prefix")
432✔
642
      options_.field_function_prefix = spec.GetValue<std::string>();
216✔
643

644
    else if (spec.GetName() == "adjoint")
216✔
645
      options_.adjoint = spec.GetValue<bool>();
216✔
646

647
  } // for p
648

649
  if (options_.restart_writes_enabled)
216✔
650
  {
651
    // Create restart directory if necessary
652
    auto dir = options_.write_restart_path.parent_path();
×
653
    if (opensn::mpi_comm.rank() == 0)
×
654
    {
655
      if (not std::filesystem::exists(dir))
×
656
      {
657
        if (not std::filesystem::create_directories(dir))
×
658
          throw std::runtime_error(GetName() + ": Failed to create restart directory " +
×
659
                                   dir.string());
×
660
      }
661
      else if (not std::filesystem::is_directory(dir))
×
662
        throw std::runtime_error(GetName() + ": Restart path exists but is not a directory " +
×
663
                                 dir.string());
×
664
    }
665
    opensn::mpi_comm.barrier();
×
666
    UpdateRestartWriteTime();
×
667
  }
×
668
}
216✔
669

670
void
671
LBSProblem::Initialize()
372✔
672
{
673
  CALI_CXX_MARK_SCOPE("LBSProblem::Initialize");
372✔
674

675
  PrintSimHeader();
372✔
676
  mpi_comm.barrier();
372✔
677

678
  InitializeSpatialDiscretization();
372✔
679
  InitializeParrays();
372✔
680
  InitializeBoundaries();
372✔
681
  InitializeGPUExtras();
372✔
682
  SetAdjoint(options_.adjoint);
372✔
683

684
  // Initialize point sources
685
  for (auto& point_source : point_sources_)
381✔
686
    point_source->Initialize(*this);
9✔
687

688
  // Initialize volumetric sources
689
  for (auto& volumetric_source : volumetric_sources_)
763✔
690
    volumetric_source->Initialize(*this);
391✔
691
}
372✔
692

693
void
694
LBSProblem::PrintSimHeader()
×
695
{
696
  if (opensn::mpi_comm.rank() == 0)
×
697
  {
698
    std::stringstream outstr;
×
699
    outstr << "\n"
×
700
           << "Initializing " << GetName() << "\n\n"
×
701
           << "Scattering order    : " << scattering_order_ << "\n"
×
702
           << "Number of moments   : " << num_moments_ << "\n"
×
703
           << "Number of groups    : " << groups_.size() << "\n"
×
704
           << "Number of groupsets : " << groupsets_.size() << "\n\n";
×
705

706
    for (const auto& groupset : groupsets_)
×
707
    {
708
      outstr << "***** Groupset " << groupset.id << " *****\n"
×
709
             << "Groups:\n";
×
710
      const auto& groups = groupset.groups;
711
      constexpr int groups_per_line = 12;
712
      for (size_t i = 0; i < groups.size(); ++i)
×
713
      {
714
        outstr << std::setw(5) << groups[i].id << ' ';
×
715
        if ((i + 1) % groups_per_line == 0)
×
716
          outstr << '\n';
×
717
      }
718
      if (!groups.empty() && groups.size() % groups_per_line != 0)
×
719
        outstr << '\n';
×
720
    }
721

722
    log.Log() << outstr.str() << '\n';
×
723
  }
×
724
}
×
725

726
void
727
LBSProblem::InitializeSources(const InputParameters& params)
372✔
728
{
729
  if (params.Has("volumetric_sources"))
372✔
730
  {
731
    const auto& vol_srcs = params.GetParam("volumetric_sources");
372✔
732
    vol_srcs.RequireBlockTypeIs(ParameterBlockType::ARRAY);
372✔
733
    for (const auto& src : vol_srcs)
763✔
734
      volumetric_sources_.push_back(src.GetValue<std::shared_ptr<VolumetricSource>>());
782✔
735
  }
736

737
  if (params.Has("point_sources"))
372✔
738
  {
739
    const auto& pt_srcs = params.GetParam("point_sources");
372✔
740
    pt_srcs.RequireBlockTypeIs(ParameterBlockType::ARRAY);
372✔
741
    for (const auto& src : pt_srcs)
381✔
742
      point_sources_.push_back(src.GetValue<std::shared_ptr<PointSource>>());
18✔
743
  }
744
}
372✔
745

746
void
747
LBSProblem::InitializeGroupsets(const InputParameters& params)
372✔
748
{
749
  // Initialize groups
750
  if (num_groups_ == 0)
372✔
751
    throw std::invalid_argument(GetName() + ": Number of groups must be > 0");
×
752
  for (size_t g = 0; g < num_groups_; ++g)
21,581✔
753
    groups_.emplace_back(static_cast<int>(g));
21,209✔
754

755
  // Initialize groupsets
756
  const auto& groupsets_array = params.GetParam("groupsets");
372✔
757
  const size_t num_gs = groupsets_array.GetNumParameters();
372✔
758
  if (num_gs == 0)
372✔
759
    throw std::invalid_argument(GetName() + ": At least one groupset must be specified");
×
760
  for (size_t gs = 0; gs < num_gs; ++gs)
803✔
761
  {
762
    const auto& groupset_params = groupsets_array.GetParam(gs);
431✔
763
    InputParameters gs_input_params = LBSGroupset::GetInputParameters();
431✔
764
    gs_input_params.SetObjectType("LBSProblem:LBSGroupset");
431✔
765
    gs_input_params.AssignParameters(groupset_params);
431✔
766
    groupsets_.emplace_back(gs_input_params, gs, *this);
431✔
767
    if (groupsets_.back().groups.empty())
431✔
768
    {
769
      std::stringstream oss;
×
770
      oss << GetName() << ": No groups added to groupset " << groupsets_.back().id;
×
771
      throw std::runtime_error(oss.str());
×
772
    }
×
773
  }
431✔
774
}
372✔
775

776
void
777
LBSProblem::InitializeXSmapAndDensities(const InputParameters& params)
372✔
778
{
779
  // Build XS map
780
  const auto& xs_array = params.GetParam("xs_map");
372✔
781
  const size_t num_xs = xs_array.GetNumParameters();
372✔
782
  for (size_t i = 0; i < num_xs; ++i)
1,001✔
783
  {
784
    const auto& item_params = xs_array.GetParam(i);
629✔
785
    InputParameters xs_entry_pars = GetXSMapEntryBlock();
629✔
786
    xs_entry_pars.AssignParameters(item_params);
629✔
787

788
    const auto& block_ids_param = xs_entry_pars.GetParam("block_ids");
629✔
789
    block_ids_param.RequireBlockTypeIs(ParameterBlockType::ARRAY);
629✔
790
    const auto& block_ids = block_ids_param.GetVectorValue<unsigned int>();
629✔
791
    auto xs = xs_entry_pars.GetSharedPtrParam<MultiGroupXS>("xs");
629✔
792
    for (const auto& block_id : block_ids)
1,354✔
793
      block_id_to_xs_map_[block_id] = xs;
725✔
794
  }
629✔
795

796
  // Assign placeholder unit densities
797
  densities_local_.assign(grid_->local_cells.size(), 1.0);
372✔
798
}
372✔
799

800
void
801
LBSProblem::InitializeMaterials()
392✔
802
{
803
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeMaterials");
392✔
804

805
  log.Log0Verbose1() << "Initializing Materials";
784✔
806

807
  // Create set of material ids locally relevant
808
  int invalid_mat_cell_count = 0;
392✔
809
  std::set<unsigned int> unique_block_ids;
392✔
810
  for (auto& cell : grid_->local_cells)
418,556✔
811
  {
812
    unique_block_ids.insert(cell.block_id);
418,164✔
813
    if (cell.block_id == std::numeric_limits<unsigned int>::max() or
418,164✔
814
        (block_id_to_xs_map_.find(cell.block_id) == block_id_to_xs_map_.end()))
418,164✔
815
      ++invalid_mat_cell_count;
×
816
  }
817
  const auto& ghost_cell_ids = grid_->cells.GetGhostGlobalIDs();
392✔
818
  for (uint64_t cell_id : ghost_cell_ids)
81,862✔
819
  {
820
    const auto& cell = grid_->cells[cell_id];
81,470✔
821
    unique_block_ids.insert(cell.block_id);
81,470✔
822
    if (cell.block_id == std::numeric_limits<unsigned int>::max() or
81,470✔
823
        (block_id_to_xs_map_.find(cell.block_id) == block_id_to_xs_map_.end()))
81,470✔
824
      ++invalid_mat_cell_count;
×
825
  }
826
  OpenSnLogicalErrorIf(invalid_mat_cell_count > 0,
392✔
827
                       std::to_string(invalid_mat_cell_count) +
828
                         " cells encountered with an invalid material id.");
829

830
  // Get ready for processing
831
  for (const auto& [blk_id, mat] : block_id_to_xs_map_)
1,153✔
832
  {
833
    mat->SetAdjointMode(options_.adjoint);
761✔
834

835
    OpenSnLogicalErrorIf(mat->GetNumGroups() < groups_.size(),
761✔
836
                         "Cross-sections for block \"" + std::to_string(blk_id) +
837
                           "\" have fewer groups (" + std::to_string(mat->GetNumGroups()) +
838
                           ") than the simulation (" + std::to_string(groups_.size()) + "). " +
839
                           "Cross-sections must have at least as many groups as the simulation.");
840
  }
841

842
  // Initialize precursor properties
843
  num_precursors_ = 0;
392✔
844
  max_precursors_per_material_ = 0;
392✔
845
  for (const auto& mat_id_xs : block_id_to_xs_map_)
1,153✔
846
  {
847
    const auto& xs = mat_id_xs.second;
761✔
848
    num_precursors_ += xs->GetNumPrecursors();
761✔
849
    max_precursors_per_material_ = std::max(xs->GetNumPrecursors(), max_precursors_per_material_);
761✔
850
  }
851

852
  // if no precursors, turn off precursors
853
  if (num_precursors_ == 0)
392✔
854
    options_.use_precursors = false;
380✔
855

856
  // check compatibility when precursors are on
857
  if (options_.use_precursors)
392✔
858
  {
859
    for (const auto& [mat_id, xs] : block_id_to_xs_map_)
16✔
860
    {
861
      OpenSnLogicalErrorIf(xs->IsFissionable() and num_precursors_ == 0,
8✔
862
                           "Incompatible cross-section data encountered for material id " +
863
                             std::to_string(mat_id) + ". When delayed neutron data is present " +
864
                             "for one fissionable matrial, it must be present for all fissionable "
865
                             "materials.");
866
    }
867
  }
868

869
  // Update transport views if available
870
  if (grid_->local_cells.size() == cell_transport_views_.size())
392✔
871
    for (const auto& cell : grid_->local_cells)
22,580✔
872
    {
873
      const auto& xs_ptr = block_id_to_xs_map_[cell.block_id];
22,560✔
874
      auto& transport_view = cell_transport_views_[cell.local_id];
22,560✔
875
      transport_view.ReassignXS(*xs_ptr);
22,560✔
876
    }
877

878
  mpi_comm.barrier();
392✔
879
}
392✔
880

881
void
882
LBSProblem::InitializeSpatialDiscretization()
364✔
883
{
884
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeSpatialDiscretization");
364✔
885

886
  log.Log() << "Initializing spatial discretization.\n";
728✔
887
  discretization_ = PieceWiseLinearDiscontinuous::New(grid_);
364✔
888

889
  ComputeUnitIntegrals();
364✔
890
}
364✔
891

892
void
893
LBSProblem::ComputeUnitIntegrals()
372✔
894
{
895
  CALI_CXX_MARK_SCOPE("LBSProblem::ComputeUnitIntegrals");
372✔
896

897
  log.Log() << "Computing unit integrals.\n";
744✔
898
  const auto& sdm = *discretization_;
372✔
899

900
  const size_t num_local_cells = grid_->local_cells.size();
372✔
901
  unit_cell_matrices_.resize(num_local_cells);
372✔
902

903
  for (const auto& cell : grid_->local_cells)
395,976✔
904
    unit_cell_matrices_[cell.local_id] =
395,604✔
905
      ComputeUnitCellIntegrals(sdm, cell, grid_->GetCoordinateSystem());
395,604✔
906

907
  const auto ghost_ids = grid_->cells.GetGhostGlobalIDs();
372✔
908
  for (auto ghost_id : ghost_ids)
76,078✔
909
    unit_ghost_cell_matrices_[ghost_id] =
75,706✔
910
      ComputeUnitCellIntegrals(sdm, grid_->cells[ghost_id], grid_->GetCoordinateSystem());
151,412✔
911

912
  // Assessing global unit cell matrix storage
913
  std::array<size_t, 2> num_local_ucms = {unit_cell_matrices_.size(),
372✔
914
                                          unit_ghost_cell_matrices_.size()};
372✔
915
  std::array<size_t, 2> num_global_ucms = {0, 0};
372✔
916

917
  mpi_comm.all_reduce(num_local_ucms.data(), 2, num_global_ucms.data(), mpi::op::sum<size_t>());
372✔
918

919
  opensn::mpi_comm.barrier();
372✔
920
  log.Log() << "Ghost cell unit cell-matrix ratio: "
372✔
921
            << (double)num_global_ucms[1] * 100 / (double)num_global_ucms[0] << "%";
744✔
922
  log.Log() << "Cell matrices computed.";
744✔
923
}
372✔
924

925
void
926
LBSProblem::InitializeParrays()
372✔
927
{
928
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeParrays");
372✔
929

930
  log.Log() << "Initializing parallel arrays."
744✔
931
            << " G=" << num_groups_ << " M=" << num_moments_ << std::endl;
372✔
932

933
  // Initialize unknown
934
  // structure
935
  flux_moments_uk_man_.unknowns.clear();
372✔
936
  for (size_t m = 0; m < num_moments_; ++m)
1,318✔
937
  {
938
    flux_moments_uk_man_.AddUnknown(UnknownType::VECTOR_N, groups_.size());
946✔
939
    flux_moments_uk_man_.unknowns.back().name = "m" + std::to_string(m);
946✔
940
  }
941

942
  // Compute local # of dof
943
  local_node_count_ = discretization_->GetNumLocalNodes();
372✔
944
  global_node_count_ = discretization_->GetNumGlobalNodes();
372✔
945

946
  // Compute num of unknowns
947
  size_t num_grps = groups_.size();
372✔
948
  size_t local_unknown_count = local_node_count_ * num_grps * num_moments_;
372✔
949

950
  log.LogAllVerbose1() << "LBS Number of phi unknowns: " << local_unknown_count;
744✔
951

952
  // Size local vectors
953
  q_moments_local_.assign(local_unknown_count, 0.0);
372✔
954
  phi_old_local_.assign(local_unknown_count, 0.0);
372✔
955
  phi_new_local_.assign(local_unknown_count, 0.0);
372✔
956

957
  // Setup precursor vector
958
  if (options_.use_precursors)
372✔
959
  {
960
    size_t num_precursor_dofs = grid_->local_cells.size() * max_precursors_per_material_;
8✔
961
    precursor_new_local_.assign(num_precursor_dofs, 0.0);
8✔
962
  }
963

964
  // Initialize transport views
965
  // Transport views act as a data structure to store information
966
  // related to the transport simulation. The most prominent function
967
  // here is that it holds the means to know where a given cell's
968
  // transport quantities are located in the unknown vectors (i.e. phi)
969
  //
970
  // Also, for a given cell, within a given sweep chunk,
971
  // we need to solve a matrix which square size is the
972
  // amount of nodes on the cell. max_cell_dof_count is
973
  // initialized here.
974
  //
975
  size_t block_MG_counter = 0; // Counts the strides of moment and group
372✔
976

977
  const Vector3 ihat(1.0, 0.0, 0.0);
372✔
978
  const Vector3 jhat(0.0, 1.0, 0.0);
372✔
979
  const Vector3 khat(0.0, 0.0, 1.0);
372✔
980

981
  min_cell_dof_count_ = std::numeric_limits<unsigned int>::max();
372✔
982
  max_cell_dof_count_ = 0;
372✔
983
  cell_transport_views_.clear();
372✔
984
  cell_transport_views_.reserve(grid_->local_cells.size());
372✔
985
  for (auto& cell : grid_->local_cells)
395,976✔
986
  {
987
    size_t num_nodes = discretization_->GetCellNumNodes(cell);
395,604✔
988

989
    // compute cell volumes
990
    double cell_volume = 0.0;
395,604✔
991
    const auto& IntV_shapeI = unit_cell_matrices_[cell.local_id].intV_shapeI;
395,604✔
992
    for (size_t i = 0; i < num_nodes; ++i)
3,092,244✔
993
      cell_volume += IntV_shapeI(i);
2,696,640✔
994

995
    size_t cell_phi_address = block_MG_counter;
395,604✔
996

997
    const size_t num_faces = cell.faces.size();
395,604✔
998
    std::vector<bool> face_local_flags(num_faces, true);
395,604✔
999
    std::vector<int> face_locality(num_faces, opensn::mpi_comm.rank());
395,604✔
1000
    std::vector<const Cell*> neighbor_cell_ptrs(num_faces, nullptr);
395,604✔
1001
    bool cell_on_boundary = false;
395,604✔
1002
    int f = 0;
395,604✔
1003
    for (auto& face : cell.faces)
2,526,300✔
1004
    {
1005
      if (not face.has_neighbor)
2,130,696✔
1006
      {
1007
        cell_on_boundary = true;
80,994✔
1008
        face_local_flags[f] = false;
80,994✔
1009
        face_locality[f] = -1;
80,994✔
1010
      } // if bndry
1011
      else
1012
      {
1013
        const int neighbor_partition = face.GetNeighborPartitionID(grid_.get());
2,049,702✔
1014
        face_local_flags[f] = (neighbor_partition == opensn::mpi_comm.rank());
2,049,702✔
1015
        face_locality[f] = neighbor_partition;
2,049,702✔
1016
        neighbor_cell_ptrs[f] = &grid_->cells[face.neighbor_id];
2,049,702✔
1017
      }
1018

1019
      ++f;
2,130,696✔
1020
    } // for f
1021

1022
    max_cell_dof_count_ = std::max(max_cell_dof_count_, static_cast<unsigned int>(num_nodes));
395,604✔
1023
    min_cell_dof_count_ = std::min(min_cell_dof_count_, static_cast<unsigned int>(num_nodes));
395,604✔
1024
    cell_transport_views_.emplace_back(cell_phi_address,
791,208✔
1025
                                       num_nodes,
1026
                                       num_grps,
1027
                                       num_moments_,
395,604✔
1028
                                       num_faces,
1029
                                       *block_id_to_xs_map_[cell.block_id],
395,604✔
1030
                                       cell_volume,
1031
                                       face_local_flags,
1032
                                       face_locality,
1033
                                       neighbor_cell_ptrs,
1034
                                       cell_on_boundary);
1035
    block_MG_counter += num_nodes * num_grps * num_moments_;
395,604✔
1036
  } // for local cell
395,604✔
1037

1038
  // Populate grid nodal mappings
1039
  // This is used in the Flux Data Structures (FLUDS)
1040
  grid_nodal_mappings_.clear();
372✔
1041
  grid_nodal_mappings_.reserve(grid_->local_cells.size());
372✔
1042
  for (auto& cell : grid_->local_cells)
395,976✔
1043
  {
1044
    CellFaceNodalMapping cell_nodal_mapping;
395,604✔
1045
    cell_nodal_mapping.reserve(cell.faces.size());
395,604✔
1046

1047
    for (auto& face : cell.faces)
2,526,300✔
1048
    {
1049
      std::vector<short> face_node_mapping;
2,130,696✔
1050
      std::vector<short> cell_node_mapping;
2,130,696✔
1051
      int adj_face_idx = -1;
2,130,696✔
1052

1053
      if (face.has_neighbor)
2,130,696✔
1054
      {
1055
        grid_->FindAssociatedVertices(face, face_node_mapping);
2,049,702✔
1056
        grid_->FindAssociatedCellVertices(face, cell_node_mapping);
2,049,702✔
1057
        adj_face_idx = face.GetNeighborAdjacentFaceIndex(grid_.get());
2,049,702✔
1058
      }
1059

1060
      cell_nodal_mapping.emplace_back(adj_face_idx, face_node_mapping, cell_node_mapping);
2,130,696✔
1061
    } // for f
2,130,696✔
1062

1063
    grid_nodal_mappings_.push_back(cell_nodal_mapping);
395,604✔
1064
  } // for local cell
395,604✔
1065

1066
  // Get grid localized communicator set
1067
  grid_local_comm_set_ = grid_->MakeMPILocalCommunicatorSet();
372✔
1068

1069
  // Initialize Field Functions
1070
  InitializeFieldFunctions();
372✔
1071

1072
  opensn::mpi_comm.barrier();
372✔
1073
  log.Log() << "Done with parallel arrays." << std::endl;
744✔
1074
}
372✔
1075

1076
void
1077
LBSProblem::InitializeFieldFunctions()
372✔
1078
{
1079
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeFieldFunctions");
372✔
1080

1081
  if (not field_functions_.empty())
372✔
1082
    return;
×
1083

1084
  // Initialize Field Functions for flux moments
1085
  phi_field_functions_local_map_.clear();
372✔
1086

1087
  for (size_t g = 0; g < groups_.size(); ++g)
21,581✔
1088
  {
1089
    for (size_t m = 0; m < num_moments_; ++m)
97,736✔
1090
    {
1091
      std::string prefix;
76,527✔
1092
      if (options_.field_function_prefix_option == "prefix")
76,527✔
1093
      {
1094
        prefix = options_.field_function_prefix;
76,527✔
1095
        if (not prefix.empty())
76,527✔
1096
          prefix += "_";
1✔
1097
      }
1098
      if (options_.field_function_prefix_option == "solver_name")
76,527✔
1099
        prefix = GetName() + "_";
×
1100

1101
      std::ostringstream oss;
76,527✔
1102
      oss << prefix << "phi_g" << std::setw(3) << std::setfill('0') << static_cast<int>(g) << "_m"
76,527✔
1103
          << std::setw(2) << std::setfill('0') << static_cast<int>(m);
76,527✔
1104
      const std::string name = oss.str();
76,527✔
1105

1106
      auto group_ff = std::make_shared<FieldFunctionGridBased>(
76,527✔
1107
        name, discretization_, Unknown(UnknownType::SCALAR));
76,527✔
1108

1109
      field_function_stack.push_back(group_ff);
153,054✔
1110
      field_functions_.push_back(group_ff);
76,527✔
1111

1112
      phi_field_functions_local_map_[{g, m}] = field_functions_.size() - 1;
76,527✔
1113
    } // for m
76,527✔
1114
  } // for g
1115

1116
  // Initialize power generation field function
1117
  if (options_.power_field_function_on)
372✔
1118
  {
1119
    std::string prefix;
4✔
1120
    if (options_.field_function_prefix_option == "prefix")
4✔
1121
    {
1122
      prefix = options_.field_function_prefix;
4✔
1123
      if (not prefix.empty())
4✔
1124
        prefix += "_";
×
1125
    }
1126
    if (options_.field_function_prefix_option == "solver_name")
4✔
1127
      prefix = GetName() + "_";
×
1128

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

1132
    field_function_stack.push_back(power_ff);
8✔
1133
    field_functions_.push_back(power_ff);
4✔
1134

1135
    power_gen_fieldfunc_local_handle_ = field_functions_.size() - 1;
4✔
1136
  }
4✔
1137
}
372✔
1138

1139
void
1140
LBSProblem::InitializeSolverSchemes()
372✔
1141
{
1142
  CALI_CXX_MARK_SCOPE("LBSProblem::InitializeSolverSchemes");
372✔
1143

1144
  log.Log() << "Initializing WGS and AGS solvers";
744✔
1145

1146
  InitializeWGSSolvers();
372✔
1147

1148
  ags_solver_ = std::make_shared<AGSLinearSolver>(*this, wgs_solvers_);
372✔
1149
  if (groupsets_.size() == 1)
372✔
1150
  {
1151
    ags_solver_->SetMaxIterations(1);
317✔
1152
    ags_solver_->SetVerbosity(false);
317✔
1153
  }
1154
  else
1155
  {
1156
    ags_solver_->SetMaxIterations(options_.max_ags_iterations);
55✔
1157
    ags_solver_->SetVerbosity(options_.verbose_ags_iterations);
55✔
1158
  }
1159
  ags_solver_->SetTolerance(options_.ags_tolerance);
372✔
1160
}
372✔
1161

1162
#ifndef __OPENSN_WITH_GPU__
1163
void
1164
LBSProblem::InitializeGPUExtras()
380✔
1165
{
1166
}
380✔
1167

1168
void
1169
LBSProblem::ResetGPUCarriers()
372✔
1170
{
1171
}
372✔
1172

1173
void
1174
LBSProblem::CheckCapableDevices()
×
1175
{
1176
}
×
1177
#endif // __OPENSN_WITH_GPU__
1178

1179
std::vector<double>
1180
LBSProblem::MakeSourceMomentsFromPhi()
4✔
1181
{
1182
  CALI_CXX_MARK_SCOPE("LBSProblem::MakeSourceMomentsFromPhi");
4✔
1183

1184
  size_t num_local_dofs = discretization_->GetNumLocalDOFs(flux_moments_uk_man_);
4✔
1185

1186
  std::vector<double> source_moments(num_local_dofs, 0.0);
4✔
1187
  for (auto& groupset : groupsets_)
8✔
1188
  {
1189
    active_set_source_function_(groupset,
4✔
1190
                                source_moments,
1191
                                phi_new_local_,
4✔
1192
                                APPLY_AGS_SCATTER_SOURCES | APPLY_WGS_SCATTER_SOURCES |
1193
                                  APPLY_AGS_FISSION_SOURCES | APPLY_WGS_FISSION_SOURCES);
4✔
1194
  }
1195

1196
  return source_moments;
4✔
1197
}
4✔
1198

1199
void
1200
LBSProblem::UpdateFieldFunctions()
1,364✔
1201
{
1202
  CALI_CXX_MARK_SCOPE("LBSProblem::UpdateFieldFunctions");
1,364✔
1203

1204
  const auto& sdm = *discretization_;
1,364✔
1205
  const auto& phi_uk_man = flux_moments_uk_man_;
1,364✔
1206

1207
  // Update flux moments
1208
  for (const auto& [g_and_m, ff_index] : phi_field_functions_local_map_)
83,647✔
1209
  {
1210
    const size_t g = g_and_m.first;
82,283✔
1211
    const size_t m = g_and_m.second;
82,283✔
1212

1213
    std::vector<double> data_vector_local(local_node_count_, 0.0);
82,283✔
1214

1215
    for (const auto& cell : grid_->local_cells)
21,968,718✔
1216
    {
1217
      const auto& cell_mapping = sdm.GetCellMapping(cell);
21,886,435✔
1218
      const size_t num_nodes = cell_mapping.GetNumNodes();
21,886,435✔
1219

1220
      for (size_t i = 0; i < num_nodes; ++i)
152,269,511✔
1221
      {
1222
        const auto imapA = sdm.MapDOFLocal(cell, i, phi_uk_man, m, g);
130,383,076✔
1223
        const auto imapB = sdm.MapDOFLocal(cell, i);
130,383,076✔
1224

1225
        data_vector_local[imapB] = phi_new_local_[imapA];
130,383,076✔
1226
      } // for node
1227
    } // for cell
1228

1229
    auto& ff_ptr = field_functions_.at(ff_index);
82,283✔
1230
    ff_ptr->UpdateFieldVector(data_vector_local);
82,283✔
1231
  }
82,283✔
1232

1233
  // Update power generation and scalar flux
1234
  if (options_.power_field_function_on)
1,364✔
1235
  {
1236
    std::vector<double> data_vector_power_local(local_node_count_, 0.0);
4✔
1237

1238
    double local_total_power = 0.0;
4✔
1239
    for (const auto& cell : grid_->local_cells)
83,268✔
1240
    {
1241
      const auto& cell_mapping = sdm.GetCellMapping(cell);
83,264✔
1242
      const size_t num_nodes = cell_mapping.GetNumNodes();
83,264✔
1243

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

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

1248
      if (not xs->IsFissionable())
83,264✔
1249
        continue;
56,360✔
1250

1251
      for (size_t i = 0; i < num_nodes; ++i)
134,520✔
1252
      {
1253
        const auto imapA = sdm.MapDOFLocal(cell, i);
107,616✔
1254
        const auto imapB = sdm.MapDOFLocal(cell, i, phi_uk_man, 0, 0);
107,616✔
1255

1256
        double nodal_power = 0.0;
1257
        for (size_t g = 0; g < groups_.size(); ++g)
860,928✔
1258
        {
1259
          const double sigma_fg = xs->GetSigmaFission()[g];
753,312✔
1260
          // const double kappa_g = xs->Kappa()[g];
1261
          const double kappa_g = options_.power_default_kappa;
753,312✔
1262

1263
          nodal_power += kappa_g * sigma_fg * phi_new_local_[imapB + g];
753,312✔
1264
        } // for g
1265

1266
        data_vector_power_local[imapA] = nodal_power;
107,616✔
1267
        local_total_power += nodal_power * Vi(i);
107,616✔
1268
      } // for node
1269
    } // for cell
1270

1271
    double scale_factor = 1.0;
4✔
1272
    if (options_.power_normalization > 0.0)
4✔
1273
    {
1274
      double global_total_power = 0.0;
4✔
1275
      mpi_comm.all_reduce(local_total_power, global_total_power, mpi::op::sum<double>());
4✔
1276
      scale_factor = options_.power_normalization / global_total_power;
4✔
1277
      Scale(data_vector_power_local, scale_factor);
4✔
1278
    }
1279

1280
    const size_t ff_index = power_gen_fieldfunc_local_handle_;
4✔
1281

1282
    auto& ff_ptr = field_functions_.at(ff_index);
4✔
1283
    ff_ptr->UpdateFieldVector(data_vector_power_local);
4✔
1284

1285
    // scale scalar flux if neccessary
1286
    if (scale_factor != 1.0)
4✔
1287
    {
1288
      for (size_t g = 0; g < groups_.size(); ++g)
32✔
1289
      {
1290
        const size_t phi_ff_index = phi_field_functions_local_map_.at({g, size_t{0}});
28✔
1291
        auto& phi_ff_ptr = field_functions_.at(phi_ff_index);
28✔
1292
        const auto& phi_vec = phi_ff_ptr->GetLocalFieldVector();
28✔
1293
        std::vector<double> phi_scaled(phi_vec.begin(), phi_vec.end());
28✔
1294
        Scale(phi_scaled, scale_factor);
28✔
1295
        phi_ff_ptr->UpdateFieldVector(phi_scaled);
28✔
1296
      }
28✔
1297
    }
1298
  } // if power enabled
4✔
1299
}
1,364✔
1300

1301
void
1302
LBSProblem::SetPhiFromFieldFunctions(PhiSTLOption which_phi,
×
1303
                                     const std::vector<size_t>& m_indices,
1304
                                     const std::vector<size_t>& g_indices)
1305
{
1306
  CALI_CXX_MARK_SCOPE("LBSProblem::SetPhiFromFieldFunctions");
×
1307

1308
  std::vector<size_t> m_ids_to_copy = m_indices;
×
1309
  std::vector<size_t> g_ids_to_copy = g_indices;
×
1310
  if (m_indices.empty())
×
1311
    for (size_t m = 0; m < num_moments_; ++m)
×
1312
      m_ids_to_copy.push_back(m);
×
1313
  if (g_ids_to_copy.empty())
×
1314
    for (size_t g = 0; g < num_groups_; ++g)
×
1315
      g_ids_to_copy.push_back(g);
×
1316

1317
  const auto& sdm = *discretization_;
×
1318
  const auto& phi_uk_man = flux_moments_uk_man_;
×
1319

1320
  for (const size_t m : m_ids_to_copy)
×
1321
  {
1322
    for (const size_t g : g_ids_to_copy)
×
1323
    {
1324
      const size_t ff_index = phi_field_functions_local_map_.at({g, m});
×
1325
      const auto& ff_ptr = field_functions_.at(ff_index);
×
1326
      const auto& ff_data = ff_ptr->GetLocalFieldVector();
×
1327

1328
      for (const auto& cell : grid_->local_cells)
×
1329
      {
1330
        const auto& cell_mapping = sdm.GetCellMapping(cell);
×
1331
        const size_t num_nodes = cell_mapping.GetNumNodes();
×
1332

1333
        for (size_t i = 0; i < num_nodes; ++i)
×
1334
        {
1335
          const auto imapA = sdm.MapDOFLocal(cell, i);
×
1336
          const auto imapB = sdm.MapDOFLocal(cell, i, phi_uk_man, m, g);
×
1337

1338
          if (which_phi == PhiSTLOption::PHI_OLD)
×
1339
            phi_old_local_[imapB] = ff_data[imapA];
×
1340
          else if (which_phi == PhiSTLOption::PHI_NEW)
×
1341
            phi_new_local_[imapB] = ff_data[imapA];
×
1342
        } // for node
1343
      } // for cell
1344
    } // for g
1345
  } // for m
1346
}
×
1347

1348
LBSProblem::~LBSProblem()
364✔
1349
{
1350
  ResetGPUCarriers();
1351
}
1,820✔
1352

364✔
1353
void
1354
LBSProblem::SetAdjoint(bool adjoint)
384✔
1355
{
1356
  if (adjoint != options_.adjoint)
384✔
1357
  {
1358
    options_.adjoint = adjoint;
12✔
1359

1360
    // If a discretization exists, the solver has already been initialized.
1361
    // Reinitialize the materials to obtain the appropriate xs and clear the
1362
    // sources to prepare for defining the adjoint problem
1363
    if (discretization_)
12✔
1364
    {
1365
      // The materials are reinitialized here to ensure that the proper cross sections
1366
      // are available to the solver. Because an adjoint solve requires volumetric or
1367
      // point sources, the material-based sources are not set within the initialize routine.
1368
      InitializeMaterials();
12✔
1369

1370
      // Forward and adjoint sources are fundamentally different, so any existing sources
1371
      // should be cleared and reset through options upon changing modes.
1372
      point_sources_.clear();
12✔
1373
      volumetric_sources_.clear();
12✔
1374
      ClearBoundaries();
12✔
1375

1376
      // Set all solutions to zero.
1377
      phi_old_local_.assign(phi_old_local_.size(), 0.0);
12✔
1378
      phi_new_local_.assign(phi_new_local_.size(), 0.0);
12✔
1379
      ZeroSolutions();
12✔
1380
      precursor_new_local_.assign(precursor_new_local_.size(), 0.0);
12✔
1381
    }
1382
  }
1383
}
384✔
1384

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