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

openmc-dev / openmc / 18537555145

15 Oct 2025 05:37PM UTC coverage: 81.983% (-3.2%) from 85.194%
18537555145

Pull #3417

github

web-flow
Merge 3615a1fcc into e9077b137
Pull Request #3417: Addition of a collision tracking feature

16802 of 23354 branches covered (71.94%)

Branch coverage included in aggregate %.

480 of 522 new or added lines in 13 files covered. (91.95%)

483 existing lines in 53 files now uncovered.

54134 of 63171 relevant lines covered (85.69%)

43199115.04 hits per line

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

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

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

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

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

35
#include <fmt/core.h>
36

37
namespace openmc {
38

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

43
namespace variance_reduction {
44

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

49
} // namespace variance_reduction
50

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

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

60
  // WW on photon and neutron only
61
  if (p.type() != ParticleType::neutron && p.type() != ParticleType::photon)
87,137,006✔
62
    return;
10,925,319✔
63

64
  // skip dead or no energy
65
  if (p.E() <= 0 || !p.alive())
76,211,687✔
66
    return;
4,201,678✔
67

68
  bool in_domain = false;
72,010,009✔
69
  // TODO: this is a linear search - should do something more clever
70
  WeightWindow weight_window;
72,010,009✔
71
  for (const auto& ww : variance_reduction::weight_windows) {
89,592,266✔
72
    weight_window = ww->get_weight_window(p);
76,058,625✔
73
    if (weight_window.is_valid())
76,058,625✔
74
      break;
58,476,368✔
75
  }
76

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

88
  // particle is not in any of the ww domains, do nothing
89
  if (!weight_window.is_valid())
72,010,009✔
90
    return;
13,533,641✔
91

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

96
  // get the paramters
97
  double weight = p.wgt();
58,476,368✔
98

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

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

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

118
  // if particle's weight is above the weight window split until they are within
119
  // the window
120
  if (weight > weight_window.upper_weight) {
58,476,368✔
121
    // do not further split the particle if above the limit
122
    if (p.n_split() >= settings::max_history_splits)
15,077,807✔
123
      return;
13,692,289✔
124

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

129
    p.n_split() += n_split;
1,385,518✔
130

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

277
  close_group(ww_group);
13✔
278

279
  return wws;
13✔
280
}
13✔
281

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

389
  // particle energy
390
  double E = p.E();
72,185,789✔
391

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

644
  // Calculate mean (new_bounds) and relative error
645
#pragma omp parallel for collapse(2) schedule(static)
151✔
646
  for (int e = 0; e < e_bins; e++) {
962✔
647
    for (int64_t m = 0; m < mesh_bins; m++) {
1,270,308✔
648
      // Calculate mean
649
      new_bounds(e, m) = sum(e, m) / n;
1,269,469✔
650
      // Calculate relative error
651
      if (sum(e, m) > 0.0) {
1,269,469✔
652
        double mean_val = new_bounds(e, m);
105,642✔
653
        double variance = (sum_sq(e, m) / n - mean_val * mean_val) / (n - 1);
105,642✔
654
        rel_err(e, m) = std::sqrt(variance) / mean_val;
105,642✔
655
      } else {
656
        rel_err(e, m) = INFTY;
1,163,827✔
657
      }
658
      if (value == "rel_err") {
1,269,469✔
659
        new_bounds(e, m) = 1.0 / rel_err(e, m);
345,000✔
660
      }
661
    }
662
  }
663

664
  // Divide by volume of mesh elements
665
#pragma omp parallel for collapse(2) schedule(static)
151✔
666
  for (int e = 0; e < e_bins; e++) {
962✔
667
    for (int64_t m = 0; m < mesh_bins; m++) {
1,270,308✔
668
      new_bounds(e, m) /= mesh_vols[m];
1,269,469✔
669
    }
670
  }
671

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

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

680
      // Find maximum value across all elements in this energy group
681
#pragma omp parallel for schedule(static) reduction(max : group_max)
953✔
682
      for (int64_t m = 0; m < mesh_bins; m++) {
1,172,742✔
683
        if (new_bounds(e, m) > group_max) {
1,171,945✔
684
          group_max = new_bounds(e, m);
2,701✔
685
        }
686
      }
687

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

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

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

735
  // Final processing
736
#pragma omp parallel for collapse(2) schedule(static)
151✔
737
  for (int e = 0; e < e_bins; e++) {
962✔
738
    for (int64_t m = 0; m < mesh_bins; m++) {
1,270,308✔
739
      // Values where the mean is zero should be ignored
740
      if (sum(e, m) <= 0.0) {
1,269,469✔
741
        new_bounds(e, m) = -1.0;
1,163,827✔
742
      }
743
      // Values where the relative error is higher than the threshold should be
744
      // ignored
745
      else if (rel_err(e, m) > threshold) {
105,642✔
746
        new_bounds(e, m) = -1.0;
1,704✔
747
      }
748
      // Set the upper bounds
749
      upper_ww_(e, m) = ratio * lower_ww_(e, m);
1,269,469✔
750
    }
751
  }
752
}
274✔
753

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

