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

openmc-dev / openmc / 21597332421

02 Feb 2026 03:59PM UTC coverage: 81.985% (+0.02%) from 81.968%
21597332421

Pull #3751

github

web-flow
Merge b413aacdb into fc0d9eec6
Pull Request #3751: Resolve conflict with weight windows and global russian roulette

17282 of 24047 branches covered (71.87%)

Branch coverage included in aggregate %.

80 of 87 new or added lines in 5 files covered. (91.95%)

63 existing lines in 1 file now uncovered.

55830 of 65130 relevant lines covered (85.72%)

43959498.43 hits per line

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

78.88
/src/weight_windows.cpp
1
#include "openmc/weight_windows.h"
2

3
#include <algorithm>
4
#include <cassert>
5
#include <cmath>
6
#include <set>
7
#include <string>
8

9
#include "xtensor/xdynamic_view.hpp"
10
#include "xtensor/xindex_view.hpp"
11
#include "xtensor/xio.hpp"
12
#include "xtensor/xmasked_view.hpp"
13
#include "xtensor/xnoalias.hpp"
14
#include "xtensor/xview.hpp"
15

16
#include "openmc/error.h"
17
#include "openmc/file_utils.h"
18
#include "openmc/hdf5_interface.h"
19
#include "openmc/mesh.h"
20
#include "openmc/message_passing.h"
21
#include "openmc/nuclide.h"
22
#include "openmc/output.h"
23
#include "openmc/particle.h"
24
#include "openmc/particle_data.h"
25
#include "openmc/physics_common.h"
26
#include "openmc/random_ray/flat_source_domain.h"
27
#include "openmc/search.h"
28
#include "openmc/settings.h"
29
#include "openmc/simulation.h"
30
#include "openmc/tallies/filter_energy.h"
31
#include "openmc/tallies/filter_mesh.h"
32
#include "openmc/tallies/filter_particle.h"
33
#include "openmc/tallies/tally.h"
34
#include "openmc/xml_interface.h"
35

36
#include <fmt/core.h>
37

