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

openmc-dev / openmc / 12917063146

22 Jan 2025 09:06PM UTC coverage: 84.955% (+0.03%) from 84.928%
12917063146

Pull #3273

github

web-flow
Merge eb5bd7f4b into 560bd22bc
Pull Request #3273: FW-CADIS Weight Window Generation with Random Ray

42 of 46 new or added lines in 3 files covered. (91.3%)

7 existing lines in 2 files now uncovered.

50193 of 59082 relevant lines covered (84.95%)

34673610.05 hits per line

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

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

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

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

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

34
#include <fmt/core.h>
35
#include <gsl/gsl-lite.hpp>
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)
68,221,678✔
62
    return;
4,927,608✔
63

64
  // skip dead or no energy
65
  if (p.E() <= 0 || !p.alive())
63,294,070✔
66
    return;
1,372,141✔
67

68
  bool in_domain = false;
61,921,929✔
69
  // TODO: this is a linear search - should do something more clever
70
  WeightWindow weight_window;
61,921,929✔
71
  for (const auto& ww : variance_reduction::weight_windows) {
80,854,467✔
72
    weight_window = ww->get_weight_window(p);
66,558,117✔
73
    if (weight_window.is_valid())
66,558,117✔
74
      break;
47,625,579✔
75
  }
76
  // particle is not in any of the ww domains, do nothing
77
  if (!weight_window.is_valid())
61,921,929✔
78
    return;
14,296,350✔
79

80
  // get the paramters
81
  double weight = p.wgt();
47,625,579✔
82

83
  // first check to see if particle should be killed for weight cutoff
84
  if (p.wgt() < weight_window.weight_cutoff) {
47,625,579✔
85
    p.wgt() = 0.0;
×
86
    return;
×
87
  }
88

89
  // check if particle is far above current weight window
90
  // only do this if the factor is not already set on the particle and a
91
  // maximum lower bound ratio is specified
92
  if (p.ww_factor() == 0.0 && weight_window.max_lb_ratio > 1.0 &&
47,628,675✔
93
      p.wgt() > weight_window.lower_weight * weight_window.max_lb_ratio) {
3,096✔
94
    p.ww_factor() =
3,096✔
95
      p.wgt() / (weight_window.lower_weight * weight_window.max_lb_ratio);
3,096✔
96
  }
97

98
  // move weight window closer to the particle weight if needed
99
  if (p.ww_factor() > 1.0)
47,625,579✔
100
    weight_window.scale(p.ww_factor());
1,579,560✔
101

102
  // if particle's weight is above the weight window split until they are within
103
  // the window
104
  if (weight > weight_window.upper_weight) {
47,625,579✔
105
    // do not further split the particle if above the limit
106
    if (p.n_split() >= settings::max_history_splits)
10,702,682✔
107
      return;
10,018,937✔
108

109
    double n_split = std::ceil(weight / weight_window.upper_weight);
683,745✔
110
    double max_split = weight_window.max_split;
683,745✔
111
    n_split = std::min(n_split, max_split);
683,745✔
112

113
    p.n_split() += n_split;
683,745✔
114

115
    // Create secondaries and divide weight among all particles
116
    int i_split = std::round(n_split);
683,745✔
117
    for (int l = 0; l < i_split - 1; l++) {
2,475,511✔
118
      p.create_secondary(weight / n_split, p.u(), p.E(), p.type());
1,791,766✔
119
    }
120
    // remaining weight is applied to current particle
121
    p.wgt() = weight / n_split;
683,745✔
122

123
  } else if (weight <= weight_window.lower_weight) {
36,922,897✔
124
    // if the particle weight is below the window, play Russian roulette
125
    double weight_survive =
126
      std::min(weight * weight_window.max_split, weight_window.survival_weight);
1,270,149✔
127
    russian_roulette(p, weight_survive);
1,270,149✔
128
  } // else particle is in the window, continue as normal
129
}
130

131
void free_memory_weight_windows()
6,953✔
132
{
133
  variance_reduction::ww_map.clear();
6,953✔
134
  variance_reduction::weight_windows.clear();
6,953✔
135
}
6,953✔
136

137
//==============================================================================
138
// WeightWindowSettings implementation
139
//==============================================================================
140

141
WeightWindows::WeightWindows(int32_t id)
221✔
142
{
143
  index_ = variance_reduction::weight_windows.size();
221✔
144
  set_id(id);
221✔
145
  set_defaults();
221✔
146
}
221✔
147

148
WeightWindows::WeightWindows(pugi::xml_node node)
73✔
149
{
150
  // Make sure required elements are present
151
  const vector<std::string> required_elems {
152
    "id", "particle_type", "lower_ww_bounds", "upper_ww_bounds"};
511✔
153
  for (const auto& elem : required_elems) {
365✔
154
    if (!check_for_node(node, elem.c_str())) {
292✔
155
      fatal_error(fmt::format("Must specify <{}> for weight windows.", elem));
×
156
    }
157
  }
158

159
  // Get weight windows ID
160
  int32_t id = std::stoi(get_node_value(node, "id"));
73✔
161
  this->set_id(id);
73✔
162

163
  // get the particle type
164
  auto particle_type_str = std::string(get_node_value(node, "particle_type"));
73✔
165
  particle_type_ = openmc::str_to_particle_type(particle_type_str);
73✔
166

167
  // Determine associated mesh
168
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
73✔
169
  set_mesh(model::mesh_map.at(mesh_id));
73✔
170

171
  // energy bounds
172
  if (check_for_node(node, "energy_bounds"))
73✔
173
    energy_bounds_ = get_node_array<double>(node, "energy_bounds");
70✔
174

175
  // get the survival value - optional
176
  if (check_for_node(node, "survival_ratio")) {
73✔
177
    survival_ratio_ = std::stod(get_node_value(node, "survival_ratio"));
73✔
178
    if (survival_ratio_ <= 1)
73✔
179
      fatal_error("Survival to lower weight window ratio must bigger than 1 "
×
180
                  "and less than the upper to lower weight window ratio.");
181
  }
182

183
  // get the max lower bound ratio - optional
184
  if (check_for_node(node, "max_lower_bound_ratio")) {
73✔
185
    max_lb_ratio_ = std::stod(get_node_value(node, "max_lower_bound_ratio"));
34✔
186
    if (max_lb_ratio_ < 1.0) {
34✔
187
      fatal_error("Maximum lower bound ratio must be larger than 1");
×
188
    }
189
  }
190

191
  // get the max split - optional
192
  if (check_for_node(node, "max_split")) {
73✔
193
    max_split_ = std::stod(get_node_value(node, "max_split"));
73✔
194
    if (max_split_ <= 1)
73✔
195
      fatal_error("max split must be larger than 1");
×
196
  }
197

198
  // weight cutoff - optional
199
  if (check_for_node(node, "weight_cutoff")) {
73✔
200
    weight_cutoff_ = std::stod(get_node_value(node, "weight_cutoff"));
73✔
201
    if (weight_cutoff_ <= 0)
73✔
202
      fatal_error("weight_cutoff must be larger than 0");
×
203
    if (weight_cutoff_ > 1)
73✔
204
      fatal_error("weight_cutoff must be less than 1");
×
205
  }
206

207
  // read the lower/upper weight bounds
208
  this->set_bounds(get_node_array<double>(node, "lower_ww_bounds"),
73✔
209
    get_node_array<double>(node, "upper_ww_bounds"));
146✔
210

211
  set_defaults();
73✔
212
}
73✔
213

