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

openmc-dev / openmc / 18875412062

28 Oct 2025 12:53PM UTC coverage: 81.805% (+0.001%) from 81.804%
18875412062

Pull #3618

github

web-flow
Merge d145e08f9 into f10d7d9f6
Pull Request #3618: Updates all `check_type('filename', filename, str)` calls to accept both `str` and `os.PathLike` objects.

16651 of 23259 branches covered (71.59%)

Branch coverage included in aggregate %.

8 of 11 new or added lines in 5 files covered. (72.73%)

89 existing lines in 2 files now uncovered.

53799 of 62860 relevant lines covered (85.59%)

43335951.24 hits per line

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

78.72
/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
// Non-member functions
54
//==============================================================================
55

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

61
  // WW on photon and neutron only
62
  if (p.type() != ParticleType::neutron && p.type() != ParticleType::photon)
87,137,247✔
63
    return;
10,927,789✔
64

65
  // skip dead or no energy
66
  if (p.E() <= 0 || !p.alive())
76,209,458✔
67
    return;
4,202,490✔
68

69
  bool in_domain = false;
72,006,968✔
70
  // TODO: this is a linear search - should do something more clever
71
  WeightWindow weight_window;
72,006,968✔
72
  for (const auto& ww : variance_reduction::weight_windows) {
89,585,022✔
73
    weight_window = ww->get_weight_window(p);
76,055,584✔
74
    if (weight_window.is_valid())
76,055,584✔
75
      break;
58,477,530✔
76
  }
77

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

89
  // particle is not in any of the ww domains, do nothing
90
  if (!weight_window.is_valid())
72,006,968✔
91
    return;
13,529,438✔
92

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

97
  // get the paramters
98
  double weight = p.wgt();
58,477,530✔
99

100
  // first check to see if particle should be killed for weight cutoff
101
  if (p.wgt() < weight_window.weight_cutoff) {
58,477,530!
102
    p.wgt() = 0.0;
×
UNCOV
103
    return;
×
104
  }
105

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

115
  // move weight window closer to the particle weight if needed
116
  if (p.ww_factor() > 1.0)
58,477,530✔
117
    weight_window.scale(p.ww_factor());
1,356,443✔
118

119
  // if particle's weight is above the weight window split until they are within
120
  // the window
121
  if (weight > weight_window.upper_weight) {
58,477,530✔
122
    // do not further split the particle if above the limit
123
    if (p.n_split() >= settings::max_history_splits)
15,082,185✔
124
      return;
13,696,475✔
125

126
    double n_split = std::ceil(weight / weight_window.upper_weight);
1,385,710✔
127
    double max_split = weight_window.max_split;
1,385,710✔
128
    n_split = std::min(n_split, max_split);
1,385,710✔
129

130
    p.n_split() += n_split;
1,385,710✔
131

132
    // Create secondaries and divide weight among all particles
133
    int i_split = std::round(n_split);
1,385,710✔
134
    for (int l = 0; l < i_split - 1; l++) {
5,629,485✔
135
      p.split(weight / n_split);
4,243,775✔
136
    }
137
    // remaining weight is applied to current particle
138
    p.wgt() = weight / n_split;
1,385,710✔
139

140
  } else if (weight <= weight_window.lower_weight) {
43,395,345✔
141
    // if the particle weight is below the window, play Russian roulette
142
    double weight_survive =
143
      std::min(weight * weight_window.max_split, weight_window.survival_weight);
1,346,999✔
144
    russian_roulette(p, weight_survive);
1,346,999✔
145
  } // else particle is in the window, continue as normal
146
}
147

148
void free_memory_weight_windows()
8,063✔
149
{
150
  variance_reduction::ww_map.clear();
8,063✔
151
  variance_reduction::weight_windows.clear();
8,063✔
152
}
8,063✔
153

154
//==============================================================================
155
// WeightWindowSettings implementation
156
//==============================================================================
157

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

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

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

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

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

188
  // energy bounds
189
  if (check_for_node(node, "energy_bounds"))
95✔
190
    energy_bounds_ = get_node_array<double>(node, "energy_bounds");
81✔
191

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

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

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

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

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

228
  set_defaults();
95✔
229
}
95✔
230

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

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

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

251
  auto wws = WeightWindows::create();
13✔
252

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

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

259
  int32_t mesh_id;
260
  read_dataset(ww_group, "mesh", mesh_id);
13✔
261

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

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

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

278
  close_group(ww_group);
13✔
279

280
  return wws;
13✔
281
}
13✔
282

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

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