38
namespace openmc {
39

40
//==============================================================================
41
// Global variables
42
//==============================================================================
43

44
namespace variance_reduction {
45

46
std::unordered_map<int32_t, int32_t> ww_map;
47
openmc::vector<unique_ptr<WeightWindows>> weight_windows;
48
openmc::vector<unique_ptr<WeightWindowsGenerator>> weight_windows_generators;
49

50
} // namespace variance_reduction
51

52
//==============================================================================
53
// WeightWindowSettings implementation
54
//==============================================================================
55

56
WeightWindows::WeightWindows(int32_t id)
247✔
57
{
58
  index_ = variance_reduction::weight_windows.size();
247✔
59
  set_id(id);
247✔
60
  set_defaults();
247✔
61
}
247✔
62

63
WeightWindows::WeightWindows(pugi::xml_node node)
92✔
64
{
65
  // Make sure required elements are present
66
  const vector<std::string> required_elems {
67
    "id", "particle_type", "lower_ww_bounds", "upper_ww_bounds"};
644✔
68
  for (const auto& elem : required_elems) {
460✔
69
    if (!check_for_node(node, elem.c_str())) {
368!
70
      fatal_error(fmt::format("Must specify <{}> for weight windows.", elem));
×
71
    }
72
  }
73

74
  // Get weight windows ID
75
  int32_t id = std::stoi(get_node_value(node, "id"));
92✔
76
  this->set_id(id);
92✔
77

78
  // get the particle type
79
  auto particle_type_str = std::string(get_node_value(node, "particle_type"));
92✔
80
  particle_type_ = openmc::str_to_particle_type(particle_type_str);
92✔
81

82
  // Determine associated mesh
83
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
92✔
84
  set_mesh(model::mesh_map.at(mesh_id));
92✔
85

86
  // energy bounds
87
  if (check_for_node(node, "energy_bounds"))
92✔
88
    energy_bounds_ = get_node_array<double>(node, "energy_bounds");
77✔
89

90
  // get the survival value - optional
91
  if (check_for_node(node, "survival_ratio")) {
92!
92
    survival_ratio_ = std::stod(get_node_value(node, "survival_ratio"));
92✔
93
    if (survival_ratio_ <= 1)
92!
94
      fatal_error("Survival to lower weight window ratio must bigger than 1 "
×
95
                  "and less than the upper to lower weight window ratio.");
96
  }
97

98
  // get the max lower bound ratio - optional
99
  if (check_for_node(node, "max_lower_bound_ratio")) {
92✔
100
    max_lb_ratio_ = std::stod(get_node_value(node, "max_lower_bound_ratio"));
34✔
101
    if (max_lb_ratio_ < 1.0) {
34!
102
      fatal_error("Maximum lower bound ratio must be larger than 1");
×
103
    }
104
  }
105

106
  // get the max split - optional
107
  if (check_for_node(node, "max_split")) {
92!
108
    max_split_ = std::stod(get_node_value(node, "max_split"));
92✔
109
    if (max_split_ <= 1)
92!
110
      fatal_error("max split must be larger than 1");
×
111
  }
112

113
  // weight cutoff - optional
114
  if (check_for_node(node, "weight_cutoff")) {
92!
115
    weight_cutoff_ = std::stod(get_node_value(node, "weight_cutoff"));
92✔
116
    if (weight_cutoff_ <= 0)
92!
117
      fatal_error("weight_cutoff must be larger than 0");
×
118
    if (weight_cutoff_ > 1)
92!
119
      fatal_error("weight_cutoff must be less than 1");
×
120
  }
121

122
  // read the lower/upper weight bounds
123
  this->set_bounds(get_node_array<double>(node, "lower_ww_bounds"),
92✔
124
    get_node_array<double>(node, "upper_ww_bounds"));
184✔
125

126
  set_defaults();
92✔
127
}
92✔
128

129
WeightWindows::~WeightWindows()
339✔
130
{
131
  variance_reduction::ww_map.erase(id());
339✔
132
}
339✔
133

134
WeightWindows* WeightWindows::create(int32_t id)
93✔
135
{
136
  variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
93✔
137
  auto wws = variance_reduction::weight_windows.back().get();
93✔
138
  variance_reduction::ww_map[wws->id()] =
93✔
139
    variance_reduction::weight_windows.size() - 1;
93✔
140
  return wws;
93✔
141
}
142

143
WeightWindows* WeightWindows::from_hdf5(
11✔
144
  hid_t wws_group, const std::string& group_name)
145
{
146
  // collect ID from the name of this group
147
  hid_t ww_group = open_group(wws_group, group_name);
11✔
148

149
  auto wws = WeightWindows::create();
11✔
150

151
  std::string particle_type;
11✔
152
  read_dataset(ww_group, "particle_type", particle_type);
11✔
153
  wws->particle_type_ = openmc::str_to_particle_type(particle_type);
11✔
154

155
  read_dataset<double>(ww_group, "energy_bounds", wws->energy_bounds_);
11✔
156

157
  int32_t mesh_id;
158
  read_dataset(ww_group, "mesh", mesh_id);
11✔
159

160
  if (model::mesh_map.count(mesh_id) == 0) {
11!
161
    fatal_error(
×
162
      fmt::format("Mesh {} used in weight windows does not exist.", mesh_id));
×
163
  }
164
  wws->set_mesh(model::mesh_map[mesh_id]);
11✔
165

166
  wws->lower_ww_ = xt::empty<double>(wws->bounds_size());
11✔
167
  wws->upper_ww_ = xt::empty<double>(wws->bounds_size());
11✔
168

169
  read_dataset<double>(ww_group, "lower_ww_bounds", wws->lower_ww_);
11✔
170
  read_dataset<double>(ww_group, "upper_ww_bounds", wws->upper_ww_);
11✔
171
  read_dataset(ww_group, "survival_ratio", wws->survival_ratio_);
11✔
172
  read_dataset(ww_group, "max_lower_bound_ratio", wws->max_lb_ratio_);
11✔
173
  read_dataset(ww_group, "max_split", wws->max_split_);
11✔
174
  read_dataset(ww_group, "weight_cutoff", wws->weight_cutoff_);
11✔
175

176
  close_group(ww_group);
11✔
177

178
  return wws;
11✔
179
}
11✔
180

181
void WeightWindows::set_defaults()
421✔
182
{
183
  // set energy bounds to the min/max energy supported by the data
184
  if (energy_bounds_.size() == 0) {
421✔
185
    int p_type = static_cast<int>(particle_type_);
262✔
186
    energy_bounds_.push_back(data::energy_min[p_type]);
262✔
187
    energy_bounds_.push_back(data::energy_max[p_type]);
262✔
188
  }
189
}
421✔
190

191
void WeightWindows::allocate_ww_bounds()
553✔
192
{
193
  auto shape = bounds_size();
553✔
194
  if (shape[0] * shape[1] == 0) {
553!
195
    auto msg = fmt::format(
196
      "Size of weight window bounds is zero for WeightWindows {}", id());
×
197
    warning(msg);
×
198
  }
×
199
  lower_ww_ = xt::empty<double>(shape);
553✔
200
  lower_ww_.fill(-1);
553✔
201
  upper_ww_ = xt::empty<double>(shape);
553✔
202
  upper_ww_.fill(-1);
553✔
203
}
553✔
204

205
void WeightWindows::set_id(int32_t id)
493✔
206
{
207
  assert(id >= 0 || id == C_NONE);
402!
208

209
  // Clear entry in mesh map in case one was already assigned
210
  if (id_ != C_NONE) {
493!
211
    variance_reduction::ww_map.erase(id_);
493✔
212
    id_ = C_NONE;
493✔
213
  }
214

215
  // Ensure no other mesh has the same ID
216
  if (variance_reduction::ww_map.find(id) != variance_reduction::ww_map.end()) {
493!
217
    throw std::runtime_error {
×
218
      fmt::format("Two weight windows have the same ID: {}", id)};
×
219
  }
220

221
  // If no ID is specified, auto-assign the next ID in the sequence
222
  if (id == C_NONE) {
493✔
223
    id = 0;
247✔
224
    for (const auto& m : variance_reduction::weight_windows) {
269✔
225
      id = std::max(id, m->id_);
22✔
226
    }
227
    ++id;
247✔
228
  }
229

230
  // Update ID and entry in the mesh map
231
  id_ = id;
493✔
232
  variance_reduction::ww_map[id] = index_;
493✔
233
}
493✔
234

235
void WeightWindows::set_energy_bounds(span<const double> bounds)
214✔
236
{
237
  energy_bounds_.clear();
214✔
238
  energy_bounds_.insert(energy_bounds_.begin(), bounds.begin(), bounds.end());
214✔
239
  // if the mesh is set, allocate space for weight window bounds
240
  if (mesh_idx_ != C_NONE)
214!
241
    allocate_ww_bounds();
214✔
242
}
214✔
243

244
void WeightWindows::set_particle_type(ParticleType p_type)
258✔
245
{
246
  if (p_type != ParticleType::neutron && p_type != ParticleType::photon)
258!
247
    fatal_error(
×
248
      fmt::format("Particle type '{}' cannot be applied to weight windows.",
×
249
        particle_type_to_str(p_type)));
×
250
  particle_type_ = p_type;
258✔
251
}
258✔
252

253
void WeightWindows::set_mesh(int32_t mesh_idx)
339✔
254
{
255
  if (mesh_idx < 0 || mesh_idx >= model::meshes.size())
339!
256
    fatal_error(fmt::format("Could not find a mesh for index {}", mesh_idx));
×
257

258
  mesh_idx_ = mesh_idx;
339✔
259
  model::meshes[mesh_idx_]->prepare_for_point_location();
339✔
260
  allocate_ww_bounds();
339✔
261
}
339✔
262

263
void WeightWindows::set_mesh(const std::unique_ptr<Mesh>& mesh)
×
264
{
265
  set_mesh(mesh.get());
×
266
}
×
267

268
void WeightWindows::set_mesh(const Mesh* mesh)
×
269
{
270
  set_mesh(model::mesh_map[mesh->id_]);
×
271
}
×
272

273
WeightWindow WeightWindows::get_weight_window(const Particle& p) const
90,881,697✔
274
{
275
  // check for particle type
276
  if (particle_type_ != p.type()) {
90,881,697✔
277
    return {};
19,709,991✔
278
  }
279

280
  // particle energy
281
  double E = p.E();
71,171,706✔
282

283
  // check to make sure energy is in range, expects sorted energy values
284
  if (E < energy_bounds_.front() || E > energy_bounds_.back())
71,171,706!
285
    return {};
92,818✔
286

287
  // Get mesh index for particle's position
288
  const auto& mesh = this->mesh();
71,078,888✔
289
  int mesh_bin = mesh->get_bin(p.r());
71,078,888✔
290

291
  // particle is outside the weight window mesh
292
  if (mesh_bin < 0)
71,078,888✔
293
    return {};
14,834✔
294

295
  // get the mesh bin in energy group
296
  int energy_bin =
297
    lower_bound_index(energy_bounds_.begin(), energy_bounds_.end(), E);
71,064,054✔
298

299
  // mesh_bin += energy_bin * mesh->n_bins();
300
  // Create individual weight window
301
  WeightWindow ww;
71,064,054✔
302
  ww.lower_weight = lower_ww_(energy_bin, mesh_bin);
71,064,054✔
303
  ww.upper_weight = upper_ww_(energy_bin, mesh_bin);
71,064,054✔
304
  ww.survival_weight = ww.lower_weight * survival_ratio_;
71,064,054✔
305
  ww.max_lb_ratio = max_lb_ratio_;
71,064,054✔
306
  ww.max_split = max_split_;
71,064,054✔
307
  ww.weight_cutoff = weight_cutoff_;
71,064,054✔
308
  return ww;
71,064,054✔
309
}
310

311
std::array<int, 2> WeightWindows::bounds_size() const
781✔
312
{
313
  int num_spatial_bins = this->mesh()->n_bins();
781✔
314
  int num_energy_bins =
315
    energy_bounds_.size() > 0 ? energy_bounds_.size() - 1 : 1;
781✔
316
  return {num_energy_bins, num_spatial_bins};
781✔
317
}
318

319
template<class T>
320
void WeightWindows::check_bounds(const T& lower, const T& upper) const
103✔
321
{
322
  // make sure that the upper and lower bounds have the same size
323
  if (lower.size() != upper.size()) {
103!
UNCOV
324
    auto msg = fmt::format("The upper and lower weight window lengths do not "
×
325
                           "match.\n Lower size: {}\n Upper size: {}",
UNCOV
326
      lower.size(), upper.size());
×
327
    fatal_error(msg);
×
328
  }
×
329
  this->check_bounds(lower);
103✔
330
}
103✔
331

332
template<class T>
333
void WeightWindows::check_bounds(const T& bounds) const
103✔
334
{
335
  // check that the number of weight window entries is correct
336
  auto dims = this->bounds_size();
103✔
337
  if (bounds.size() != dims[0] * dims[1]) {
103!
UNCOV
338
    auto err_msg =
×
339
      fmt::format("In weight window domain {} the number of spatial "
340
                  "energy/spatial bins ({}) does not match the number "
341
                  "of weight bins ({})",
UNCOV
342
        id_, dims, bounds.size());
×
343
    fatal_error(err_msg);
×
344
  }
×
345
}
103✔
346

UNCOV
347
void WeightWindows::set_bounds(const xt::xtensor<double, 2>& lower_bounds,
×
348
  const xt::xtensor<double, 2>& upper_bounds)
349
{
350

UNCOV
351
  this->check_bounds(lower_bounds, upper_bounds);
×
352

353
  // set new weight window values
UNCOV
354
  lower_ww_ = lower_bounds;
×
355
  upper_ww_ = upper_bounds;
×
356
}
×
357

UNCOV
358
void WeightWindows::set_bounds(
×
359
  const xt::xtensor<double, 2>& lower_bounds, double ratio)
360
{
UNCOV
361
  this->check_bounds(lower_bounds);
×
362

363
  // set new weight window values
UNCOV
364
  lower_ww_ = lower_bounds;
×
365
  upper_ww_ = lower_bounds;
×
366
  upper_ww_ *= ratio;
×
367
}
×
368

369
void WeightWindows::set_bounds(
103✔
370
  span<const double> lower_bounds, span<const double> upper_bounds)
371
{
372
  check_bounds(lower_bounds, upper_bounds);
103✔
373
  auto shape = this->bounds_size();
103✔
374
  lower_ww_ = xt::empty<double>(shape);
103✔
375
  upper_ww_ = xt::empty<double>(shape);
103✔
376

377
  // set new weight window values
378
  xt::view(lower_ww_, xt::all()) =
206✔
379
    xt::adapt(lower_bounds.data(), lower_ww_.shape());
309✔
380
  xt::view(upper_ww_, xt::all()) =
206✔
381
    xt::adapt(upper_bounds.data(), upper_ww_.shape());
309✔
382
}
103✔
383

UNCOV
384
void WeightWindows::set_bounds(span<const double> lower_bounds, double ratio)
×
385
{
UNCOV
386
  this->check_bounds(lower_bounds);
×
387

UNCOV
388
  auto shape = this->bounds_size();
×
389
  lower_ww_ = xt::empty<double>(shape);
×
390
  upper_ww_ = xt::empty<double>(shape);
×
391

392
  // set new weight window values
UNCOV
393
  xt::view(lower_ww_, xt::all()) =
×
394
    xt::adapt(lower_bounds.data(), lower_ww_.shape());
×
395
  xt::view(upper_ww_, xt::all()) =
×
396
    xt::adapt(lower_bounds.data(), upper_ww_.shape());
×
397
  upper_ww_ *= ratio;
×
398
}
×
399

400
void WeightWindows::update_weights(const Tally* tally, const std::string& value,
252✔
401
  double threshold, double ratio, WeightWindowUpdateMethod method)
402
{
403
  ///////////////////////////
404
  // Setup and checks
405
  ///////////////////////////
406
  this->check_tally_update_compatibility(tally);
252✔
407

408
  // Dimensions of weight window arrays
409
  int e_bins = lower_ww_.shape()[0];
252✔
410
  int64_t mesh_bins = lower_ww_.shape()[1];
252✔
411

412
  // Initialize weight window arrays to -1.0 by default
413
#pragma omp parallel for collapse(2) schedule(static)
140✔
414
  for (int e = 0; e < e_bins; e++) {
934✔
415
    for (int64_t m = 0; m < mesh_bins; m++) {
1,190,071✔
416
      lower_ww_(e, m) = -1.0;
1,189,249✔
417
      upper_ww_(e, m) = -1.0;
1,189,249✔
418
    }
419
  }
420

421
  // determine which value to use
422
  const std::set<std::string> allowed_values = {"mean", "rel_err"};
1,260✔
423
  if (allowed_values.count(value) == 0) {
252!
UNCOV
424
    fatal_error(fmt::format("Invalid value '{}' specified for weight window "
×
425
                            "generation. Must be one of: 'mean' or 'rel_err'",
426
      value));
427
  }
428

429
  // determine the index of the specified score
430
  int score_index = tally->score_index("flux");
252✔
431
  if (score_index == C_NONE) {
252!
UNCOV
432
    fatal_error(
×
433
      fmt::format("A 'flux' score required for weight window generation "
×
434
                  "is not present on tally {}.",
UNCOV
435
        tally->id()));
×
436
  }
437

438
  ///////////////////////////
439
  // Extract tally data
440
  //
441
  // At the end of this section, the mean and rel_err array
442
  // is a 2D view of tally data (n_e_groups, n_mesh_bins)
443
  //
444
  ///////////////////////////
445

446
  // build a shape for a view of the tally results, this will always be
447
  // dimension 5 (3 filter dimensions, 1 score dimension, 1 results dimension)
448
  // Look for the size of the last dimension of the results array
449
  const auto& results_arr = tally->results();
252✔
450
  const int results_dim = static_cast<int>(results_arr.shape()[2]);
252✔
451
  std::array<int, 5> shape = {1, 1, 1, tally->n_scores(), results_dim};
252✔
452

453
  // set the shape for the filters applied on the tally
454
  for (int i = 0; i < tally->filters().size(); i++) {
964✔
455
    const auto& filter = model::tally_filters[tally->filters(i)];
712✔
456
    shape[i] = filter->n_bins();
712✔
457
  }
458

459
  // build the transpose information to re-order data according to filter type
460
  std::array<int, 5> transpose = {0, 1, 2, 3, 4};
252✔
461

462
  // track our filter types and where we've added new ones
463
  std::vector<FilterType> filter_types = tally->filter_types();
252✔
464

465
  // assign other filter types to dummy positions if needed
466
  if (!tally->has_filter(FilterType::PARTICLE))
252✔
467
    filter_types.push_back(FilterType::PARTICLE);
22✔
468

469
  if (!tally->has_filter(FilterType::ENERGY))
252✔
470
    filter_types.push_back(FilterType::ENERGY);
22✔
471

472
  // particle axis mapping
473
  transpose[0] =
252✔
474
    std::find(filter_types.begin(), filter_types.end(), FilterType::PARTICLE) -
252✔
475
    filter_types.begin();
252✔
476

477
  // energy axis mapping
478
  transpose[1] =
252✔
479
    std::find(filter_types.begin(), filter_types.end(), FilterType::ENERGY) -
252✔
480
    filter_types.begin();
252✔
481

482
  // mesh axis mapping
483
  transpose[2] =
252✔
484
    std::find(filter_types.begin(), filter_types.end(), FilterType::MESH) -
252✔
485
    filter_types.begin();
252✔
486

487
  // get a fully reshaped view of the tally according to tally ordering of
488
  // filters
489
  auto tally_values = xt::reshape_view(results_arr, shape);
252✔
490

491
  // get a that is (particle, energy, mesh, scores, values)
492
  auto transposed_view = xt::transpose(tally_values, transpose);
252✔
493

494
  // determine the dimension and index of the particle data
495
  int particle_idx = 0;
252✔
496
  if (tally->has_filter(FilterType::PARTICLE)) {
252✔
497
    // get the particle filter
498
    auto pf = tally->get_filter<ParticleFilter>();
230✔
499
    const auto& particles = pf->particles();
230✔
500

501
    // find the index of the particle that matches these weight windows
502
    auto p_it =
503
      std::find(particles.begin(), particles.end(), this->particle_type_);
230✔
504
    // if the particle filter doesn't have particle data for the particle
505
    // used on this weight windows instance, report an error
506
    if (p_it == particles.end()) {
230!
507
      auto msg = fmt::format("Particle type '{}' not present on Filter {} for "
508
                             "Tally {} used to update WeightWindows {}",
UNCOV
509
        particle_type_to_str(this->particle_type_), pf->id(), tally->id(),
×
510
        this->id());
×
511
      fatal_error(msg);
×
512
    }
×
513

514
    // use the index of the particle in the filter to down-select data later
515
    particle_idx = p_it - particles.begin();
230✔
516
  }
517

518
  // down-select data based on particle and score
519
  auto sum = xt::dynamic_view(
1,260✔
520
    transposed_view, {particle_idx, xt::all(), xt::all(), score_index,
504✔
521
                       static_cast<int>(TallyResult::SUM)});
1,008✔
522
  auto sum_sq = xt::dynamic_view(
1,260✔
523
    transposed_view, {particle_idx, xt::all(), xt::all(), score_index,
504✔
524
                       static_cast<int>(TallyResult::SUM_SQ)});
1,008✔
525
  int n = tally->n_realizations_;
252✔
526

527
  //////////////////////////////////////////////
528
  //
529
  // Assign new weight windows
530
  //
531
  // Use references to the existing weight window data
532
  // to store and update the values
533
  //
534
  //////////////////////////////////////////////
535

536
  // up to this point the data arrays are views into the tally results (no
537
  // computation has been performed) now we'll switch references to the tally's
538
  // bounds to avoid allocating additional memory
539
  auto& new_bounds = this->lower_ww_;
252✔
540
  auto& rel_err = this->upper_ww_;
252✔
541

542
  // get mesh volumes
543
  auto mesh_vols = this->mesh()->volumes();
252✔
544

545
  // Calculate mean (new_bounds) and relative error
546
#pragma omp parallel for collapse(2) schedule(static)
140✔
547
  for (int e = 0; e < e_bins; e++) {
934✔
548
    for (int64_t m = 0; m < mesh_bins; m++) {
1,190,071✔
549
      // Calculate mean
550
      new_bounds(e, m) = sum(e, m) / n;
1,189,249✔
551
      // Calculate relative error
552
      if (sum(e, m) > 0.0) {
1,189,249✔
553
        double mean_val = new_bounds(e, m);
101,480✔
554
        double variance = (sum_sq(e, m) / n - mean_val * mean_val) / (n - 1);
101,480✔
555
        rel_err(e, m) = std::sqrt(variance) / mean_val;
101,480✔
556
      } else {
557
        rel_err(e, m) = INFTY;
1,087,769✔
558
      }
559
      if (value == "rel_err") {
1,189,249✔
560
        new_bounds(e, m) = 1.0 / rel_err(e, m);
345,000✔
561
      }
562
    }
563
  }
564

565
  // Divide by volume of mesh elements
566
#pragma omp parallel for collapse(2) schedule(static)
140✔
567
  for (int e = 0; e < e_bins; e++) {
934✔
568
    for (int64_t m = 0; m < mesh_bins; m++) {
1,190,071✔
569
      new_bounds(e, m) /= mesh_vols[m];
1,189,249✔
570
    }
571
  }
572

573
  if (method == WeightWindowUpdateMethod::MAGIC) {
252✔
574
    // For MAGIC, weight windows are proportional to the forward fluxes.
575
    // We normalize weight windows independently for each energy group.
576

577
    // Find group maximum and normalize (per energy group)
578
    for (int e = 0; e < e_bins; e++) {
1,870✔
579
      double group_max = 0.0;
1,716✔
580

581
      // Find maximum value across all elements in this energy group
582
#pragma omp parallel for schedule(static) reduction(max : group_max)
936✔
583
      for (int64_t m = 0; m < mesh_bins; m++) {
1,092,505✔
584
        if (new_bounds(e, m) > group_max) {
1,091,725✔
585
          group_max = new_bounds(e, m);
2,520✔
586
        }
587
      }
588

589
      // Normalize values in this energy group by the maximum value
590
      if (group_max > 0.0) {
1,716✔
591
        double norm_factor = 1.0 / (2.0 * group_max);
1,683✔
592
#pragma omp parallel for schedule(static)
918✔
593
        for (int64_t m = 0; m < mesh_bins; m++) {
1,091,590✔
594
          new_bounds(e, m) *= norm_factor;
1,090,825✔
595
        }
596
      }
597
    }
598
  } else {
599
    // For FW-CADIS, weight windows are inversely proportional to the adjoint
600
    // fluxes. We normalize the weight windows across all energy groups.
601
#pragma omp parallel for collapse(2) schedule(static)
56✔
602
    for (int e = 0; e < e_bins; e++) {
84✔
603
      for (int64_t m = 0; m < mesh_bins; m++) {
97,566✔
604
        // Take the inverse, but are careful not to divide by zero
605
        if (new_bounds(e, m) != 0.0) {
97,524✔
606
          new_bounds(e, m) = 1.0 / new_bounds(e, m);
69,660✔
607
        } else {
608
          new_bounds(e, m) = 0.0;
27,864!
609
        }
610
      }
611
    }
612

613
    // Find the maximum value across all elements
614
    double max_val = 0.0;
98✔
615
#pragma omp parallel for collapse(2) schedule(static) reduction(max : max_val)
56✔
616
    for (int e = 0; e < e_bins; e++) {
84✔
617
      for (int64_t m = 0; m < mesh_bins; m++) {
97,566✔
618
        if (new_bounds(e, m) > max_val) {
97,524✔
619
          max_val = new_bounds(e, m);
405✔
620
        }
621
      }
622
    }
623

624
    // Parallel normalization
625
    if (max_val > 0.0) {
98✔
626
      double norm_factor = 1.0 / (2.0 * max_val);
68✔
627
#pragma omp parallel for collapse(2) schedule(static)
38✔
628
      for (int e = 0; e < e_bins; e++) {
60✔
629
        for (int64_t m = 0; m < mesh_bins; m++) {
69,690✔
630
          new_bounds(e, m) *= norm_factor;
69,660✔
631
        }
632
      }
633
    }
634
  }
635

636
  // Final processing
637
#pragma omp parallel for collapse(2) schedule(static)
140✔
638
  for (int e = 0; e < e_bins; e++) {
934✔
639
    for (int64_t m = 0; m < mesh_bins; m++) {
1,190,071✔
640
      // Values where the mean is zero should be ignored
641
      if (sum(e, m) <= 0.0) {
1,189,249✔
642
        new_bounds(e, m) = -1.0;
1,087,769✔
643
      }
644
      // Values where the relative error is higher than the threshold should be
645
      // ignored
646
      else if (rel_err(e, m) > threshold) {
101,480✔
647
        new_bounds(e, m) = -1.0;
1,420✔
648
      }
649
      // Set the upper bounds
650
      upper_ww_(e, m) = ratio * lower_ww_(e, m);
1,189,249✔
651
    }
652
  }
653
}
252✔
654

655
void WeightWindows::check_tally_update_compatibility(const Tally* tally)
252✔
656
{
657
  // define the set of allowed filters for the tally
658
  const std::set<FilterType> allowed_filters = {
659
    FilterType::MESH, FilterType::ENERGY, FilterType::PARTICLE};
252✔
660

661
  // retrieve a mapping of filter type to filter index for the tally
662
  auto filter_indices = tally->filter_indices();
252✔
663

664
  // a mesh filter is required for a tally used to update weight windows
665
  if (!filter_indices.count(FilterType::MESH)) {
252!
UNCOV
666
    fatal_error(
×
667
      "A mesh filter is required for a tally to update weight window bounds");
668
  }
669

670
  // ensure the mesh filter is using the same mesh as this weight window object
671
  auto mesh_filter = tally->get_filter<MeshFilter>();
252✔
672

673
  // make sure that all of the filters present on the tally are allowed
674
  for (auto filter_pair : filter_indices) {
964✔
675
    if (allowed_filters.find(filter_pair.first) == allowed_filters.end()) {
712!
UNCOV
676
      fatal_error(fmt::format("Invalid filter type '{}' found on tally "
×
677
                              "used for weight window generation.",
UNCOV
678
        model::tally_filters[tally->filters(filter_pair.second)]->type_str()));
×
679
    }
680
  }
681

682
  if (mesh_filter->mesh() != mesh_idx_) {
252!
UNCOV
683
    int32_t mesh_filter_id = model::meshes[mesh_filter->mesh()]->id();
×
684
    int32_t ww_mesh_id = model::meshes[this->mesh_idx_]->id();
×
685
    fatal_error(fmt::format("Mesh filter {} uses a different mesh ({}) than "
×
686
                            "weight window {} mesh ({})",
UNCOV
687
      mesh_filter->id(), mesh_filter_id, id_, ww_mesh_id));
×
688
  }
689

690
  // if an energy filter exists, make sure the energy grid matches that of this
691
  // weight window object
692
  if (auto energy_filter = tally->get_filter<EnergyFilter>()) {
252✔
693
    std::vector<double> filter_bins = energy_filter->bins();
230✔
694
    std::set<double> filter_e_bounds(
695
      energy_filter->bins().begin(), energy_filter->bins().end());
230✔
696
    if (filter_e_bounds.size() != energy_bounds().size()) {
230!
UNCOV
697
      fatal_error(
×
698
        fmt::format("Energy filter {} does not have the same number of energy "
×
699
                    "bounds ({}) as weight window object {} ({})",
UNCOV
700
          energy_filter->id(), filter_e_bounds.size(), id_,
×
701
          energy_bounds().size()));
×
702
    }
703

704
    for (auto e : energy_bounds()) {
2,252✔
705
      if (filter_e_bounds.count(e) == 0) {
2,022!
UNCOV
706
        fatal_error(fmt::format(
×
707
          "Energy bounds of filter {} and weight windows {} do not match",
UNCOV
708
          energy_filter->id(), id_));
×
709
      }
710
    }
711
  }
230✔
712
}
252✔
713

714
void WeightWindows::to_hdf5(hid_t group) const
134✔
715
{
716
  hid_t ww_group = create_group(group, fmt::format("weight_windows_{}", id()));
268✔
717

718
  write_dataset(ww_group, "mesh", this->mesh()->id());
134✔
719
  write_dataset(
134✔
720
    ww_group, "particle_type", openmc::particle_type_to_str(particle_type_));
268✔
721
  write_dataset(ww_group, "energy_bounds", energy_bounds_);
134✔
722
  write_dataset(ww_group, "lower_ww_bounds", lower_ww_);
134✔
723
  write_dataset(ww_group, "upper_ww_bounds", upper_ww_);
134✔
724
  write_dataset(ww_group, "survival_ratio", survival_ratio_);
134✔
725
  write_dataset(ww_group, "max_lower_bound_ratio", max_lb_ratio_);
134✔
726
  write_dataset(ww_group, "max_split", max_split_);
134✔
727
  write_dataset(ww_group, "weight_cutoff", weight_cutoff_);
134✔
728

729
  close_group(ww_group);
134✔
730
}
134✔
731

732
WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node)
82✔
733
{
734
  // read information from the XML node
735
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
82✔
736
  int32_t mesh_idx = model::mesh_map[mesh_id];
82✔
737
  max_realizations_ = std::stoi(get_node_value(node, "max_realizations"));
82✔
738

739
  int32_t active_batches = settings::n_batches - settings::n_inactive;
82✔
740
  if (max_realizations_ > active_batches) {
82✔
741
    auto msg =
742
      fmt::format("The maximum number of specified tally realizations ({}) is "
743
                  "greater than the number of active batches ({}).",
744
        max_realizations_, active_batches);
31✔
745
    warning(msg);
17✔
746
  }
17✔
747
  auto tmp_str = get_node_value(node, "particle_type", true, true);
82✔
748
  auto particle_type = str_to_particle_type(tmp_str);
82✔
749

750
  update_interval_ = std::stoi(get_node_value(node, "update_interval"));
82✔
751
  on_the_fly_ = get_node_value_bool(node, "on_the_fly");
82✔
752

753
  std::vector<double> e_bounds;
82✔
754
  if (check_for_node(node, "energy_bounds")) {
82✔
755
    e_bounds = get_node_array<double>(node, "energy_bounds");
23✔
756
  } else {
757
    int p_type = static_cast<int>(particle_type);
59✔
758
    e_bounds.push_back(data::energy_min[p_type]);
59✔
759
    e_bounds.push_back(data::energy_max[p_type]);
59✔
760
  }
761

762
  // set method
763
  std::string method_string = get_node_value(node, "method");
82✔
764
  if (method_string == "magic") {
82✔
765
    method_ = WeightWindowUpdateMethod::MAGIC;
33✔
766
    if (settings::solver_type == SolverType::RANDOM_RAY &&
33!
767
        FlatSourceDomain::adjoint_) {
UNCOV
768
      fatal_error("Random ray weight window generation with MAGIC cannot be "
×
769
                  "done in adjoint mode.");
770
    }
771
  } else if (method_string == "fw_cadis") {
49!
772
    method_ = WeightWindowUpdateMethod::FW_CADIS;
49✔
773
    if (settings::solver_type != SolverType::RANDOM_RAY) {
49!
UNCOV
774
      fatal_error("FW-CADIS can only be run in random ray solver mode.");
×
775
    }
776
    FlatSourceDomain::adjoint_ = true;
49✔
777
  } else {
UNCOV
778
    fatal_error(fmt::format(
×
779
      "Unknown weight window update method '{}' specified", method_string));
780
  }
781

782
  // parse non-default update parameters if specified
783
  if (check_for_node(node, "update_parameters")) {
82✔
784
    pugi::xml_node params_node = node.child("update_parameters");
22✔
785
    if (check_for_node(params_node, "value"))
22!
786
      tally_value_ = get_node_value(params_node, "value");
22✔
787
    if (check_for_node(params_node, "threshold"))
22!
788
      threshold_ = std::stod(get_node_value(params_node, "threshold"));
22✔
789
    if (check_for_node(params_node, "ratio")) {
22!
790
      ratio_ = std::stod(get_node_value(params_node, "ratio"));
22✔
791
    }
792
  }
793

794
  // check update parameter values
795
  if (tally_value_ != "mean" && tally_value_ != "rel_err") {
82!
UNCOV
796
    fatal_error(fmt::format("Unsupported tally value '{}' specified for "
×
797
                            "weight window generation.",
UNCOV
798
      tally_value_));
×
799
  }
800
  if (threshold_ <= 0.0)
82!
UNCOV
801
    fatal_error(fmt::format("Invalid relative error threshold '{}' (<= 0.0) "
×
802
                            "specified for weight window generation",
UNCOV
803
      ratio_));
×
804
  if (ratio_ <= 1.0)
82!
UNCOV
805
    fatal_error(fmt::format("Invalid weight window ratio '{}' (<= 1.0) "
×
806
                            "specified for weight window generation"));
807

808
  // create a matching weight windows object
809
  auto wws = WeightWindows::create();
82✔
810
  ww_idx_ = wws->index();
82✔
811
  wws->set_mesh(mesh_idx);
82✔
812
  if (e_bounds.size() > 0)
82!
813
    wws->set_energy_bounds(e_bounds);
82✔
814
  wws->set_particle_type(particle_type);
82✔
815
  wws->set_defaults();
82✔
816
}
82✔
817