214
WeightWindows::~WeightWindows()
294✔
215
{
216
  variance_reduction::ww_map.erase(id());
294✔
217
}
294✔
218

219
WeightWindows* WeightWindows::create(int32_t id)
53✔
220
{
221
  variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
53✔
222
  auto wws = variance_reduction::weight_windows.back().get();
53✔
223
  variance_reduction::ww_map[wws->id()] =
53✔
224
    variance_reduction::weight_windows.size() - 1;
53✔
225
  return wws;
53✔
226
}
227

228
WeightWindows* WeightWindows::from_hdf5(
12✔
229
  hid_t wws_group, const std::string& group_name)
230
{
231
  // collect ID from the name of this group
232
  hid_t ww_group = open_group(wws_group, group_name);
12✔
233

234
  auto wws = WeightWindows::create();
12✔
235

236
  std::string particle_type;
12✔
237
  read_dataset(ww_group, "particle_type", particle_type);
12✔
238
  wws->particle_type_ = openmc::str_to_particle_type(particle_type);
12✔
239

240
  read_dataset<double>(ww_group, "energy_bounds", wws->energy_bounds_);
12✔
241

242
  int32_t mesh_id;
243
  read_dataset(ww_group, "mesh", mesh_id);
12✔
244

245
  if (model::mesh_map.count(mesh_id) == 0) {
12✔
246
    fatal_error(
×
247
      fmt::format("Mesh {} used in weight windows does not exist.", mesh_id));
×
248
  }
249
  wws->set_mesh(model::mesh_map[mesh_id]);
12✔
250

251
  wws->lower_ww_ = xt::empty<double>(wws->bounds_size());
12✔
252
  wws->upper_ww_ = xt::empty<double>(wws->bounds_size());
12✔
253

254
  read_dataset<double>(ww_group, "lower_ww_bounds", wws->lower_ww_);
12✔
255
  read_dataset<double>(ww_group, "upper_ww_bounds", wws->upper_ww_);
12✔
256
  read_dataset(ww_group, "survival_ratio", wws->survival_ratio_);
12✔
257
  read_dataset(ww_group, "max_lower_bound_ratio", wws->max_lb_ratio_);
12✔
258
  read_dataset(ww_group, "max_split", wws->max_split_);
12✔
259
  read_dataset(ww_group, "weight_cutoff", wws->weight_cutoff_);
12✔
260

261
  close_group(ww_group);
12✔
262

263
  return wws;
12✔
264
}
12✔
265

266
void WeightWindows::set_defaults()
335✔
267
{
268
  // set energy bounds to the min/max energy supported by the data
269
  if (energy_bounds_.size() == 0) {
335✔
270
    int p_type = static_cast<int>(particle_type_);
224✔
271
    energy_bounds_.push_back(data::energy_min[p_type]);
224✔
272
    energy_bounds_.push_back(data::energy_max[p_type]);
224✔
273
  }
274
}
335✔
275

276
void WeightWindows::allocate_ww_bounds()
479✔
277
{
278
  auto shape = bounds_size();
479✔
279
  if (shape[0] * shape[1] == 0) {
479✔
280
    auto msg = fmt::format(
281
      "Size of weight window bounds is zero for WeightWindows {}", id());
×
282
    warning(msg);
×
283
  }
284
  lower_ww_ = xt::empty<double>(shape);
479✔
285
  lower_ww_.fill(-1);
479✔
286
  upper_ww_ = xt::empty<double>(shape);
479✔
287
  upper_ww_.fill(-1);
479✔
288
}
479✔
289

290
void WeightWindows::set_id(int32_t id)
462✔
291
{
292
  Expects(id >= 0 || id == C_NONE);
462✔
293

294
  // Clear entry in mesh map in case one was already assigned
295
  if (id_ != C_NONE) {
462✔
296
    variance_reduction::ww_map.erase(id_);
462✔
297
    id_ = C_NONE;
462✔
298
  }
299

300
  // Ensure no other mesh has the same ID
301
  if (variance_reduction::ww_map.find(id) != variance_reduction::ww_map.end()) {
462✔
302
    throw std::runtime_error {
×
303
      fmt::format("Two weight windows have the same ID: {}", id)};
×
304
  }
305

306
  // If no ID is specified, auto-assign the next ID in the sequence
307
  if (id == C_NONE) {
462✔
308
    id = 0;
221✔
309
    for (const auto& m : variance_reduction::weight_windows) {
245✔
310
      id = std::max(id, m->id_);
24✔
311
    }
312
    ++id;
221✔
313
  }
314

315
  // Update ID and entry in the mesh map
316
  id_ = id;
462✔
317
  variance_reduction::ww_map[id] = index_;
462✔
318
}
462✔
319

320
void WeightWindows::set_energy_bounds(gsl::span<const double> bounds)
185✔
321
{
322
  energy_bounds_.clear();
185✔
323
  energy_bounds_.insert(energy_bounds_.begin(), bounds.begin(), bounds.end());
185✔
324
  // if the mesh is set, allocate space for weight window bounds
325
  if (mesh_idx_ != C_NONE)
185✔
326
    allocate_ww_bounds();
185✔
327
}
185✔
328

329
void WeightWindows::set_particle_type(ParticleType p_type)
233✔
330
{
331
  if (p_type != ParticleType::neutron && p_type != ParticleType::photon)
233✔
332
    fatal_error(
×
333
      fmt::format("Particle type '{}' cannot be applied to weight windows.",
×
334
        particle_type_to_str(p_type)));
×
335
  particle_type_ = p_type;
233✔
336
}
233✔
337

