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

openmc-dev / openmc / 29060094959

10 Jul 2026 12:29AM UTC coverage: 80.472% (-0.8%) from 81.292%
29060094959

Pull #3951

github

web-flow
Merge dfc4a1991 into 3c3ebba98
Pull Request #3951: wwinp files: Fix MemoryError in WeightWindowsList.export_to_hdf5 and speed up from_wwinp. Alternative Approach

16740 of 24259 branches covered (69.01%)

Branch coverage included in aggregate %.

70 of 128 new or added lines in 10 files covered. (54.69%)

787 existing lines in 49 files now uncovered.

57490 of 67984 relevant lines covered (84.56%)

17348614.33 hits per line

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

78.85
/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 "openmc/tensor.h"
10

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

31
#include <fmt/core.h>
32

33
namespace openmc {
34

35
//==============================================================================
36
// Global variables
37
//==============================================================================
38

39
namespace variance_reduction {
40

41
std::unordered_map<int32_t, int32_t> ww_map;
42
openmc::vector<unique_ptr<WeightWindows>> weight_windows;
43
openmc::vector<unique_ptr<WeightWindowsGenerator>> weight_windows_generators;
44

45
} // namespace variance_reduction
46

47
//==============================================================================
48
// WeightWindowSettings implementation
49
//==============================================================================
50

51
WeightWindows::WeightWindows(int32_t id)
46✔
52
{
53
  index_ = variance_reduction::weight_windows.size();
46✔
54
  set_id(id);
46✔
55
  set_defaults();
46✔
56
}
46✔
57

58
WeightWindows::WeightWindows(pugi::xml_node node)
46✔
59
{
60
  // Make sure required elements are present
61
  const vector<std::string> required_elems {
46✔
62
    "id", "particle_type", "lower_ww_bounds", "upper_ww_bounds"};
230!
63
  for (const auto& elem : required_elems) {
230✔
64
    if (!check_for_node(node, elem.c_str())) {
184!
65
      fatal_error(fmt::format("Must specify <{}> for weight windows.", elem));
×
66
    }
67
  }
68

69
  // Get weight windows ID
70
  int32_t id = std::stoi(get_node_value(node, "id"));
92✔
71
  this->set_id(id);
46✔
72

73
  // get the particle type
74
  auto particle_type_str = std::string(get_node_value(node, "particle_type"));
46✔
75
  particle_type_ = ParticleType {particle_type_str};
46✔
76

77
  // Determine associated mesh
78
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
92✔
79
  set_mesh(model::mesh_map.at(mesh_id));
46✔
80

81
  // energy bounds
82
  if (check_for_node(node, "energy_bounds"))
46✔
83
    energy_bounds_ = get_node_array<double>(node, "energy_bounds");
40✔
84

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

93
  // get the max lower bound ratio - optional
94
  if (check_for_node(node, "max_lower_bound_ratio")) {
46✔
95
    max_lb_ratio_ = std::stod(get_node_value(node, "max_lower_bound_ratio"));
48✔
96
    if (max_lb_ratio_ < 1.0) {
24!
97
      fatal_error("Maximum lower bound ratio must be larger than 1");
×
98
    }
99
  }
100

101
  // get the max split - optional
102
  if (check_for_node(node, "max_split")) {
46!
103
    max_split_ = std::stod(get_node_value(node, "max_split"));
92✔
104
    if (max_split_ <= 1)
46!
105
      fatal_error("max split must be larger than 1");
×
106
  }
107

108
  // weight cutoff - optional
109
  if (check_for_node(node, "weight_cutoff")) {
46!
110
    weight_cutoff_ = std::stod(get_node_value(node, "weight_cutoff"));
92✔
111
    if (weight_cutoff_ <= 0)
46!
112
      fatal_error("weight_cutoff must be larger than 0");
×
113
    if (weight_cutoff_ > 1)
46!
114
      fatal_error("weight_cutoff must be less than 1");
×
115
  }
116

117
  // read the lower/upper weight bounds
118
  this->set_bounds(get_node_array<double>(node, "lower_ww_bounds"),
46✔
119
    get_node_array<double>(node, "upper_ww_bounds"));
46✔
120

121
  set_defaults();
46✔
122
}
46✔
123

124
WeightWindows::~WeightWindows()
92✔
125
{
126
  variance_reduction::ww_map.erase(id());
92✔
127
}
276✔
128

129
WeightWindows* WeightWindows::create(int32_t id)
18✔
130
{
131
  variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
18✔
132
  auto wws = variance_reduction::weight_windows.back().get();
18✔
133
  variance_reduction::ww_map[wws->id()] =
18✔
134
    variance_reduction::weight_windows.size() - 1;
18✔
135
  return wws;
18✔
136
}
137

138
WeightWindows* WeightWindows::from_hdf5(
2✔
139
  hid_t wws_group, const std::string& group_name)
140
{
141
  // collect ID from the name of this group
142
  hid_t ww_group = open_group(wws_group, group_name);
2✔
143

144
  auto wws = WeightWindows::create();
2✔
145

146
  std::string particle_type;
2✔
147
  read_dataset(ww_group, "particle_type", particle_type);
2✔
148
  wws->particle_type_ = ParticleType {particle_type};
2✔
149

150
  read_dataset<double>(ww_group, "energy_bounds", wws->energy_bounds_);
2✔
151

152
  int32_t mesh_id;
2✔
153
  read_dataset(ww_group, "mesh", mesh_id);
2✔
154

155
  if (model::mesh_map.count(mesh_id) == 0) {
2!
156
    fatal_error(
×
157
      fmt::format("Mesh {} used in weight windows does not exist.", mesh_id));
×
158
  }
159
  wws->set_mesh(model::mesh_map[mesh_id]);
2✔
160

161
  wws->lower_ww_ =
2✔
162
    tensor::Tensor<double>({static_cast<size_t>(wws->bounds_size()[0]),
2✔
163
      static_cast<size_t>(wws->bounds_size()[1])});
2✔
164
  wws->upper_ww_ =
2✔
165
    tensor::Tensor<double>({static_cast<size_t>(wws->bounds_size()[0]),
2✔
166
      static_cast<size_t>(wws->bounds_size()[1])});
2✔
167

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

175
  close_group(ww_group);
2✔
176

177
  return wws;
2✔
178
}
2✔
179

180
void WeightWindows::set_defaults()
108✔
181
{
182
  // set energy bounds to the min/max energy supported by the data
183
  if (energy_bounds_.size() == 0) {
108✔
184
    int p_type = particle_type_.transport_index();
52✔
185
    if (p_type == C_NONE) {
52!
186
      fatal_error("Weight windows particle is not supported for transport.");
×
187
    }
188
    energy_bounds_.push_back(data::energy_min[p_type]);
52✔
189
    energy_bounds_.push_back(data::energy_max[p_type]);
52✔
190
  }
191
}
108✔
192

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

209
void WeightWindows::set_id(int32_t id)
120✔
210
{
211
  assert(id >= 0 || id == C_NONE);
120!
212

213
  // Clear entry in mesh map in case one was already assigned
214
  if (id_ != C_NONE) {
120!
215
    variance_reduction::ww_map.erase(id_);
120✔
216
    id_ = C_NONE;
120✔
217
  }
218

219
  // Ensure no other mesh has the same ID
220
  if (variance_reduction::ww_map.find(id) != variance_reduction::ww_map.end()) {
120!
221
    throw std::runtime_error {
×
222
      fmt::format("Two weight windows have the same ID: {}", id)};
×
223
  }
224

225
  // If no ID is specified, auto-assign the next ID in the sequence
226
  if (id == C_NONE) {
120✔
227
    id = 0;
46✔
228
    for (const auto& m : variance_reduction::weight_windows) {
50✔
229
      id = std::max(id, m->id_);
8!
230
    }
231
    ++id;
46✔
232
  }
233

234
  // Update ID and entry in the mesh map
235
  id_ = id;
120✔
236
  variance_reduction::ww_map[id] = index_;
120✔
237
}
120✔
238

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

248
void WeightWindows::set_particle_type(ParticleType p_type)
48✔
249
{
250
  if (!p_type.is_neutron() && !p_type.is_photon())
48!
251
    fatal_error(fmt::format(
×
252
      "Particle type '{}' cannot be applied to weight windows.", p_type.str()));
×
253
  particle_type_ = p_type;
48✔
254
}
48✔
255

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

261
  mesh_idx_ = mesh_idx;
92✔
262
  model::meshes[mesh_idx_]->prepare_for_point_location();
92✔
263
  allocate_ww_bounds();
92✔
264
}
92✔
265

266
void WeightWindows::set_mesh(const std::unique_ptr<Mesh>& mesh)
×
267
{
268
  set_mesh(mesh.get());
×
269
}
×
270

271
void WeightWindows::set_mesh(const Mesh* mesh)
×
272
{
273
  set_mesh(model::mesh_map[mesh->id_]);
×
274
}
×
275

276
std::pair<bool, WeightWindow> WeightWindows::get_weight_window(
68,806,874✔
277
  const Particle& p) const
278
{
279
  // check for particle type
280
  if (particle_type_ != p.type()) {
68,806,874✔
281
    return {false, {}};
23,764,930✔
282
  }
283

284
  // particle energy
285
  double E = p.E();
45,041,944✔
286

287
  // check to make sure energy is in range, expects sorted energy values
288
  if (E < energy_bounds_.front() || E > energy_bounds_.back())
45,041,944!
289
    return {false, {}};
16,866✔
290

291
  // Get mesh index for particle's position
292
  const auto& mesh = this->mesh();
45,025,078✔
293
  int mesh_bin = mesh->get_bin(p.r());
45,025,078✔
294

295
  // particle is outside the weight window mesh
296
  if (mesh_bin < 0)
45,025,078✔
297
    return {false, {}};
16,142✔
298

299
  // get the mesh bin in energy group
300
  int energy_bin =
45,008,936✔
301
    lower_bound_index(energy_bounds_.begin(), energy_bounds_.end(), E);
45,008,936✔
302

303
  // mesh_bin += energy_bin * mesh->n_bins();
304
  // Create individual weight window
305
  WeightWindow ww;
45,008,936✔
306
  ww.lower_weight = lower_ww_(energy_bin, mesh_bin);
45,008,936✔
307
  ww.upper_weight = upper_ww_(energy_bin, mesh_bin);
45,008,936✔
308
  ww.survival_weight = ww.lower_weight * survival_ratio_;
45,008,936✔
309
  ww.max_lb_ratio = max_lb_ratio_;
45,008,936✔
310
  ww.max_split = max_split_;
45,008,936✔
311
  ww.weight_cutoff = weight_cutoff_;
45,008,936✔
312
  return {true, ww};
45,008,936✔
313
}
314

315
std::array<int, 2> WeightWindows::bounds_size() const
236✔
316
{
317
  int num_spatial_bins = this->mesh()->n_bins();
236✔
318
  int num_energy_bins =
236✔
319
    energy_bounds_.size() > 0 ? energy_bounds_.size() - 1 : 1;
236✔
320
  return {num_energy_bins, num_spatial_bins};
236✔
321
}
322

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

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

351
void WeightWindows::set_bounds(const tensor::Tensor<double>& lower_bounds,
×
352
  const tensor::Tensor<double>& upper_bounds)
353
{
354

355
  this->check_bounds(lower_bounds, upper_bounds);
×
356

357
  // set new weight window values
358
  lower_ww_ = lower_bounds;
×
359
  upper_ww_ = upper_bounds;
×
360
}
×
361

362
void WeightWindows::set_bounds(
×
363
  const tensor::Tensor<double>& lower_bounds, double ratio)
364
{
365
  this->check_bounds(lower_bounds);
×
366

367
  // set new weight window values
368
  lower_ww_ = lower_bounds;
×
369
  upper_ww_ = lower_bounds;
×
370
  upper_ww_ *= ratio;
×
371
}
×
372

373
void WeightWindows::set_bounds(
48✔
374
  span<const double> lower_bounds, span<const double> upper_bounds)
375
{
376
  check_bounds(lower_bounds, upper_bounds);
48✔
377
  auto shape = this->bounds_size();
48✔
378
  lower_ww_ = tensor::Tensor<double>(
48✔
379
    {static_cast<size_t>(shape[0]), static_cast<size_t>(shape[1])});
48✔
380
  upper_ww_ = tensor::Tensor<double>(
48✔
381
    {static_cast<size_t>(shape[0]), static_cast<size_t>(shape[1])});
48✔
382

383
  // Copy weight window values from input spans into the tensors
384
  std::copy(lower_bounds.data(), lower_bounds.data() + lower_ww_.size(),
48✔
385
    lower_ww_.data());
386
  std::copy(upper_bounds.data(), upper_bounds.data() + upper_ww_.size(),
48✔
387
    upper_ww_.data());
388
}
48✔
389

390
void WeightWindows::set_bounds(span<const double> lower_bounds, double ratio)
×
391
{
392
  this->check_bounds(lower_bounds);
×
393

394
  auto shape = this->bounds_size();
×
395
  lower_ww_ = tensor::Tensor<double>(
×
396
    {static_cast<size_t>(shape[0]), static_cast<size_t>(shape[1])});
×
397
  upper_ww_ = tensor::Tensor<double>(
×
398
    {static_cast<size_t>(shape[0]), static_cast<size_t>(shape[1])});
×
399

400
  // Copy lower bounds into both arrays, then scale upper by ratio
401
  std::copy(lower_bounds.data(), lower_bounds.data() + lower_ww_.size(),
×
402
    lower_ww_.data());
403
  std::copy(lower_bounds.data(), lower_bounds.data() + upper_ww_.size(),
×
404
    upper_ww_.data());
405
  upper_ww_ *= ratio;
×
406
}
×
407

408
void WeightWindows::update_weights(const Tally* tally, const std::string& value,
46✔
409
  double threshold, double ratio, WeightWindowUpdateMethod method)