975
  wws->update_weights(tally, tally_value_, threshold_, ratio_, method_);
131✔
976

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

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

986
//==============================================================================
987
// Non-member functions
988
//==============================================================================
989

990
void finalize_variance_reduction()
7,853✔
991
{
992
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
7,935✔
993
    wwg->create_tally();
82✔
994
  }
995
}
7,853✔
996

997
//==============================================================================
998
// C API
999
//==============================================================================
1000

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

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

1018
  *idx = it->second;
195✔
1019
  return 0;
195✔
1020
}
1021

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

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

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

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

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

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

1053
  // get the requested tally
1054
  const Tally* tally = model::tallies.at(tally_idx).get();
143✔
1055

1056
  // get the WeightWindows object
1057
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
143✔
1058

1059
  wws->update_weights(tally, value, threshold, ratio);
143✔
1060

1061
  return 0;
143✔
1062
}
1063

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1239
extern "C" size_t openmc_weight_windows_size()
182✔
1240
{
1241
  return variance_reduction::weight_windows.size();
182✔
1242
}
1243

1244
extern "C" int openmc_weight_windows_export(const char* filename)
170✔
1245
{
1246

1247
  if (!mpi::master)
170✔
1248
    return 0;
30✔
1249

1250
  std::string name = filename ? filename : "weight_windows.h5";
280✔
1251

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

1254
  hid_t ww_file = file_open(name, 'w');
140✔
1255

1256
  // Write file type
1257
  write_attribute(ww_file, "filetype", "weight_windows");
140✔
1258

1259
  // Write revisiion number for state point file
1260
  write_attribute(ww_file, "version", VERSION_WEIGHT_WINDOWS);
140✔
1261

1262
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
140✔
1263

1264
  hid_t mesh_group = create_group(ww_file, "meshes");
140✔
1265

1266
  std::vector<int32_t> mesh_ids;
140✔
1267
  std::vector<int32_t> ww_ids;
140✔
1268
  for (const auto& ww : variance_reduction::weight_windows) {
280✔
1269

1270
    ww->to_hdf5(weight_windows_group);
140✔
1271
    ww_ids.push_back(ww->id());
140✔
1272

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

1278
    mesh_ids.push_back(mesh_id);
140✔
1279
    ww->mesh()->to_hdf5(mesh_group);
140✔
1280
  }
1281

1282
  write_attribute(mesh_group, "n_meshes", mesh_ids.size());
140✔
1283
  write_attribute(mesh_group, "ids", mesh_ids);
140✔
1284
  close_group(mesh_group);
140✔
1285

1286
  write_attribute(weight_windows_group, "n_weight_windows", ww_ids.size());
140✔
1287
  write_attribute(weight_windows_group, "ids", ww_ids);
140✔
1288
  close_group(weight_windows_group);
140✔
1289

1290
  file_close(ww_file);
140✔
1291

1292
  return 0;
140✔
1293
}
140✔
1294

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

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

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

1306
  hid_t ww_file = file_open(name, 'r');
13✔
1307

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

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

1329
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
13✔
1330

1331
  std::vector<std::string> names = group_names(weight_windows_group);
13✔
1332

1333
  for (const auto& name : names) {
26✔
1334
    WeightWindows::from_hdf5(weight_windows_group, name);
13✔
1335
  }
1336

1337
  close_group(weight_windows_group);
13✔
1338

1339
  file_close(ww_file);
13✔
1340

1341
  return 0;
13✔
1342
}
13✔
1343

1344
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc