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

openmc-dev / openmc / 13763261523

10 Mar 2025 11:12AM UTC coverage: 85.133% (+0.004%) from 85.129%
13763261523

Pull #3252

github

web-flow
Merge bdc3a6ead into 906548db2
Pull Request #3252: Adding vtkhdf option to write vtk data

83 of 101 new or added lines in 1 file covered. (82.18%)

529 existing lines in 15 files now uncovered.

51616 of 60630 relevant lines covered (85.13%)

37229330.6 hits per line

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

80.4
/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)
76,541,976✔
62
    return;
8,348,509✔
63

64
  // skip dead or no energy
65
  if (p.E() <= 0 || !p.alive())
68,193,467✔
66
    return;
6,808,191✔
67

68
  bool in_domain = false;
61,385,276✔
69
  // TODO: this is a linear search - should do something more clever
70
  WeightWindow weight_window;
61,385,276✔
71
  for (const auto& ww : variance_reduction::weight_windows) {
78,924,594✔
72
    weight_window = ww->get_weight_window(p);
65,635,115✔
73
    if (weight_window.is_valid())
65,635,115✔
74
      break;
48,095,797✔
75
  }
76
  // particle is not in any of the ww domains, do nothing
77
  if (!weight_window.is_valid())
61,385,276✔
78
    return;
13,289,479✔
79

80
  // get the paramters
81
  double weight = p.wgt();
48,095,797✔
82

83
  // first check to see if particle should be killed for weight cutoff
84
  if (p.wgt() < weight_window.weight_cutoff) {
48,095,797✔
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 &&
48,098,635✔
93
      p.wgt() > weight_window.lower_weight * weight_window.max_lb_ratio) {
2,838✔
94
    p.ww_factor() =
2,838✔
95
      p.wgt() / (weight_window.lower_weight * weight_window.max_lb_ratio);
2,838✔
96
  }
97

98
  // move weight window closer to the particle weight if needed
99
  if (p.ww_factor() > 1.0)
48,095,797✔
100
    weight_window.scale(p.ww_factor());
1,447,930✔
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) {
48,095,797✔
105
    // do not further split the particle if above the limit
106
    if (p.n_split() >= settings::max_history_splits)
10,837,894✔
107
      return;
9,182,690✔
108

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

113
    p.n_split() += n_split;
1,655,204✔
114

115
    // Create secondaries and divide weight among all particles
116
    int i_split = std::round(n_split);
1,655,204✔
117
    for (int l = 0; l < i_split - 1; l++) {
8,435,494✔
118
      p.split(weight / n_split);
6,780,290✔
119
    }
120
    // remaining weight is applied to current particle
121
    p.wgt() = weight / n_split;
1,655,204✔
122

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

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

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

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

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

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

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

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

175
  // get the survival value - optional
176
  if (check_for_node(node, "survival_ratio")) {
79✔
177
    survival_ratio_ = std::stod(get_node_value(node, "survival_ratio"));
79✔
178
    if (survival_ratio_ <= 1)
79✔
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")) {
79✔
185
    max_lb_ratio_ = std::stod(get_node_value(node, "max_lower_bound_ratio"));
32✔
186
    if (max_lb_ratio_ < 1.0) {
32✔
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")) {
79✔
193
    max_split_ = std::stod(get_node_value(node, "max_split"));
79✔
194
    if (max_split_ <= 1)
79✔
195
      fatal_error("max split must be larger than 1");
×
196
  }
197

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

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

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

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

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

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

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

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

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

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

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

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

261
  close_group(ww_group);
11✔
262

263
  return wws;
11✔
264
}
11✔
265

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

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

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

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

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

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

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

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

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

343
  mesh_idx_ = mesh_idx;
325✔
344
  model::meshes[mesh_idx_]->prepare_for_point_location();
325✔
345
  allocate_ww_bounds();
325✔
346
}
325✔
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
65,635,115✔
359
{
360
  // check for particle type
361
  if (particle_type_ != p.type()) {
65,635,115✔
362
    return {};
4,012,888✔
363
  }
364

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

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

373
  // particle energy
374
  double E = p.E();
61,622,227✔
375

376
  // check to make sure energy is in range, expects sorted energy values
377
  if (E < energy_bounds_.front() || E > energy_bounds_.back())
61,622,227✔
378
    return {};
53,372✔
379

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

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

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

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

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

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

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

469
void WeightWindows::set_bounds(span<const double> lower_bounds, double ratio)
×
470
{
×
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

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

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

493
  lower_ww_.fill(-1);
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) {
×
499
    fatal_error(fmt::format("Invalid value '{}' specified for weight window "
×
500
                            "generation. Must be one of: 'mean' or 'rel_err'",
501
      value));
502
  }
90✔
503

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

270✔
513
  ///////////////////////////
180✔
514
  // Extract tally data
270✔
515
  //
90✔
516
  // At the end of this section, the mean and rel_err array
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};
2,394✔
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))
2,394✔
540
    filter_types.push_back(FilterType::PARTICLE);