410
{
411
  ///////////////////////////
412
  // Setup and checks
413
  ///////////////////////////
414
  this->check_tally_update_compatibility(tally);
46✔
415

416
  // Dimensions of weight window arrays
417
  int e_bins = lower_ww_.shape(0);
46!
418
  int64_t mesh_bins = lower_ww_.shape(1);
46!
419

420
  // Initialize weight window arrays to -1.0 by default
421
#pragma omp parallel for collapse(2) schedule(static)
422
  for (int e = 0; e < e_bins; e++) {
376✔
423
    for (int64_t m = 0; m < mesh_bins; m++) {
466,506✔
424
      lower_ww_(e, m) = -1.0;
466,176✔
425
      upper_ww_(e, m) = -1.0;
466,176✔
426
    }
427
  }
428

429
  // determine which value to use
430
  const std::set<std::string> allowed_values = {"mean", "rel_err"};
138!
431
  if (allowed_values.count(value) == 0) {
46!
432
    fatal_error(fmt::format("Invalid value '{}' specified for weight window "
×
433
                            "generation. Must be one of: 'mean' or 'rel_err'",
434
      value));
435
  }
436

437
  // determine the index of the specified score
438
  int score_index = tally->score_index("flux");
46✔
439
  if (score_index == C_NONE) {
46!
440
    fatal_error(
×
441
      fmt::format("A 'flux' score required for weight window generation "
×
442
                  "is not present on tally {}.",
443
        tally->id()));
×
444
  }
445

446
  ///////////////////////////
447
  // Extract tally data
448
  //
449
  // At the end of this section, mean and rel_err are
450
  // 2D tensors of tally data (n_e_groups, n_mesh_bins)
451
  //
452
  ///////////////////////////
453

454
  // build a shape for the tally results, this will always be
455
  // dimension 5 (3 filter dimensions, 1 score dimension, 1 results dimension)
456
  // Look for the size of the last dimension of the results tensor
457
  const auto& results = tally->results();
46!
458
  const int results_dim = static_cast<int>(results.shape(2));
46!
459
  std::array<int, 5> shape = {1, 1, 1, tally->n_scores(), results_dim};
46✔
460

461
  // set the shape for the filters applied on the tally
462
  for (int i = 0; i < tally->filters().size(); i++) {
176✔
463
    const auto& filter = model::tally_filters[tally->filters(i)];
130✔
464
    shape[i] = filter->n_bins();
130✔
465
  }
466

467
  // build the transpose information to re-order data according to filter type
468
  std::array<int, 5> transpose = {0, 1, 2, 3, 4};
46✔
469

470
  // track our filter types and where we've added new ones
471
  std::vector<FilterType> filter_types = tally->filter_types();
46✔
472

473
  // assign other filter types to dummy positions if needed
474
  if (!tally->has_filter(FilterType::PARTICLE))
46✔
475
    filter_types.push_back(FilterType::PARTICLE);
4✔
476

477
  if (!tally->has_filter(FilterType::ENERGY))
46✔
478
    filter_types.push_back(FilterType::ENERGY);
4✔
479

480
  // particle axis mapping
481
  transpose[0] =
46✔
482
    std::find(filter_types.begin(), filter_types.end(), FilterType::PARTICLE) -
46✔
483
    filter_types.begin();
46✔
484

485
  // energy axis mapping
486
  transpose[1] =
46✔
487
    std::find(filter_types.begin(), filter_types.end(), FilterType::ENERGY) -
46✔
488
    filter_types.begin();
46✔
489

490
  // mesh axis mapping
491
  transpose[2] =
46✔
492
    std::find(filter_types.begin(), filter_types.end(), FilterType::MESH) -
46✔
493
    filter_types.begin();
46✔
494

495
  // determine the index of the particle within its filter
496
  int particle_idx = 0;
46✔
497
  if (tally->has_filter(FilterType::PARTICLE)) {
46✔
498
    auto pf = tally->get_filter<ParticleFilter>();
42✔
499
    const auto& particles = pf->particles();
42!
500

501
    auto p_it =
42✔
502
      std::find(particles.begin(), particles.end(), this->particle_type_);
42!
503
    if (p_it == particles.end()) {
42!
504
      auto msg = fmt::format("Particle type '{}' not present on Filter {} for "
×
505
                             "Tally {} used to update WeightWindows {}",
506
        this->particle_type_.str(), pf->id(), tally->id(), this->id());
×
507
      fatal_error(msg);
×
508
    }
×
509

510
    particle_idx = p_it - particles.begin();
42✔
511
  }
512

513
  // The tally results array is 3D: (n_filter_combos, n_scores, n_result_types).
514
  // The first dimension is a row-major flattening of up to 3 filter dimensions
515
  // (particle, energy, mesh) whose storage order depends on which filters the
516
  // tally has. We need to map our desired indices (particle, energy, mesh)
517
  // into the correct flat filter combination index.
518
  //
519
  // transpose[i] tells us which storage position holds dimension i:
520
  //   i=0 -> particle, i=1 -> energy, i=2 -> mesh
521
  // shape[j] gives the number of bins for filter storage position j.
522

523
  // Row-major strides for the 3 filter dimensions
524
  const int stride0 = shape[1] * shape[2];
46✔
525
  const int stride1 = shape[2];
46✔
526

527
  tensor::Tensor<double> sum(
46✔
528
    {static_cast<size_t>(e_bins), static_cast<size_t>(mesh_bins)});
46✔
529
  tensor::Tensor<double> sum_sq(
46✔
530
    {static_cast<size_t>(e_bins), static_cast<size_t>(mesh_bins)});
46✔
531

532
  const int i_sum = static_cast<int>(TallyResult::SUM);
46✔
533
  const int i_sum_sq = static_cast<int>(TallyResult::SUM_SQ);
46✔
534

535
  for (int e = 0; e < e_bins; e++) {
376✔
536
    for (int64_t m = 0; m < mesh_bins; m++) {
466,506✔
537
      // Place particle, energy, and mesh indices into their storage positions
538
      std::array<int, 3> idx = {0, 0, 0};
466,176✔
539
      idx[transpose[0]] = particle_idx;
466,176✔
540
      idx[transpose[1]] = e;
466,176✔
541
      idx[transpose[2]] = static_cast<int>(m);
466,176✔
542

543
      // Compute flat filter combination index (row-major over filter dims)
544
      int flat = idx[0] * stride0 + idx[1] * stride1 + idx[2];
466,176✔
545

546
      sum(e, m) = results(flat, score_index, i_sum);
466,176✔
547
      sum_sq(e, m) = results(flat, score_index, i_sum_sq);
466,176✔
548
    }
549
  }
550
  int n = tally->n_realizations_;
46✔
551

552
  //////////////////////////////////////////////
553
  //
554
  // Assign new weight windows
555
  //
556
  // Use references to the existing weight window data
557
  // to store and update the values
558
  //
559
  //////////////////////////////////////////////
560

561
  // up to this point the data arrays are views into the tally results (no
562
  // computation has been performed) now we'll switch references to the tally's
563
  // bounds to avoid allocating additional memory
564
  auto& new_bounds = this->lower_ww_;
46✔
565
  auto& rel_err = this->upper_ww_;
46✔
566

567
  // get mesh volumes
568
  auto mesh_vols = this->mesh()->volumes();
46✔
569

570
  // Calculate mean (new_bounds) and relative error
571
#pragma omp parallel for collapse(2) schedule(static)
572
  for (int e = 0; e < e_bins; e++) {
376✔
573
    for (int64_t m = 0; m < mesh_bins; m++) {
466,506✔
574
      // Calculate mean
575
      new_bounds(e, m) = sum(e, m) / n;
466,176✔
576
      // Calculate relative error
577
      if (sum(e, m) > 0.0) {
466,176✔
578
        double mean_val = new_bounds(e, m);
42,002✔
579
        double variance = (sum_sq(e, m) / n - mean_val * mean_val) / (n - 1);
42,002✔
580
        rel_err(e, m) = std::sqrt(variance) / mean_val;
42,002✔
581
      } else {
582
        rel_err(e, m) = INFTY;
424,174✔
583
      }
584
      if (value == "rel_err") {
466,176✔
585
        new_bounds(e, m) = 1.0 / rel_err(e, m);
138,000✔
586
      }
587
    }
588
  }
589

590
  // Divide by volume of mesh elements
591
#pragma omp parallel for collapse(2) schedule(static)
592
  for (int e = 0; e < e_bins; e++) {
376✔
593
    for (int64_t m = 0; m < mesh_bins; m++) {
466,506✔
594
      new_bounds(e, m) /= mesh_vols[m];
466,176✔
595
    }
596
  }
597

598
  if (method == WeightWindowUpdateMethod::MAGIC) {
46✔
599
    // For MAGIC, weight windows are proportional to the forward fluxes.
600
    // We normalize weight windows independently for each energy group.
601

602
    // Find group maximum and normalize (per energy group)
603
    for (int e = 0; e < e_bins; e++) {
344✔
604
      double group_max = 0.0;
605

606
      // Find maximum value across all elements in this energy group
607
#pragma omp parallel for schedule(static) reduction(max : group_max)
608
      for (int64_t m = 0; m < mesh_bins; m++) {
437,254✔
609
        if (new_bounds(e, m) > group_max) {
436,940✔
610
          group_max = new_bounds(e, m);
1,018✔
611
        }
612
      }
613

614
      // Normalize values in this energy group by the maximum value
615
      if (group_max > 0.0) {
314✔
616
        double norm_factor = 1.0 / (2.0 * group_max);
308✔
617
#pragma omp parallel for schedule(static)
618
        for (int64_t m = 0; m < mesh_bins; m++) {
436,888✔
619
          new_bounds(e, m) *= norm_factor;
436,580✔
620
        }
621
      }
622
    }
623
  } else {
624
    // For (FW-)CADIS, weight windows are inversely proportional to the adjoint
625
    // fluxes. We normalize the weight windows across all energy groups.
626
#pragma omp parallel for collapse(2) schedule(static)
627
    for (int e = 0; e < e_bins; e++) {
32✔
628
      for (int64_t m = 0; m < mesh_bins; m++) {
29,252✔
629
        // Take the inverse, but are careful not to divide by zero
630
        if (new_bounds(e, m) != 0.0) {
29,236!
631
          new_bounds(e, m) = 1.0 / new_bounds(e, m);
29,236✔
632
        } else {
UNCOV
633
          new_bounds(e, m) = 0.0;
×
634
        }
635
      }
636
    }
637

638
    // Find the maximum value across all elements
639
    double max_val = 0.0;
640
#pragma omp parallel for collapse(2) schedule(static) reduction(max : max_val)
641
    for (int e = 0; e < e_bins; e++) {
32✔
642
      for (int64_t m = 0; m < mesh_bins; m++) {
29,252✔
643
        if (new_bounds(e, m) > max_val) {
29,236✔
644
          max_val = new_bounds(e, m);
212✔
645
        }
646
      }
647
    }
648

649
    // Parallel normalization
650
    if (max_val > 0.0) {
16!
651
      double norm_factor = 1.0 / (2.0 * max_val);
16✔
652
#pragma omp parallel for collapse(2) schedule(static)
653
      for (int e = 0; e < e_bins; e++) {
32✔
654
        for (int64_t m = 0; m < mesh_bins; m++) {
29,252✔
655
          new_bounds(e, m) *= norm_factor;
29,236✔
656
        }
657
      }
658
    }
659
  }
660

661
  // Final processing
662
#pragma omp parallel for collapse(2) schedule(static)
663
  for (int e = 0; e < e_bins; e++) {
376✔
664
    for (int64_t m = 0; m < mesh_bins; m++) {
466,506✔
665
      // Values where the mean is zero should be ignored
666
      if (sum(e, m) <= 0.0) {
466,176✔
667
        new_bounds(e, m) = -1.0;
424,174✔
668
      }
669
      // Values where the relative error is higher than the threshold should be
670
      // ignored
671
      else if (rel_err(e, m) > threshold) {
42,002✔
672
        new_bounds(e, m) = -1.0;
568✔
673
      }
674
      // Set the upper bounds
675
      upper_ww_(e, m) = ratio * lower_ww_(e, m);
466,176✔
676
    }
677
  }
678
}
138✔
679

