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

openmc-dev / openmc / 13425575973

20 Feb 2025 01:03AM UTC coverage: 85.021% (-0.007%) from 85.028%
13425575973

push

github

web-flow
remove gsl-lite dependency (#3225)

Co-authored-by: Paul Romano <paul.k.romano@gmail.com>

96 of 105 new or added lines in 38 files covered. (91.43%)

9 existing lines in 1 file now uncovered.

50630 of 59550 relevant lines covered (85.02%)

35588090.97 hits per line

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

80.29
/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/xindex_view.hpp"
10
#include "xtensor/xio.hpp"
11
#include "xtensor/xmasked_view.hpp"
12
#include "xtensor/xnoalias.hpp"
13
#include "xtensor/xstrided_view.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)
83,501,854✔
62
    return;
9,106,866✔
63

64
  // skip dead or no energy
65
  if (p.E() <= 0 || !p.alive())
74,394,988✔
66
    return;
7,427,066✔
67

68
  bool in_domain = false;
66,967,922✔
69
  // TODO: this is a linear search - should do something more clever
70
  WeightWindow weight_window;
66,967,922✔
71
  for (const auto& ww : variance_reduction::weight_windows) {
86,101,134✔
72
    weight_window = ww->get_weight_window(p);
71,604,110✔
73
    if (weight_window.is_valid())
71,604,110✔
74
      break;
52,470,898✔
75
  }
76
  // particle is not in any of the ww domains, do nothing
77
  if (!weight_window.is_valid())
66,967,922✔
78
    return;
14,497,024✔
79

80
  // get the paramters
81
  double weight = p.wgt();
52,470,898✔
82

83
  // first check to see if particle should be killed for weight cutoff
84
  if (p.wgt() < weight_window.weight_cutoff) {
52,470,898✔
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 &&
52,473,994✔
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)
52,470,898✔
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) {
52,470,898✔
105
    // do not further split the particle if above the limit
106
    if (p.n_split() >= settings::max_history_splits)
11,824,859✔
107
      return;
10,019,226✔
108

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

113
    p.n_split() += n_split;
1,805,633✔
114

115
    // Create secondaries and divide weight among all particles
116
    int i_split = std::round(n_split);
1,805,633✔
117
    for (int l = 0; l < i_split - 1; l++) {
9,202,046✔
118
      p.split(weight / n_split);
7,396,413✔
119
    }
120
    // remaining weight is applied to current particle
121
    p.wgt() = weight / n_split;
1,805,633✔
122

123
  } else if (weight <= weight_window.lower_weight) {
40,646,039✔
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,412,105✔
127
    russian_roulette(p, weight_survive);
1,412,105✔
128
  } // else particle is in the window, continue as normal
129
}
130

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

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

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