541

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

545
  // particle axis mapping
11,970✔
546
  transpose[0] =
2,394✔
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();
2,394✔
554

2,394✔
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>();
2,394✔
572
    const auto& particles = pf->particles();
2,394✔
573

574
    // find the index of the particle that matches these weight windows
575
    auto p_it =
9,532✔
576
      std::find(particles.begin(), particles.end(), this->particle_type_);
7,138✔
577
    // if the particle filter doesn't have particle data for the particle
7,138✔
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 {}",
2,394✔
582
        particle_type_to_str(this->particle_type_), pf->id(), tally->id(),
583
        this->id());
584
      fatal_error(msg);
2,394✔
585
    }
586

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

2,394✔
591
  // down-select data based on particle and score
22✔
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(),
2,394✔
595
    score_index, static_cast<int>(TallyResult::SUM_SQ));
2,394✔
596
  int n = tally->n_realizations_;
2,394✔
597

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

2,394✔
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_;
2,394✔
611
  auto& rel_err = this->upper_ww_;
612

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

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

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

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

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

2,372✔
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++) {
2,372✔
637
        group_view[i] /= mesh_vols[i];
638
      }
639

640
      double group_max =
2,394✔
641
        *std::max_element(group_view.begin(), group_view.end());
4,788✔
642
      // normalize values in this energy group by the maximum value for this
2,394✔
643
      // group
4,788✔
644
      if (group_max > 0.0)
2,394✔
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
    }
2,394✔
659

2,394✔
660
    // We take the inverse, but are careful not to divide by zero e.g. if some
661
    // mesh bins are not reachable in the physical geometry.
662
    xt::noalias(new_bounds) =
2,394✔
663
      xt::where(xt::not_equal(new_bounds, 0.0), 1.0 / new_bounds, 0.0);
664
    auto max_val = xt::amax(new_bounds)();
2,394✔
665
    xt::noalias(new_bounds) = new_bounds / (2.0 * max_val);
4,788✔
666

2,394✔
667
    // For bins that were missed, we use the minimum weight window value. This
668
    // shouldn't matter except for plotting.
2,394✔
669
    auto min_val = xt::amin(new_bounds)();
11✔
670
    xt::noalias(new_bounds) =
671
      xt::where(xt::not_equal(new_bounds, 0.0), new_bounds, min_val);
672
  }
2,394✔
673

674
  // make sure that values where the mean is zero are set s.t. the weight window
2,394✔
675
  // value will be ignored
676
  xt::filter(new_bounds, sum <= 0.0).fill(-1.0);
2,394✔
677

678
  // make sure the weight windows are ignored for any locations where the
679
  // relative error is higher than the specified relative error threshold
1,870✔
680
  xt::filter(new_bounds, rel_err > threshold).fill(-1.0);
