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

openmc-dev / openmc / 18656608910

20 Oct 2025 03:16PM UTC coverage: 81.844% (-3.4%) from 85.218%
18656608910

Pull #3454

github

web-flow
Merge 5eee478a5 into 055ea15a2
Pull Request #3454: Adding variance of variance and normality tests for tally statistics

16610 of 23118 branches covered (71.85%)

Branch coverage included in aggregate %.

188 of 312 new or added lines in 7 files covered. (60.26%)

2157 existing lines in 77 files now uncovered.

53896 of 63029 relevant lines covered (85.51%)

42554448.35 hits per line

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

78.57
/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/tallies/filter_energy.h"
30
#include "openmc/tallies/filter_mesh.h"
31
#include "openmc/tallies/filter_particle.h"
32
#include "openmc/tallies/tally.h"
33
#include "openmc/xml_interface.h"
34

35
#include <fmt/core.h>
36

37
namespace openmc {
38

39
//==============================================================================
40
// Global variables
41
//==============================================================================
42

43
namespace variance_reduction {
44

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

49
} // namespace variance_reduction
50

51
//==============================================================================
52
// Non-member functions
53
//==============================================================================
54

55
void apply_weight_windows(Particle& p)
2,147,483,647✔
56
{
57
  if (!settings::weight_windows_on)
2,147,483,647✔
58
    return;
2,147,483,647✔
59

60
  // WW on photon and neutron only
61
  if (p.type() != ParticleType::neutron && p.type() != ParticleType::photon)
82,034,289✔
62
    return;
10,928,406✔
63

64
  // skip dead or no energy
65
  if (p.E() <= 0 || !p.alive())
71,105,883✔
66
    return;
4,085,792✔
67

68
  bool in_domain = false;
67,020,091✔
69
  // TODO: this is a linear search - should do something more clever
70
  WeightWindow weight_window;
67,020,091✔
71
  for (const auto& ww : variance_reduction::weight_windows) {
84,398,678✔
72
    weight_window = ww->get_weight_window(p);
71,068,707✔
73
    if (weight_window.is_valid())
71,068,707✔
74
      break;
53,690,120✔
75
  }
76

77
  // If particle has not yet had its birth weight window value set, set it to
78
  // the current weight window (or 1.0 if not born in a weight window).
79
  if (p.wgt_ww_born() == -1.0) {
67,020,091✔
80
    if (weight_window.is_valid()) {
736,680✔
81
      p.wgt_ww_born() =
670,878✔
82
        (weight_window.lower_weight + weight_window.upper_weight) / 2;
670,878✔
83
    } else {
84
      p.wgt_ww_born() = 1.0;
65,802✔
85
    }
86
  }
87

88
  // particle is not in any of the ww domains, do nothing
89
  if (!weight_window.is_valid())
67,020,091✔
90
    return;
13,329,971✔
91

92
  // Normalize weight windows based on particle's starting weight
93
  // and the value of the weight window the particle was born in.
94
  weight_window.scale(p.wgt_born() / p.wgt_ww_born());
53,690,120✔
95

96
  // get the paramters
97
  double weight = p.wgt();
53,690,120✔
98

99
  // first check to see if particle should be killed for weight cutoff
100
  if (p.wgt() < weight_window.weight_cutoff) {
53,690,120!
101
    p.wgt() = 0.0;
×
102
    return;
×
103
  }
104

105
  // check if particle is far above current weight window
106
  // only do this if the factor is not already set on the particle and a
107
  // maximum lower bound ratio is specified
108
  if (p.ww_factor() == 0.0 && weight_window.max_lb_ratio > 1.0 &&
53,692,958✔
109
      p.wgt() > weight_window.lower_weight * weight_window.max_lb_ratio) {
2,838!
110
    p.ww_factor() =
2,838✔
111
      p.wgt() / (weight_window.lower_weight * weight_window.max_lb_ratio);
2,838✔
112
  }
113

114
  // move weight window closer to the particle weight if needed
115
  if (p.ww_factor() > 1.0)
53,690,120✔
116
    weight_window.scale(p.ww_factor());
1,356,443✔
117

118
  // if particle's weight is above the weight window split until they are within
119
  // the window
120
  if (weight > weight_window.upper_weight) {
53,690,120✔
121
    // do not further split the particle if above the limit
122
    if (p.n_split() >= settings::max_history_splits)
13,442,061✔
123
      return;
12,135,198✔
124

125
    double n_split = std::ceil(weight / weight_window.upper_weight);
1,306,863✔
126
    double max_split = weight_window.max_split;
1,306,863✔
127
    n_split = std::min(n_split, max_split);
1,306,863✔
128

129
    p.n_split() += n_split;
1,306,863✔
130

131
    // Create secondaries and divide weight among all particles
132
    int i_split = std::round(n_split);
1,306,863✔
133
    for (int l = 0; l < i_split - 1; l++) {
5,388,973✔
134
      p.split(weight / n_split);
4,082,110✔
135
    }
136
    // remaining weight is applied to current particle
137
    p.wgt() = weight / n_split;
1,306,863✔
138

139
  } else if (weight <= weight_window.lower_weight) {
40,248,059✔
140
    // if the particle weight is below the window, play Russian roulette
141
    double weight_survive =
142
      std::min(weight * weight_window.max_split, weight_window.survival_weight);
1,266,428✔
143
    russian_roulette(p, weight_survive);
1,266,428✔
144
  } // else particle is in the window, continue as normal
145
}
146

147
void free_memory_weight_windows()
7,771✔
148
{
149
  variance_reduction::ww_map.clear();
7,771✔
150
  variance_reduction::weight_windows.clear();
7,771✔
151
}
7,771✔
152

153
//==============================================================================
154
// WeightWindowSettings implementation
155
//==============================================================================
156

157
WeightWindows::WeightWindows(int32_t id)
247✔
158
{
159
  index_ = variance_reduction::weight_windows.size();
247✔
160
  set_id(id);
247✔
161
  set_defaults();
247✔
162
}
247✔
163

164
WeightWindows::WeightWindows(pugi::xml_node node)
91✔
165
{
166
  // Make sure required elements are present
167
  const vector<std::string> required_elems {
168
    "id", "particle_type", "lower_ww_bounds", "upper_ww_bounds"};
637✔
169
  for (const auto& elem : required_elems) {
455✔
170
    if (!check_for_node(node, elem.c_str())) {
364!
171
      fatal_error(fmt::format("Must specify <{}> for weight windows.", elem));
×
172
    }
173
  }
174

175
  // Get weight windows ID
176
  int32_t id = std::stoi(get_node_value(node, "id"));
91✔
177
  this->set_id(id);
91✔
178

179
  // get the particle type
180
  auto particle_type_str = std::string(get_node_value(node, "particle_type"));
91✔
181
  particle_type_ = openmc::str_to_particle_type(particle_type_str);
91✔
182

183
  // Determine associated mesh
184
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
91✔
185
  set_mesh(model::mesh_map.at(mesh_id));
91✔
186

187
  // energy bounds
188
  if (check_for_node(node, "energy_bounds"))
91✔
189
    energy_bounds_ = get_node_array<double>(node, "energy_bounds");
77✔
190

191
  // get the survival value - optional
192
  if (check_for_node(node, "survival_ratio")) {
91!
193
    survival_ratio_ = std::stod(get_node_value(node, "survival_ratio"));
91✔
194
    if (survival_ratio_ <= 1)
91!
195
      fatal_error("Survival to lower weight window ratio must bigger than 1 "
×
196
                  "and less than the upper to lower weight window ratio.");
197
  }
198

199
  // get the max lower bound ratio - optional
200
  if (check_for_node(node, "max_lower_bound_ratio")) {
91✔
201
    max_lb_ratio_ = std::stod(get_node_value(node, "max_lower_bound_ratio"));
33✔
202
    if (max_lb_ratio_ < 1.0) {
33!
203
      fatal_error("Maximum lower bound ratio must be larger than 1");
×
204
    }
205
  }
206

207
  // get the max split - optional
208
  if (check_for_node(node, "max_split")) {
91!
209
    max_split_ = std::stod(get_node_value(node, "max_split"));
91✔
210
    if (max_split_ <= 1)
91!
211
      fatal_error("max split must be larger than 1");
×
212
  }
213

214
  // weight cutoff - optional
215
  if (check_for_node(node, "weight_cutoff")) {
91!
216
    weight_cutoff_ = std::stod(get_node_value(node, "weight_cutoff"));
91✔
217
    if (weight_cutoff_ <= 0)
91!
218
      fatal_error("weight_cutoff must be larger than 0");
×
219
    if (weight_cutoff_ > 1)
91!
220
      fatal_error("weight_cutoff must be less than 1");
×
221
  }
222

223
  // read the lower/upper weight bounds
224
  this->set_bounds(get_node_array<double>(node, "lower_ww_bounds"),
91✔
225
    get_node_array<double>(node, "upper_ww_bounds"));
182✔
226

227
  set_defaults();
91✔
228
}
91✔
229

230
WeightWindows::~WeightWindows()
338✔
231
{
232
  variance_reduction::ww_map.erase(id());
338✔
233
}
338✔
234

235
WeightWindows* WeightWindows::create(int32_t id)
93✔
236
{
237
  variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
93✔
238
  auto wws = variance_reduction::weight_windows.back().get();
93✔
239
  variance_reduction::ww_map[wws->id()] =
93✔
240
    variance_reduction::weight_windows.size() - 1;
93✔
241
  return wws;
93✔
242
}
243

244
WeightWindows* WeightWindows::from_hdf5(
11✔
245
  hid_t wws_group, const std::string& group_name)
246
{
247
  // collect ID from the name of this group
248
  hid_t ww_group = open_group(wws_group, group_name);
11✔
249

250
  auto wws = WeightWindows::create();
11✔
251

252
  std::string particle_type;
11✔
253
  read_dataset(ww_group, "particle_type", particle_type);
11✔
254
  wws->particle_type_ = openmc::str_to_particle_type(particle_type);
11✔
255

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

258
  int32_t mesh_id;
259
  read_dataset(ww_group, "mesh", mesh_id);
11✔
260

261
  if (model::mesh_map.count(mesh_id) == 0) {
11!
262
    fatal_error(
×
263
      fmt::format("Mesh {} used in weight windows does not exist.", mesh_id));
×
264
  }
265
  wws->set_mesh(model::mesh_map[mesh_id]);
11✔
266

267
  wws->lower_ww_ = xt::empty<double>(wws->bounds_size());
11✔
268
  wws->upper_ww_ = xt::empty<double>(wws->bounds_size());
11✔
269

270
  read_dataset<double>(ww_group, "lower_ww_bounds", wws->lower_ww_);
11✔
271
  read_dataset<double>(ww_group, "upper_ww_bounds", wws->upper_ww_);
11✔
272
  read_dataset(ww_group, "survival_ratio", wws->survival_ratio_);
11✔
273
  read_dataset(ww_group, "max_lower_bound_ratio", wws->max_lb_ratio_);
11✔
274
  read_dataset(ww_group, "max_split", wws->max_split_);
11✔
275
  read_dataset(ww_group, "weight_cutoff", wws->weight_cutoff_);
11✔
276

277
  close_group(ww_group);
11✔
278

279
  return wws;
11✔
280
}
11✔
281

282
void WeightWindows::set_defaults()
420✔
283
{
284
  // set energy bounds to the min/max energy supported by the data
285
  if (energy_bounds_.size() == 0) {
420✔
286
    int p_type = static_cast<int>(particle_type_);
261✔
287
    energy_bounds_.push_back(data::energy_min[p_type]);
261✔
288
    energy_bounds_.push_back(data::energy_max[p_type]);
261✔
289
  }
290
}
420✔
291

292
void WeightWindows::allocate_ww_bounds()
552✔
293
{
294
  auto shape = bounds_size();
552✔
295
  if (shape[0] * shape[1] == 0) {
552!
296
    auto msg = fmt::format(
297
      "Size of weight window bounds is zero for WeightWindows {}", id());
×
298
    warning(msg);
×
UNCOV
299
  }
×
300
  lower_ww_ = xt::empty<double>(shape);
552✔
301
  lower_ww_.fill(-1);
552✔
302
  upper_ww_ = xt::empty<double>(shape);
552✔
303
  upper_ww_.fill(-1);
552✔
304
}
552✔
305

306
void WeightWindows::set_id(int32_t id)
492✔
307
{
308
  assert(id >= 0 || id == C_NONE);
401!
309

310
  // Clear entry in mesh map in case one was already assigned
311
  if (id_ != C_NONE) {
492!
312
    variance_reduction::ww_map.erase(id_);
492✔
313
    id_ = C_NONE;
492✔
314
  }
315

316
  // Ensure no other mesh has the same ID
317
  if (variance_reduction::ww_map.find(id) != variance_reduction::ww_map.end()) {
492!
318
    throw std::runtime_error {
×
319
      fmt::format("Two weight windows have the same ID: {}", id)};
×
320
  }
321

322
  // If no ID is specified, auto-assign the next ID in the sequence
323
  if (id == C_NONE) {
492✔
324
    id = 0;
247✔
325
    for (const auto& m : variance_reduction::weight_windows) {
269✔
326
      id = std::max(id, m->id_);
22✔
327
    }
328
    ++id;
247✔
329
  }
330

331
  // Update ID and entry in the mesh map
332
  id_ = id;
492✔
333
  variance_reduction::ww_map[id] = index_;
492✔
334
}
492✔
335

336
void WeightWindows::set_energy_bounds(span<const double> bounds)
214✔
337
{
338
  energy_bounds_.clear();
214✔
339
  energy_bounds_.insert(energy_bounds_.begin(), bounds.begin(), bounds.end());
214✔
340
  // if the mesh is set, allocate space for weight window bounds
341
  if (mesh_idx_ != C_NONE)
214!
342
    allocate_ww_bounds();
214✔
343
}
214✔
344

345
void WeightWindows::set_particle_type(ParticleType p_type)
258✔
346
{
347
  if (p_type != ParticleType::neutron && p_type != ParticleType::photon)
258!
348
    fatal_error(
×
349
      fmt::format("Particle type '{}' cannot be applied to weight windows.",
×
350
        particle_type_to_str(p_type)));
×
351
  particle_type_ = p_type;
258✔
352
}
258✔
353

354
void WeightWindows::set_mesh(int32_t mesh_idx)
338✔
355
{
356
  if (mesh_idx < 0 || mesh_idx >= model::meshes.size())
338!
357
    fatal_error(fmt::format("Could not find a mesh for index {}", mesh_idx));
×
358

359
  mesh_idx_ = mesh_idx;
338✔
360
  model::meshes[mesh_idx_]->prepare_for_point_location();
338✔
361
  allocate_ww_bounds();
338✔
362
}
338✔
363

364
void WeightWindows::set_mesh(const std::unique_ptr<Mesh>& mesh)
×
365
{
366
  set_mesh(mesh.get());
×
UNCOV
367
}
×
368

369
void WeightWindows::set_mesh(const Mesh* mesh)
×
370
{
371
  set_mesh(model::mesh_map[mesh->id_]);
×
UNCOV
372
}
×
373

374
WeightWindow WeightWindows::get_weight_window(const Particle& p) const
71,068,707✔
375
{
376
  // check for particle type
377
  if (particle_type_ != p.type()) {
71,068,707✔
378
    return {};
3,872,836✔
379
  }
380

381
  // Get mesh index for particle's position
382
  const auto& mesh = this->mesh();
67,195,871✔
383
  int mesh_bin = mesh->get_bin(p.r());
67,195,871✔
384

385
  // particle is outside the weight window mesh
386
  if (mesh_bin < 0)
67,195,871!
387
    return {};
×
388

389
  // particle energy
390
  double E = p.E();
67,195,871✔
391

392
  // check to make sure energy is in range, expects sorted energy values
393
  if (E < energy_bounds_.front() || E > energy_bounds_.back())
67,195,871!
394
    return {};
92,598✔
395

396
  // get the mesh bin in energy group
397
  int energy_bin =
398
    lower_bound_index(energy_bounds_.begin(), energy_bounds_.end(), E);
67,103,273✔
399

400
  // mesh_bin += energy_bin * mesh->n_bins();
401
  // Create individual weight window
402
  WeightWindow ww;
67,103,273✔
403
  ww.lower_weight = lower_ww_(energy_bin, mesh_bin);
67,103,273✔
404
  ww.upper_weight = upper_ww_(energy_bin, mesh_bin);
67,103,273✔
405
  ww.survival_weight = ww.lower_weight * survival_ratio_;
67,103,273✔
406
  ww.max_lb_ratio = max_lb_ratio_;
67,103,273✔
407
  ww.max_split = max_split_;
67,103,273✔
408
  ww.weight_cutoff = weight_cutoff_;
67,103,273✔
409
  return ww;
67,103,273✔
410
}
411

412
std::array<int, 2> WeightWindows::bounds_size() const
778✔
413
{
414
  int num_spatial_bins = this->mesh()->n_bins();
778✔
415
  int num_energy_bins =
416
    energy_bounds_.size() > 0 ? energy_bounds_.size() - 1 : 1;
778✔
417
  return {num_energy_bins, num_spatial_bins};
778✔
418
}
419

420
template<class T>
421
void WeightWindows::check_bounds(const T& lower, const T& upper) const
102✔
422
{
423
  // make sure that the upper and lower bounds have the same size
424
  if (lower.size() != upper.size()) {
102!
425
    auto msg = fmt::format("The upper and lower weight window lengths do not "
×
426
                           "match.\n Lower size: {}\n Upper size: {}",
427
      lower.size(), upper.size());
×
428
    fatal_error(msg);
×
429
  }
×
430
  this->check_bounds(lower);
102✔
431
}
102✔
432

433
template<class T>
434
void WeightWindows::check_bounds(const T& bounds) const
102✔
435
{
436
  // check that the number of weight window entries is correct
437
  auto dims = this->bounds_size();
102!
438
  if (bounds.size() != dims[0] * dims[1]) {
102!
439
    auto err_msg =
×
440
      fmt::format("In weight window domain {} the number of spatial "
441
                  "energy/spatial bins ({}) does not match the number "
442
                  "of weight bins ({})",
443
        id_, dims, bounds.size());
×
UNCOV
444
    fatal_error(err_msg);
×
UNCOV
445
  }
×
446
}
102✔
447

UNCOV
448
void WeightWindows::set_bounds(const xt::xtensor<double, 2>& lower_bounds,
×
449
  const xt::xtensor<double, 2>& upper_bounds)
450
{
451

452
  this->check_bounds(lower_bounds, upper_bounds);
×
453

454
  // set new weight window values
UNCOV
455
  lower_ww_ = lower_bounds;
×
UNCOV
456
  upper_ww_ = upper_bounds;
×
UNCOV
457
}
×
458

UNCOV
459
void WeightWindows::set_bounds(
×
460
  const xt::xtensor<double, 2>& lower_bounds, double ratio)
461
{
UNCOV
462
  this->check_bounds(lower_bounds);
×
463

464
  // set new weight window values
465
  lower_ww_ = lower_bounds;
×
466
  upper_ww_ = lower_bounds;
×
467
  upper_ww_ *= ratio;
×
UNCOV
468
}
×
469

470
void WeightWindows::set_bounds(
102✔
471
  span<const double> lower_bounds, span<const double> upper_bounds)
472
{
473
  check_bounds(lower_bounds, upper_bounds);
102✔
474
  auto shape = this->bounds_size();
102✔
475
  lower_ww_ = xt::empty<double>(shape);
102✔
476
  upper_ww_ = xt::empty<double>(shape);
102✔
477

478
  // set new weight window values
479
  xt::view(lower_ww_, xt::all()) =
204✔
480
    xt::adapt(lower_bounds.data(), lower_ww_.shape());
306✔
481
  xt::view(upper_ww_, xt::all()) =
204✔
482
    xt::adapt(upper_bounds.data(), upper_ww_.shape());
306✔
483
}
102✔
484

485
void WeightWindows::set_bounds(span<const double> lower_bounds, double ratio)
×
486
{
487
  this->check_bounds(lower_bounds);
×
488

UNCOV
489
  auto shape = this->bounds_size();
×
UNCOV
490
  lower_ww_ = xt::empty<double>(shape);
×
491
  upper_ww_ = xt::empty<double>(shape);
×
492

493
  // set new weight window values
UNCOV
494
  xt::view(lower_ww_, xt::all()) =
×
UNCOV
495
    xt::adapt(lower_bounds.data(), lower_ww_.shape());
×
496
  xt::view(upper_ww_, xt::all()) =
×
UNCOV
497
    xt::adapt(lower_bounds.data(), upper_ww_.shape());
×
UNCOV
498
  upper_ww_ *= ratio;
×
UNCOV
499
}
×
500

501
void WeightWindows::update_weights(const Tally* tally, const std::string& value,
252✔
502
  double threshold, double ratio, WeightWindowUpdateMethod method)
503
{
504
  ///////////////////////////
505
  // Setup and checks
506
  ///////////////////////////
507
  this->check_tally_update_compatibility(tally);
252✔
508

509
  // Dimensions of weight window arrays
510
  int e_bins = lower_ww_.shape()[0];
252✔
511
  int64_t mesh_bins = lower_ww_.shape()[1];
252✔
512

513
  // Initialize weight window arrays to -1.0 by default
514
#pragma omp parallel for collapse(2) schedule(static)
140✔
515
  for (int e = 0; e < e_bins; e++) {
934✔
516
    for (int64_t m = 0; m < mesh_bins; m++) {
1,190,071✔
517
      lower_ww_(e, m) = -1.0;
1,189,249✔
518
      upper_ww_(e, m) = -1.0;
1,189,249✔
519
    }
520
  }
521

522
  // determine which value to use
523
  const std::set<std::string> allowed_values = {"mean", "rel_err"};
1,260✔
524
  if (allowed_values.count(value) == 0) {
252!
UNCOV
525
    fatal_error(fmt::format("Invalid value '{}' specified for weight window "
×
526
                            "generation. Must be one of: 'mean' or 'rel_err'",
527
      value));
528
  }
529

530
  // determine the index of the specified score
531
  int score_index = tally->score_index("flux");
252✔
532
  if (score_index == C_NONE) {
252!
533
    fatal_error(
×
UNCOV
534
      fmt::format("A 'flux' score required for weight window generation "
×
535
                  "is not present on tally {}.",
UNCOV
536
        tally->id()));
×
537
  }
538

539
  ///////////////////////////
540
  // Extract tally data
541
  //
542
  // At the end of this section, the mean and rel_err array
543
  // is a 2D view of tally data (n_e_groups, n_mesh_bins)
544
  //
545
  ///////////////////////////
546

547
  // build a shape for a view of the tally results, this will always be
548
  // dimension 5 (3 filter dimensions, 1 score dimension, 1 results dimension)
549
  // Look for the size of the last dimension of the results array
550
  const auto& results_arr = tally->results();
252✔
551
  const int results_dim = static_cast<int>(results_arr.shape()[2]);
252✔
552
  std::array<int, 5> shape = {1, 1, 1, tally->n_scores(), results_dim};
252✔
553

554
  // set the shape for the filters applied on the tally
555
  for (int i = 0; i < tally->filters().size(); i++) {
964✔
556
    const auto& filter = model::tally_filters[tally->filters(i)];
712✔
557
    shape[i] = filter->n_bins();
712✔
558
  }
559

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

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

566
  // assign other filter types to dummy positions if needed
567
  if (!tally->has_filter(FilterType::PARTICLE))
252✔
568
    filter_types.push_back(FilterType::PARTICLE);
22✔
569

570
  if (!tally->has_filter(FilterType::ENERGY))
252✔
571
    filter_types.push_back(FilterType::ENERGY);
22✔
572

573
  // particle axis mapping
574
  transpose[0] =
252✔
575
    std::find(filter_types.begin(), filter_types.end(), FilterType::PARTICLE) -
252✔
576
    filter_types.begin();
252✔
577

578
  // energy axis mapping
579
  transpose[1] =
252✔
580
    std::find(filter_types.begin(), filter_types.end(), FilterType::ENERGY) -
252✔
581
    filter_types.begin();
252✔
582

583
  // mesh axis mapping
584
  transpose[2] =
252✔
585
    std::find(filter_types.begin(), filter_types.end(), FilterType::MESH) -
252✔
586
    filter_types.begin();
252✔
587

588
  // get a fully reshaped view of the tally according to tally ordering of
589
  // filters
590
  auto tally_values = xt::reshape_view(results_arr, shape);
252✔
591

592
  // get a that is (particle, energy, mesh, scores, values)
593
  auto transposed_view = xt::transpose(tally_values, transpose);
252✔
594

595
  // determine the dimension and index of the particle data
596
  int particle_idx = 0;
252✔
597
  if (tally->has_filter(FilterType::PARTICLE)) {
252✔
598
    // get the particle filter
599
    auto pf = tally->get_filter<ParticleFilter>();
230✔
600
    const auto& particles = pf->particles();
230✔
601

602
    // find the index of the particle that matches these weight windows
603
    auto p_it =
604
      std::find(particles.begin(), particles.end(), this->particle_type_);
230✔
605
    // if the particle filter doesn't have particle data for the particle
606
    // used on this weight windows instance, report an error
607
    if (p_it == particles.end()) {
230!
608
      auto msg = fmt::format("Particle type '{}' not present on Filter {} for "
609
                             "Tally {} used to update WeightWindows {}",
UNCOV
610
        particle_type_to_str(this->particle_type_), pf->id(), tally->id(),
×
UNCOV
611
        this->id());
×
UNCOV
612
      fatal_error(msg);
×
UNCOV
613
    }
×
614

615
    // use the index of the particle in the filter to down-select data later
616
    particle_idx = p_it - particles.begin();
230✔
617
  }
618

619
  // down-select data based on particle and score
620
  auto sum = xt::dynamic_view(
1,260✔
621
    transposed_view, {particle_idx, xt::all(), xt::all(), score_index,
504✔
622
                       static_cast<int>(TallyResult::SUM)});
1,008✔
623
  auto sum_sq = xt::dynamic_view(
1,260✔
624
    transposed_view, {particle_idx, xt::all(), xt::all(), score_index,
504✔
625
                       static_cast<int>(TallyResult::SUM_SQ)});
1,008✔
626
  int n = tally->n_realizations_;
252✔
627

628
  //////////////////////////////////////////////
629
  //
630
  // Assign new weight windows
631
  //
632
  // Use references to the existing weight window data
633
  // to store and update the values
634
  //
635
  //////////////////////////////////////////////
636

637
  // up to this point the data arrays are views into the tally results (no
638
  // computation has been performed) now we'll switch references to the tally's
639
  // bounds to avoid allocating additional memory
640
  auto& new_bounds = this->lower_ww_;
252✔
641
  auto& rel_err = this->upper_ww_;
252✔
642

643
  // get mesh volumes
644
  auto mesh_vols = this->mesh()->volumes();
252✔
645

646
  // Calculate mean (new_bounds) and relative error
647
#pragma omp parallel for collapse(2) schedule(static)
140✔
648
  for (int e = 0; e < e_bins; e++) {
934✔
649
    for (int64_t m = 0; m < mesh_bins; m++) {
1,190,071✔
650
      // Calculate mean
651
      new_bounds(e, m) = sum(e, m) / n;
1,189,249✔
652
      // Calculate relative error
653
      if (sum(e, m) > 0.0) {
1,189,249✔
654
        double mean_val = new_bounds(e, m);
101,480✔
655
        double variance = (sum_sq(e, m) / n - mean_val * mean_val) / (n - 1);
101,480✔
656
        rel_err(e, m) = std::sqrt(variance) / mean_val;
101,480✔
657
      } else {
658
        rel_err(e, m) = INFTY;
1,087,769✔
659
      }
660
      if (value == "rel_err") {
1,189,249✔
661
        new_bounds(e, m) = 1.0 / rel_err(e, m);
345,000✔
662
      }
663
    }
664
  }
665

666
  // Divide by volume of mesh elements
667
#pragma omp parallel for collapse(2) schedule(static)
140✔
668
  for (int e = 0; e < e_bins; e++) {
934✔
669
    for (int64_t m = 0; m < mesh_bins; m++) {
1,190,071✔
670
      new_bounds(e, m) /= mesh_vols[m];
1,189,249✔
671
    }
672
  }
673

674
  if (method == WeightWindowUpdateMethod::MAGIC) {
252✔
675
    // For MAGIC, weight windows are proportional to the forward fluxes.
676
    // We normalize weight windows independently for each energy group.
677

678
    // Find group maximum and normalize (per energy group)
679
    for (int e = 0; e < e_bins; e++) {
1,870✔
680
      double group_max = 0.0;
1,716✔
681

682
      // Find maximum value across all elements in this energy group
683
#pragma omp parallel for schedule(static) reduction(max : group_max)
936✔
684
      for (int64_t m = 0; m < mesh_bins; m++) {
1,092,505✔
685
        if (new_bounds(e, m) > group_max) {
1,091,725✔
686
          group_max = new_bounds(e, m);
2,520✔
687
        }
688
      }
689

690
      // Normalize values in this energy group by the maximum value
691
      if (group_max > 0.0) {
1,716✔
692
        double norm_factor = 1.0 / (2.0 * group_max);
1,683✔
693
#pragma omp parallel for schedule(static)
918✔
694
        for (int64_t m = 0; m < mesh_bins; m++) {
1,091,590✔
695
          new_bounds(e, m) *= norm_factor;
1,090,825✔
696
        }
697
      }
698
    }
699
  } else {
700
    // For FW-CADIS, weight windows are inversely proportional to the adjoint
701
    // fluxes. We normalize the weight windows across all energy groups.
702
#pragma omp parallel for collapse(2) schedule(static)
56✔
703
    for (int e = 0; e < e_bins; e++) {
84✔
704
      for (int64_t m = 0; m < mesh_bins; m++) {
97,566✔
705
        // Take the inverse, but are careful not to divide by zero
706
        if (new_bounds(e, m) != 0.0) {
97,524✔
707
          new_bounds(e, m) = 1.0 / new_bounds(e, m);
69,660✔
708
        } else {
709
          new_bounds(e, m) = 0.0;
27,864!
710
        }
711
      }
712
    }
713

714
    // Find the maximum value across all elements
715
    double max_val = 0.0;
98✔
716
#pragma omp parallel for collapse(2) schedule(static) reduction(max : max_val)
56✔
717
    for (int e = 0; e < e_bins; e++) {
84✔
718
      for (int64_t m = 0; m < mesh_bins; m++) {
97,566✔
719
        if (new_bounds(e, m) > max_val) {
97,524✔
720
          max_val = new_bounds(e, m);
405✔
721
        }
722
      }
723
    }
724

725
    // Parallel normalization
726
    if (max_val > 0.0) {
98✔
727
      double norm_factor = 1.0 / (2.0 * max_val);
68✔
728
#pragma omp parallel for collapse(2) schedule(static)
38✔
729
      for (int e = 0; e < e_bins; e++) {
60✔
730
        for (int64_t m = 0; m < mesh_bins; m++) {
69,690✔
731
          new_bounds(e, m) *= norm_factor;
69,660✔
732
        }
733
      }
734
    }
735
  }
736

737
  // Final processing
738
#pragma omp parallel for collapse(2) schedule(static)
140✔
739
  for (int e = 0; e < e_bins; e++) {
934✔
740
    for (int64_t m = 0; m < mesh_bins; m++) {
1,190,071✔
741
      // Values where the mean is zero should be ignored
742
      if (sum(e, m) <= 0.0) {
1,189,249✔
743
        new_bounds(e, m) = -1.0;
1,087,769✔
744
      }
745
      // Values where the relative error is higher than the threshold should be
746
      // ignored
747
      else if (rel_err(e, m) > threshold) {
101,480✔
748
        new_bounds(e, m) = -1.0;
1,420✔
749
      }
750
      // Set the upper bounds
751
      upper_ww_(e, m) = ratio * lower_ww_(e, m);
1,189,249✔
752
    }
753
  }
754
}
252✔
755

756
void WeightWindows::check_tally_update_compatibility(const Tally* tally)
252✔
757
{
758
  // define the set of allowed filters for the tally
759
  const std::set<FilterType> allowed_filters = {
760
    FilterType::MESH, FilterType::ENERGY, FilterType::PARTICLE};
252✔
761

762
  // retrieve a mapping of filter type to filter index for the tally
763
  auto filter_indices = tally->filter_indices();
252✔
764

765
  // a mesh filter is required for a tally used to update weight windows
766
  if (!filter_indices.count(FilterType::MESH)) {
252!
UNCOV
767
    fatal_error(
×
768
      "A mesh filter is required for a tally to update weight window bounds");
769
  }
770

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

774
  // make sure that all of the filters present on the tally are allowed
775
  for (auto filter_pair : filter_indices) {
964✔
776
    if (allowed_filters.find(filter_pair.first) == allowed_filters.end()) {
712!
UNCOV
777
      fatal_error(fmt::format("Invalid filter type '{}' found on tally "
×
778
                              "used for weight window generation.",
UNCOV
779
        model::tally_filters[tally->filters(filter_pair.second)]->type_str()));
×
780
    }
781
  }
782

783
  if (mesh_filter->mesh() != mesh_idx_) {
252!
UNCOV
784
    int32_t mesh_filter_id = model::meshes[mesh_filter->mesh()]->id();
×
UNCOV
785
    int32_t ww_mesh_id = model::meshes[this->mesh_idx_]->id();
×
UNCOV
786
    fatal_error(fmt::format("Mesh filter {} uses a different mesh ({}) than "
×
787
                            "weight window {} mesh ({})",
UNCOV
788
      mesh_filter->id(), mesh_filter_id, id_, ww_mesh_id));
×
789
  }
790

791
  // if an energy filter exists, make sure the energy grid matches that of this
792
  // weight window object
793
  if (auto energy_filter = tally->get_filter<EnergyFilter>()) {
252✔
794
    std::vector<double> filter_bins = energy_filter->bins();
230✔
795
    std::set<double> filter_e_bounds(
796
      energy_filter->bins().begin(), energy_filter->bins().end());
230✔
797
    if (filter_e_bounds.size() != energy_bounds().size()) {
230!
UNCOV
798
      fatal_error(
×
UNCOV
799
        fmt::format("Energy filter {} does not have the same number of energy "
×
800
                    "bounds ({}) as weight window object {} ({})",
UNCOV
801
          energy_filter->id(), filter_e_bounds.size(), id_,
×
UNCOV
802
          energy_bounds().size()));
×
803
    }
804

805
    for (auto e : energy_bounds()) {
2,252✔
806
      if (filter_e_bounds.count(e) == 0) {
2,022!
UNCOV
807
        fatal_error(fmt::format(
×
808
          "Energy bounds of filter {} and weight windows {} do not match",
UNCOV
809
          energy_filter->id(), id_));
×
810
      }
811
    }
812
  }
230✔
813
}
252✔
814

815
void WeightWindows::to_hdf5(hid_t group) const
134✔
816
{
817
  hid_t ww_group = create_group(group, fmt::format("weight_windows_{}", id()));
268✔
818

819
  write_dataset(ww_group, "mesh", this->mesh()->id());
134✔
820
  write_dataset(
134✔
821
    ww_group, "particle_type", openmc::particle_type_to_str(particle_type_));
268✔
822
  write_dataset(ww_group, "energy_bounds", energy_bounds_);
134✔
823
  write_dataset(ww_group, "lower_ww_bounds", lower_ww_);
134✔
824
  write_dataset(ww_group, "upper_ww_bounds", upper_ww_);
134✔
825
  write_dataset(ww_group, "survival_ratio", survival_ratio_);
134✔
826
  write_dataset(ww_group, "max_lower_bound_ratio", max_lb_ratio_);
134✔
827
  write_dataset(ww_group, "max_split", max_split_);
134✔
828
  write_dataset(ww_group, "weight_cutoff", weight_cutoff_);
134✔
829

830
  close_group(ww_group);
134✔
831
}
134✔
832

833
WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node)
82✔
834
{
835
  // read information from the XML node
836
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
82✔
837
  int32_t mesh_idx = model::mesh_map[mesh_id];
82✔
838
  max_realizations_ = std::stoi(get_node_value(node, "max_realizations"));
82✔
839

840
  int32_t active_batches = settings::n_batches - settings::n_inactive;
82✔
841
  if (max_realizations_ > active_batches) {
82✔
842
    auto msg =
843
      fmt::format("The maximum number of specified tally realizations ({}) is "
844
                  "greater than the number of active batches ({}).",
845
        max_realizations_, active_batches);
31✔
846
    warning(msg);
17✔
847
  }
17✔
848
  auto tmp_str = get_node_value(node, "particle_type", true, true);
82✔
849
  auto particle_type = str_to_particle_type(tmp_str);
82✔
850

851
  update_interval_ = std::stoi(get_node_value(node, "update_interval"));
82✔
852
  on_the_fly_ = get_node_value_bool(node, "on_the_fly");
82✔
853

854
  std::vector<double> e_bounds;
82✔
855
  if (check_for_node(node, "energy_bounds")) {
82✔
856
    e_bounds = get_node_array<double>(node, "energy_bounds");
23✔
857
  } else {
858
    int p_type = static_cast<int>(particle_type);
59✔
859
    e_bounds.push_back(data::energy_min[p_type]);
59✔
860
    e_bounds.push_back(data::energy_max[p_type]);
59✔
861
  }
862

863
  // set method
864
  std::string method_string = get_node_value(node, "method");
82✔
865
  if (method_string == "magic") {
82✔
866
    method_ = WeightWindowUpdateMethod::MAGIC;
33✔
867
    if (settings::solver_type == SolverType::RANDOM_RAY &&
33!
868
        FlatSourceDomain::adjoint_) {
UNCOV
869
      fatal_error("Random ray weight window generation with MAGIC cannot be "
×
870
                  "done in adjoint mode.");
871
    }
872
  } else if (method_string == "fw_cadis") {
49!
873
    method_ = WeightWindowUpdateMethod::FW_CADIS;
49✔
874
    if (settings::solver_type != SolverType::RANDOM_RAY) {
49!
UNCOV
875
      fatal_error("FW-CADIS can only be run in random ray solver mode.");
×
876
    }
877
    FlatSourceDomain::adjoint_ = true;
49✔
878
  } else {
UNCOV
879
    fatal_error(fmt::format(
×
880
      "Unknown weight window update method '{}' specified", method_string));
881
  }
882

883
  // parse non-default update parameters if specified
884
  if (check_for_node(node, "update_parameters")) {
82✔
885
    pugi::xml_node params_node = node.child("update_parameters");
22✔
886
    if (check_for_node(params_node, "value"))
22!
887
      tally_value_ = get_node_value(params_node, "value");
22✔
888
    if (check_for_node(params_node, "threshold"))
22!
889
      threshold_ = std::stod(get_node_value(params_node, "threshold"));
22✔
890
    if (check_for_node(params_node, "ratio")) {
22!
891
      ratio_ = std::stod(get_node_value(params_node, "ratio"));
22✔
892
    }
893
  }
894

895
  // check update parameter values
896
  if (tally_value_ != "mean" && tally_value_ != "rel_err") {
82!
UNCOV
897
    fatal_error(fmt::format("Unsupported tally value '{}' specified for "
×
898
                            "weight window generation.",
UNCOV
899
      tally_value_));
×
900
  }
901
  if (threshold_ <= 0.0)
82!
UNCOV
902
    fatal_error(fmt::format("Invalid relative error threshold '{}' (<= 0.0) "
×
903
                            "specified for weight window generation",
UNCOV
904
      ratio_));
×
905
  if (ratio_ <= 1.0)
82!
UNCOV
906
    fatal_error(fmt::format("Invalid weight window ratio '{}' (<= 1.0) "
×
907
                            "specified for weight window generation"));
908

909
  // create a matching weight windows object
910
  auto wws = WeightWindows::create();
82✔
911
  ww_idx_ = wws->index();
82✔
912
  wws->set_mesh(mesh_idx);
82✔
913
  if (e_bounds.size() > 0)
82!
914
    wws->set_energy_bounds(e_bounds);
82✔
915
  wws->set_particle_type(particle_type);
82✔
916
  wws->set_defaults();
82✔
917
}
82✔
918