148
WeightWindows::WeightWindows(pugi::xml_node node)
85✔
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"};
595✔
153
  for (const auto& elem : required_elems) {
425✔
154
    if (!check_for_node(node, elem.c_str())) {
340✔
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"));
85✔
161
  this->set_id(id);
85✔
162

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

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

171
  // energy bounds
172
  if (check_for_node(node, "energy_bounds"))
85✔
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")) {
85✔
177
    survival_ratio_ = std::stod(get_node_value(node, "survival_ratio"));
85✔
178
    if (survival_ratio_ <= 1)
85✔
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")) {
85✔
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")) {
85✔
193
    max_split_ = std::stod(get_node_value(node, "max_split"));
85✔
194
    if (max_split_ <= 1)
85✔
195
      fatal_error("max split must be larger than 1");
×
196
  }
197

198
  // weight cutoff - optional
199
  if (check_for_node(node, "weight_cutoff")) {
85✔
200
    weight_cutoff_ = std::stod(get_node_value(node, "weight_cutoff"));
85✔
201
    if (weight_cutoff_ <= 0)
85✔
202
      fatal_error("weight_cutoff must be larger than 0");
×
203
    if (weight_cutoff_ > 1)
85✔
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"),
85✔
209
    get_node_array<double>(node, "upper_ww_bounds"));
170✔
210

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

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

219
WeightWindows* WeightWindows::create(int32_t id)
65✔
220
{
221
  variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
65✔
222
  auto wws = variance_reduction::weight_windows.back().get();
65✔
223
  variance_reduction::ww_map[wws->id()] =
65✔
224
    variance_reduction::weight_windows.size() - 1;
65✔
225
  return wws;
65✔
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()
371✔
267
{
268
  // set energy bounds to the min/max energy supported by the data
269
  if (energy_bounds_.size() == 0) {
371✔
270
    int p_type = static_cast<int>(particle_type_);
248✔
271
    energy_bounds_.push_back(data::energy_min[p_type]);
248✔
272
    energy_bounds_.push_back(data::energy_max[p_type]);
248✔
273
  }
274
}
371✔
275

276
void WeightWindows::allocate_ww_bounds()
515✔
277
{
278
  auto shape = bounds_size();
515✔
279
  if (shape[0] * shape[1] == 0) {
515✔
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);
515✔
285
  lower_ww_.fill(-1);
515✔
286
  upper_ww_ = xt::empty<double>(shape);
515✔
287
  upper_ww_.fill(-1);
515✔
288
}
515✔
289

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

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

300
  // Ensure no other mesh has the same ID
301
  if (variance_reduction::ww_map.find(id) != variance_reduction::ww_map.end()) {
486✔
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) {
486✔
308
    id = 0;
233✔
309
    for (const auto& m : variance_reduction::weight_windows) {
257✔
310
      id = std::max(id, m->id_);
24✔
311
    }
312
    ++id;
233✔
313
  }
314

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

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

329
void WeightWindows::set_particle_type(ParticleType p_type)
245✔
330
{
331
  if (p_type != ParticleType::neutron && p_type != ParticleType::photon)
245✔
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;
245✔
336
}
245✔
337

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

343
  mesh_idx_ = mesh_idx;
318✔
344
  model::meshes[mesh_idx_]->prepare_for_point_location();
318✔
345
  allocate_ww_bounds();
318✔
346
}
318✔
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
71,604,110✔
359
{
360
  // check for particle type
361
  if (particle_type_ != p.type()) {
71,604,110✔
362
    return {};
4,377,696✔
363
  }
364

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

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

373
  // particle energy
374
  double E = p.E();
67,226,414✔
375

376
  // check to make sure energy is in range, expects sorted energy values
377
  if (E < energy_bounds_.front() || E > energy_bounds_.back())
67,226,414✔
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);
67,168,190✔
383

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

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

404
template<class T>
405
void WeightWindows::check_bounds(const T& lower, const T& upper) const
97✔
406
{
407
  // make sure that the upper and lower bounds have the same size
408
  if (lower.size() != upper.size()) {
97✔
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);
97✔
415
}
97✔
416

97✔
417
template<class T>
418
void WeightWindows::check_bounds(const T& bounds) const
419
{
97✔
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 "
97✔
426
                  "of weight bins ({})",
97✔
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;
97✔
441
}
442

443
void WeightWindows::set_bounds(
97✔
444
  const xt::xtensor<double, 2>& lower_bounds, double ratio)
97✔
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
}
97✔
453

97✔
454
void WeightWindows::set_bounds(
455
  span<const double> lower_bounds, span<const double> upper_bounds)
456
{
97✔
457
  check_bounds(lower_bounds, upper_bounds);
97✔
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()) =
97✔
466
    xt::adapt(upper_bounds.data(), upper_ww_.shape());
×
467
}
468

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

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

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

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

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

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

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

291✔
513
  ///////////////////////////
194✔
514
  // Extract tally data
291✔
515
  //
97✔
516
  // At the end of this section, the mean and rel_err array
UNCOV
517
  // is a 2D view of tally data (n_e_groups, n_mesh_bins)
×
518
  //
519
  ///////////////////////////
×
520

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

484✔
628
  if (method == WeightWindowUpdateMethod::MAGIC) {
629
    // If we are computing weight windows with forward fluxes derived from a
630
    // Monte Carlo or forward random ray solve, we use the MAGIC algorithm.
×
631
    for (int e = 0; e < e_bins; e++) {
×
632
      // select all
×
633
      auto group_view = xt::view(new_bounds, e);
×
634

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

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

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

508✔
660
    xt::noalias(new_bounds) = 1.0 / new_bounds;
661

662
    auto max_val = xt::amax(new_bounds)();
508✔
663

664
    xt::noalias(new_bounds) = new_bounds / (2.0 * max_val);
508✔
665
  }
1,016✔
666

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

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

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

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

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

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

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

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

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

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

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

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

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

754
  close_group(ww_group);
755
}
508✔
756

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

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

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