307
void WeightWindows::set_id(int32_t id)
554✔
308
{
309
  assert(id >= 0 || id == C_NONE);
463!
310

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

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

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

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

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

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

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

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

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

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

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

382
  // Get mesh index for particle's position
383
  const auto& mesh = this->mesh();
72,182,748✔
384
  int mesh_bin = mesh->get_bin(p.r());
72,182,748✔
385

386
  // particle is outside the weight window mesh
387
  if (mesh_bin < 0)
72,182,748!
UNCOV
388
    return {};
×
389

390
  // particle energy
391
  double E = p.E();
72,182,748✔
392

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

397
  // get the mesh bin in energy group
398
  int energy_bin =
399
    lower_bound_index(energy_bounds_.begin(), energy_bounds_.end(), E);
72,090,150✔
400

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

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

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

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

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

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

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

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

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

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

479
  // set new weight window values
480
  xt::view(lower_ww_, xt::all()) =
216✔
481
    xt::adapt(lower_bounds.data(), lower_ww_.shape());
324✔
482
  xt::view(upper_ww_, xt::all()) =
216✔
483
    xt::adapt(upper_bounds.data(), upper_ww_.shape());
324✔
484
}
108✔
485

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

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

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

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

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

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

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

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

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

548
  // build a shape for a view of the tally results, this will always be
549
  // dimension 5 (3 filter dimensions, 1 score dimension, 1 results dimension)
550
  std::array<int, 5> shape = {
274✔
551
    1, 1, 1, tally->n_scores(), static_cast<int>(TallyResult::SIZE)};
274✔
552

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

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

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

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

569
  if (!tally->has_filter(FilterType::ENERGY))
274✔
570
    filter_types.push_back(FilterType::ENERGY);
26✔
571

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

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

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

587
  // get a fully reshaped view of the tally according to tally ordering of
588
  // filters
589
  auto tally_values = xt::reshape_view(tally->results(), shape);
274✔
590

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

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

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

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

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

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

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

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

645
  // Calculate mean (new_bounds) and relative error
646
#pragma omp parallel for collapse(2) schedule(static)
140✔
647
  for (int e = 0; e < e_bins; e++) {
990✔
648
    for (int64_t m = 0; m < mesh_bins; m++) {
1,350,545✔
649
      // Calculate mean
650
      new_bounds(e, m) = sum(e, m) / n;
1,349,689✔
651
      // Calculate relative error
652
      if (sum(e, m) > 0.0) {
1,349,689✔
653
        double mean_val = new_bounds(e, m);
109,804✔
654
        double variance = (sum_sq(e, m) / n - mean_val * mean_val) / (n - 1);
109,804✔
655
        rel_err(e, m) = std::sqrt(variance) / mean_val;
109,804✔
656
      } else {
657
        rel_err(e, m) = INFTY;
1,239,885✔
658
      }
659
      if (value == "rel_err") {
1,349,689✔
660
        new_bounds(e, m) = 1.0 / rel_err(e, m);
345,000✔
661
      }
662
    }
663
  }
664

665
  // Divide by volume of mesh elements
666
#pragma omp parallel for collapse(2) schedule(static)
140✔
667
  for (int e = 0; e < e_bins; e++) {
990✔
668
    for (int64_t m = 0; m < mesh_bins; m++) {
1,350,545✔
669
      new_bounds(e, m) /= mesh_vols[m];
1,349,689✔
670
    }
671
  }
672

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

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

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

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

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

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

736
  // Final processing
737
#pragma omp parallel for collapse(2) schedule(static)
140✔
738
  for (int e = 0; e < e_bins; e++) {
990✔
739
    for (int64_t m = 0; m < mesh_bins; m++) {
1,350,545✔
740
      // Values where the mean is zero should be ignored
741
      if (sum(e, m) <= 0.0) {
1,349,689✔
742
        new_bounds(e, m) = -1.0;
1,239,885✔
743
      }
744
      // Values where the relative error is higher than the threshold should be
745
      // ignored
746
      else if (rel_err(e, m) > threshold) {
109,804✔
747
        new_bounds(e, m) = -1.0;
1,988✔
748
      }
749
      // Set the upper bounds
750
      upper_ww_(e, m) = ratio * lower_ww_(e, m);
1,349,689✔
751
    }
752
  }
753
}
274✔
754

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

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

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

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

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

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

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

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

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

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

829
  close_group(ww_group);
140✔
830
}
140✔
831

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

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

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

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

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

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

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

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

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

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

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

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

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

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