919
void WeightWindowsGenerator::create_tally()
82✔
920
{
921
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
82✔
922

923
  // create a tally based on the WWG information
924
  Tally* ww_tally = Tally::create();
82✔
925
  tally_idx_ = model::tally_map[ww_tally->id()];
82✔
926
  ww_tally->set_scores({"flux"});
164!
927

928
  int32_t mesh_id = wws->mesh()->id();
82✔
929
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
82✔
930
  // see if there's already a mesh filter using this mesh
931
  bool found_mesh_filter = false;
82✔
932
  for (const auto& f : model::tally_filters) {
259✔
933
    if (f->type() == FilterType::MESH) {
188✔
934
      const auto* mesh_filter = dynamic_cast<MeshFilter*>(f.get());
11!
935
      if (mesh_filter->mesh() == mesh_idx && !mesh_filter->translated()) {
11!
936
        ww_tally->add_filter(f.get());
11✔
937
        found_mesh_filter = true;
11✔
938
        break;
11✔
939
      }
940
    }
941
  }
942

943
  if (!found_mesh_filter) {
82✔
944
    auto mesh_filter = Filter::create("mesh");
71✔
945
    openmc_mesh_filter_set_mesh(mesh_filter->index(), model::mesh_map[mesh_id]);
71✔
946
    ww_tally->add_filter(mesh_filter);
71✔
947
  }
948

949
  const auto& e_bounds = wws->energy_bounds();
82✔
950
  if (e_bounds.size() > 0) {
82!
951
    auto energy_filter = Filter::create("energy");
82✔
952
    openmc_energy_filter_set_bins(
164✔
953
      energy_filter->index(), e_bounds.size(), e_bounds.data());
82✔
954
    ww_tally->add_filter(energy_filter);
82✔
955
  }
956

957
  // add a particle filter
958
  auto particle_type = wws->particle_type();
82✔
959
  auto particle_filter = Filter::create("particle");
82✔
960
  auto pf = dynamic_cast<ParticleFilter*>(particle_filter);
82!
961
  pf->set_particles({&particle_type, 1});
82✔
962
  ww_tally->add_filter(particle_filter);
82✔
963
}
82✔
964