681

1,716✔
682
  // update the bounds of this weight window class
683
  // noalias avoids additional memory allocation
684
  xt::noalias(upper_ww_) = ratio * lower_ww_;
2,403,511✔
685
}
2,401,795✔
686

687
void WeightWindows::check_tally_update_compatibility(const Tally* tally)
688
{
689
  // define the set of allowed filters for the tally
1,716✔
690
  const std::set<FilterType> allowed_filters = {
691
    FilterType::MESH, FilterType::ENERGY, FilterType::PARTICLE};
692

1,716✔
693
  // retrieve a mapping of filter type to filter index for the tally
1,683✔
694
  auto filter_indices = tally->filter_indices();
1,716✔
695

696
  // a mesh filter is required for a tally used to update weight windows
697
  if (!filter_indices.count(FilterType::MESH)) {
698
    fatal_error(
4,480✔
699
      "A mesh filter is required for a tally to update weight window bounds");
700
  }
2,240✔
701

702
  // ensure the mesh filter is using the same mesh as this weight window object
703
  auto mesh_filter = tally->get_filter<MeshFilter>();
6,551,360✔
704

6,549,120✔
705
  // make sure that all of the filters present on the tally are allowed
706
  for (auto filter_pair : filter_indices) {
2,240✔
707
    if (allowed_filters.find(filter_pair.first) == allowed_filters.end()) {
708
      fatal_error(fmt::format("Invalid filter type '{}' found on tally "
709
                              "used for weight window generation.",
710
        model::tally_filters[tally->filters(filter_pair.second)]->type_str()));
2,240✔
711
    }
4,480✔
712
  }
2,240✔
713

2,240✔
714
  if (mesh_filter->mesh() != mesh_idx_) {
715
    int32_t mesh_filter_id = model::meshes[mesh_filter->mesh()]->id();
716
    int32_t ww_mesh_id = model::meshes[this->mesh_idx_]->id();
717
    fatal_error(fmt::format("Mesh filter {} uses a different mesh ({}) than "
2,240✔
718
                            "weight window {} mesh ({})",
2,240✔
719
      mesh_filter->id(), mesh_filter_id, id_, ww_mesh_id));
4,480✔
720
  }
721

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

2,394✔
736
    for (auto e : energy_bounds()) {
737
      if (filter_e_bounds.count(e) == 0) {
738
        fatal_error(fmt::format(
739
          "Energy bounds of filter {} and weight windows {} do not match",
2,394✔
740
          energy_filter->id(), id_));
741
      }
742
    }
2,394✔
743
  }
744
}
745

2,394✔
UNCOV
746
void WeightWindows::to_hdf5(hid_t group) const
×
747
{
748
  hid_t ww_group = create_group(group, fmt::format("weight_windows_{}", id()));
749

750
  write_dataset(ww_group, "mesh", this->mesh()->id());
751
  write_dataset(
2,394✔
752
    ww_group, "particle_type", openmc::particle_type_to_str(particle_type_));
753
  write_dataset(ww_group, "energy_bounds", energy_bounds_);
754
  write_dataset(ww_group, "lower_ww_bounds", lower_ww_);
9,532✔
755
  write_dataset(ww_group, "upper_ww_bounds", upper_ww_);
7,138✔
756
  write_dataset(ww_group, "survival_ratio", survival_ratio_);
×
757
  write_dataset(ww_group, "max_lower_bound_ratio", max_lb_ratio_);
758
  write_dataset(ww_group, "max_split", max_split_);
×
759
  write_dataset(ww_group, "weight_cutoff", weight_cutoff_);
760

761
  close_group(ww_group);
762
}
2,394✔
UNCOV
763