964
void WeightWindowsGenerator::update() const
2,417✔
965
{
966
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
2,417✔
967

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

970
  // If in random ray mode, only update on the last batch
971
  if (settings::solver_type == SolverType::RANDOM_RAY) {
2,417✔
972
    if (simulation::current_batch != settings::n_batches) {
2,252✔
973
      return;
2,154✔
974
    }
975
    // If in Monte Carlo mode and beyond the number of max realizations or
976
    // not at the correct update interval, skip the update
977
  } else if (max_realizations_ < tally->n_realizations_ ||
165✔
978
             tally->n_realizations_ % update_interval_ != 0) {
33!
979
    return;
132✔
980
  }
981

982
  wws->update_weights(tally, tally_value_, threshold_, ratio_, method_);
131✔
983

984
  // if we're not doing on the fly generation, reset the tally results once
985
  // we're done with the update
986
  if (!on_the_fly_)
131!
UNCOV
987
    tally->reset();
×
988

989
  // TODO: deactivate or remove tally once weight window generation is
990
  // complete
991
}
992

993
//==============================================================================
994
// Non-member functions
995
//==============================================================================
996

997
void finalize_variance_reduction()
7,720✔
998
{
999
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
7,802✔
1000
    wwg->create_tally();
82✔
1001
  }
1002
}
7,720✔
1003

1004
//==============================================================================
1005
// C API
1006
//==============================================================================
1007

1008
int verify_ww_index(int32_t index)
2,353✔
1009
{
1010
  if (index < 0 || index >= variance_reduction::weight_windows.size()) {
2,353!
UNCOV
1011
    set_errmsg(fmt::format("Index '{}' for weight windows is invalid", index));
×
UNCOV
1012
    return OPENMC_E_OUT_OF_BOUNDS;
×
1013
  }
1014
  return 0;
2,353✔
1015
}
1016

1017
extern "C" int openmc_get_weight_windows_index(int32_t id, int32_t* idx)
195✔
1018
{
1019
  auto it = variance_reduction::ww_map.find(id);
195✔
1020
  if (it == variance_reduction::ww_map.end()) {
195!
UNCOV
1021
    set_errmsg(fmt::format("No weight windows exist with ID={}", id));
×
UNCOV
1022
    return OPENMC_E_INVALID_ID;
×
1023
  }
1024

1025
  *idx = it->second;
195✔
1026
  return 0;
195✔
1027
}
1028

1029
extern "C" int openmc_weight_windows_get_id(int32_t index, int32_t* id)
611✔
1030
{
1031
  if (int err = verify_ww_index(index))
611!
UNCOV
1032
    return err;
×
1033

1034
  const auto& wws = variance_reduction::weight_windows.at(index);
611✔
1035
  *id = wws->id();
611✔
1036
  return 0;
611✔
1037
}
1038

1039
extern "C" int openmc_weight_windows_set_id(int32_t index, int32_t id)
182✔
1040
{
1041
  if (int err = verify_ww_index(index))
182!
UNCOV
1042
    return err;
×
1043

1044
  const auto& wws = variance_reduction::weight_windows.at(index);
182✔
1045
  wws->set_id(id);
182✔
1046
  return 0;
182✔
1047
}
1048

1049
extern "C" int openmc_weight_windows_update_magic(int32_t ww_idx,
143✔
1050
  int32_t tally_idx, const char* value, double threshold, double ratio)
1051
{
1052
  if (int err = verify_ww_index(ww_idx))
143!
UNCOV
1053
    return err;
×
1054

1055
  if (tally_idx < 0 || tally_idx >= model::tallies.size()) {
143!
UNCOV
1056
    set_errmsg(fmt::format("Index '{}' for tally is invalid", tally_idx));
×
UNCOV
1057
    return OPENMC_E_OUT_OF_BOUNDS;
×
1058
  }
1059

1060
  // get the requested tally
1061
  const Tally* tally = model::tallies.at(tally_idx).get();
143✔
1062

1063
  // get the WeightWindows object
1064
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
143✔
1065

1066
  wws->update_weights(tally, value, threshold, ratio);
143✔
1067

1068
  return 0;
143✔
1069
}
1070

1071
extern "C" int openmc_weight_windows_set_mesh(int32_t ww_idx, int32_t mesh_idx)
182✔
1072
{
1073
  if (int err = verify_ww_index(ww_idx))
182!
UNCOV
1074
    return err;
×
1075
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
182✔
1076
  wws->set_mesh(mesh_idx);
182✔
1077
  return 0;
182✔
1078
}
1079