965
void WeightWindowsGenerator::update() const
263✔
966
{
967
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
263✔
968

969
  Tally* tally = model::tallies[tally_idx_].get();
263✔
970

971
  // if we're beyond the number of max realizations or not at the corrrect
972
  // update interval, skip the update
973
  if (max_realizations_ < tally->n_realizations_ ||
263✔
974
      tally->n_realizations_ % update_interval_ != 0)
131!
975
    return;
132✔
976

977
  wws->update_weights(tally, tally_value_, threshold_, ratio_, method_);
131✔
978

979
  // if we're not doing on the fly generation, reset the tally results once
980
  // we're done with the update
981
  if (!on_the_fly_)
131!
UNCOV
982
    tally->reset();
×
983

984
  // TODO: deactivate or remove tally once weight window generation is
985
  // complete
986
}
987

988
//==============================================================================
989
// Non-member functions
990
//==============================================================================
991

992
void finalize_variance_reduction()
7,465✔
993
{
994
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
7,547✔
995
    wwg->create_tally();
82✔
996
  }
997
}
7,465✔
998

999
//==============================================================================
1000
// C API
1001
//==============================================================================
1002

1003
int verify_ww_index(int32_t index)
1,991✔
1004
{
1005
  if (index < 0 || index >= variance_reduction::weight_windows.size()) {
1,991!
UNCOV
1006
    set_errmsg(fmt::format("Index '{}' for weight windows is invalid", index));
×
UNCOV
1007
    return OPENMC_E_OUT_OF_BOUNDS;
×
1008
  }
1009
  return 0;
1,991✔
1010
}
1011