818
void WeightWindowsGenerator::create_tally()
82✔
819
{
820
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
82✔
821

822
  // create a tally based on the WWG information
823
  Tally* ww_tally = Tally::create();
82✔
824
  tally_idx_ = model::tally_map[ww_tally->id()];
82✔
825
  ww_tally->set_scores({"flux"});
164!
826

827
  int32_t mesh_id = wws->mesh()->id();
82✔
828
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
82✔
829
  // see if there's already a mesh filter using this mesh
830
  bool found_mesh_filter = false;
82✔
831
  for (const auto& f : model::tally_filters) {
259✔
832
    if (f->type() == FilterType::MESH) {
188✔
833
      const auto* mesh_filter = dynamic_cast<MeshFilter*>(f.get());
11!
834
      if (mesh_filter->mesh() == mesh_idx && !mesh_filter->translated() &&
22!
835
          !mesh_filter->rotated()) {
11!
836
        ww_tally->add_filter(f.get());
11✔
837
        found_mesh_filter = true;
11✔
838
        break;
11✔
839
      }
840
    }
841
  }
842

843
  if (!found_mesh_filter) {
82✔
844
    auto mesh_filter = Filter::create("mesh");
71✔
845
    openmc_mesh_filter_set_mesh(mesh_filter->index(), model::mesh_map[mesh_id]);
71✔
846
    ww_tally->add_filter(mesh_filter);
71✔
847
  }
848

849
  const auto& e_bounds = wws->energy_bounds();
82✔
850
  if (e_bounds.size() > 0) {
82!
851
    auto energy_filter = Filter::create("energy");
82✔
852
    openmc_energy_filter_set_bins(
164✔
853
      energy_filter->index(), e_bounds.size(), e_bounds.data());
82✔
854
    ww_tally->add_filter(energy_filter);
82✔
855
  }
856

857
  // add a particle filter
858
  auto particle_type = wws->particle_type();
82✔
859
  auto particle_filter = Filter::create("particle");
82✔
860
  auto pf = dynamic_cast<ParticleFilter*>(particle_filter);
82!
861
  pf->set_particles({&particle_type, 1});
82✔
862
  ww_tally->add_filter(particle_filter);
82✔
863
}
82✔
864