338
void WeightWindows::set_mesh(int32_t mesh_idx)
294✔
339
{
340
  if (mesh_idx < 0 || mesh_idx >= model::meshes.size())
294✔
341
    fatal_error(fmt::format("Could not find a mesh for index {}", mesh_idx));
×
342

343
  mesh_idx_ = mesh_idx;
294✔
344
  model::meshes[mesh_idx_]->prepare_for_point_location();
294✔
345
  allocate_ww_bounds();
294✔
346
}
294✔
347

348
void WeightWindows::set_mesh(const std::unique_ptr<Mesh>& mesh)
×
349
{
350
  set_mesh(mesh.get());
×
351
}
352

353
void WeightWindows::set_mesh(const Mesh* mesh)
×
354
{
355
  set_mesh(model::mesh_map[mesh->id_]);
×
356
}
357

358
WeightWindow WeightWindows::get_weight_window(const Particle& p) const
66,558,117✔
359
{
360
  // check for particle type
361
  if (particle_type_ != p.type()) {
66,558,117✔
362
    return {};
4,377,696✔
363
  }
364

365
  // Get mesh index for particle's position
366
  const auto& mesh = this->mesh();
62,180,421✔
367
  int mesh_bin = mesh->get_bin(p.r());
62,180,421✔
368

369
  // particle is outside the weight window mesh
370
  if (mesh_bin < 0)
62,180,421✔
371
    return {};
×
372

373
  // particle energy
374
  double E = p.E();
62,180,421✔
375

376
  // check to make sure energy is in range, expects sorted energy values
377
  if (E < energy_bounds_.front() || E > energy_bounds_.back())
62,180,421✔
378
    return {};
58,224✔
379

380
  // get the mesh bin in energy group
381
  int energy_bin =
382
    lower_bound_index(energy_bounds_.begin(), energy_bounds_.end(), E);
62,122,197✔
383

384
  // mesh_bin += energy_bin * mesh->n_bins();
385
  // Create individual weight window
386
  WeightWindow ww;
62,122,197✔
387
  ww.lower_weight = lower_ww_(energy_bin, mesh_bin);
62,122,197✔
388
  ww.upper_weight = upper_ww_(energy_bin, mesh_bin);
62,122,197✔
389
  ww.survival_weight = ww.lower_weight * survival_ratio_;
62,122,197✔
390
  ww.max_lb_ratio = max_lb_ratio_;
62,122,197✔
391
  ww.max_split = max_split_;
62,122,197✔
392
  ww.weight_cutoff = weight_cutoff_;
62,122,197✔
393
  return ww;
62,122,197✔
394
}
395

396
std::array<int, 2> WeightWindows::bounds_size() const
673✔
397
{
398
  int num_spatial_bins = this->mesh()->n_bins();
673✔
399
  int num_energy_bins =
400
    energy_bounds_.size() > 0 ? energy_bounds_.size() - 1 : 1;
673✔
401
  return {num_energy_bins, num_spatial_bins};
673✔
402
}
403

404
template<class T>
405
void WeightWindows::check_bounds(const T& lower, const T& upper) const
85✔
406
{
407
  // make sure that the upper and lower bounds have the same size
408
  if (lower.size() != upper.size()) {
85✔
409
    auto msg = fmt::format("The upper and lower weight window lengths do not "
×
410
                           "match.\n Lower size: {}\n Upper size: {}",
411
      lower.size(), upper.size());
×
412
    fatal_error(msg);
×
413
  }
×
414
  this->check_bounds(lower);
85✔
415
}
85✔
416

85✔
417
template<class T>
418
void WeightWindows::check_bounds(const T& bounds) const
419
{
85✔
420
  // check that the number of weight window entries is correct
×
421
  auto dims = this->bounds_size();
422
  if (bounds.size() != dims[0] * dims[1]) {
×
423
    auto err_msg =
×
424
      fmt::format("In weight window domain {} the number of spatial "
×
425
                  "energy/spatial bins ({}) does not match the number "
85✔
426
                  "of weight bins ({})",
85✔
427
        id_, dims, bounds.size());
×
428
    fatal_error(err_msg);
429
  }
430
}
×
431

×
432
void WeightWindows::set_bounds(const xt::xtensor<double, 2>& lower_bounds,
433
  const xt::xtensor<double, 2>& upper_bounds)
×
434
{
×
435

×
436
  this->check_bounds(lower_bounds, upper_bounds);
×
437

438
  // set new weight window values
439
  lower_ww_ = lower_bounds;
440
  upper_ww_ = upper_bounds;
85✔
441
}
442

443
void WeightWindows::set_bounds(
85✔
444
  const xt::xtensor<double, 2>& lower_bounds, double ratio)
85✔
445
{
×
446
  this->check_bounds(lower_bounds);
447

448
  // set new weight window values
449
  lower_ww_ = lower_bounds;
×
450
  upper_ww_ = lower_bounds;
×
451
  upper_ww_ *= ratio;
×
452
}
85✔
453

85✔
454
void WeightWindows::set_bounds(
455
  gsl::span<const double> lower_bounds, gsl::span<const double> upper_bounds)
456
{
85✔
457
  check_bounds(lower_bounds, upper_bounds);
85✔
458
  auto shape = this->bounds_size();
×
459
  lower_ww_ = xt::empty<double>(shape);
460
  upper_ww_ = xt::empty<double>(shape);
461

462
  // set new weight window values
×
463
  xt::view(lower_ww_, xt::all()) =
×
464
    xt::adapt(lower_bounds.data(), lower_ww_.shape());
×
465
  xt::view(upper_ww_, xt::all()) =
85✔
466
    xt::adapt(upper_bounds.data(), upper_ww_.shape());
×
467
}
468

469
void WeightWindows::set_bounds(
×
470
  gsl::span<const double> lower_bounds, double ratio)
×
471
{
×
472
  this->check_bounds(lower_bounds);
473

474
  auto shape = this->bounds_size();
475
  lower_ww_ = xt::empty<double>(shape);
×
476
  upper_ww_ = xt::empty<double>(shape);
×
477

×
478
  // set new weight window values
479
  xt::view(lower_ww_, xt::all()) =
480
    xt::adapt(lower_bounds.data(), lower_ww_.shape());
×
481
  xt::view(upper_ww_, xt::all()) =
482
    xt::adapt(lower_bounds.data(), upper_ww_.shape());
483
  upper_ww_ *= ratio;
484
}
×
485

486
void WeightWindows::update_magic(
487
  const Tally* tally, const std::string& value, double threshold, double ratio)