1012
extern "C" int openmc_get_weight_windows_index(int32_t id, int32_t* idx)
165✔
1013
{
1014
  auto it = variance_reduction::ww_map.find(id);
165✔
1015
  if (it == variance_reduction::ww_map.end()) {
165!
UNCOV
1016
    set_errmsg(fmt::format("No weight windows exist with ID={}", id));
×
UNCOV
1017
    return OPENMC_E_INVALID_ID;
×
1018
  }
1019

1020
  *idx = it->second;
165✔
1021
  return 0;
165✔
1022
}
1023

1024
extern "C" int openmc_weight_windows_get_id(int32_t index, int32_t* id)
517✔
1025
{
1026
  if (int err = verify_ww_index(index))
517!
UNCOV
1027
    return err;
×
1028

1029
  const auto& wws = variance_reduction::weight_windows.at(index);
517✔
1030
  *id = wws->id();
517✔
1031
  return 0;
517✔
1032
}
1033

1034
extern "C" int openmc_weight_windows_set_id(int32_t index, int32_t id)
154✔
1035
{
1036
  if (int err = verify_ww_index(index))
154!
UNCOV
1037
    return err;
×
1038

1039
  const auto& wws = variance_reduction::weight_windows.at(index);
154✔
1040
  wws->set_id(id);
154✔
1041
  return 0;
154✔
1042
}
1043

