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

openmc-dev / openmc / 25930573650

15 May 2026 05:01PM UTC coverage: 81.375% (+0.05%) from 81.326%
25930573650

Pull #3863

github

web-flow
Merge 95bd57fc1 into d56cda254
Pull Request #3863: Shared Secondary Particle Bank

17950 of 25871 branches covered (69.38%)

Branch coverage included in aggregate %.

407 of 417 new or added lines in 17 files covered. (97.6%)

1464 existing lines in 34 files now uncovered.

59095 of 68808 relevant lines covered (85.88%)

48517262.56 hits per line

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

79.16
/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)
270✔
52
{
53
  index_ = variance_reduction::weight_windows.size();
270✔
54
  set_id(id);
270✔
55
  set_defaults();
270✔
56
}
270✔
57

58
WeightWindows::WeightWindows(pugi::xml_node node)
217✔
59
{
60
  // Make sure required elements are present
61
  const vector<std::string> required_elems {
217✔
62
    "id", "particle_type", "lower_ww_bounds", "upper_ww_bounds"};
1,085!
63
  for (const auto& elem : required_elems) {
1,085✔
64
    if (!check_for_node(node, elem.c_str())) {
868!
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"));
434✔
71
  this->set_id(id);
217✔
72

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

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

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

85
  // get the survival value - optional
86
  if (check_for_node(node, "survival_ratio")) {
217!
87
    survival_ratio_ = std::stod(get_node_value(node, "survival_ratio"));
434✔
88
    if (survival_ratio_ <= 1)
217!
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")) {
217✔
95
    max_lb_ratio_ = std::stod(get_node_value(node, "max_lower_bound_ratio"));
124✔
96
    if (max_lb_ratio_ < 1.0) {
62!
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")) {
217!
103
    max_split_ = std::stod(get_node_value(node, "max_split"));
434✔
104
    if (max_split_ <= 1)
217!
105
      fatal_error("max split must be larger than 1");
×
106
  }
107

108
  // weight cutoff - optional
109
  if (check_for_node(node, "weight_cutoff")) {
217!
110
    weight_cutoff_ = std::stod(get_node_value(node, "weight_cutoff"));
434✔
111
    if (weight_cutoff_ <= 0)
217!
112
      fatal_error("weight_cutoff must be larger than 0");
×
113
    if (weight_cutoff_ > 1)
217!
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"),
217✔
119
    get_node_array<double>(node, "upper_ww_bounds"));
217✔
120

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

124
WeightWindows::~WeightWindows()
487✔
125
{
126
  variance_reduction::ww_map.erase(id());
487✔
127
}
1,461✔
128

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

138
WeightWindows* WeightWindows::from_hdf5(
11✔
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);
11✔
143

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

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

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

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

155
  if (model::mesh_map.count(mesh_id) == 0) {
11!
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]);
11✔
160

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

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

175
  close_group(ww_group);
11✔
176

177
  return wws;
11✔
178
}
11✔
179

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

193
void WeightWindows::allocate_ww_bounds()
724✔
194
{
195
  auto shape = bounds_size();
724✔
196
  if (shape[0] * shape[1] == 0) {
724!
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>(
724✔
202
    {static_cast<size_t>(shape[0]), static_cast<size_t>(shape[1])});
724✔
203
  lower_ww_.fill(-1);
724✔
204
  upper_ww_ = tensor::Tensor<double>(
724✔
205
    {static_cast<size_t>(shape[0]), static_cast<size_t>(shape[1])});
724✔
206
  upper_ww_.fill(-1);
724✔
207
}
724✔
208

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

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

219
  // Ensure no other mesh has the same ID
220
  if (variance_reduction::ww_map.find(id) != variance_reduction::ww_map.end()) {
641!
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) {
641✔
227
    id = 0;
270✔
228
    for (const auto& m : variance_reduction::weight_windows) {
292✔
229
      id = std::max(id, m->id_);
44!
230
    }
231
    ++id;
270✔
232
  }
233

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

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

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

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

261
  mesh_idx_ = mesh_idx;
487✔
262
  model::meshes[mesh_idx_]->prepare_for_point_location();
487✔
263
  allocate_ww_bounds();
487✔
264
}
487✔
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(
345,269,303✔
277
  const Particle& p) const
278
{
279
  // check for particle type
280
  if (particle_type_ != p.type()) {
345,269,303✔
281
    return {false, {}};
113,291,807✔
282
  }
283

284
  // particle energy
285
  double E = p.E();
231,977,496✔
286

287
  // check to make sure energy is in range, expects sorted energy values
288
  if (E < energy_bounds_.front() || E > energy_bounds_.back())
231,977,496!
289
    return {false, {}};
91,965✔
290

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

295
  // particle is outside the weight window mesh
296
  if (mesh_bin < 0)
231,885,531✔
297
    return {false, {}};
104,124✔
298

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

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

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

323
template<class T>
324
void WeightWindows::check_bounds(const T& lower, const T& upper) const
228!
325
{
326
  // make sure that the upper and lower bounds have the same size
327
  if (lower.size() != upper.size()) {
228!
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);
228✔
334
}
228✔
335

336
template<class T>
337
void WeightWindows::check_bounds(const T& bounds) const
228✔
338
{
339
  // check that the number of weight window entries is correct
340
  auto dims = this->bounds_size();
228✔
341
  if (bounds.size() != dims[0] * dims[1]) {
228!
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
}
228✔
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(
228✔
374
  span<const double> lower_bounds, span<const double> upper_bounds)
375
{
376
  check_bounds(lower_bounds, upper_bounds);
228✔
377
  auto shape = this->bounds_size();
228✔
378
  lower_ww_ = tensor::Tensor<double>(
228✔
379
    {static_cast<size_t>(shape[0]), static_cast<size_t>(shape[1])});
228✔
380
  upper_ww_ = tensor::Tensor<double>(
228✔
381
    {static_cast<size_t>(shape[0]), static_cast<size_t>(shape[1])});
228✔
382

383
  // Copy weight window values from input spans into the tensors
384
  std::copy(lower_bounds.data(), lower_bounds.data() + lower_ww_.size(),
228✔
385
    lower_ww_.data());
386
  std::copy(upper_bounds.data(), upper_bounds.data() + upper_ww_.size(),
228✔
387
    upper_ww_.data());
388
}
228✔
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,
287✔
409
  double threshold, double ratio, WeightWindowUpdateMethod method)
410
{
411
  ///////////////////////////
412
  // Setup and checks
413
  ///////////////////////////
414
  this->check_tally_update_compatibility(tally);
287✔
415

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

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

429
  // determine which value to use
430
  const std::set<std::string> allowed_values = {"mean", "rel_err"};
861!
431
  if (allowed_values.count(value) == 0) {
287!
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");
287✔
439
  if (score_index == C_NONE) {
287!
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();
287!
458
  const int results_dim = static_cast<int>(results.shape(2));
287!
459
  std::array<int, 5> shape = {1, 1, 1, tally->n_scores(), results_dim};
287✔
460

461
  // set the shape for the filters applied on the tally
462
  for (int i = 0; i < tally->filters().size(); i++) {
1,104✔
463
    const auto& filter = model::tally_filters[tally->filters(i)];
817✔
464
    shape[i] = filter->n_bins();
817✔
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};
287✔
469

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

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

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

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

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

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

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

501
    auto p_it =
265✔
502
      std::find(particles.begin(), particles.end(), this->particle_type_);
265!
503
    if (p_it == particles.end()) {
265!
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();
265✔
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];
287✔
525
  const int stride1 = shape[2];
287✔
526

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

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

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

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

546
      sum(e, m) = results(flat, score_index, i_sum);
2,622,568✔
547
      sum_sq(e, m) = results(flat, score_index, i_sum_sq);
2,622,568✔
548
    }
549
  }
550
  int n = tally->n_realizations_;
287✔
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_;
287✔
565
  auto& rel_err = this->upper_ww_;
287✔
566

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

570
  // Calculate mean (new_bounds) and relative error
571
#pragma omp parallel for collapse(2) schedule(static)
164✔
572
  for (int e = 0; e < e_bins; e++) {
956✔
573
    for (int64_t m = 0; m < mesh_bins; m++) {
1,180,891✔
574
      // Calculate mean
575
      new_bounds(e, m) = sum(e, m) / n;
1,180,058✔
576
      // Calculate relative error
577
      if (sum(e, m) > 0.0) {
1,180,058✔
578
        double mean_val = new_bounds(e, m);
105,005✔
579
        double variance = (sum_sq(e, m) / n - mean_val * mean_val) / (n - 1);
105,005✔
580
        rel_err(e, m) = std::sqrt(variance) / mean_val;
105,005✔
581
      } else {
582
        rel_err(e, m) = INFTY;
1,075,053✔
583
      }
584
      if (value == "rel_err") {
1,180,058✔
585
        new_bounds(e, m) = 1.0 / rel_err(e, m);
345,000✔
586
      }
587
    }
588
  }
589

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

598
  if (method == WeightWindowUpdateMethod::MAGIC) {
287✔
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++) {
1,892✔
604
      double group_max = 0.0;
942✔
605

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

614
      // Normalize values in this energy group by the maximum value
615
      if (group_max > 0.0) {
1,727✔
616
        double norm_factor = 1.0 / (2.0 * group_max);
1,694✔
617
#pragma omp parallel for schedule(static)
924✔
618
        for (int64_t m = 0; m < mesh_bins; m++) {
1,092,220✔
619
          new_bounds(e, m) *= norm_factor;
1,091,450✔
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)
74✔
627
    for (int e = 0; e < e_bins; e++) {
96✔
628
      for (int64_t m = 0; m < mesh_bins; m++) {
87,756✔
629
        // Take the inverse, but are careful not to divide by zero
630
        if (new_bounds(e, m) != 0.0) {
87,708✔
631
          new_bounds(e, m) = 1.0 / new_bounds(e, m);
73,090✔
632
        } else {
633
          new_bounds(e, m) = 0.0;
14,618✔
634
        }
635
      }
636
    }
637

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

649
    // Parallel normalization
650
    if (max_val > 0.0) {
122✔
651
      double norm_factor = 1.0 / (2.0 * max_val);
90✔
652
#pragma omp parallel for collapse(2) schedule(static)
50✔
653
      for (int e = 0; e < e_bins; e++) {
80✔
654
        for (int64_t m = 0; m < mesh_bins; m++) {
73,130✔
655
          new_bounds(e, m) *= norm_factor;
73,090✔
656
        }
657
      }
658
    }
659
  }
660

661
  // Final processing
662
#pragma omp parallel for collapse(2) schedule(static)
164✔
663
  for (int e = 0; e < e_bins; e++) {
956✔
664
    for (int64_t m = 0; m < mesh_bins; m++) {
1,180,891✔
665
      // Values where the mean is zero should be ignored
666
      if (sum(e, m) <= 0.0) {
1,180,058✔
667
        new_bounds(e, m) = -1.0;
1,075,053✔
668
      }
669
      // Values where the relative error is higher than the threshold should be
670
      // ignored
671
      else if (rel_err(e, m) > threshold) {
105,005✔
672
        new_bounds(e, m) = -1.0;
1,420✔
673
      }
674
      // Set the upper bounds
675
      upper_ww_(e, m) = ratio * lower_ww_(e, m);
1,180,058✔
676
    }
677
  }
678
}
861✔
679

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

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

689
  // a mesh filter is required for a tally used to update weight windows
690
  if (!filter_indices.count(FilterType::MESH)) {
287!
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>();
287✔
697

698
  // make sure that all of the filters present on the tally are allowed
699
  for (auto filter_pair : filter_indices) {
1,104✔
700
    if (allowed_filters.find(filter_pair.first) == allowed_filters.end()) {
817!
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_) {
287!
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>()) {
287✔
718
    std::vector<double> filter_bins = energy_filter->bins();
265✔
719
    std::set<double> filter_e_bounds(
265✔
720
      energy_filter->bins().begin(), energy_filter->bins().end());
265✔
721
    if (filter_e_bounds.size() != energy_bounds().size()) {
265!
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()) {
2,357✔
730
      if (filter_e_bounds.count(e) == 0) {
2,092!
731
        fatal_error(fmt::format(
×
732
          "Energy bounds of filter {} and weight windows {} do not match",
733
          energy_filter->id(), id_));
×
734
      }
735
    }
736
  }
265✔
737
}
287✔
738

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

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

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

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

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

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

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

789
  // set method
790
  std::string method_string = get_node_value(node, "method");
105✔
791
  if (method_string == "magic") {
105✔
792
    method_ = WeightWindowUpdateMethod::MAGIC;
44✔
793
    if (settings::solver_type == SolverType::RANDOM_RAY &&
44!
794
        FlatSourceDomain::adjoint_) {
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") {
61!
799
    method_ = WeightWindowUpdateMethod::FW_CADIS;
61✔
800
    if (settings::solver_type != SolverType::RANDOM_RAY) {
61!
801
      fatal_error("FW-CADIS can only be run in random ray solver mode.");
×
802
    }
803
    FlatSourceDomain::adjoint_ = true;
61✔
804
    if (check_for_node(node, "targets")) {
61✔
805
      FlatSourceDomain::fw_cadis_local_ = true;
15✔
806
      targets_ = get_node_array<size_t>(node, "targets");
15✔
807
      FlatSourceDomain::fw_cadis_local_targets_.insert(
15✔
808
        std::end(FlatSourceDomain::fw_cadis_local_targets_),
15✔
809
        std::begin(targets_), std::end(targets_));
15✔
810
    }
811
  } else {
UNCOV
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")) {
105✔
818
    pugi::xml_node params_node = node.child("update_parameters");
22✔
819
    if (check_for_node(params_node, "value"))
22!
820
      tally_value_ = get_node_value(params_node, "value");
22✔
821
    if (check_for_node(params_node, "threshold"))
22!
822
      threshold_ = std::stod(get_node_value(params_node, "threshold"));
44✔
823
    if (check_for_node(params_node, "ratio")) {
22!
824
      ratio_ = std::stod(get_node_value(params_node, "ratio"));
44✔
825
    }
826
  }
827

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

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

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

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

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

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

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

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

899
void WeightWindowsGenerator::update() const
2,632✔
900
{
901
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
2,632✔
902

903
  Tally* tally = model::tallies[tally_idx_].get();
2,632✔
904

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

917
  wws->update_weights(tally, tally_value_, threshold_, ratio_, method_);
166✔
918

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

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

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

932
std::pair<bool, WeightWindow> search_weight_window(const Particle& p)
290,935,628✔
933
{
934
  // TODO: this is a linear search - should do something more clever
935
  for (const auto& ww : variance_reduction::weight_windows) {
404,423,524✔
936
    auto [ww_found, weight_window] = ww->get_weight_window(p);
345,269,303✔
937
    if (ww_found)
345,269,303✔
938
      return {true, weight_window};
231,781,407✔
939
  }
940
  return {false, {}};
59,154,221✔
941
}
942

943
void apply_weight_windows(Particle& p)
177,984,996✔
944
{
945
  if (!settings::weight_windows_on)
177,984,996✔
946
    return;
177,042,215✔
947

948
  // WW on photon and neutron only
949
  if (!p.type().is_neutron() && !p.type().is_photon())
964,575!
950
    return;
951

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

956
  auto [ww_found, ww] = search_weight_window(p);
942,781✔
957
  if (ww_found && ww.is_valid()) {
942,781✔
958
    apply_weight_window(p, ww);
781,732✔
959
  } else {
960
    if (p.wgt_ww_born() == -1.0)
161,049✔
961
      p.wgt_ww_born() = 1.0;
51,386✔
962
  }
963
}
964

965
void apply_weight_window(Particle& p, WeightWindow weight_window)
290,697,180✔
966
{
967
  if (!weight_window.is_valid())
290,697,180✔
968
    return;
969

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

974
  // If particle has not yet had its birth weight window value set, set it to
975
  // the current weight window.
976
  if (p.wgt_ww_born() == -1.0)
189,329,829✔
977
    p.wgt_ww_born() =
739,204✔
978
      (weight_window.lower_weight + weight_window.upper_weight) / 2;
739,204✔
979

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

984
  // get the paramters
985
  double weight = p.wgt();
189,329,829✔
986

987
  // first check to see if particle should be killed for weight cutoff
988
  if (p.wgt() < weight_window.weight_cutoff) {
189,329,829✔
989
    p.wgt() = 0.0;
550✔
990
    return;
550✔
991
  }
992

993
  // check if particle is far above current weight window
994
  // only do this if the factor is not already set on the particle and a
995
  // maximum lower bound ratio is specified
996
  if (p.ww_factor() == 0.0 && weight_window.max_lb_ratio > 1.0 &&
189,329,279✔
997
      p.wgt() > weight_window.lower_weight * weight_window.max_lb_ratio) {
138,611✔
998
    p.ww_factor() =
102,344✔
999
      p.wgt() / (weight_window.lower_weight * weight_window.max_lb_ratio);
102,344✔
1000
  }
1001

1002
  // move weight window closer to the particle weight if needed
1003
  if (p.ww_factor() > 1.0)
189,329,279✔
1004
    weight_window.scale(p.ww_factor());
8,700,208✔
1005

1006
  // if particle's weight is above the weight window split until they are within
1007
  // the window
1008
  if (weight > weight_window.upper_weight) {
189,329,279✔
1009
    // do not further split the particle if above the limit
1010
    if (p.n_split() >= settings::max_history_splits)
15,357,012✔
1011
      return;
11,723,470✔
1012

1013
    double n_split = std::ceil(weight / weight_window.upper_weight);
3,633,542✔
1014
    double max_split = weight_window.max_split;
3,633,542✔
1015
    n_split = std::min(n_split, max_split);
3,633,542✔
1016

1017
    p.n_split() += n_split;
3,633,542✔
1018

1019
    // Create secondaries and divide weight among all particles
1020
    int i_split = std::round(n_split);
3,633,542✔
1021
    for (int l = 0; l < i_split - 1; l++) {
13,941,942✔
1022
      p.split(weight / n_split);
10,308,400✔
1023
    }
1024
    // remaining weight is applied to current particle
1025
    p.wgt() = weight / n_split;
3,633,542✔
1026

1027
  } else if (weight <= weight_window.lower_weight) {
173,972,267✔
1028
    // if the particle weight is below the window, play Russian roulette
1029
    double weight_survive =
6,307,423✔
1030
      std::min(weight * weight_window.max_split, weight_window.survival_weight);
6,307,423✔
1031
    russian_roulette(p, weight_survive);
6,307,423✔
1032
  } // else particle is in the window, continue as normal
1033
}
1034

1035
void free_memory_weight_windows()
8,654✔
1036
{
1037
  variance_reduction::ww_map.clear();
8,654✔
1038
  variance_reduction::weight_windows.clear();
8,654✔
1039
}
8,654✔
1040

1041
void finalize_variance_reduction()
8,498✔
1042
{
1043
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
8,603✔
1044
    wwg->create_tally();
105✔
1045
  }
1046
}
8,498✔
1047

1048
//==============================================================================
1049
// C API
1050
//==============================================================================
1051

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

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

1069
  *idx = it->second;
165✔
1070
  return 0;
165✔
1071
}
1072

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

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

1083
extern "C" int openmc_weight_windows_set_id(int32_t index, int32_t id)
154✔
1084
{
1085
  if (int err = verify_ww_index(index))
154!
1086
    return err;
1087

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

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

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

1104
  // get the requested tally
1105
  const Tally* tally = model::tallies.at(tally_idx).get();
121✔
1106

1107
  // get the WeightWindows object
1108
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
121✔
1109

1110
  wws->update_weights(tally, value, threshold, ratio);
121✔
1111

1112
  return 0;
121✔
1113
}
1114

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1293
extern "C" size_t openmc_weight_windows_size()
154✔
1294
{
1295
  return variance_reduction::weight_windows.size();
154✔
1296
}
1297

1298
extern "C" int openmc_weight_windows_export(const char* filename)
199✔
1299
{
1300

1301
  if (!mpi::master)
199✔
1302
    return 0;
1303

1304
  std::string name = filename ? filename : "weight_windows.h5";
301✔
1305

1306
  write_message(fmt::format("Exporting weight windows to {}...", name), 5);
197✔
1307

1308
  hid_t ww_file = file_open(name, 'w');
167✔
1309

1310
  // Write file type
1311
  write_attribute(ww_file, "filetype", "weight_windows");
167✔
1312

1313
  // Write revisiion number for state point file
1314
  write_attribute(ww_file, "version", VERSION_WEIGHT_WINDOWS);
167✔
1315

1316
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
167✔
1317

1318
  hid_t mesh_group = create_group(ww_file, "meshes");
167✔
1319

1320
  std::vector<int32_t> mesh_ids;
167✔
1321
  std::vector<int32_t> ww_ids;
167✔
1322
  for (const auto& ww : variance_reduction::weight_windows) {
334✔
1323

1324
    ww->to_hdf5(weight_windows_group);
167✔
1325
    ww_ids.push_back(ww->id());
167✔
1326

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

1332
    mesh_ids.push_back(mesh_id);
167✔
1333
    ww->mesh()->to_hdf5(mesh_group);
167✔
1334
  }
1335

1336
  write_attribute(mesh_group, "n_meshes", mesh_ids.size());
167✔
1337
  write_attribute(mesh_group, "ids", mesh_ids);
167✔
1338
  close_group(mesh_group);
167✔
1339

1340
  write_attribute(weight_windows_group, "n_weight_windows", ww_ids.size());
167✔
1341
  write_attribute(weight_windows_group, "ids", ww_ids);
167✔
1342
  close_group(weight_windows_group);
167✔
1343

1344
  file_close(ww_file);
167✔
1345

1346
  return 0;
167✔
1347
}
366✔
1348

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

1353
  if (mpi::master)
11!
1354
    write_message(fmt::format("Importing weight windows from {}...", name), 5);
24✔
1355

1356
  if (!file_exists(name)) {
11!
UNCOV
1357
    set_errmsg(fmt::format("File '{}' does not exist", name));
×
1358
  }
1359

1360
  hid_t ww_file = file_open(name, 'r');
11✔
1361

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

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

1383
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
11✔
1384

1385
  hid_t mesh_group = open_group(ww_file, "meshes");
11✔
1386

1387
  read_meshes(mesh_group);
11✔
1388

1389
  std::vector<std::string> names = group_names(weight_windows_group);
11✔
1390

1391
  for (const auto& name : names) {
22✔
1392
    WeightWindows::from_hdf5(weight_windows_group, name);
11✔
1393
  }
1394

1395
  close_group(weight_windows_group);
11✔
1396

1397
  file_close(ww_file);
11✔
1398

1399
  return 0;
11✔
1400
}
22✔
1401

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