680
void WeightWindows::check_tally_update_compatibility(const Tally* tally)
46✔
681
{
682
  // define the set of allowed filters for the tally
683
  const std::set<FilterType> allowed_filters = {
46✔
684
    FilterType::MESH, FilterType::ENERGY, FilterType::PARTICLE};
46✔
685

686
  // retrieve a mapping of filter type to filter index for the tally
687
  auto filter_indices = tally->filter_indices();
46✔
688

689
  // a mesh filter is required for a tally used to update weight windows
690
  if (!filter_indices.count(FilterType::MESH)) {
46!
691
    fatal_error(
×
692
      "A mesh filter is required for a tally to update weight window bounds");
693
  }
694

695
  // ensure the mesh filter is using the same mesh as this weight window object
696
  auto mesh_filter = tally->get_filter<MeshFilter>();
46✔
697

698
  // make sure that all of the filters present on the tally are allowed
699
  for (auto filter_pair : filter_indices) {
176✔
700
    if (allowed_filters.find(filter_pair.first) == allowed_filters.end()) {
130!
701
      fatal_error(fmt::format("Invalid filter type '{}' found on tally "
×
702
                              "used for weight window generation.",
703
        model::tally_filters[tally->filters(filter_pair.second)]->type_str()));
×
704
    }
705
  }
706

707
  if (mesh_filter->mesh() != mesh_idx_) {
46!
708
    int32_t mesh_filter_id = model::meshes[mesh_filter->mesh()]->id();
×
709
    int32_t ww_mesh_id = model::meshes[this->mesh_idx_]->id();
×
710
    fatal_error(fmt::format("Mesh filter {} uses a different mesh ({}) than "
×
711
                            "weight window {} mesh ({})",
712
      mesh_filter->id(), mesh_filter_id, id_, ww_mesh_id));
×
713
  }
714

715
  // if an energy filter exists, make sure the energy grid matches that of this
716
  // weight window object
717
  if (auto energy_filter = tally->get_filter<EnergyFilter>()) {
46✔
718
    std::vector<double> filter_bins = energy_filter->bins();
42✔
719
    std::set<double> filter_e_bounds(
42✔
720
      energy_filter->bins().begin(), energy_filter->bins().end());
42✔
721
    if (filter_e_bounds.size() != energy_bounds().size()) {
42!
722
      fatal_error(
×
723
        fmt::format("Energy filter {} does not have the same number of energy "
×
724
                    "bounds ({}) as weight window object {} ({})",
725
          energy_filter->id(), filter_e_bounds.size(), id_,
×
726
          energy_bounds().size()));
×
727
    }
728

729
    for (auto e : energy_bounds()) {
410✔
730
      if (filter_e_bounds.count(e) == 0) {
368!
731
        fatal_error(fmt::format(
×
732
          "Energy bounds of filter {} and weight windows {} do not match",
733
          energy_filter->id(), id_));
×
734
      }
735
    }
736
  }
42✔
737
}
46✔
738