×
488
{
×
489
  ///////////////////////////
490
  // Setup and checks
491
  ///////////////////////////
×
492
  this->check_tally_update_compatibility(tally);
493

494
  lower_ww_.fill(-1);
×
495
  upper_ww_.fill(-1);
496

497
  // determine which value to use
×
498
  const std::set<std::string> allowed_values = {"mean", "rel_err"};
×
499
  if (allowed_values.count(value) == 0) {
×
500
    fatal_error(fmt::format("Invalid value '{}' specified for weight window "
501
                            "generation. Must be one of: 'mean' or 'rel_err'",
502
      value));
85✔
503
  }
504

505
  // determine the index of the specified score
85✔
506
  int score_index = tally->score_index("flux");
85✔
507
  if (score_index == C_NONE) {
85✔
508
    fatal_error(
85✔
509
      fmt::format("A 'flux' score required for weight window generation "
510
                  "is not present on tally {}.",
511
        tally->id()));
170✔
512
  }
255✔
513

170✔
514
  ///////////////////////////
255✔
515
  // Extract tally data
85✔
516
  //
517
  // At the end of this section, the mean and rel_err array
×
518
  // is a 2D view of tally data (n_e_groups, n_mesh_bins)
519
  //
520
  ///////////////////////////
×
521

522
  // build a shape for a view of the tally results, this will always be
×
523
  // dimension 5 (3 filter dimensions, 1 score dimension, 1 results dimension)
×
524
  std::array<int, 5> shape = {
×
525
    1, 1, 1, tally->n_scores(), static_cast<int>(TallyResult::SIZE)};
526

527
  // set the shape for the filters applied on the tally
×
528
  for (int i = 0; i < tally->filters().size(); i++) {
×
529
    const auto& filter = model::tally_filters[tally->filters(i)];
×
530
    shape[i] = filter->n_bins();
×
531
  }
×
532

533
  // build the transpose information to re-order data according to filter type
534
  std::array<int, 5> transpose = {0, 1, 2, 3, 4};
496✔
535

536
  // track our filter types and where we've added new ones
537
  std::vector<FilterType> filter_types = tally->filter_types();
538

539
  // assign other filter types to dummy positions if needed
540
  if (!tally->has_filter(FilterType::PARTICLE))
496✔
541
    filter_types.push_back(FilterType::PARTICLE);
542

496✔
543
  if (!tally->has_filter(FilterType::ENERGY))
496✔
544
    filter_types.push_back(FilterType::ENERGY);
545

546
  // particle axis mapping
2,480✔
547
  transpose[0] =
496✔
548
    std::find(filter_types.begin(), filter_types.end(), FilterType::PARTICLE) -
×
549
    filter_types.begin();
550

551
  // energy axis mapping
552
  transpose[1] =
553
    std::find(filter_types.begin(), filter_types.end(), FilterType::ENERGY) -
554
    filter_types.begin();
496✔
555

496✔
556
  // mesh axis mapping
×
557
  transpose[2] =
×
558
    std::find(filter_types.begin(), filter_types.end(), FilterType::MESH) -
559
    filter_types.begin();
×
560

561
  // get a fully reshaped view of the tally according to tally ordering of
562
  // filters
563
  auto tally_values = xt::reshape_view(tally->results(), shape);
564

565
  // get a that is (particle, energy, mesh, scores, values)
566
  auto transposed_view = xt::transpose(tally_values, transpose);
567

568
  // determine the dimension and index of the particle data
569
  int particle_idx = 0;
570
  if (tally->has_filter(FilterType::PARTICLE)) {
571
    // get the particle filter
572
    auto pf = tally->get_filter<ParticleFilter>();
496✔
573
    const auto& particles = pf->particles();
496✔
574

575
    // find the index of the particle that matches these weight windows
576
    auto p_it =
1,936✔
577
      std::find(particles.begin(), particles.end(), this->particle_type_);
1,440✔
578
    // if the particle filter doesn't have particle data for the particle
1,440✔
579
    // used on this weight windows instance, report an error
580
    if (p_it == particles.end()) {
581
      auto msg = fmt::format("Particle type '{}' not present on Filter {} for "
582
                             "Tally {} used to update WeightWindows {}",
496✔
583
        particle_type_to_str(this->particle_type_), pf->id(), tally->id(),
584
        this->id());
585
      fatal_error(msg);
496✔
586
    }
587

588
    // use the index of the particle in the filter to down-select data later
496✔
589
    particle_idx = p_it - particles.begin();
24✔
590
  }
591

496✔
592
  // down-select data based on particle and score
24✔
593
  auto sum = xt::view(transposed_view, particle_idx, xt::all(), xt::all(),
594
    score_index, static_cast<int>(TallyResult::SUM));
595
  auto sum_sq = xt::view(transposed_view, particle_idx, xt::all(), xt::all(),
496✔
596
    score_index, static_cast<int>(TallyResult::SUM_SQ));
496✔
597
  int n = tally->n_realizations_;
496✔
598

599
  //////////////////////////////////////////////
600
  //
496✔
601
  // Assign new weight windows
496✔
602
  //
496✔
603
  // Use references to the existing weight window data
604
  // to store and update the values
605
  //
496✔
606
  //////////////////////////////////////////////
496✔
607

496✔
608
  // up to this point the data arrays are views into the tally results (no
609
  // computation has been performed) now we'll switch references to the tally's
610
  // bounds to avoid allocating additional memory
611
  auto& new_bounds = this->lower_ww_;
496✔
612
  auto& rel_err = this->upper_ww_;
613

614
  // noalias avoids memory allocation here
496✔
615
  xt::noalias(new_bounds) = sum / n;
616

617
  xt::noalias(rel_err) =
496✔
618
    xt::sqrt(((sum_sq / n) - xt::square(new_bounds)) / (n - 1)) / new_bounds;
496✔
619
  xt::filter(rel_err, sum <= 0.0).fill(INFTY);
620

472✔
621
  if (value == "rel_err")
472✔
622
    xt::noalias(new_bounds) = 1 / rel_err;
623

624
  // get mesh volumes
625
  auto mesh_vols = this->mesh()->volumes();
472✔
626

627
  int e_bins = new_bounds.shape()[0];
628

472✔
629
  if (settings::solver_type == SolverType::MONTE_CARLO ||
630
      !FlatSourceDomain::adjoint_) {
NEW
631
    // If we are computing weight windows with forward fluxes derived from a
×
NEW
632
    // Monte Carlo or forward random ray solve, we use the MAGIC algorithm.
×
NEW
633
    for (int e = 0; e < e_bins; e++) {
×
NEW
634
      // select all
×
635
      auto group_view = xt::view(new_bounds, e);
636

637
      // divide by volume of mesh elements
472✔
638
      for (int i = 0; i < group_view.size(); i++) {
639
        group_view[i] /= mesh_vols[i];
640
      }
641

496✔
642
      double group_max =
992✔
643
        *std::max_element(group_view.begin(), group_view.end());
496✔
644
      // normalize values in this energy group by the maximum value for this
992✔
645
      // group
496✔
646
      if (group_max > 0.0)
647
        group_view /= 2.0 * group_max;
648
    }
649
  } else {
650
    // If we are computing weight windows with adjoint fluxes derived from an
651
    // adjoint random ray solve, we use the FW-CADIS algorithm.
652
    for (int e = 0; e < e_bins; e++) {
653
      // select all
654
      auto group_view = xt::view(new_bounds, e);
655

656
      // divide by volume of mesh elements
657
      for (int i = 0; i < group_view.size(); i++) {
658
        group_view[i] /= mesh_vols[i];
659
      }
496✔
660
    }
496✔
661

662
    xt::noalias(new_bounds) = 1.0 / new_bounds;
663

496✔
664
    auto max_val = xt::amax(new_bounds)();
665

496✔
666
    xt::noalias(new_bounds) = new_bounds / (2.0 * max_val);
992✔
667
  }
496✔
668

669
  // make sure that values where the mean is zero are set s.t. the weight window
496✔
670
  // value will be ignored
12✔
671
  xt::filter(new_bounds, sum <= 0.0).fill(-1.0);
672

673
  // make sure the weight windows are ignored for any locations where the
496✔
674
  // relative error is higher than the specified relative error threshold
675
  xt::filter(new_bounds, rel_err > threshold).fill(-1.0);
496✔
676

677
  // update the bounds of this weight window class
496✔
678
  // noalias avoids additional memory allocation
340✔
679
  xt::noalias(upper_ww_) = ratio * lower_ww_;
680
}
681