×
UNCOV
764
WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node)
×
UNCOV
765
{
×
766
  // read information from the XML node
UNCOV
767
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
×
768
  int32_t mesh_idx = model::mesh_map[mesh_id];
769
  max_realizations_ = std::stoi(get_node_value(node, "max_realizations"));
770

771
  int32_t active_batches = settings::n_batches - settings::n_inactive;
772
  if (max_realizations_ > active_batches) {
2,394✔
773
    auto msg =
2,372✔
774
      fmt::format("The maximum number of specified tally realizations ({}) is "
775
                  "greater than the number of active batches ({}).",
2,372✔
776
        max_realizations_, active_batches);
2,372✔
UNCOV
777
    warning(msg);
×
UNCOV
778
  }
×
779
  auto tmp_str = get_node_value(node, "particle_type", true, true);
UNCOV
780
  auto particle_type = str_to_particle_type(tmp_str);
×
781

×
782
  update_interval_ = std::stoi(get_node_value(node, "update_interval"));
783
  on_the_fly_ = get_node_value_bool(node, "on_the_fly");
784

8,678✔
785
  std::vector<double> e_bounds;
6,306✔
UNCOV
786
  if (check_for_node(node, "energy_bounds")) {
×
787
    e_bounds = get_node_array<double>(node, "energy_bounds");
UNCOV
788
  } else {
×
789
    int p_type = static_cast<int>(particle_type);
790
    e_bounds.push_back(data::energy_min[p_type]);
791
    e_bounds.push_back(data::energy_max[p_type]);
2,372✔
792
  }
2,394✔
793

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

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

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

59✔
840
  // create a matching weight windows object
841
  auto wws = WeightWindows::create();
842
  ww_idx_ = wws->index();
843
  wws->set_mesh(mesh_idx);
81✔
844
  if (e_bounds.size() > 0)
81✔
845
    wws->set_energy_bounds(e_bounds);
33✔
846
  wws->set_particle_type(particle_type);
33✔
847
  wws->set_defaults();
UNCOV
848
}
×
849

850
void WeightWindowsGenerator::create_tally()
851
{
48✔
852
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
48✔
853

48✔
UNCOV
854
  // create a tally based on the WWG information
×
855
  Tally* ww_tally = Tally::create();
856
  tally_idx_ = model::tally_map[ww_tally->id()];
48✔
857
  ww_tally->set_scores({"flux"});
UNCOV
858

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

874
  if (!found_mesh_filter) {
875
    auto mesh_filter = Filter::create("mesh");
81✔
876
    openmc_mesh_filter_set_mesh(mesh_filter->index(), model::mesh_map[mesh_id]);
×
877
    ww_tally->add_filter(mesh_filter);
878
  }
×
879

880
  const auto& e_bounds = wws->energy_bounds();
81✔
UNCOV
881
  if (e_bounds.size() > 0) {
×
882
    auto energy_filter = Filter::create("energy");
UNCOV
883
    openmc_energy_filter_set_bins(
×
884
      energy_filter->index(), e_bounds.size(), e_bounds.data());
81✔
UNCOV
885
    ww_tally->add_filter(energy_filter);
×
886
  }
887

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

81✔
896
void WeightWindowsGenerator::update() const
81✔
897
{
898
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
81✔
899

900
  Tally* tally = model::tallies[tally_idx_].get();
81✔
901

902
  // if we're beyond the number of max realizations or not at the corrrect
903
  // update interval, skip the update
81✔
904
  if (max_realizations_ < tally->n_realizations_ ||
81✔
905
      tally->n_realizations_ % update_interval_ != 0)
162✔
906
    return;
907

81✔
908
  wws->update_weights(tally, tally_value_, threshold_, ratio_, method_);
81✔
909

910
  // if we're not doing on the fly generation, reset the tally results once
81✔
911
  // we're done with the update
258✔
912
  if (!on_the_fly_)
188✔
913
    tally->reset();
11✔
914

11✔
915
  // TODO: deactivate or remove tally once weight window generation is
11✔
916
  // complete
11✔
917
}
11✔
918

919
//==============================================================================
920
// Non-member functions
921
//==============================================================================
922

81✔
923
void finalize_variance_reduction()
70✔
924
{
70✔
925
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
70✔
926
    wwg->create_tally();
927
  }
928
}
81✔
929