1080
extern "C" int openmc_weight_windows_get_mesh(int32_t ww_idx, int32_t* mesh_idx)
13✔
1081
{
1082
  if (int err = verify_ww_index(ww_idx))
13!
UNCOV
1083
    return err;
×
1084
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
13✔
1085
  *mesh_idx = model::mesh_map.at(wws->mesh()->id());
13✔
1086
  return 0;
13✔
1087
}
1088

1089
extern "C" int openmc_weight_windows_set_energy_bounds(
156✔
1090
  int32_t ww_idx, double* e_bounds, size_t e_bounds_size)
1091
{
1092
  if (int err = verify_ww_index(ww_idx))
156!
UNCOV
1093
    return err;
×
1094
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
156✔
1095
  wws->set_energy_bounds({e_bounds, e_bounds_size});
156✔
1096
  return 0;
156✔
1097
}
1098

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

1110
extern "C" int openmc_weight_windows_set_particle(int32_t index, int particle)
208✔
1111
{
1112
  if (int err = verify_ww_index(index))
208!
UNCOV
1113
    return err;
×
1114

1115
  const auto& wws = variance_reduction::weight_windows.at(index);
208✔
1116
  wws->set_particle_type(static_cast<ParticleType>(particle));
208✔
1117
  return 0;
208✔
1118
}
1119

1120
extern "C" int openmc_weight_windows_get_particle(int32_t index, int* particle)
52✔
1121
{
1122
  if (int err = verify_ww_index(index))
52!
UNCOV
1123
    return err;
×
1124

1125
  const auto& wws = variance_reduction::weight_windows.at(index);
52✔
1126
  *particle = static_cast<int>(wws->particle_type());
52✔
1127
  return 0;
52✔
1128
}
1129

1130
extern "C" int openmc_weight_windows_get_bounds(int32_t index,
572✔
1131
  const double** lower_bounds, const double** upper_bounds, size_t* size)
1132
{
1133
  if (int err = verify_ww_index(index))
572!
UNCOV
1134
    return err;
×
1135

1136
  const auto& wws = variance_reduction::weight_windows[index];
572✔
1137
  *size = wws->lower_ww_bounds().size();
572✔
1138
  *lower_bounds = wws->lower_ww_bounds().data();
572✔
1139
  *upper_bounds = wws->upper_ww_bounds().data();
572✔
1140
  return 0;
572✔
1141
}
1142

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

1149
  const auto& wws = variance_reduction::weight_windows[index];
13✔
1150
  wws->set_bounds({lower_bounds, size}, {upper_bounds, size});
13✔
1151
  return 0;
13✔
1152
}
1153

1154
extern "C" int openmc_weight_windows_get_survival_ratio(
39✔
1155
  int32_t index, double* ratio)
1156
{
1157
  if (int err = verify_ww_index(index))
39!
UNCOV
1158
    return err;
×
1159
  const auto& wws = variance_reduction::weight_windows[index];
39✔
1160
  *ratio = wws->survival_ratio();
39✔
1161
  return 0;
39✔
1162
}
1163

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

1175
extern "C" int openmc_weight_windows_get_max_lower_bound_ratio(
39✔
1176
  int32_t index, double* lb_ratio)
1177
{
1178
  if (int err = verify_ww_index(index))
39!
UNCOV
1179
    return err;
×
1180
  const auto& wws = variance_reduction::weight_windows[index];
39✔
1181
  *lb_ratio = wws->max_lower_bound_ratio();
39✔
1182
  return 0;
39✔
1183
}
1184

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

1195
extern "C" int openmc_weight_windows_get_weight_cutoff(
39✔
1196
  int32_t index, double* cutoff)
1197
{
1198
  if (int err = verify_ww_index(index))
39!
UNCOV
1199
    return err;
×
1200
  const auto& wws = variance_reduction::weight_windows[index];
39✔
1201
  *cutoff = wws->weight_cutoff();
39✔
1202
  return 0;
39✔
1203
}
1204

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

1215
extern "C" int openmc_weight_windows_get_max_split(
39✔
1216
  int32_t index, int* max_split)
1217
{
1218
  if (int err = verify_ww_index(index))
39!
UNCOV
1219
    return err;
×
1220
  const auto& wws = variance_reduction::weight_windows[index];
39✔
1221
  *max_split = wws->max_split();
39✔
1222
  return 0;
39✔
1223
}
1224

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

1234
extern "C" int openmc_extend_weight_windows(
182✔
1235
  int32_t n, int32_t* index_start, int32_t* index_end)