739
void WeightWindows::to_hdf5(hid_t group) const
20✔
740
{
741
  hid_t ww_group = create_group(group, fmt::format("weight_windows_{}", id()));
20✔
742

743
  write_dataset(ww_group, "mesh", this->mesh()->id());
20✔
744
  write_dataset(ww_group, "particle_type", particle_type_.str());
20✔
745
  write_dataset(ww_group, "energy_bounds", energy_bounds_);
20✔
746
  write_dataset(ww_group, "lower_ww_bounds", lower_ww_);
20✔
747
  write_dataset(ww_group, "upper_ww_bounds", upper_ww_);
20✔
748
  write_dataset(ww_group, "survival_ratio", survival_ratio_);
20✔
749
  write_dataset(ww_group, "max_lower_bound_ratio", max_lb_ratio_);
20✔
750
  write_dataset(ww_group, "max_split", max_split_);
20✔
751
  write_dataset(ww_group, "weight_cutoff", weight_cutoff_);
20✔
752

753
  close_group(ww_group);
20✔
754
}
20✔
755

756
WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node)
16✔
757
{
758
  // read information from the XML node
759
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
32✔
760
  int32_t mesh_idx = model::mesh_map[mesh_id];
16✔
761
  max_realizations_ = std::stoi(get_node_value(node, "max_realizations"));
32✔
762

763
  int32_t active_batches = settings::n_batches - settings::n_inactive;
16✔
764
  if (max_realizations_ > active_batches) {
16✔
765
    auto msg =
4✔
766
      fmt::format("The maximum number of specified tally realizations ({}) is "
767
                  "greater than the number of active batches ({}).",
768
        max_realizations_, active_batches);
4✔
769
    warning(msg);
4✔
770
  }
4✔
771
  auto tmp_str = get_node_value(node, "particle_type", false, true);
16✔
772
  auto particle_type = ParticleType {tmp_str};
16✔
773

774
  update_interval_ = std::stoi(get_node_value(node, "update_interval"));
32✔
775
  on_the_fly_ = get_node_value_bool(node, "on_the_fly");
16✔
776

777
  std::vector<double> e_bounds;
16✔
778
  if (check_for_node(node, "energy_bounds")) {
16✔
779
    e_bounds = get_node_array<double>(node, "energy_bounds");
8✔
780
  } else {
781
    int p_type = particle_type.transport_index();
12✔
782
    if (p_type == C_NONE) {
12!
783
      fatal_error("Weight windows particle is not supported for transport.");
×
784
    }
785
    e_bounds.push_back(data::energy_min[p_type]);
12✔
786
    e_bounds.push_back(data::energy_max[p_type]);
12✔
787
  }
788

789
  // set method
790
  std::string method_string = get_node_value(node, "method");
16✔
791
  if (method_string == "magic") {
16✔
792
    method_ = WeightWindowUpdateMethod::MAGIC;
8✔
793
    if (settings::solver_type == SolverType::RANDOM_RAY &&
8!
794
        FlatSourceDomain::adjoint_requested_) {
795
      fatal_error("Random ray weight window generation with MAGIC cannot be "
×
796
                  "done in adjoint mode.");
797
    }
798
  } else if (method_string == "fw_cadis") {
8!
799
    method_ = WeightWindowUpdateMethod::FW_CADIS;
8✔
800
    if (settings::solver_type != SolverType::RANDOM_RAY) {
8!
801
      fatal_error("FW-CADIS can only be run in random ray solver mode.");
×
802
    }
803
    FlatSourceDomain::adjoint_requested_ = true;
8✔
804
    if (check_for_node(node, "targets")) {
8✔
805
      FlatSourceDomain::fw_cadis_local_ = true;
2✔
806
      targets_ = get_node_array<size_t>(node, "targets");
2✔
807
      FlatSourceDomain::fw_cadis_local_targets_.insert(
2✔
808
        std::end(FlatSourceDomain::fw_cadis_local_targets_),
2✔
809
        std::begin(targets_), std::end(targets_));
2✔
810
    }
811
  } else {
812
    fatal_error(fmt::format(
×
813
      "Unknown weight window update method '{}' specified", method_string));
814
  }
815

816
  // parse non-default update parameters if specified
817
  if (check_for_node(node, "update_parameters")) {
16✔
818
    pugi::xml_node params_node = node.child("update_parameters");
4✔
819
    if (check_for_node(params_node, "value"))
4!
820
      tally_value_ = get_node_value(params_node, "value");
4✔
821
    if (check_for_node(params_node, "threshold"))
4!
822
      threshold_ = std::stod(get_node_value(params_node, "threshold"));
8✔
823
    if (check_for_node(params_node, "ratio")) {
4!
824
      ratio_ = std::stod(get_node_value(params_node, "ratio"));
8✔
825
    }
826
  }
827

828
  // check update parameter values
829
  if (tally_value_ != "mean" && tally_value_ != "rel_err") {
16!
830
    fatal_error(fmt::format("Unsupported tally value '{}' specified for "
×
831
                            "weight window generation.",
832
      tally_value_));
×
833
  }
834
  if (threshold_ <= 0.0)
16!
835
    fatal_error(fmt::format("Invalid relative error threshold '{}' (<= 0.0) "
×
836
                            "specified for weight window generation",
837
      ratio_));
×
838
  if (ratio_ <= 1.0)
16!
839
    fatal_error(fmt::format("Invalid weight window ratio '{}' (<= 1.0) "
×
840
                            "specified for weight window generation",
841
      ratio_));
×
842

843
  // create a matching weight windows object
844
  auto wws = WeightWindows::create();
16✔
845
  ww_idx_ = wws->index();
16✔
846
  wws->set_mesh(mesh_idx);
16✔
847
  if (e_bounds.size() > 0)
16!
848
    wws->set_energy_bounds(e_bounds);
16✔
849
  wws->set_particle_type(particle_type);
16✔
850
  wws->set_defaults();
16✔
851
}
16✔
852

853
void WeightWindowsGenerator::create_tally()
16✔
854
{
855
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
16✔
856

857
  // create a tally based on the WWG information
858
  Tally* ww_tally = Tally::create();
16✔
859
  tally_idx_ = model::tally_map[ww_tally->id()];
16✔
860
  ww_tally->set_scores({"flux"});
32!
861

862
  int32_t mesh_id = wws->mesh()->id();
16✔
863
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
16✔
864
  // see if there's already a mesh filter using this mesh
865
  bool found_mesh_filter = false;
16✔
866
  for (const auto& f : model::tally_filters) {
46✔
867
    if (f->type() == FilterType::MESH) {
34✔
868
      const auto* mesh_filter = dynamic_cast<MeshFilter*>(f.get());
4!
869
      if (mesh_filter->mesh() == mesh_idx && !mesh_filter->translated() &&
8!
870
          !mesh_filter->rotated()) {
4✔
871
        ww_tally->add_filter(f.get());
4✔
872
        found_mesh_filter = true;
873
        break;
874
      }
875
    }
876
  }
877

878
  if (!found_mesh_filter) {
12✔
879
    auto mesh_filter = Filter::create("mesh");
12✔
880
    openmc_mesh_filter_set_mesh(mesh_filter->index(), model::mesh_map[mesh_id]);
12✔
881
    ww_tally->add_filter(mesh_filter);
12✔
882
  }
883

884
  const auto& e_bounds = wws->energy_bounds();
16!
885
  if (e_bounds.size() > 0) {
16!
886
    auto energy_filter = Filter::create("energy");
16✔
887
    openmc_energy_filter_set_bins(
16✔
888
      energy_filter->index(), e_bounds.size(), e_bounds.data());
16✔
889
    ww_tally->add_filter(energy_filter);
16✔
890
  }
891

892
  // add a particle filter
893
  auto particle_type = wws->particle_type();
16✔
894
  auto particle_filter = Filter::create("particle");
16✔
895
  auto pf = dynamic_cast<ParticleFilter*>(particle_filter);
16!
896
  pf->set_particles({&particle_type, 1});
16✔
897
  ww_tally->add_filter(particle_filter);
16✔
898
}
16✔
899