1044
extern "C" int openmc_weight_windows_update_magic(int32_t ww_idx,
121✔
1045
  int32_t tally_idx, const char* value, double threshold, double ratio)
1046
{
1047
  if (int err = verify_ww_index(ww_idx))
121!
UNCOV
1048
    return err;
×
1049

1050
  if (tally_idx < 0 || tally_idx >= model::tallies.size()) {
121!
UNCOV
1051
    set_errmsg(fmt::format("Index '{}' for tally is invalid", tally_idx));
×
UNCOV
1052
    return OPENMC_E_OUT_OF_BOUNDS;
×
1053
  }
1054

1055
  // get the requested tally
1056
  const Tally* tally = model::tallies.at(tally_idx).get();
121✔
1057

1058
  // get the WeightWindows object
1059
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
121✔
1060

1061
  wws->update_weights(tally, value, threshold, ratio);
121✔
1062

1063
  return 0;
121✔
1064
}
1065

1066
extern "C" int openmc_weight_windows_set_mesh(int32_t ww_idx, int32_t mesh_idx)
154✔
1067
{
1068
  if (int err = verify_ww_index(ww_idx))
154!
UNCOV
1069
    return err;
×
1070
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
154✔
1071
  wws->set_mesh(mesh_idx);
154✔
1072
  return 0;
154✔
1073
}
1074

