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

openmc-dev / openmc / 13209514200

07 Feb 2025 11:06PM UTC coverage: 84.905% (+0.04%) from 84.867%
13209514200

Pull #2655

github

web-flow
Merge ada075afa into 6e0f156d3
Pull Request #2655: Raytrace plots

392 of 442 new or added lines in 5 files covered. (88.69%)

1006 existing lines in 45 files now uncovered.

50343 of 59293 relevant lines covered (84.91%)

34881754.74 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 <cmath>
5
#include <set>
6
#include <string>
7

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

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

34
#include <fmt/core.h>
35
#include <gsl/gsl-lite.hpp>
36

37
namespace openmc {
38

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

43
namespace variance_reduction {
44

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

49
} // namespace variance_reduction
50

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

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

60
  // WW on photon and neutron only
61
  if (p.type() != ParticleType::neutron && p.type() != ParticleType::photon)
83,506,917✔
62
    return;
9,107,716✔
63

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

68
  bool in_domain = false;
66,972,036✔
69
  // TODO: this is a linear search - should do something more clever
70
  WeightWindow weight_window;
66,972,036✔
71
  for (const auto& ww : variance_reduction::weight_windows) {
86,111,430✔
72
    weight_window = ww->get_weight_window(p);
71,608,224✔
73
    if (weight_window.is_valid())
71,608,224✔
74
      break;
52,468,830✔
75
  }
76
  // particle is not in any of the ww domains, do nothing
77
  if (!weight_window.is_valid())
66,972,036✔
78
    return;
14,503,206✔
79

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

83
  // first check to see if particle should be killed for weight cutoff
84
  if (p.wgt() < weight_window.weight_cutoff) {
52,468,830✔
85
    p.wgt() = 0.0;
×
UNCOV
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,471,926✔
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,468,830✔
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,468,830✔
105
    // do not further split the particle if above the limit
106
    if (p.n_split() >= settings::max_history_splits)
11,822,664✔
107
      return;
10,016,957✔
108

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

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

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

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

131
void free_memory_weight_windows()
6,943✔
132
{
133
  variance_reduction::ww_map.clear();
6,943✔
134
  variance_reduction::weight_windows.clear();
6,943✔
135
}
6,943✔
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✔
UNCOV
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✔
UNCOV
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✔
UNCOV
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✔
UNCOV
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✔
UNCOV
202
      fatal_error("weight_cutoff must be larger than 0");
×
203
    if (weight_cutoff_ > 1)
85✔
UNCOV
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(
×
UNCOV
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());
×
UNCOV
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
  Expects(id >= 0 || id == C_NONE);
486✔
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 {
×
UNCOV
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(gsl::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.",
×
UNCOV
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✔
UNCOV
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

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

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

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

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

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

373
  // particle energy
374
  double E = p.E();
67,230,528✔
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,230,528✔
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,172,304✔
383

384
  // mesh_bin += energy_bin * mesh->n_bins();
385
  // Create individual weight window
386
  WeightWindow ww;
67,172,304✔
387
  ww.lower_weight = lower_ww_(energy_bin, mesh_bin);
67,172,304✔
388
  ww.upper_weight = upper_ww_(energy_bin, mesh_bin);
67,172,304✔
389
  ww.survival_weight = ww.lower_weight * survival_ratio_;
67,172,304✔
390
  ww.max_lb_ratio = max_lb_ratio_;
67,172,304✔
391
  ww.max_split = max_split_;
67,172,304✔
392
  ww.weight_cutoff = weight_cutoff_;
67,172,304✔
393
  return ww;
67,172,304✔
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✔
UNCOV
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);
×
UNCOV
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✔
UNCOV
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 =
×
UNCOV
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✔
UNCOV
427
        id_, dims, bounds.size());
×
428
    fatal_error(err_msg);
429
  }
430
}
×
UNCOV
431

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

×
UNCOV
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✔
UNCOV
445
{
×
446
  this->check_bounds(lower_bounds);
447

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

755
  close_group(ww_group);
756
}
508✔
757

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

180✔
988
  return 0;
180✔
UNCOV
989
}
×
UNCOV
990

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

168✔
1217
  file_close(ww_file);
1218

1219
  return 0;
94✔
1220
}
1221

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

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

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

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

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

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

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

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

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

84✔
1264
  close_group(weight_windows_group);
1265

84✔
1266
  file_close(ww_file);
1267

84✔
1268
  return 0;
84✔
1269
}
1270

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