865
void WeightWindowsGenerator::update() const
2,417✔
866
{
867
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
2,417✔
868

869
  Tally* tally = model::tallies[tally_idx_].get();
2,417✔
870

871
  // If in random ray mode, only update on the last batch
872
  if (settings::solver_type == SolverType::RANDOM_RAY) {
2,417✔
873
    if (simulation::current_batch != settings::n_batches) {
2,252✔
874
      return;
2,154✔
875
    }
876
    // If in Monte Carlo mode and beyond the number of max realizations or
877
    // not at the correct update interval, skip the update
878
  } else if (max_realizations_ < tally->n_realizations_ ||
165✔
879
             tally->n_realizations_ % update_interval_ != 0) {
33!
880
    return;
132✔
881
  }
882

883
  wws->update_weights(tally, tally_value_, threshold_, ratio_, method_);
131✔
884

885
  // if we're not doing on the fly generation, reset the tally results once
886
  // we're done with the update
887
  if (!on_the_fly_)
131!
UNCOV
888
    tally->reset();
×
889

890
  // TODO: deactivate or remove tally once weight window generation is
891
  // complete
892
}
893

894
//==============================================================================
895
// Non-member functions
896
//==============================================================================
897

898
WeightWindow search_weight_window(const Particle& p)
82,232,067✔
899
{
900
  // TODO: this is a linear search - should do something more clever
901
  int mesh_bin;
902
  WeightWindow weight_window;
82,232,067✔
903
  for (const auto& ww : variance_reduction::weight_windows) {
115,646,200✔
904
    weight_window = ww->get_weight_window(p);
90,881,697✔
905
    if (weight_window.is_valid())
90,881,697✔
906
      return weight_window;
57,467,564✔
907
  }
908
  return {};
24,764,503✔
909
}
910