1075
extern "C" int openmc_weight_windows_get_mesh(int32_t ww_idx, int32_t* mesh_idx)
11✔
1076
{
1077
  if (int err = verify_ww_index(ww_idx))
11!
UNCOV
1078
    return err;
×
1079
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
11✔
1080
  *mesh_idx = model::mesh_map.at(wws->mesh()->id());
11✔
1081
  return 0;
11✔
1082
}
1083

1084
extern "C" int openmc_weight_windows_set_energy_bounds(
132✔
1085
  int32_t ww_idx, double* e_bounds, size_t e_bounds_size)
1086
{
1087
  if (int err = verify_ww_index(ww_idx))
132!
UNCOV
1088
    return err;
×
1089
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
132✔
1090
  wws->set_energy_bounds({e_bounds, e_bounds_size});
132✔
1091
  return 0;
132✔
1092
}
1093

1094
extern "C" int openmc_weight_windows_get_energy_bounds(
11✔
1095
  int32_t ww_idx, const double** e_bounds, size_t* e_bounds_size)
1096
{
1097
  if (int err = verify_ww_index(ww_idx))
11!
UNCOV
1098
    return err;
×
1099
  const auto& wws = variance_reduction::weight_windows[ww_idx].get();
11✔
1100
  *e_bounds = wws->energy_bounds().data();
11✔
1101
  *e_bounds_size = wws->energy_bounds().size();
11✔
1102
  return 0;
11✔
1103
}
1104