1236
{
1237
  if (index_start)
182!
1238
    *index_start = variance_reduction::weight_windows.size();
182✔
1239
  if (index_end)
182!
UNCOV
1240
    *index_end = variance_reduction::weight_windows.size() + n - 1;
×
1241
  for (int i = 0; i < n; ++i)
364✔
1242
    variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
182✔
1243
  return 0;
182✔
1244
}
1245

1246
extern "C" size_t openmc_weight_windows_size()
182✔
1247
{
1248
  return variance_reduction::weight_windows.size();
182✔
1249
}
1250

1251
extern "C" int openmc_weight_windows_export(const char* filename)
170✔
1252
{
1253

1254
  if (!mpi::master)
170✔
1255
    return 0;
30✔
1256

1257
  std::string name = filename ? filename : "weight_windows.h5";
280✔
1258

1259
  write_message(fmt::format("Exporting weight windows to {}...", name), 5);
140✔
1260

1261
  hid_t ww_file = file_open(name, 'w');
140✔
1262

1263
  // Write file type
1264
  write_attribute(ww_file, "filetype", "weight_windows");
140✔
1265

1266
  // Write revisiion number for state point file
1267
  write_attribute(ww_file, "version", VERSION_WEIGHT_WINDOWS);
140✔
1268

1269
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
140✔
1270

1271
  hid_t mesh_group = create_group(ww_file, "meshes");
140✔
1272

1273
  std::vector<int32_t> mesh_ids;
140✔
1274
  std::vector<int32_t> ww_ids;
140✔
1275
  for (const auto& ww : variance_reduction::weight_windows) {
280✔
1276

1277
    ww->to_hdf5(weight_windows_group);
140✔
1278
    ww_ids.push_back(ww->id());
140✔
1279

1280
    // if the mesh has already been written, move on
1281
    int32_t mesh_id = ww->mesh()->id();
140✔
1282
    if (std::find(mesh_ids.begin(), mesh_ids.end(), mesh_id) != mesh_ids.end())
140!
UNCOV
1283
      continue;
×
1284

1285
    mesh_ids.push_back(mesh_id);
140✔
1286
    ww->mesh()->to_hdf5(mesh_group);
140✔
1287
  }
1288

1289
  write_attribute(mesh_group, "n_meshes", mesh_ids.size());
140✔
1290
  write_attribute(mesh_group, "ids", mesh_ids);
140✔
1291
  close_group(mesh_group);
140✔
1292

1293
  write_attribute(weight_windows_group, "n_weight_windows", ww_ids.size());
140✔
1294
  write_attribute(weight_windows_group, "ids", ww_ids);
140✔
1295
  close_group(weight_windows_group);
140✔
1296

1297
  file_close(ww_file);
140✔
1298

1299
  return 0;
140✔
1300
}
140✔
1301

1302
extern "C" int openmc_weight_windows_import(const char* filename)
13✔
1303
{
1304
  std::string name = filename ? filename : "weight_windows.h5";
13!
1305

1306
  if (mpi::master)
13!
1307
    write_message(fmt::format("Importing weight windows from {}...", name), 5);
13✔
1308

1309
  if (!file_exists(name)) {
13!
UNCOV
1310
    set_errmsg(fmt::format("File '{}' does not exist", name));
×
1311
  }
1312

1313
  hid_t ww_file = file_open(name, 'r');
13✔
1314

1315
  // Check that filetype is correct
1316
  std::string filetype;
13✔
1317
  read_attribute(ww_file, "filetype", filetype);
13✔
1318
  if (filetype != "weight_windows") {
13!
UNCOV
1319
    file_close(ww_file);
×
UNCOV
1320
    set_errmsg(fmt::format("File '{}' is not a weight windows file.", name));
×
UNCOV
1321
    return OPENMC_E_INVALID_ARGUMENT;
×
1322
  }
1323

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

1336
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
13✔
1337

1338
  hid_t mesh_group = open_group(ww_file, "meshes");
13✔
1339

1340
  read_meshes(mesh_group);
13✔
1341

1342
  std::vector<std::string> names = group_names(weight_windows_group);
13✔
1343

1344
  for (const auto& name : names) {
26✔
1345
    WeightWindows::from_hdf5(weight_windows_group, name);
13✔
1346
  }
1347

1348
  close_group(weight_windows_group);
13✔
1349

1350
  file_close(ww_file);
13✔
1351

1352
  return 0;
13✔
1353
}
13✔
1354

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

© 2025 Coveralls, Inc