81✔
930
//==============================================================================
81✔
931
// C API
162✔
932
//==============================================================================
81✔
933

81✔
934
int verify_ww_index(int32_t index)
935
{
936
  if (index < 0 || index >= variance_reduction::weight_windows.size()) {
937
    set_errmsg(fmt::format("Index '{}' for weight windows is invalid", index));
81✔
938
    return OPENMC_E_OUT_OF_BOUNDS;
81✔
939
  }
81✔
940
  return 0;
81✔
941
}
81✔
942

81✔
943
extern "C" int openmc_get_weight_windows_index(int32_t id, int32_t* idx)
944
{
2,405✔
945
  auto it = variance_reduction::ww_map.find(id);
946
  if (it == variance_reduction::ww_map.end()) {
2,405✔
947
    set_errmsg(fmt::format("No weight windows exist with ID={}", id));
948
    return OPENMC_E_INVALID_ID;
2,405✔
949
  }
950

951
  *idx = it->second;
952
  return 0;
2,405✔
953
}
2,273✔
954

132✔
955
extern "C" int openmc_weight_windows_get_id(int32_t index, int32_t* id)
956
{
2,273✔
957
  if (int err = verify_ww_index(index))
958
    return err;
959

960
  const auto& wws = variance_reduction::weight_windows.at(index);
2,273✔
UNCOV
961
  *id = wws->id();
×
962
  return 0;
963
}
964

965
extern "C" int openmc_weight_windows_set_id(int32_t index, int32_t id)
966
{
967
  if (int err = verify_ww_index(index))
968
    return err;
969

970
  const auto& wws = variance_reduction::weight_windows.at(index);
971
  wws->set_id(id);
6,382✔
972
  return 0;
973
}
6,463✔
974

81✔
975
extern "C" int openmc_weight_windows_update_magic(int32_t ww_idx,
976
  int32_t tally_idx, const char* value, double threshold, double ratio)
6,382✔
977
{
978
  if (int err = verify_ww_index(ww_idx))
979
    return err;
980

981
  if (tally_idx < 0 || tally_idx >= model::tallies.size()) {
982
    set_errmsg(fmt::format("Index '{}' for tally is invalid", tally_idx));
1,991✔
983
    return OPENMC_E_OUT_OF_BOUNDS;
984
  }
1,991✔
UNCOV
985

×
UNCOV
986
  // get the requested tally
×
987
  const Tally* tally = model::tallies.at(tally_idx).get();
988

1,991✔
989
  // get the WeightWindows object
990
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
991

165✔
992
  wws->update_weights(tally, value, threshold, ratio);
993

165✔
994
  return 0;
165✔
UNCOV
995
}
×
UNCOV
996

×
997
extern "C" int openmc_weight_windows_set_mesh(int32_t ww_idx, int32_t mesh_idx)
998
{
999
  if (int err = verify_ww_index(ww_idx))
165✔
1000
    return err;
165✔
1001
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
1002
  wws->set_mesh(mesh_idx);
1003
  return 0;
517✔
1004
}
1005

517✔
UNCOV
1006
extern "C" int openmc_weight_windows_get_mesh(int32_t ww_idx, int32_t* mesh_idx)
×
1007
{
1008
  if (int err = verify_ww_index(ww_idx))
517✔
1009
    return err;
517✔
1010
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
517✔
1011
  *mesh_idx = model::mesh_map.at(wws->mesh()->id());
1012
  return 0;
1013
}
154✔
1014

1015
extern "C" int openmc_weight_windows_set_energy_bounds(
154✔
UNCOV
1016
  int32_t ww_idx, double* e_bounds, size_t e_bounds_size)