1105
extern "C" int openmc_weight_windows_set_particle(int32_t index, int particle)
176✔
1106
{
1107
  if (int err = verify_ww_index(index))
176!
UNCOV
1108
    return err;
×
1109

1110
  const auto& wws = variance_reduction::weight_windows.at(index);
176✔
1111
  wws->set_particle_type(static_cast<ParticleType>(particle));
176✔
1112
  return 0;
176✔
1113
}
1114

1115
extern "C" int openmc_weight_windows_get_particle(int32_t index, int* particle)
44✔
1116
{
1117
  if (int err = verify_ww_index(index))
44!
UNCOV
1118
    return err;
×
1119

1120
  const auto& wws = variance_reduction::weight_windows.at(index);
44✔
1121
  *particle = static_cast<int>(wws->particle_type());
44✔
1122
  return 0;
44✔
1123
}
1124

1125
extern "C" int openmc_weight_windows_get_bounds(int32_t index,
484✔
1126
  const double** lower_bounds, const double** upper_bounds, size_t* size)
1127
{
1128
  if (int err = verify_ww_index(index))
484!
UNCOV
1129
    return err;
×
1130

1131
  const auto& wws = variance_reduction::weight_windows[index];
484✔
1132
  *size = wws->lower_ww_bounds().size();
484✔
1133
  *lower_bounds = wws->lower_ww_bounds().data();
484✔
1134
  *upper_bounds = wws->upper_ww_bounds().data();
484✔
1135
  return 0;
484✔
1136
}
1137

1138
extern "C" int openmc_weight_windows_set_bounds(int32_t index,
11✔
1139
  const double* lower_bounds, const double* upper_bounds, size_t size)
1140
{
1141
  if (int err = verify_ww_index(index))
11!
UNCOV
1142
    return err;
×
1143

1144
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1145
  wws->set_bounds({lower_bounds, size}, {upper_bounds, size});
11✔
1146
  return 0;
11✔
1147
}
1148

1149
extern "C" int openmc_weight_windows_get_survival_ratio(
33✔
1150
  int32_t index, double* ratio)
1151
{
1152
  if (int err = verify_ww_index(index))
33!
UNCOV
1153
    return err;
×
1154
  const auto& wws = variance_reduction::weight_windows[index];
33✔
1155
  *ratio = wws->survival_ratio();
33✔
1156
  return 0;
33✔
1157
}
1158

1159
extern "C" int openmc_weight_windows_set_survival_ratio(
11✔
1160
  int32_t index, double ratio)
1161
{
1162
  if (int err = verify_ww_index(index))
11!
UNCOV
1163
    return err;
×
1164
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1165
  wws->survival_ratio() = ratio;
11✔
1166
  std::cout << "Survival ratio: " << wws->survival_ratio() << std::endl;
11✔
1167
  return 0;
11✔
1168
}
1169