900
void WeightWindowsGenerator::update() const
360✔
901
{
902
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
360✔
903

904
  Tally* tally = model::tallies[tally_idx_].get();
360✔
905

906
  // If in random ray mode, only update on the last batch
907
  if (settings::solver_type == SolverType::RANDOM_RAY) {
360✔
908
    if (simulation::current_batch != settings::n_batches) {
320✔
909
      return;
910
    }
911
    // If in Monte Carlo mode and beyond the number of max realizations or
912
    // not at the correct update interval, skip the update
913
  } else if (max_realizations_ < tally->n_realizations_ ||
40✔
914
             tally->n_realizations_ % update_interval_ != 0) {
8!
915
    return;
916
  }
917

918
  wws->update_weights(tally, tally_value_, threshold_, ratio_, method_);
24✔
919

920
  // if we're not doing on the fly generation, reset the tally results once
921
  // we're done with the update
922
  if (!on_the_fly_)
24!
923
    tally->reset();
×
924

925
  // TODO: deactivate or remove tally once weight window generation is
926
  // complete
927
}
928

929
//==============================================================================
930
// Non-member functions
931
//==============================================================================
932

933
std::pair<bool, WeightWindow> search_weight_window(const Particle& p)
57,011,612✔
934
{
935
  // TODO: this is a linear search - should do something more clever
936
  for (const auto& ww : variance_reduction::weight_windows) {
80,809,550✔
937
    auto [ww_found, weight_window] = ww->get_weight_window(p);
68,806,874✔
938
    if (ww_found)
68,806,874✔
939
      return {true, weight_window};
45,008,936✔
940
  }
941
  return {false, {}};
12,002,676✔
942
}
943

944
void apply_weight_windows(Particle& p)
32,364,332✔
945
{
946
  if (!settings::weight_windows_on)
32,364,332✔
947
    return;
32,188,572✔
948

949
  // WW on photon and neutron only
950
  if (!p.type().is_neutron() && !p.type().is_photon())
179,054!
951
    return;
952

953
  // skip dead or no energy
954
  if (p.E() <= 0 || !p.alive())
179,054!
955
    return;
956

957
  auto [ww_found, ww] = search_weight_window(p);
175,760✔
958
  if (ww_found && ww.is_valid()) {
175,760✔
959
    apply_weight_window(p, ww);
144,730✔
960
  } else {
961
    if (p.wgt_ww_born() == -1.0)
31,030✔
962
      p.wgt_ww_born() = 1.0;
11,370✔
963
  }
964
}
965

966
void apply_weight_window(Particle& p, WeightWindow weight_window)
56,968,898✔
967
{
968
  if (!weight_window.is_valid())
56,968,898✔
969
    return;
970

971
  // skip dead or no energy
972
  if (p.E() <= 0 || !p.alive())
37,473,526✔
973
    return;
974

975
  // If particle has not yet had its birth weight window value set, set it to
976
  // the current weight window.
977
  if (p.wgt_ww_born() == -1.0)
36,341,692✔
978
    p.wgt_ww_born() =
138,050✔
979
      (weight_window.lower_weight + weight_window.upper_weight) / 2;
138,050✔
980

981
  // Normalize weight windows based on particle's starting weight
982
  // and the value of the weight window the particle was born in.
983
  weight_window.scale(p.wgt_born() / p.wgt_ww_born());
36,341,692✔
984

985
  // get the paramters
986
  double weight = p.wgt();
36,341,692✔
987

988
  // first check to see if particle should be killed for weight cutoff
989
  if (p.wgt() < weight_window.weight_cutoff) {
36,341,692✔
990
    p.wgt() = 0.0;
100✔
991
    return;
100✔
992
  }
993

994
  // check if particle is far above current weight window
995
  // only do this if the factor is not already set on the particle and a
996
  // maximum lower bound ratio is specified
997
  if (p.ww_factor() == 0.0 && weight_window.max_lb_ratio > 1.0 &&
36,341,592✔
998
      p.wgt() > weight_window.lower_weight * weight_window.max_lb_ratio) {
29,202✔
999
    p.ww_factor() =
22,608✔
1000
      p.wgt() / (weight_window.lower_weight * weight_window.max_lb_ratio);
22,608✔
1001
  }
1002

1003
  // move weight window closer to the particle weight if needed
1004
  if (p.ww_factor() > 1.0)
36,341,592✔
1005
    weight_window.scale(p.ww_factor());
3,294,156✔
1006

1007
  // if particle's weight is above the weight window split until they are within
1008
  // the window
1009
  if (weight > weight_window.upper_weight) {
36,341,592✔
1010
    // do not further split the particle if above the limit
1011
    if (p.n_split() >= settings::max_history_splits)
2,827,208✔
1012
      return;
2,130,484✔
1013

1014
    double n_split = std::ceil(weight / weight_window.upper_weight);
696,724✔
1015
    double max_split = weight_window.max_split;
696,724✔
1016
    n_split = std::min(n_split, max_split);
696,724✔
1017

1018
    p.n_split() += n_split;
696,724✔
1019

1020
    // Create secondaries and divide weight among all particles
1021
    int i_split = std::round(n_split);
696,724✔
1022
    for (int l = 0; l < i_split - 1; l++) {
2,669,028✔
1023
      p.split(weight / n_split);
1,972,304✔
1024
    }
1025
    // remaining weight is applied to current particle
1026
    p.wgt() = weight / n_split;
696,724✔
1027

1028
  } else if (weight <= weight_window.lower_weight) {
33,514,384✔
1029
    // if the particle weight is below the window, play Russian roulette
1030
    double weight_survive =
1,213,016✔
1031
      std::min(weight * weight_window.max_split, weight_window.survival_weight);
1,213,016✔
1032
    russian_roulette(p, weight_survive);
1,213,016✔
1033
  } // else particle is in the window, continue as normal
1034
}
1035

1036
void free_memory_weight_windows()
1,444✔
1037
{
1038
  variance_reduction::ww_map.clear();
1,444✔
1039
  variance_reduction::weight_windows.clear();
1,444✔
1040
  variance_reduction::weight_windows_generators.clear();
1,444✔
1041
}
1,444✔
1042

1043
void finalize_variance_reduction()
1,420✔
1044
{
1045
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
1,436✔
1046
    wwg->create_tally();
16✔
1047
  }
1048
}
1,420✔
1049

1050
//==============================================================================
1051
// C API
1052
//==============================================================================
1053