911
void apply_weight_windows(Particle& p)
167,087,893✔
912
{
913
  if (!settings::weight_windows_on)
167,087,893✔
914
    return;
166,343,152✔
915

916
  // WW on photon and neutron only
917
  if (p.type() != ParticleType::neutron && p.type() != ParticleType::photon)
748,418!
NEW
918
    return;
×
919

920
  // skip dead or no energy
921
  if (p.E() <= 0 || !p.alive())
748,418!
922
    return;
3,677✔
923

924
  auto ww = search_weight_window(p);
744,741✔
925
  if (ww.is_valid()) {
744,741✔
926
    apply_weight_window(p, ww);
677,508✔
927
  } else {
928
    if (p.wgt_ww_born() == -1.0)
67,233✔
929
      p.wgt_ww_born() = 1.0;
65,802✔
930
  }
931
}
932

933
void apply_weight_window(Particle& p, WeightWindow weight_window)
71,049,796✔
934
{
935
  if (!weight_window.is_valid())
71,049,796✔
936
    return;
13,582,232✔
937

938
  // skip dead or no energy
939
  if (p.E() <= 0 || !p.alive())
57,467,564✔
940
    return;
3,596,176✔
941

942
  // If particle has not yet had its birth weight window value set, set it to
943
  // the current weight window.
944
  if (p.wgt_ww_born() == -1.0)
53,871,388✔
945
    p.wgt_ww_born() =
671,878✔
946
      (weight_window.lower_weight + weight_window.upper_weight) / 2;
671,878✔
947

948
  // Normalize weight windows based on particle's starting weight
949
  // and the value of the weight window the particle was born in.
950
  weight_window.scale(p.wgt_born() / p.wgt_ww_born());
53,871,388✔
951

952
  // get the paramters
953
  double weight = p.wgt();
53,871,388✔
954

955
  // first check to see if particle should be killed for weight cutoff
956
  if (p.wgt() < weight_window.weight_cutoff) {
53,871,388!
NEW
957
    p.wgt() = 0.0;
×
NEW
958
    return;
×
959
  }
960

961
  // check if particle is far above current weight window
962
  // only do this if the factor is not already set on the particle and a
963
  // maximum lower bound ratio is specified
964
  if (p.ww_factor() == 0.0 && weight_window.max_lb_ratio > 1.0 &&
53,874,226✔
965
      p.wgt() > weight_window.lower_weight * weight_window.max_lb_ratio) {
2,838!
966
    p.ww_factor() =
2,838✔
967
      p.wgt() / (weight_window.lower_weight * weight_window.max_lb_ratio);
2,838✔
968
  }
969

970
  // move weight window closer to the particle weight if needed
971
  if (p.ww_factor() > 1.0)
53,871,388✔
972
    weight_window.scale(p.ww_factor());
1,356,443✔
973

974
  // if particle's weight is above the weight window split until they are within
975
  // the window
976
  if (weight > weight_window.upper_weight) {
53,871,388✔
977
    // do not further split the particle if above the limit
978
    if (p.n_split() >= settings::max_history_splits)
13,448,906✔
979
      return;
12,136,853✔
980

981
    double n_split = std::ceil(weight / weight_window.upper_weight);
1,312,053✔
982
    double max_split = weight_window.max_split;
1,312,053✔
983
    n_split = std::min(n_split, max_split);
1,312,053✔
984

985
    p.n_split() += n_split;
1,312,053✔
986

987
    // Create secondaries and divide weight among all particles
988
    int i_split = std::round(n_split);
1,312,053✔
989
    for (int l = 0; l < i_split - 1; l++) {
5,399,482✔
990
      p.split(weight / n_split);
4,087,429✔
991
    }
992
    // remaining weight is applied to current particle
993
    p.wgt() = weight / n_split;
1,312,053✔
994

995
  } else if (weight <= weight_window.lower_weight) {
40,422,482✔
996
    // if the particle weight is below the window, play Russian roulette
997
    double weight_survive =
998
      std::min(weight * weight_window.max_split, weight_window.survival_weight);
1,267,683✔
999
    russian_roulette(p, weight_survive);
1,267,683✔
1000
  } // else particle is in the window, continue as normal
1001
}
1002