1170
extern "C" int openmc_weight_windows_get_max_lower_bound_ratio(
33✔
1171
  int32_t index, double* lb_ratio)
1172
{
1173
  if (int err = verify_ww_index(index))
33!
UNCOV
1174
    return err;
×
1175
  const auto& wws = variance_reduction::weight_windows[index];
33✔
1176
  *lb_ratio = wws->max_lower_bound_ratio();
33✔
1177
  return 0;
33✔
1178
}
1179

1180
extern "C" int openmc_weight_windows_set_max_lower_bound_ratio(
11✔
1181
  int32_t index, double lb_ratio)
1182
{
1183
  if (int err = verify_ww_index(index))
11!
UNCOV
1184
    return err;
×
1185
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1186
  wws->max_lower_bound_ratio() = lb_ratio;
11✔
1187
  return 0;
11✔
1188
}
1189

1190
extern "C" int openmc_weight_windows_get_weight_cutoff(
33✔
1191
  int32_t index, double* cutoff)
1192
{
1193
  if (int err = verify_ww_index(index))
33!
UNCOV
1194
    return err;
×
1195
  const auto& wws = variance_reduction::weight_windows[index];
33✔
1196
  *cutoff = wws->weight_cutoff();
33✔
1197
  return 0;
33✔
1198
}
1199

1200
extern "C" int openmc_weight_windows_set_weight_cutoff(
11✔
1201
  int32_t index, double cutoff)
1202
{
1203
  if (int err = verify_ww_index(index))
11!
UNCOV
1204
    return err;
×
1205
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1206
  wws->weight_cutoff() = cutoff;
11✔
1207
  return 0;
11✔
1208
}
1209

1210
extern "C" int openmc_weight_windows_get_max_split(
33✔
1211
  int32_t index, int* max_split)
1212
{
1213
  if (int err = verify_ww_index(index))
33!
UNCOV
1214
    return err;
×
1215
  const auto& wws = variance_reduction::weight_windows[index];
33✔
1216
  *max_split = wws->max_split();
33✔
1217
  return 0;
33✔
1218
}
1219

1220
extern "C" int openmc_weight_windows_set_max_split(int32_t index, int max_split)
11✔
1221
{
1222
  if (int err = verify_ww_index(index))
11!
UNCOV
1223
    return err;
×
1224
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1225
  wws->max_split() = max_split;
11✔
1226
  return 0;
11✔
1227
}
1228

1229
extern "C" int openmc_extend_weight_windows(
154✔
1230
  int32_t n, int32_t* index_start, int32_t* index_end)
1231
{
1232
  if (index_start)
154!
1233
    *index_start = variance_reduction::weight_windows.size();
154✔
1234
  if (index_end)
154!
UNCOV
1235
    *index_end = variance_reduction::weight_windows.size() + n - 1;
×
1236
  for (int i = 0; i < n; ++i)
308✔
1237
    variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
154✔
1238
  return 0;
154✔
1239
}
1240

1241
extern "C" size_t openmc_weight_windows_size()
154✔
1242
{
1243
  return variance_reduction::weight_windows.size();
154✔
1244
}
1245

1246
extern "C" int openmc_weight_windows_export(const char* filename)
164✔
1247
{
1248

1249
  if (!mpi::master)
164✔
1250
    return 0;
30✔
1251

1252
  std::string name = filename ? filename : "weight_windows.h5";
268✔
1253

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

1256
  hid_t ww_file = file_open(name, 'w');
134✔
1257

1258
  // Write file type
1259
  write_attribute(ww_file, "filetype", "weight_windows");
134✔
1260

1261
  // Write revisiion number for state point file
1262
  write_attribute(ww_file, "version", VERSION_WEIGHT_WINDOWS);
134✔
1263

1264
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
134✔
1265

1266
  hid_t mesh_group = create_group(ww_file, "meshes");
134✔
1267

1268
  std::vector<int32_t> mesh_ids;
134✔
1269
  std::vector<int32_t> ww_ids;
134✔
1270
  for (const auto& ww : variance_reduction::weight_windows) {
268✔
1271

1272
    ww->to_hdf5(weight_windows_group);
134✔
1273
    ww_ids.push_back(ww->id());
134✔
1274

1275
    // if the mesh has already been written, move on
1276
    int32_t mesh_id = ww->mesh()->id();
134✔
1277
    if (std::find(mesh_ids.begin(), mesh_ids.end(), mesh_id) != mesh_ids.end())
134!
UNCOV
1278
      continue;
×
1279

1280
    mesh_ids.push_back(mesh_id);
134✔
1281
    ww->mesh()->to_hdf5(mesh_group);
134✔
1282
  }
1283

1284
  write_attribute(mesh_group, "n_meshes", mesh_ids.size());
134✔
1285
  write_attribute(mesh_group, "ids", mesh_ids);
134✔
1286
  close_group(mesh_group);
134✔
1287

1288
  write_attribute(weight_windows_group, "n_weight_windows", ww_ids.size());
134✔
1289
  write_attribute(weight_windows_group, "ids", ww_ids);
134✔
1290
  close_group(weight_windows_group);
134✔
1291

1292
  file_close(ww_file);
134✔
1293

1294
  return 0;
134✔
1295
}
134✔
1296

1297
extern "C" int openmc_weight_windows_import(const char* filename)
11✔
1298
{
1299
  std::string name = filename ? filename : "weight_windows.h5";
11!
1300

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

1304
  if (!file_exists(name)) {
11!
UNCOV
1305
    set_errmsg(fmt::format("File '{}' does not exist", name));
×
1306
  }
1307

1308
  hid_t ww_file = file_open(name, 'r');
11✔
1309

1310
  // Check that filetype is correct
1311
  std::string filetype;
11✔
1312
  read_attribute(ww_file, "filetype", filetype);
11✔
1313
  if (filetype != "weight_windows") {
11!
UNCOV
1314
    file_close(ww_file);
×
UNCOV
1315
    set_errmsg(fmt::format("File '{}' is not a weight windows file.", name));
×
UNCOV
1316
    return OPENMC_E_INVALID_ARGUMENT;
×
1317
  }
1318

1319
  // Check that the file version is compatible
1320
  std::array<int, 2> file_version;
1321
  read_attribute(ww_file, "version", file_version);
11✔
1322
  if (file_version[0] != VERSION_WEIGHT_WINDOWS[0]) {
11!
1323
    std::string err_msg =
1324
      fmt::format("File '{}' has version {} which is incompatible with the "
1325
                  "expected version ({}).",
1326
        name, file_version, VERSION_WEIGHT_WINDOWS);
×
UNCOV
1327
    set_errmsg(err_msg);
×
UNCOV
1328
    return OPENMC_E_INVALID_ARGUMENT;
×
UNCOV
1329
  }
×
1330

1331
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
11✔
1332

1333
  std::vector<std::string> names = group_names(weight_windows_group);
11✔
1334

1335
  for (const auto& name : names) {
22✔
1336
    WeightWindows::from_hdf5(weight_windows_group, name);
11✔
1337
  }
1338

1339
  close_group(weight_windows_group);
11✔
1340

1341
  file_close(ww_file);
11✔
1342

1343
  return 0;
11✔
1344
}
11✔
1345

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