1054
int verify_ww_index(int32_t index)
362✔
1055
{
1056
  if (index < 0 || index >= variance_reduction::weight_windows.size()) {
362!
1057
    set_errmsg(fmt::format("Index '{}' for weight windows is invalid", index));
×
1058
    return OPENMC_E_OUT_OF_BOUNDS;
×
1059
  }
1060
  return 0;
1061
}
1062

1063
extern "C" int openmc_get_weight_windows_index(int32_t id, int32_t* idx)
30✔
1064
{
1065
  auto it = variance_reduction::ww_map.find(id);
30!
1066
  if (it == variance_reduction::ww_map.end()) {
30!
1067
    set_errmsg(fmt::format("No weight windows exist with ID={}", id));
×
1068
    return OPENMC_E_INVALID_ID;
×
1069
  }
1070

1071
  *idx = it->second;
30✔
1072
  return 0;
30✔
1073
}
1074

1075
extern "C" int openmc_weight_windows_get_id(int32_t index, int32_t* id)
94✔
1076
{
1077
  if (int err = verify_ww_index(index))
94!
1078
    return err;
1079

1080
  const auto& wws = variance_reduction::weight_windows.at(index);
94✔
1081
  *id = wws->id();
94✔
1082
  return 0;
94✔
1083
}
1084

1085
extern "C" int openmc_weight_windows_set_id(int32_t index, int32_t id)
28✔
1086
{
1087
  if (int err = verify_ww_index(index))
28!
1088
    return err;
1089

1090
  const auto& wws = variance_reduction::weight_windows.at(index);
28✔
1091
  wws->set_id(id);
28✔
1092
  return 0;
28✔
1093
}
1094

1095
extern "C" int openmc_weight_windows_update_magic(int32_t ww_idx,
22✔
1096
  int32_t tally_idx, const char* value, double threshold, double ratio)
1097
{
1098
  if (int err = verify_ww_index(ww_idx))
22!
1099
    return err;
1100

1101
  if (tally_idx < 0 || tally_idx >= model::tallies.size()) {
22!
1102
    set_errmsg(fmt::format("Index '{}' for tally is invalid", tally_idx));
×
1103
    return OPENMC_E_OUT_OF_BOUNDS;
×
1104
  }
1105

1106
  // get the requested tally
1107
  const Tally* tally = model::tallies.at(tally_idx).get();
22✔
1108

1109
  // get the WeightWindows object
1110
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
22✔
1111

1112
  wws->update_weights(tally, value, threshold, ratio);
22✔
1113

1114
  return 0;
22✔
1115
}
1116

1117
extern "C" int openmc_weight_windows_set_mesh(int32_t ww_idx, int32_t mesh_idx)
28✔
1118
{
1119
  if (int err = verify_ww_index(ww_idx))
28!
1120
    return err;
1121
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
28✔
1122
  wws->set_mesh(mesh_idx);
28✔
1123
  return 0;
28✔
1124
}
1125

1126
extern "C" int openmc_weight_windows_get_mesh(int32_t ww_idx, int32_t* mesh_idx)
2✔
1127
{
1128
  if (int err = verify_ww_index(ww_idx))
2!
1129
    return err;
1130
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
2✔
1131
  *mesh_idx = model::mesh_map.at(wws->mesh()->id());
2✔
1132
  return 0;
2✔
1133
}
1134

1135
extern "C" int openmc_weight_windows_set_energy_bounds(
24✔
1136
  int32_t ww_idx, double* e_bounds, size_t e_bounds_size)
1137
{
1138
  if (int err = verify_ww_index(ww_idx))
24!
1139
    return err;
1140
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
24✔
1141
  wws->set_energy_bounds({e_bounds, e_bounds_size});
24✔
1142
  return 0;
24✔
1143
}
1144

1145
extern "C" int openmc_weight_windows_get_energy_bounds(
2✔
1146
  int32_t ww_idx, const double** e_bounds, size_t* e_bounds_size)
1147
{
1148
  if (int err = verify_ww_index(ww_idx))
2!
1149
    return err;
1150
  const auto& wws = variance_reduction::weight_windows[ww_idx].get();
2✔
1151
  *e_bounds = wws->energy_bounds().data();
2✔
1152
  *e_bounds_size = wws->energy_bounds().size();
2✔
1153
  return 0;
2✔
1154
}
1155

1156
extern "C" int openmc_weight_windows_set_particle(
32✔
1157
  int32_t index, int32_t particle)
1158
{
1159
  if (int err = verify_ww_index(index))
32!
1160
    return err;
1161

1162
  const auto& wws = variance_reduction::weight_windows.at(index);
32✔
1163
  wws->set_particle_type(ParticleType {particle});
32✔
1164
  return 0;
32✔
1165
}
1166

1167
extern "C" int openmc_weight_windows_get_particle(
8✔
1168
  int32_t index, int32_t* particle)
1169
{
1170
  if (int err = verify_ww_index(index))
8!
1171
    return err;
1172

1173
  const auto& wws = variance_reduction::weight_windows.at(index);
8✔
1174
  *particle = wws->particle_type().pdg_number();
8✔
1175
  return 0;
8✔
1176
}
1177

1178
extern "C" int openmc_weight_windows_get_bounds(int32_t index,
88✔
1179
  const double** lower_bounds, const double** upper_bounds, size_t* size)
1180
{
1181
  if (int err = verify_ww_index(index))
88!
1182
    return err;
1183

1184
  const auto& wws = variance_reduction::weight_windows[index];
88✔
1185
  *size = wws->lower_ww_bounds().size();
88✔
1186
  *lower_bounds = wws->lower_ww_bounds().data();
88✔
1187
  *upper_bounds = wws->upper_ww_bounds().data();
88✔
1188
  return 0;
88✔
1189
}
1190

1191
extern "C" int openmc_weight_windows_set_bounds(int32_t index,
2✔
1192
  const double* lower_bounds, const double* upper_bounds, size_t size)
1193
{
1194
  if (int err = verify_ww_index(index))
2!
1195
    return err;
1196

1197
  const auto& wws = variance_reduction::weight_windows[index];
2✔
1198
  wws->set_bounds(span<const double>(lower_bounds, size),
2✔
1199
    span<const double>(upper_bounds, size));
1200
  return 0;
2✔
1201
}
1202

1203
extern "C" int openmc_weight_windows_get_survival_ratio(
6✔
1204
  int32_t index, double* ratio)
1205
{
1206
  if (int err = verify_ww_index(index))
6!
1207
    return err;
1208
  const auto& wws = variance_reduction::weight_windows[index];
6✔
1209
  *ratio = wws->survival_ratio();
6✔
1210
  return 0;
6✔
1211
}
1212

1213
extern "C" int openmc_weight_windows_set_survival_ratio(
2✔
1214
  int32_t index, double ratio)
1215
{
1216
  if (int err = verify_ww_index(index))
2!
1217
    return err;
1218
  const auto& wws = variance_reduction::weight_windows[index];
2✔
1219
  wws->survival_ratio() = ratio;
2✔
1220
  std::cout << "Survival ratio: " << wws->survival_ratio() << std::endl;
2✔
1221
  return 0;
2✔
1222
}
1223

1224
extern "C" int openmc_weight_windows_get_max_lower_bound_ratio(
6✔
1225
  int32_t index, double* lb_ratio)