×
1017
{
1018
  if (int err = verify_ww_index(ww_idx))
154✔
1019
    return err;
154✔
1020
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
154✔
1021
  wws->set_energy_bounds({e_bounds, e_bounds_size});
1022
  return 0;
1023
}
121✔
1024

1025
extern "C" int openmc_weight_windows_get_energy_bounds(
1026
  int32_t ww_idx, const double** e_bounds, size_t* e_bounds_size)
121✔
UNCOV
1027
{
×
1028
  if (int err = verify_ww_index(ww_idx))
1029
    return err;
121✔
UNCOV
1030
  const auto& wws = variance_reduction::weight_windows[ww_idx].get();
×
UNCOV
1031
  *e_bounds = wws->energy_bounds().data();
×
1032
  *e_bounds_size = wws->energy_bounds().size();
1033
  return 0;
1034
}
1035

121✔
1036
extern "C" int openmc_weight_windows_set_particle(int32_t index, int particle)
1037
{
1038
  if (int err = verify_ww_index(index))
121✔
1039
    return err;
1040

121✔
1041
  const auto& wws = variance_reduction::weight_windows.at(index);
1042
  wws->set_particle_type(static_cast<ParticleType>(particle));
121✔
1043
  return 0;
1044
}
1045

154✔
1046
extern "C" int openmc_weight_windows_get_particle(int32_t index, int* particle)
1047
{
154✔
UNCOV
1048
  if (int err = verify_ww_index(index))
×
1049
    return err;
154✔
1050

154✔
1051
  const auto& wws = variance_reduction::weight_windows.at(index);
154✔
1052
  *particle = static_cast<int>(wws->particle_type());
1053
  return 0;
1054
}
11✔
1055

1056
extern "C" int openmc_weight_windows_get_bounds(int32_t index,
11✔
UNCOV
1057
  const double** lower_bounds, const double** upper_bounds, size_t* size)
×
1058
{
11✔
1059
  if (int err = verify_ww_index(index))
11✔
1060
    return err;
11✔
1061

1062
  const auto& wws = variance_reduction::weight_windows[index];
1063
  *size = wws->lower_ww_bounds().size();
132✔
1064
  *lower_bounds = wws->lower_ww_bounds().data();
1065
  *upper_bounds = wws->upper_ww_bounds().data();
1066
  return 0;
132✔
UNCOV
1067
}
×
1068

132✔
1069
extern "C" int openmc_weight_windows_set_bounds(int32_t index,
132✔
1070
  const double* lower_bounds, const double* upper_bounds, size_t size)
132✔
1071
{
1072
  if (int err = verify_ww_index(index))
1073
    return err;
11✔
1074

1075
  const auto& wws = variance_reduction::weight_windows[index];
1076
  wws->set_bounds({lower_bounds, size}, {upper_bounds, size});
11✔
UNCOV
1077
  return 0;
×
1078
}
11✔
1079

11✔
1080
extern "C" int openmc_weight_windows_get_survival_ratio(
11✔
1081
  int32_t index, double* ratio)
11✔
1082
{
1083
  if (int err = verify_ww_index(index))
1084
    return err;
176✔
1085
  const auto& wws = variance_reduction::weight_windows[index];
1086
  *ratio = wws->survival_ratio();
176✔
UNCOV
1087
  return 0;
×
1088
}
1089

176✔
1090
extern "C" int openmc_weight_windows_set_survival_ratio(
176✔
1091
  int32_t index, double ratio)
176✔
1092
{
1093
  if (int err = verify_ww_index(index))
1094
    return err;
44✔
1095
  const auto& wws = variance_reduction::weight_windows[index];
1096
  wws->survival_ratio() = ratio;
44✔
UNCOV
1097
  std::cout << "Survival ratio: " << wws->survival_ratio() << std::endl;
×
1098
  return 0;
1099
}
44✔
1100