3,156✔
778
  std::vector<double> e_bounds;
2,672✔
779
  if (check_for_node(node, "energy_bounds")) {
×
780
    e_bounds = get_node_array<double>(node, "energy_bounds");
781
  } else {
×
782
    int p_type = static_cast<int>(particle_type);
783
    e_bounds.push_back(data::energy_min[p_type]);
784
    e_bounds.push_back(data::energy_max[p_type]);
484✔
785
  }
508✔
786

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

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

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

29✔
833
  // create a matching weight windows object
834
  auto wws = WeightWindows::create();
835
  ww_idx_ = wws->index();
836
  wws->set_mesh(mesh_idx);
53✔
837
  if (e_bounds.size() > 0)
53✔
838
    wws->set_energy_bounds(e_bounds);
36✔
839
  wws->set_particle_type(particle_type);
36✔
840
  wws->set_defaults();
841
}
×
842

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

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

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

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

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

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

53✔
889
void WeightWindowsGenerator::update() const
53✔
890
{
891
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
53✔
892

893
  Tally* tally = model::tallies[tally_idx_].get();
53✔
894

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

53✔
901
  wws->update_weights(tally, tally_value_, threshold_, ratio_, method_);
53✔
902

903
  // if we're not doing on the fly generation, reset the tally results once
53✔
904
  // we're done with the update
140✔
905
  if (!on_the_fly_)
99✔
906
    tally->reset();
12✔
907

12✔
908
  // TODO: deactivate or remove tally once weight window generation is
12✔
909
  // complete
12✔
910
}
12✔
911

912
//==============================================================================
913
// Non-member functions
914
//==============================================================================
915

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

53✔
923
//==============================================================================
53✔
924
// C API
106✔
925
//==============================================================================
53✔
926

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

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

944
  *idx = it->second;
945
  return 0;
520✔
946
}
376✔
947

144✔
948
extern "C" int openmc_weight_windows_get_id(int32_t index, int32_t* id)
949
{
376✔
950
  if (int err = verify_ww_index(index))
951
    return err;
952

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

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

963
  const auto& wws = variance_reduction::weight_windows.at(index);
964
  wws->set_id(id);
6,945✔
965
  return 0;
966
}
6,998✔
967

53✔
968
extern "C" int openmc_weight_windows_update_magic(int32_t ww_idx,
969
  int32_t tally_idx, const char* value, double threshold, double ratio)
6,945✔
970
{
971
  if (int err = verify_ww_index(ww_idx))
972
    return err;
973

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

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

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

180✔
985
  wws->update_weights(tally, value, threshold, ratio);
986

180✔
987
  return 0;
180✔
988
}
×
989

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

36✔
1170
extern "C" int openmc_weight_windows_export(const char* filename)
1171
{
1172

12✔
1173
  if (!mpi::master)
1174
    return 0;
1175

12✔
1176
  std::string name = filename ? filename : "weight_windows.h5";
×
1177

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

12✔
1180
  hid_t ww_file = file_open(name, 'w');
1181

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

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

36✔
1188
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
36✔
1189

36✔
1190
  hid_t mesh_group = create_group(ww_file, "meshes");
1191

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

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

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

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

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

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

168✔
1216
  file_close(ww_file);
1217

1218
  return 0;
94✔
1219
}
1220

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

168✔
1225
  if (mpi::master)
1226
    write_message(fmt::format("Importing weight windows from {}...", name), 5);
84✔
1227

1228
  if (!file_exists(name)) {
84✔
1229
    set_errmsg(fmt::format("File '{}' does not exist", name));
1230
  }
1231

84✔
1232
  hid_t ww_file = file_open(name, 'r');
1233

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

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

1255
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
1256

84✔
1257
  std::vector<std::string> names = group_names(weight_windows_group);
84✔
1258

84✔
1259
  for (const auto& name : names) {
1260
    WeightWindows::from_hdf5(weight_windows_group, name);
84✔
1261
  }
84✔
1262

84✔
1263
  close_group(weight_windows_group);
1264

84✔
1265
  file_close(ww_file);
1266

84✔
1267
  return 0;
84✔
1268
}
1269

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