2,356✔
682
void WeightWindows::check_tally_update_compatibility(const Tally* tally)
683
{
2,030✔
684
  // define the set of allowed filters for the tally
685
  const std::set<FilterType> allowed_filters = {
686
    FilterType::MESH, FilterType::ENERGY, FilterType::PARTICLE};
2,657,390✔
687

2,655,360✔
688
  // retrieve a mapping of filter type to filter index for the tally
689
  auto filter_indices = tally->filter_indices();
690

691
  // a mesh filter is required for a tally used to update weight windows
2,030✔
692
  if (!filter_indices.count(FilterType::MESH)) {
693
    fatal_error(
694
      "A mesh filter is required for a tally to update weight window bounds");
2,030✔
695
  }
1,884✔
696

2,030✔
697
  // ensure the mesh filter is using the same mesh as this weight window object
326✔
698
  auto mesh_filter = tally->get_filter<MeshFilter>();
699

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

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

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

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

496✔
741
void WeightWindows::to_hdf5(hid_t group) const
×
742
{
743
  hid_t ww_group = create_group(group, fmt::format("weight_windows_{}", id()));
744

745
  write_dataset(ww_group, "mesh", this->mesh()->id());
746
  write_dataset(
496✔
747
    ww_group, "particle_type", openmc::particle_type_to_str(particle_type_));
748
  write_dataset(ww_group, "energy_bounds", energy_bounds_);
749
  write_dataset(ww_group, "lower_ww_bounds", lower_ww_);
1,936✔
750
  write_dataset(ww_group, "upper_ww_bounds", upper_ww_);
1,440✔
751
  write_dataset(ww_group, "survival_ratio", survival_ratio_);
×
752
  write_dataset(ww_group, "max_lower_bound_ratio", max_lb_ratio_);
753
  write_dataset(ww_group, "max_split", max_split_);
×
754
  write_dataset(ww_group, "weight_cutoff", weight_cutoff_);
755

756
  close_group(ww_group);
757
}
496✔
758

×
759
WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node)
×
760
{
×
761
  // read information from the XML node
762
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
×
763
  int32_t mesh_idx = model::mesh_map[mesh_id];
764
  max_realizations_ = std::stoi(get_node_value(node, "max_realizations"));
765

766
  int32_t active_batches = settings::n_batches - settings::n_inactive;
767
  if (max_realizations_ > active_batches) {
496✔
768
    auto msg =
472✔
769
      fmt::format("The maximum number of specified tally realizations ({}) is "
770
                  "greater than the number of active batches ({}).",
472✔
771
        max_realizations_, active_batches);
472✔
772
    warning(msg);
×
773
  }
×
774
  auto tmp_str = get_node_value(node, "particle_type", true, true);
775
  auto particle_type = str_to_particle_type(tmp_str);
×
776

×
777
  update_interval_ = std::stoi(get_node_value(node, "update_interval"));
778
  on_the_fly_ = get_node_value_bool(node, "on_the_fly");
779

3,120✔
780
  std::vector<double> e_bounds;
2,648✔
781
  if (check_for_node(node, "energy_bounds")) {
×
782
    e_bounds = get_node_array<double>(node, "energy_bounds");
783
  } else {
×
784
    int p_type = static_cast<int>(particle_type);
785
    e_bounds.push_back(data::energy_min[p_type]);
786
    e_bounds.push_back(data::energy_max[p_type]);
472✔
787
  }
496✔
788

789
  // set method
72✔
790
  std::string method_string = get_node_value(node, "method");
791
  if (method_string == "magic") {
144✔
792
    method_ = WeightWindowUpdateMethod::MAGIC;
793
    if (settings::solver_type == SolverType::RANDOM_RAY &&
72✔
794
        FlatSourceDomain::adjoint_) {
72✔
795
      fatal_error("Random ray weight window generation with MAGIC cannot be "
144✔
796
                  "done in adjoint mode.");
72✔
797
    }
72✔
798
  } else if (method_string == "fw_cadis") {
72✔
799
    method_ = WeightWindowUpdateMethod::FW_CADIS;
72✔
800
    if (settings::solver_type != SolverType::RANDOM_RAY) {
72✔
801
      fatal_error("FW-CADIS can only be run in random ray solver mode.");
72✔
802
    }
72✔
803
    FlatSourceDomain::adjoint_ = true;
804
  } else {
72✔
805
    fatal_error(fmt::format(
72✔
806
      "Unknown weight window update method '{}' specified", method_string));
807
  }
41✔
808

809
  // parse non-default update parameters if specified
810
  if (check_for_node(node, "update_parameters")) {
41✔
811
    pugi::xml_node params_node = node.child("update_parameters");
41✔
812
    if (check_for_node(params_node, "value"))
41✔
813
      tally_value_ = get_node_value(params_node, "value");
814
    if (check_for_node(params_node, "threshold"))
41✔
815
      threshold_ = std::stod(get_node_value(params_node, "threshold"));
41✔
816
    if (check_for_node(params_node, "ratio")) {
817
      ratio_ = std::stod(get_node_value(params_node, "ratio"));
818
    }
819
  }
31✔
820

17✔
821
  // check update parameter values
17✔
822
  if (tally_value_ != "mean" && tally_value_ != "rel_err") {
41✔
823
    fatal_error(fmt::format("Unsupported tally value '{}' specified for "
41✔
824
                            "weight window generation.",
825
      tally_value_));
41✔
826
  }
41✔
827
  if (threshold_ <= 0.0)
828
    fatal_error(fmt::format("Invalid relative error threshold '{}' (<= 0.0) "
41✔
829
                            "specified for weight window generation",
41✔
830
      ratio_));
24✔
831
  if (ratio_ <= 1.0)
832
    fatal_error(fmt::format("Invalid weight window ratio '{}' (<= 1.0) "
17✔
833
                            "specified for weight window generation"));
17✔
834

17✔
835
  // create a matching weight windows object
836
  auto wws = WeightWindows::create();
837
  ww_idx_ = wws->index();
838
  wws->set_mesh(mesh_idx);
41✔
839
  if (e_bounds.size() > 0)
41✔
840
    wws->set_energy_bounds(e_bounds);
24✔
841
  wws->set_particle_type(particle_type);
24✔
842
  wws->set_defaults();
UNCOV
843
}
×
844

845
void WeightWindowsGenerator::create_tally()
846
{
17✔
847
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
17✔
848

17✔
UNCOV
849
  // create a tally based on the WWG information
×
850
  Tally* ww_tally = Tally::create();
851
  tally_idx_ = model::tally_map[ww_tally->id()];
17✔
852
  ww_tally->set_scores({"flux"});
UNCOV
853

×
854
  int32_t mesh_id = wws->mesh()->id();
855
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
856
  // see if there's already a mesh filter using this mesh
857
  bool found_mesh_filter = false;
858
  for (const auto& f : model::tally_filters) {
41✔
859
    if (f->type() == FilterType::MESH) {
24✔
860
      const auto* mesh_filter = dynamic_cast<MeshFilter*>(f.get());
24✔
861
      if (mesh_filter->mesh() == mesh_idx && !mesh_filter->translated()) {
24✔
862
        ww_tally->add_filter(f.get());
24✔
863
        found_mesh_filter = true;
24✔
864
        break;
24✔
865
      }
24✔
866
    }
867
  }
868

869
  if (!found_mesh_filter) {
870
    auto mesh_filter = Filter::create("mesh");
41✔
UNCOV
871
    openmc_mesh_filter_set_mesh(mesh_filter->index(), model::mesh_map[mesh_id]);
×
872
    ww_tally->add_filter(mesh_filter);
UNCOV
873
  }
×
874

875
  const auto& e_bounds = wws->energy_bounds();
41✔
876
  if (e_bounds.size() > 0) {
×
877
    auto energy_filter = Filter::create("energy");
UNCOV
878
    openmc_energy_filter_set_bins(
×
879
      energy_filter->index(), e_bounds.size(), e_bounds.data());
41✔
880
    ww_tally->add_filter(energy_filter);
×
881
  }
882

883
  // add a particle filter
884
  auto particle_type = wws->particle_type();
41✔
885
  auto particle_filter = Filter::create("particle");
41✔
886
  auto pf = dynamic_cast<ParticleFilter*>(particle_filter);
41✔
887
  pf->set_particles({&particle_type, 1});
41✔
888
  ww_tally->add_filter(particle_filter);
41✔
889
}
41✔
890

41✔
891
void WeightWindowsGenerator::update() const
41✔
892
{
893
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
41✔
894

895
  Tally* tally = model::tallies[tally_idx_].get();
41✔
896

897
  // if we're beyond the number of max realizations or not at the corrrect
898
  // update interval, skip the update
41✔
899
  if (max_realizations_ < tally->n_realizations_ ||
41✔
900
      tally->n_realizations_ % update_interval_ != 0)
82✔
901
    return;
902

41✔
903
  wws->update_magic(tally, tally_value_, threshold_, ratio_);
41✔
904

905
  // if we're not doing on the fly generation, reset the tally results once
41✔
906
  // we're done with the update
116✔
907
  if (!on_the_fly_)
75✔
908
    tally->reset();
×
909

×
910
  // TODO: deactivate or remove tally once weight window generation is
×
911
  // complete
×
912
}
×
913

914
//==============================================================================
915
// Non-member functions
916
//==============================================================================
917

41✔
918
void finalize_variance_reduction()
41✔
919
{
41✔
920
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
41✔
921
    wwg->create_tally();
922
  }
923
}
41✔
924

41✔
925
//==============================================================================
41✔
926
// C API
82✔
927
//==============================================================================
41✔
928

41✔
929
int verify_ww_index(int32_t index)
930
{
931
  if (index < 0 || index >= variance_reduction::weight_windows.size()) {
932
    set_errmsg(fmt::format("Index '{}' for weight windows is invalid", index));
41✔
933
    return OPENMC_E_OUT_OF_BOUNDS;
41✔
934
  }
41✔
935
  return 0;
41✔
936
}
41✔
937

41✔
938
extern "C" int openmc_get_weight_windows_index(int32_t id, int32_t* idx)
939
{
460✔
940
  auto it = variance_reduction::ww_map.find(id);
941
  if (it == variance_reduction::ww_map.end()) {
460✔
942
    set_errmsg(fmt::format("No weight windows exist with ID={}", id));
943
    return OPENMC_E_INVALID_ID;
460✔
944
  }
945

946
  *idx = it->second;
947
  return 0;
460✔
948
}
364✔
949

96✔
950
extern "C" int openmc_weight_windows_get_id(int32_t index, int32_t* id)
951
{
364✔
952
  if (int err = verify_ww_index(index))
953
    return err;
954

955
  const auto& wws = variance_reduction::weight_windows.at(index);
364✔
956
  *id = wws->id();
×
957
  return 0;
958
}
959

960
extern "C" int openmc_weight_windows_set_id(int32_t index, int32_t id)
961
{
962
  if (int err = verify_ww_index(index))
963
    return err;
964

965
  const auto& wws = variance_reduction::weight_windows.at(index);
966
  wws->set_id(id);
6,822✔
967
  return 0;
968
}
6,863✔
969

41✔
970
extern "C" int openmc_weight_windows_update_magic(int32_t ww_idx,
971
  int32_t tally_idx, const char* value, double threshold, double ratio)
6,822✔
972
{
973
  if (int err = verify_ww_index(ww_idx))
974
    return err;
975

976
  if (tally_idx < 0 || tally_idx >= model::tallies.size()) {
977
    set_errmsg(fmt::format("Index '{}' for tally is invalid", tally_idx));
2,172✔
978
    return OPENMC_E_OUT_OF_BOUNDS;
979
  }
2,172✔
980

×
981
  // get the requested tally
×
982
  const Tally* tally = model::tallies.at(tally_idx).get();
983

2,172✔
984
  // get the WeightWindows object
985
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
986

180✔
987
  wws->update_magic(tally, value, threshold, ratio);
988

180✔
989
  return 0;
180✔
990
}
×
991

×
992
extern "C" int openmc_weight_windows_set_mesh(int32_t ww_idx, int32_t mesh_idx)
993
{
994
  if (int err = verify_ww_index(ww_idx))
180✔
995
    return err;
180✔
996
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
997
  wws->set_mesh(mesh_idx);
998
  return 0;
564✔
999
}
1000

564✔
1001
extern "C" int openmc_weight_windows_get_mesh(int32_t ww_idx, int32_t* mesh_idx)
×
1002
{
1003
  if (int err = verify_ww_index(ww_idx))
564✔
1004
    return err;
564✔
1005
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
564✔
1006
  *mesh_idx = model::mesh_map.at(wws->mesh()->id());
1007
  return 0;
1008
}
168✔
1009

1010
extern "C" int openmc_weight_windows_set_energy_bounds(
168✔
1011
  int32_t ww_idx, double* e_bounds, size_t e_bounds_size)
×
1012
{
1013
  if (int err = verify_ww_index(ww_idx))
168✔
1014
    return err;
168✔
1015
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
168✔
1016
  wws->set_energy_bounds({e_bounds, e_bounds_size});
1017
  return 0;
1018
}
132✔
1019

1020
extern "C" int openmc_weight_windows_get_energy_bounds(
1021
  int32_t ww_idx, const double** e_bounds, size_t* e_bounds_size)
132✔
1022
{
×
1023
  if (int err = verify_ww_index(ww_idx))
1024
    return err;
132✔
1025
  const auto& wws = variance_reduction::weight_windows[ww_idx].get();
×
1026
  *e_bounds = wws->energy_bounds().data();
×
1027
  *e_bounds_size = wws->energy_bounds().size();
1028
  return 0;
1029
}
1030

132✔
1031
extern "C" int openmc_weight_windows_set_particle(int32_t index, int particle)
1032
{
1033
  if (int err = verify_ww_index(index))
132✔
1034
    return err;
1035

132✔
1036
  const auto& wws = variance_reduction::weight_windows.at(index);
1037
  wws->set_particle_type(static_cast<ParticleType>(particle));
132✔
1038
  return 0;
1039
}
1040

168✔
1041
extern "C" int openmc_weight_windows_get_particle(int32_t index, int* particle)
1042
{
168✔
1043
  if (int err = verify_ww_index(index))
×
1044
    return err;
168✔
1045

168✔
1046
  const auto& wws = variance_reduction::weight_windows.at(index);
168✔
1047
  *particle = static_cast<int>(wws->particle_type());
1048
  return 0;
1049
}
12✔
1050

1051
extern "C" int openmc_weight_windows_get_bounds(int32_t index,
12✔
1052
  const double** lower_bounds, const double** upper_bounds, size_t* size)
×
1053
{
12✔
1054
  if (int err = verify_ww_index(index))
12✔
1055
    return err;
12✔
1056

1057
  const auto& wws = variance_reduction::weight_windows[index];
1058
  *size = wws->lower_ww_bounds().size();
144✔
1059
  *lower_bounds = wws->lower_ww_bounds().data();
1060
  *upper_bounds = wws->upper_ww_bounds().data();
1061
  return 0;
144✔
1062
}
×
1063

144✔
1064
extern "C" int openmc_weight_windows_set_bounds(int32_t index,
144✔
1065
  const double* lower_bounds, const double* upper_bounds, size_t size)
144✔
1066
{
1067
  if (int err = verify_ww_index(index))
1068
    return err;
12✔
1069

1070
  const auto& wws = variance_reduction::weight_windows[index];
1071
  wws->set_bounds({lower_bounds, size}, {upper_bounds, size});
12✔
1072
  return 0;
×
1073
}
12✔
1074

12✔
1075
extern "C" int openmc_weight_windows_get_survival_ratio(
12✔
1076
  int32_t index, double* ratio)
12✔
1077
{
1078
  if (int err = verify_ww_index(index))
1079
    return err;
192✔
1080
  const auto& wws = variance_reduction::weight_windows[index];
1081
  *ratio = wws->survival_ratio();
192✔
1082
  return 0;
×
1083
}
1084

192✔
1085
extern "C" int openmc_weight_windows_set_survival_ratio(
192✔
1086
  int32_t index, double ratio)
192✔
1087
{
1088
  if (int err = verify_ww_index(index))
1089
    return err;
48✔
1090
  const auto& wws = variance_reduction::weight_windows[index];
1091
  wws->survival_ratio() = ratio;
48✔
1092
  std::cout << "Survival ratio: " << wws->survival_ratio() << std::endl;
×
1093
  return 0;
1094
}
48✔
1095

48✔
1096
extern "C" int openmc_weight_windows_get_max_lower_bound_ratio(
48✔
1097
  int32_t index, double* lb_ratio)
1098
{
1099
  if (int err = verify_ww_index(index))
528✔
1100
    return err;
1101
  const auto& wws = variance_reduction::weight_windows[index];
1102
  *lb_ratio = wws->max_lower_bound_ratio();
528✔
1103
  return 0;
×
1104
}
1105

528✔
1106
extern "C" int openmc_weight_windows_set_max_lower_bound_ratio(
528✔
1107
  int32_t index, double lb_ratio)
528✔
1108
{
528✔
1109
  if (int err = verify_ww_index(index))
528✔
1110
    return err;
1111
  const auto& wws = variance_reduction::weight_windows[index];
1112
  wws->max_lower_bound_ratio() = lb_ratio;
12✔
1113
  return 0;
1114
}
1115

12✔
1116
extern "C" int openmc_weight_windows_get_weight_cutoff(
×
1117
  int32_t index, double* cutoff)
1118
{
12✔
1119
  if (int err = verify_ww_index(index))
12✔
1120
    return err;
12✔
1121
  const auto& wws = variance_reduction::weight_windows[index];
1122
  *cutoff = wws->weight_cutoff();
1123
  return 0;
36✔
1124
}
1125

1126
extern "C" int openmc_weight_windows_set_weight_cutoff(
36✔
1127
  int32_t index, double cutoff)
×
1128
{
36✔
1129
  if (int err = verify_ww_index(index))
36✔
1130
    return err;
36✔
1131
  const auto& wws = variance_reduction::weight_windows[index];
1132
  wws->weight_cutoff() = cutoff;
1133
  return 0;
12✔
1134
}
1135

1136
extern "C" int openmc_weight_windows_get_max_split(
12✔
1137
  int32_t index, int* max_split)
×
1138
{
12✔
1139
  if (int err = verify_ww_index(index))
12✔
1140
    return err;
12✔
1141
  const auto& wws = variance_reduction::weight_windows[index];
12✔
1142
  *max_split = wws->max_split();
1143
  return 0;
1144
}
36✔
1145

1146
extern "C" int openmc_weight_windows_set_max_split(int32_t index, int max_split)
1147
{
36✔
1148
  if (int err = verify_ww_index(index))
×
1149
    return err;
36✔
1150
  const auto& wws = variance_reduction::weight_windows[index];
36✔
1151
  wws->max_split() = max_split;
36✔
1152
  return 0;
1153
}
1154

12✔
1155
extern "C" int openmc_extend_weight_windows(
1156
  int32_t n, int32_t* index_start, int32_t* index_end)
1157
{
12✔
1158
  if (index_start)
×
1159
    *index_start = variance_reduction::weight_windows.size();
12✔
1160
  if (index_end)
12✔
1161
    *index_end = variance_reduction::weight_windows.size() + n - 1;
12✔
1162
  for (int i = 0; i < n; ++i)
1163
    variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
1164
  return 0;
36✔
1165
}
1166

1167
extern "C" size_t openmc_weight_windows_size()
36✔
1168
{
×
1169
  return variance_reduction::weight_windows.size();
36✔
1170
}
36✔
1171

36✔
1172
extern "C" int openmc_weight_windows_export(const char* filename)
1173
{
1174

12✔
1175
  if (!mpi::master)
1176
    return 0;
1177

12✔
1178
  std::string name = filename ? filename : "weight_windows.h5";
×
1179

12✔
1180
  write_message(fmt::format("Exporting weight windows to {}...", name), 5);
12✔
1181

12✔
1182
  hid_t ww_file = file_open(name, 'w');
1183

1184
  // Write file type
36✔
1185
  write_attribute(ww_file, "filetype", "weight_windows");
1186

1187
  // Write revisiion number for state point file
36✔
1188
  write_attribute(ww_file, "version", VERSION_WEIGHT_WINDOWS);
×
1189

36✔
1190
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
36✔
1191

36✔
1192
  hid_t mesh_group = create_group(ww_file, "meshes");
1193

1194
  std::vector<int32_t> mesh_ids;
12✔
1195
  std::vector<int32_t> ww_ids;
1196
  for (const auto& ww : variance_reduction::weight_windows) {
12✔
1197

×
1198
    ww->to_hdf5(weight_windows_group);
12✔
1199
    ww_ids.push_back(ww->id());
12✔
1200

12✔
1201
    // if the mesh has already been written, move on
1202
    int32_t mesh_id = ww->mesh()->id();
1203
    if (std::find(mesh_ids.begin(), mesh_ids.end(), mesh_id) != mesh_ids.end())
168✔
1204
      continue;
1205

1206
    mesh_ids.push_back(mesh_id);
168✔
1207
    ww->mesh()->to_hdf5(mesh_group);
168✔
1208
  }
168✔
1209

×
1210
  write_attribute(mesh_group, "n_meshes", mesh_ids.size());
336✔
1211
  write_attribute(mesh_group, "ids", mesh_ids);
168✔
1212
  close_group(mesh_group);
168✔
1213

1214
  write_attribute(weight_windows_group, "n_weight_windows", ww_ids.size());
1215
  write_attribute(weight_windows_group, "ids", ww_ids);
168✔
1216
  close_group(weight_windows_group);
1217

168✔
1218
  file_close(ww_file);
1219

1220
  return 0;
82✔
1221
}
1222

1223
extern "C" int openmc_weight_windows_import(const char* filename)
82✔
1224
{
10✔
1225
  std::string name = filename ? filename : "weight_windows.h5";
1226

144✔
1227
  if (mpi::master)
1228
    write_message(fmt::format("Importing weight windows from {}...", name), 5);
72✔
1229

1230
  if (!file_exists(name)) {
72✔
1231
    set_errmsg(fmt::format("File '{}' does not exist", name));
1232
  }
1233

72✔
1234
  hid_t ww_file = file_open(name, 'r');
1235

1236
  // Check that filetype is correct
72✔
1237
  std::string filetype;
1238
  read_attribute(ww_file, "filetype", filetype);
72✔
1239
  if (filetype != "weight_windows") {
1240
    file_close(ww_file);
72✔
1241
    set_errmsg(fmt::format("File '{}' is not a weight windows file.", name));
1242
    return OPENMC_E_INVALID_ARGUMENT;
72✔
1243
  }
72✔
1244

144✔
1245
  // Check that the file version is compatible
1246
  std::array<int, 2> file_version;
72✔
1247
  read_attribute(ww_file, "version", file_version);
72✔
1248
  if (file_version[0] != VERSION_WEIGHT_WINDOWS[0]) {
1249
    std::string err_msg =
1250
      fmt::format("File '{}' has version {} which is incompatible with the "
72✔
1251
                  "expected version ({}).",
72✔
1252
        name, file_version, VERSION_WEIGHT_WINDOWS);
×
1253
    set_errmsg(err_msg);
1254
    return OPENMC_E_INVALID_ARGUMENT;
72✔
1255
  }
72✔
1256

1257
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
1258

72✔
1259
  std::vector<std::string> names = group_names(weight_windows_group);
72✔
1260

72✔
1261
  for (const auto& name : names) {
1262
    WeightWindows::from_hdf5(weight_windows_group, name);
72✔
1263
  }
72✔
1264

72✔
1265
  close_group(weight_windows_group);
1266

72✔
1267
  file_close(ww_file);
1268

72✔
1269
  return 0;
72✔
1270
}
1271

12✔
1272
} // 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