1003
void free_memory_weight_windows()
8,186✔
1004
{
1005
  variance_reduction::ww_map.clear();
8,186✔
1006
  variance_reduction::weight_windows.clear();
8,186✔
1007
}
8,186✔
1008

1009
void finalize_variance_reduction()
8,040✔
1010
{
1011
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
8,122✔
1012
    wwg->create_tally();
82✔
1013
  }
1014
}
8,040✔
1015

1016
//==============================================================================
1017
// C API
1018
//==============================================================================
1019

1020
int verify_ww_index(int32_t index)
1,991✔
1021
{
1022
  if (index < 0 || index >= variance_reduction::weight_windows.size()) {
1,991!
1023
    set_errmsg(fmt::format("Index '{}' for weight windows is invalid", index));
×
UNCOV
1024
    return OPENMC_E_OUT_OF_BOUNDS;
×
1025
  }
1026
  return 0;
1,991✔
1027
}
1028

1029
extern "C" int openmc_get_weight_windows_index(int32_t id, int32_t* idx)
165✔
1030
{
1031
  auto it = variance_reduction::ww_map.find(id);
165✔
1032
  if (it == variance_reduction::ww_map.end()) {
165!
1033
    set_errmsg(fmt::format("No weight windows exist with ID={}", id));
×
UNCOV
1034
    return OPENMC_E_INVALID_ID;
×
1035
  }
1036

1037
  *idx = it->second;
165✔
1038
  return 0;
165✔
1039
}
1040

1041
extern "C" int openmc_weight_windows_get_id(int32_t index, int32_t* id)
517✔
1042
{
1043
  if (int err = verify_ww_index(index))
517!
UNCOV
1044
    return err;
×
1045

1046
  const auto& wws = variance_reduction::weight_windows.at(index);
517✔
1047
  *id = wws->id();
517✔
1048
  return 0;
517✔
1049
}
1050

1051
extern "C" int openmc_weight_windows_set_id(int32_t index, int32_t id)
154✔
1052
{
1053
  if (int err = verify_ww_index(index))
154!
UNCOV
1054
    return err;
×
1055

1056
  const auto& wws = variance_reduction::weight_windows.at(index);
154✔
1057
  wws->set_id(id);
154✔
1058
  return 0;
154✔
1059
}
1060

1061
extern "C" int openmc_weight_windows_update_magic(int32_t ww_idx,
121✔
1062
  int32_t tally_idx, const char* value, double threshold, double ratio)
1063
{
1064
  if (int err = verify_ww_index(ww_idx))
121!
UNCOV
1065
    return err;
×
1066

1067
  if (tally_idx < 0 || tally_idx >= model::tallies.size()) {
121!
1068
    set_errmsg(fmt::format("Index '{}' for tally is invalid", tally_idx));
×
UNCOV
1069
    return OPENMC_E_OUT_OF_BOUNDS;
×
1070
  }
1071

1072
  // get the requested tally
1073
  const Tally* tally = model::tallies.at(tally_idx).get();
121✔
1074

1075
  // get the WeightWindows object
1076
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
121✔
1077

1078
  wws->update_weights(tally, value, threshold, ratio);
121✔
1079

1080
  return 0;
121✔
1081
}
1082

1083
extern "C" int openmc_weight_windows_set_mesh(int32_t ww_idx, int32_t mesh_idx)
154✔
1084
{
1085
  if (int err = verify_ww_index(ww_idx))
154!
UNCOV
1086
    return err;
×
1087
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
154✔
1088
  wws->set_mesh(mesh_idx);
154✔
1089
  return 0;
154✔
1090
}
1091

1092
extern "C" int openmc_weight_windows_get_mesh(int32_t ww_idx, int32_t* mesh_idx)
11✔
1093
{
1094
  if (int err = verify_ww_index(ww_idx))
11!
UNCOV
1095
    return err;
×
1096
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
11✔
1097
  *mesh_idx = model::mesh_map.at(wws->mesh()->id());
11✔
1098
  return 0;
11✔
1099
}
1100

1101
extern "C" int openmc_weight_windows_set_energy_bounds(
132✔
1102
  int32_t ww_idx, double* e_bounds, size_t e_bounds_size)
1103
{
1104
  if (int err = verify_ww_index(ww_idx))
132!
UNCOV
1105
    return err;
×
1106
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
132✔
1107
  wws->set_energy_bounds({e_bounds, e_bounds_size});
132✔
1108
  return 0;
132✔
1109
}
1110

1111
extern "C" int openmc_weight_windows_get_energy_bounds(
11✔
1112
  int32_t ww_idx, const double** e_bounds, size_t* e_bounds_size)
1113
{
1114
  if (int err = verify_ww_index(ww_idx))
11!
UNCOV
1115
    return err;
×
1116
  const auto& wws = variance_reduction::weight_windows[ww_idx].get();
11✔
1117
  *e_bounds = wws->energy_bounds().data();
11✔
1118
  *e_bounds_size = wws->energy_bounds().size();
11✔
1119
  return 0;
11✔
1120
}
1121

1122
extern "C" int openmc_weight_windows_set_particle(int32_t index, int particle)
176✔
1123
{
1124
  if (int err = verify_ww_index(index))
176!
UNCOV
1125
    return err;
×
1126

1127
  const auto& wws = variance_reduction::weight_windows.at(index);
176✔
1128
  wws->set_particle_type(static_cast<ParticleType>(particle));
176✔
1129
  return 0;
176✔
1130
}
1131

1132
extern "C" int openmc_weight_windows_get_particle(int32_t index, int* particle)
44✔
1133
{
1134
  if (int err = verify_ww_index(index))
44!
UNCOV
1135
    return err;
×
1136

1137
  const auto& wws = variance_reduction::weight_windows.at(index);
44✔
1138
  *particle = static_cast<int>(wws->particle_type());
44✔
1139
  return 0;
44✔
1140
}
1141

1142
extern "C" int openmc_weight_windows_get_bounds(int32_t index,
484✔
1143
  const double** lower_bounds, const double** upper_bounds, size_t* size)
1144
{
1145
  if (int err = verify_ww_index(index))
484!
UNCOV
1146
    return err;
×
1147

1148
  const auto& wws = variance_reduction::weight_windows[index];
484✔
1149
  *size = wws->lower_ww_bounds().size();
484✔
1150
  *lower_bounds = wws->lower_ww_bounds().data();
484✔
1151
  *upper_bounds = wws->upper_ww_bounds().data();
484✔
1152
  return 0;
484✔
1153
}
1154

1155
extern "C" int openmc_weight_windows_set_bounds(int32_t index,
11✔
1156
  const double* lower_bounds, const double* upper_bounds, size_t size)
1157
{
1158
  if (int err = verify_ww_index(index))
11!
UNCOV
1159
    return err;
×
1160

1161
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1162
  wws->set_bounds({lower_bounds, size}, {upper_bounds, size});
11✔
1163
  return 0;
11✔
1164
}
1165

1166
extern "C" int openmc_weight_windows_get_survival_ratio(
33✔
1167
  int32_t index, double* ratio)
1168
{
1169
  if (int err = verify_ww_index(index))
33!
UNCOV
1170
    return err;
×
1171
  const auto& wws = variance_reduction::weight_windows[index];
33✔
1172
  *ratio = wws->survival_ratio();
33✔
1173
  return 0;
33✔
1174
}
1175

1176
extern "C" int openmc_weight_windows_set_survival_ratio(
11✔
1177
  int32_t index, double ratio)
1178
{
1179
  if (int err = verify_ww_index(index))
11!
UNCOV
1180
    return err;
×
1181
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1182
  wws->survival_ratio() = ratio;
11✔
1183
  std::cout << "Survival ratio: " << wws->survival_ratio() << std::endl;
11✔
1184
  return 0;
11✔
1185
}
1186

1187
extern "C" int openmc_weight_windows_get_max_lower_bound_ratio(
33✔
1188
  int32_t index, double* lb_ratio)
1189
{
1190
  if (int err = verify_ww_index(index))
33!
UNCOV
1191
    return err;
×
1192
  const auto& wws = variance_reduction::weight_windows[index];
33✔
1193
  *lb_ratio = wws->max_lower_bound_ratio();
33✔
1194
  return 0;
33✔
1195
}
1196

1197
extern "C" int openmc_weight_windows_set_max_lower_bound_ratio(
11✔
1198
  int32_t index, double lb_ratio)
1199
{
1200
  if (int err = verify_ww_index(index))
11!
UNCOV
1201
    return err;
×
1202
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1203
  wws->max_lower_bound_ratio() = lb_ratio;
11✔
1204
  return 0;
11✔
1205
}
1206

1207
extern "C" int openmc_weight_windows_get_weight_cutoff(
33✔
1208
  int32_t index, double* cutoff)
1209
{
1210
  if (int err = verify_ww_index(index))
33!
UNCOV
1211
    return err;
×
1212
  const auto& wws = variance_reduction::weight_windows[index];
33✔
1213
  *cutoff = wws->weight_cutoff();
33✔
1214
  return 0;
33✔
1215
}
1216

1217
extern "C" int openmc_weight_windows_set_weight_cutoff(
11✔
1218
  int32_t index, double cutoff)
1219
{
1220
  if (int err = verify_ww_index(index))
11!
UNCOV
1221
    return err;
×
1222
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1223
  wws->weight_cutoff() = cutoff;
11✔
1224
  return 0;
11✔
1225
}
1226

1227
extern "C" int openmc_weight_windows_get_max_split(
33✔
1228
  int32_t index, int* max_split)
1229
{
1230
  if (int err = verify_ww_index(index))
33!
UNCOV
1231
    return err;
×
1232
  const auto& wws = variance_reduction::weight_windows[index];
33✔
1233
  *max_split = wws->max_split();
33✔
1234
  return 0;
33✔
1235
}
1236

1237
extern "C" int openmc_weight_windows_set_max_split(int32_t index, int max_split)
11✔
1238
{
1239
  if (int err = verify_ww_index(index))
11!
UNCOV
1240
    return err;
×
1241
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1242
  wws->max_split() = max_split;
11✔
1243
  return 0;
11✔
1244
}
1245

1246
extern "C" int openmc_extend_weight_windows(
154✔
1247
  int32_t n, int32_t* index_start, int32_t* index_end)
1248
{
1249
  if (index_start)
154!
1250
    *index_start = variance_reduction::weight_windows.size();
154✔
1251
  if (index_end)
154!
UNCOV
1252
    *index_end = variance_reduction::weight_windows.size() + n - 1;
×
1253
  for (int i = 0; i < n; ++i)
308✔
1254
    variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
154✔
1255
  return 0;
154✔
1256
}
1257

1258
extern "C" size_t openmc_weight_windows_size()
154✔
1259
{
1260
  return variance_reduction::weight_windows.size();
154✔
1261
}
1262

1263
extern "C" int openmc_weight_windows_export(const char* filename)
164✔
1264
{
1265

1266
  if (!mpi::master)
164✔
1267
    return 0;
30✔
1268

1269
  std::string name = filename ? filename : "weight_windows.h5";
268✔
1270

1271
  write_message(fmt::format("Exporting weight windows to {}...", name), 5);
134✔
1272

1273
  hid_t ww_file = file_open(name, 'w');
134✔
1274

1275
  // Write file type
1276
  write_attribute(ww_file, "filetype", "weight_windows");
134✔
1277

1278
  // Write revisiion number for state point file
1279
  write_attribute(ww_file, "version", VERSION_WEIGHT_WINDOWS);
134✔
1280

1281
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
134✔
1282

1283
  hid_t mesh_group = create_group(ww_file, "meshes");
134✔
1284

1285
  std::vector<int32_t> mesh_ids;
134✔
1286
  std::vector<int32_t> ww_ids;
134✔
1287
  for (const auto& ww : variance_reduction::weight_windows) {
268✔
1288

1289
    ww->to_hdf5(weight_windows_group);
134✔
1290
    ww_ids.push_back(ww->id());
134✔
1291

1292
    // if the mesh has already been written, move on
1293
    int32_t mesh_id = ww->mesh()->id();
134✔
1294
    if (std::find(mesh_ids.begin(), mesh_ids.end(), mesh_id) != mesh_ids.end())
134!
UNCOV
1295
      continue;
×
1296

1297
    mesh_ids.push_back(mesh_id);
134✔
1298
    ww->mesh()->to_hdf5(mesh_group);
134✔
1299
  }
1300

1301
  write_attribute(mesh_group, "n_meshes", mesh_ids.size());
134✔
1302
  write_attribute(mesh_group, "ids", mesh_ids);
134✔
1303
  close_group(mesh_group);
134✔
1304

1305
  write_attribute(weight_windows_group, "n_weight_windows", ww_ids.size());
134✔
1306
  write_attribute(weight_windows_group, "ids", ww_ids);
134✔
1307
  close_group(weight_windows_group);
134✔
1308

1309
  file_close(ww_file);
134✔
1310

1311
  return 0;
134✔
1312
}
134✔
1313

1314
extern "C" int openmc_weight_windows_import(const char* filename)
11✔
1315
{
1316
  std::string name = filename ? filename : "weight_windows.h5";
11!
1317

1318
  if (mpi::master)
11!
1319
    write_message(fmt::format("Importing weight windows from {}...", name), 5);
11✔
1320

1321
  if (!file_exists(name)) {
11!
UNCOV
1322
    set_errmsg(fmt::format("File '{}' does not exist", name));
×
1323
  }
1324

1325
  hid_t ww_file = file_open(name, 'r');
11✔
1326

1327
  // Check that filetype is correct
1328
  std::string filetype;
11✔
1329
  read_attribute(ww_file, "filetype", filetype);
11✔
1330
  if (filetype != "weight_windows") {
11!
1331
    file_close(ww_file);
×
1332
    set_errmsg(fmt::format("File '{}' is not a weight windows file.", name));
×
UNCOV
1333
    return OPENMC_E_INVALID_ARGUMENT;
×
1334
  }
1335

1336
  // Check that the file version is compatible
1337
  std::array<int, 2> file_version;
1338
  read_attribute(ww_file, "version", file_version);
11✔
1339
  if (file_version[0] != VERSION_WEIGHT_WINDOWS[0]) {
11!
1340
    std::string err_msg =
1341
      fmt::format("File '{}' has version {} which is incompatible with the "
1342
                  "expected version ({}).",
1343
        name, file_version, VERSION_WEIGHT_WINDOWS);
×
1344
    set_errmsg(err_msg);
×
1345
    return OPENMC_E_INVALID_ARGUMENT;
×
UNCOV
1346
  }
×
1347

1348
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
11✔
1349

1350
  hid_t mesh_group = open_group(ww_file, "meshes");
11✔
1351

1352
  read_meshes(mesh_group);
11✔
1353

1354
  std::vector<std::string> names = group_names(weight_windows_group);
11✔
1355

1356
  for (const auto& name : names) {
22✔
1357
    WeightWindows::from_hdf5(weight_windows_group, name);
11✔
1358
  }
1359

1360
  close_group(weight_windows_group);
11✔
1361

1362
  file_close(ww_file);
11✔
1363

1364
  return 0;
11✔
1365
}
11✔
1366

1367
} // namespace openmc
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