44✔
1101
extern "C" int openmc_weight_windows_get_max_lower_bound_ratio(
44✔
1102
  int32_t index, double* lb_ratio)
1103
{
1104
  if (int err = verify_ww_index(index))
484✔
1105
    return err;
1106
  const auto& wws = variance_reduction::weight_windows[index];
1107
  *lb_ratio = wws->max_lower_bound_ratio();
484✔
UNCOV
1108
  return 0;
×
1109
}
1110

484✔
1111
extern "C" int openmc_weight_windows_set_max_lower_bound_ratio(
484✔
1112
  int32_t index, double lb_ratio)
484✔
1113
{
484✔
1114
  if (int err = verify_ww_index(index))
484✔
1115
    return err;
1116
  const auto& wws = variance_reduction::weight_windows[index];
1117
  wws->max_lower_bound_ratio() = lb_ratio;
11✔
1118
  return 0;
1119
}
1120

11✔
UNCOV
1121
extern "C" int openmc_weight_windows_get_weight_cutoff(
×
1122
  int32_t index, double* cutoff)
1123
{
11✔
1124
  if (int err = verify_ww_index(index))
11✔
1125
    return err;
11✔
1126
  const auto& wws = variance_reduction::weight_windows[index];
1127
  *cutoff = wws->weight_cutoff();
1128
  return 0;
33✔
1129
}
1130

1131
extern "C" int openmc_weight_windows_set_weight_cutoff(
33✔
UNCOV
1132
  int32_t index, double cutoff)
×
1133
{
33✔
1134
  if (int err = verify_ww_index(index))
33✔
1135
    return err;
33✔
1136
  const auto& wws = variance_reduction::weight_windows[index];
1137
  wws->weight_cutoff() = cutoff;
1138
  return 0;
11✔
1139
}
1140

1141
extern "C" int openmc_weight_windows_get_max_split(
11✔
UNCOV
1142
  int32_t index, int* max_split)
×
1143
{
11✔
1144
  if (int err = verify_ww_index(index))
11✔
1145
    return err;
11✔
1146
  const auto& wws = variance_reduction::weight_windows[index];
11✔
1147
  *max_split = wws->max_split();
1148
  return 0;
1149
}
33✔
1150

1151
extern "C" int openmc_weight_windows_set_max_split(int32_t index, int max_split)
1152
{
33✔
UNCOV
1153
  if (int err = verify_ww_index(index))
×
1154
    return err;
33✔
1155
  const auto& wws = variance_reduction::weight_windows[index];
33✔
1156
  wws->max_split() = max_split;
33✔
1157
  return 0;
1158
}
1159

11✔
1160
extern "C" int openmc_extend_weight_windows(
1161
  int32_t n, int32_t* index_start, int32_t* index_end)
1162
{
11✔
UNCOV
1163
  if (index_start)
×
1164
    *index_start = variance_reduction::weight_windows.size();
11✔
1165
  if (index_end)
11✔
1166
    *index_end = variance_reduction::weight_windows.size() + n - 1;
11✔
1167
  for (int i = 0; i < n; ++i)
1168
    variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
1169
  return 0;
33✔
1170
}
1171

1172
extern "C" size_t openmc_weight_windows_size()
33✔
UNCOV
1173
{
×
1174
  return variance_reduction::weight_windows.size();
33✔
1175
}
33✔
1176

33✔
1177
extern "C" int openmc_weight_windows_export(const char* filename)
1178
{
1179

11✔
1180
  if (!mpi::master)
1181
    return 0;
1182

11✔
UNCOV
1183
  std::string name = filename ? filename : "weight_windows.h5";
×
1184

11✔
1185
  write_message(fmt::format("Exporting weight windows to {}...", name), 5);
11✔
1186

11✔
1187
  hid_t ww_file = file_open(name, 'w');
1188

1189
  // Write file type
33✔
1190
  write_attribute(ww_file, "filetype", "weight_windows");
1191

1192
  // Write revisiion number for state point file
33✔
UNCOV
1193
  write_attribute(ww_file, "version", VERSION_WEIGHT_WINDOWS);
×
1194

33✔
1195
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
33✔
1196

33✔
1197
  hid_t mesh_group = create_group(ww_file, "meshes");
1198

1199
  std::vector<int32_t> mesh_ids;
11✔
1200
  std::vector<int32_t> ww_ids;
1201
  for (const auto& ww : variance_reduction::weight_windows) {
11✔
UNCOV
1202

×
1203
    ww->to_hdf5(weight_windows_group);
11✔
1204
    ww_ids.push_back(ww->id());
11✔
1205

11✔
1206
    // if the mesh has already been written, move on
1207
    int32_t mesh_id = ww->mesh()->id();
1208
    if (std::find(mesh_ids.begin(), mesh_ids.end(), mesh_id) != mesh_ids.end())
154✔
1209
      continue;
1210

1211
    mesh_ids.push_back(mesh_id);
154✔
1212
    ww->mesh()->to_hdf5(mesh_group);
154✔
1213
  }
154✔
UNCOV
1214

×
1215
  write_attribute(mesh_group, "n_meshes", mesh_ids.size());
308✔
1216
  write_attribute(mesh_group, "ids", mesh_ids);
154✔
1217
  close_group(mesh_group);
154✔
1218

1219
  write_attribute(weight_windows_group, "n_weight_windows", ww_ids.size());
1220
  write_attribute(weight_windows_group, "ids", ww_ids);
154✔
1221
  close_group(weight_windows_group);
1222

154✔
1223
  file_close(ww_file);
1224

1225
  return 0;
151✔
1226
}
1227

1228
extern "C" int openmc_weight_windows_import(const char* filename)
151✔
1229
{
30✔
1230
  std::string name = filename ? filename : "weight_windows.h5";
1231

242✔
1232
  if (mpi::master)
1233
    write_message(fmt::format("Importing weight windows from {}...", name), 5);
121✔
1234

1235
  if (!file_exists(name)) {
121✔
1236
    set_errmsg(fmt::format("File '{}' does not exist", name));
1237
  }
1238

121✔
1239
  hid_t ww_file = file_open(name, 'r');
1240

1241
  // Check that filetype is correct
121✔
1242
  std::string filetype;
1243
  read_attribute(ww_file, "filetype", filetype);
121✔
1244
  if (filetype != "weight_windows") {
1245
    file_close(ww_file);
121✔
1246
    set_errmsg(fmt::format("File '{}' is not a weight windows file.", name));
1247
    return OPENMC_E_INVALID_ARGUMENT;
121✔
1248
  }
121✔
1249

242✔
1250
  // Check that the file version is compatible
1251
  std::array<int, 2> file_version;
121✔
1252
  read_attribute(ww_file, "version", file_version);
121✔
1253
  if (file_version[0] != VERSION_WEIGHT_WINDOWS[0]) {
1254
    std::string err_msg =
1255
      fmt::format("File '{}' has version {} which is incompatible with the "
121✔
1256
                  "expected version ({}).",
121✔
UNCOV
1257
        name, file_version, VERSION_WEIGHT_WINDOWS);
×
1258
    set_errmsg(err_msg);
1259
    return OPENMC_E_INVALID_ARGUMENT;
121✔
1260
  }
121✔
1261

1262
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
1263

121✔
1264
  std::vector<std::string> names = group_names(weight_windows_group);
121✔
1265

121✔
1266
  for (const auto& name : names) {
1267
    WeightWindows::from_hdf5(weight_windows_group, name);
121✔
1268
  }
121✔
1269

121✔
1270
  close_group(weight_windows_group);
1271

121✔
1272
  file_close(ww_file);
1273

121✔
1274
  return 0;
121✔
1275
}
1276

11✔
1277
} // 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