1226
{
1227
  if (int err = verify_ww_index(index))
6!
1228
    return err;
1229
  const auto& wws = variance_reduction::weight_windows[index];
6✔
1230
  *lb_ratio = wws->max_lower_bound_ratio();
6✔
1231
  return 0;
6✔
1232
}
1233

1234
extern "C" int openmc_weight_windows_set_max_lower_bound_ratio(
2✔
1235
  int32_t index, double lb_ratio)
1236
{
1237
  if (int err = verify_ww_index(index))
2!
1238
    return err;
1239
  const auto& wws = variance_reduction::weight_windows[index];
2✔
1240
  wws->max_lower_bound_ratio() = lb_ratio;
2✔
1241
  return 0;
2✔
1242
}
1243

1244
extern "C" int openmc_weight_windows_get_weight_cutoff(
6✔
1245
  int32_t index, double* cutoff)
1246
{
1247
  if (int err = verify_ww_index(index))
6!
1248
    return err;
1249
  const auto& wws = variance_reduction::weight_windows[index];
6✔
1250
  *cutoff = wws->weight_cutoff();
6✔
1251
  return 0;
6✔
1252
}
1253

1254
extern "C" int openmc_weight_windows_set_weight_cutoff(
2✔
1255
  int32_t index, double cutoff)
1256
{
1257
  if (int err = verify_ww_index(index))
2!
1258
    return err;
1259
  const auto& wws = variance_reduction::weight_windows[index];
2✔
1260
  wws->weight_cutoff() = cutoff;
2✔
1261
  return 0;
2✔
1262
}
1263

1264
extern "C" int openmc_weight_windows_get_max_split(
6✔
1265
  int32_t index, int* max_split)
1266
{
1267
  if (int err = verify_ww_index(index))
6!
1268
    return err;
1269
  const auto& wws = variance_reduction::weight_windows[index];
6✔
1270
  *max_split = wws->max_split();
6✔
1271
  return 0;
6✔
1272
}
1273

1274
extern "C" int openmc_weight_windows_set_max_split(int32_t index, int max_split)
2✔
1275
{
1276
  if (int err = verify_ww_index(index))
2!
1277
    return err;
1278
  const auto& wws = variance_reduction::weight_windows[index];
2✔
1279
  wws->max_split() = max_split;
2✔
1280
  return 0;
2✔
1281
}
1282

1283
extern "C" int openmc_extend_weight_windows(
28✔
1284
  int32_t n, int32_t* index_start, int32_t* index_end)
1285
{
1286
  if (index_start)
28!
1287
    *index_start = variance_reduction::weight_windows.size();
28✔
1288
  if (index_end)
28!
1289
    *index_end = variance_reduction::weight_windows.size() + n - 1;
×
1290
  for (int i = 0; i < n; ++i)
56✔
1291
    variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
28✔
1292
  return 0;
28✔
1293
}
1294

1295
extern "C" size_t openmc_weight_windows_size()
28✔
1296
{
1297
  return variance_reduction::weight_windows.size();
28✔
1298
}
1299

1300
extern "C" int openmc_weight_windows_export(const char* filename)
20✔
1301
{
1302

1303
  if (!mpi::master)
20!
1304
    return 0;
1305

1306
  std::string name = filename ? filename : "weight_windows.h5";
36✔
1307

1308
  write_message(fmt::format("Exporting weight windows to {}...", name), 5);
20✔
1309

1310
  hid_t ww_file = file_open(name, 'w');
20✔
1311

1312
  // Write file type
1313
  write_attribute(ww_file, "filetype", "weight_windows");
20✔
1314

1315
  // Write revisiion number for state point file
1316
  write_attribute(ww_file, "version", VERSION_WEIGHT_WINDOWS);
20✔
1317

1318
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
20✔
1319

1320
  hid_t mesh_group = create_group(ww_file, "meshes");
20✔
1321

1322
  std::vector<int32_t> mesh_ids;
20✔
1323
  std::vector<int32_t> ww_ids;
20✔
1324
  for (const auto& ww : variance_reduction::weight_windows) {
40✔
1325

1326
    ww->to_hdf5(weight_windows_group);
20✔
1327
    ww_ids.push_back(ww->id());
20✔
1328

1329
    // if the mesh has already been written, move on
1330
    int32_t mesh_id = ww->mesh()->id();
20!
1331
    if (std::find(mesh_ids.begin(), mesh_ids.end(), mesh_id) != mesh_ids.end())
20!
1332
      continue;
×
1333

1334
    mesh_ids.push_back(mesh_id);
20✔
1335
    ww->mesh()->to_hdf5(mesh_group);
20✔
1336
  }
1337

1338
  write_attribute(mesh_group, "n_meshes", mesh_ids.size());
20✔
1339
  write_attribute(mesh_group, "ids", mesh_ids);
20✔
1340
  close_group(mesh_group);
20✔
1341

1342
  write_attribute(weight_windows_group, "n_weight_windows", ww_ids.size());
20✔
1343
  write_attribute(weight_windows_group, "ids", ww_ids);
20✔
1344
  close_group(weight_windows_group);
20✔
1345

1346
  file_close(ww_file);
20✔
1347

1348
  return 0;
20✔
1349
}
40✔
1350

1351
extern "C" int openmc_weight_windows_import(const char* filename)
2✔
1352
{
1353
  std::string name = filename ? filename : "weight_windows.h5";
2!
1354

1355
  if (mpi::master)
2!
1356
    write_message(fmt::format("Importing weight windows from {}...", name), 5);
4✔
1357

1358
  if (!file_exists(name)) {
2!
1359
    set_errmsg(fmt::format("File '{}' does not exist", name));
×
1360
  }
1361

1362
  hid_t ww_file = file_open(name, 'r');
2✔
1363

1364
  // Check that filetype is correct
1365
  std::string filetype;
2✔
1366
  read_attribute(ww_file, "filetype", filetype);
2✔
1367
  if (filetype != "weight_windows") {
2!
1368
    file_close(ww_file);
×
1369
    set_errmsg(fmt::format("File '{}' is not a weight windows file.", name));
×
1370
    return OPENMC_E_INVALID_ARGUMENT;
×
1371
  }
1372

1373
  // Check that the file version is compatible
1374
  std::array<int, 2> file_version;
2✔
1375
  read_attribute(ww_file, "version", file_version);
2✔
1376
  if (file_version[0] != VERSION_WEIGHT_WINDOWS[0]) {
2!
1377
    std::string err_msg =
×
1378
      fmt::format("File '{}' has version {} which is incompatible with the "
1379
                  "expected version ({}).",
1380
        name, file_version, VERSION_WEIGHT_WINDOWS);
×
1381
    set_errmsg(err_msg);
×
1382
    return OPENMC_E_INVALID_ARGUMENT;
×
1383
  }
×
1384

1385
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
2✔
1386

1387
  hid_t mesh_group = open_group(ww_file, "meshes");
2✔
1388

1389
  read_meshes(mesh_group);
2✔
1390

1391
  std::vector<std::string> names = group_names(weight_windows_group);
2✔
1392

1393
  for (const auto& name : names) {
4✔
1394
    WeightWindows::from_hdf5(weight_windows_group, name);
2✔
1395
  }
1396

1397
  close_group(weight_windows_group);
2✔
1398

1399
  file_close(ww_file);
2✔
1400

1401
  return 0;
2✔
1402
}
4✔
1403

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