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

openmc-dev / openmc / 13183778412

06 Feb 2025 04:50PM UTC coverage: 82.601% (-2.3%) from 84.867%
13183778412

Pull #3087

github

web-flow
Merge f09af412b into 6e0f156d3
Pull Request #3087: wheel building with scikit build core

107123 of 129687 relevant lines covered (82.6%)

12608225.33 hits per line

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

57.12
/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)
58,184,772✔
62
    return;
9,106,016✔
63

64
  // skip dead or no energy
65
  if (p.E() <= 0 || !p.alive())
49,078,756✔
66
    return;
6,774,182✔
67

68
  bool in_domain = false;
42,304,574✔
69
  // TODO: this is a linear search - should do something more clever
70
  WeightWindow weight_window;
42,304,574✔
71
  for (const auto& ww : variance_reduction::weight_windows) {
60,278,101✔
72
    weight_window = ww->get_weight_window(p);
46,940,762✔
73
    if (weight_window.is_valid())
46,940,762✔
74
      break;
28,967,235✔
75
  }
76
  // particle is not in any of the ww domains, do nothing
77
  if (!weight_window.is_valid())
42,304,574✔
78
    return;
13,337,339✔
79

80
  // get the paramters
81
  double weight = p.wgt();
28,967,235✔
82

83
  // first check to see if particle should be killed for weight cutoff
84
  if (p.wgt() < weight_window.weight_cutoff) {
28,967,235✔
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 &&
28,970,331✔
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)
28,967,235✔
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) {
28,967,235✔
105
    // do not further split the particle if above the limit
106
    if (p.n_split() >= settings::max_history_splits)
5,405,778✔
107
      return;
4,018,426✔
108

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

113
    p.n_split() += n_split;
1,387,352✔
114

115
    // Create secondaries and divide weight among all particles
116
    int i_split = std::round(n_split);
1,387,352✔
117
    for (int l = 0; l < i_split - 1; l++) {
7,835,033✔
118
      p.split(weight / n_split);
6,447,681✔
119
    }
120
    // remaining weight is applied to current particle
121
    p.wgt() = weight / n_split;
1,387,352✔
122

123
  } else if (weight <= weight_window.lower_weight) {
23,561,457✔
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);
893,206✔
127
    russian_roulette(p, weight_survive);
893,206✔
128
  } // else particle is in the window, continue as normal
129
}
130

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

234
  auto wws = WeightWindows::create();
×
235

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

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

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

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

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

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

261
  close_group(ww_group);
×
262

263
  return wws;
×
264
}
265

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

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

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

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

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

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

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

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

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

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

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

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

373
  // particle energy
374
  double E = p.E();
42,563,066✔
375

376
  // check to make sure energy is in range, expects sorted energy values
377
  if (E < energy_bounds_.front() || E > energy_bounds_.back())
42,563,066✔
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);
42,504,842✔
383

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

533
  // build the transpose information to re-order data according to filter type
534
  std::array<int, 5> transpose = {0, 1, 2, 3, 4};
376✔
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))
376✔
541
    filter_types.push_back(FilterType::PARTICLE);
542

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

546
  // particle axis mapping
1,880✔
547
  transpose[0] =
376✔
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();
376✔
555

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

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

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

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

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

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

376✔
592
  // down-select data based on particle and score
×
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(),
376✔
596
    score_index, static_cast<int>(TallyResult::SUM_SQ));
376✔
597
  int n = tally->n_realizations_;
376✔
598

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

376✔
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_;
376✔
612
  auto& rel_err = this->upper_ww_;
613

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

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

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

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

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

376✔
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
×
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++) {
376✔
638
        group_view[i] /= mesh_vols[i];
639
      }
640

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

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

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

665
    xt::noalias(new_bounds) = new_bounds / (2.0 * max_val);
376✔
666
  }
752✔
667

376✔
668
  // make sure that values where the mean is zero are set s.t. the weight window
669
  // value will be ignored
376✔
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
376✔
674
  xt::filter(new_bounds, rel_err > threshold).fill(-1.0);
675

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

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

1,657,500✔
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,668✔
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,668✔
694
  }
1,668✔
695

1,668✔
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>()) {
376✔
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()) {
376✔
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_,
376✔
727
          energy_bounds().size()));
376✔
728
    }
729

376✔
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",
376✔
734
          energy_filter->id(), id_));
735
      }
736
    }
376✔
737
  }
738
}
739

376✔
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(
376✔
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,504✔
749
  write_dataset(ww_group, "upper_ww_bounds", upper_ww_);
1,128✔
750
  write_dataset(ww_group, "survival_ratio", survival_ratio_);
×
751
  write_dataset(ww_group, "max_lower_bound_ratio", max_lb_ratio_);
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
}
376✔
757

×
758
WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node)
×
759
{
×
760
  // read information from the XML node
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) {
376✔
767
    auto msg =
376✔
768
      fmt::format("The maximum number of specified tally realizations ({}) is "
769
                  "greater than the number of active batches ({}).",
376✔
770
        max_realizations_, active_batches);
376✔
771
    warning(msg);
×
772
  }
×
773
  auto tmp_str = get_node_value(node, "particle_type", true, true);
774
  auto particle_type = str_to_particle_type(tmp_str);
×
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

2,760✔
779
  std::vector<double> e_bounds;
2,384✔
780
  if (check_for_node(node, "energy_bounds")) {
×
781
    e_bounds = get_node_array<double>(node, "energy_bounds");
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]);
376✔
786
  }
376✔
787

788
  // set method
60✔
789
  std::string method_string = get_node_value(node, "method");
790
  if (method_string == "magic") {
120✔
791
    method_ = WeightWindowUpdateMethod::MAGIC;
792
    if (settings::solver_type == SolverType::RANDOM_RAY &&
60✔
793
        FlatSourceDomain::adjoint_) {
60✔
794
      fatal_error("Random ray weight window generation with MAGIC cannot be "
120✔
795
                  "done in adjoint mode.");
60✔
796
    }
60✔
797
  } else if (method_string == "fw_cadis") {
60✔
798
    method_ = WeightWindowUpdateMethod::FW_CADIS;
60✔
799
    if (settings::solver_type != SolverType::RANDOM_RAY) {
60✔
800
      fatal_error("FW-CADIS can only be run in random ray solver mode.");
60✔
801
    }
60✔
802
    FlatSourceDomain::adjoint_ = true;
803
  } else {
60✔
804
    fatal_error(fmt::format(
60✔
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();
842
}
×
843

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

17✔
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"});
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✔
875
  if (e_bounds.size() > 0) {
×
876
    auto energy_filter = Filter::create("energy");
877
    openmc_energy_filter_set_bins(
×
878
      energy_filter->index(), e_bounds.size(), e_bounds.data());
53✔
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✔
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);
5,470✔
966
  return 0;
967
}
5,523✔
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)
5,470✔
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));
×
977
    return OPENMC_E_OUT_OF_BOUNDS;
978
  }
×
979

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

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

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

×
988
  return 0;
×
989
}
×
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))
×
994
    return err;
×
995
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
996
  wws->set_mesh(mesh_idx);
997
  return 0;
×
998
}
999

×
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))
×
1003
    return err;
×
1004
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
×
1005
  *mesh_idx = model::mesh_map.at(wws->mesh()->id());
1006
  return 0;
1007
}
×
1008

1009
extern "C" int openmc_weight_windows_set_energy_bounds(
×
1010
  int32_t ww_idx, double* e_bounds, size_t e_bounds_size)
×
1011
{
1012
  if (int err = verify_ww_index(ww_idx))
×
1013
    return err;
×
1014
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
×
1015
  wws->set_energy_bounds({e_bounds, e_bounds_size});
1016
  return 0;
1017
}
×
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)
×
1021
{
×
1022
  if (int err = verify_ww_index(ww_idx))
1023
    return err;
×
1024
  const auto& wws = variance_reduction::weight_windows[ww_idx].get();
×
1025
  *e_bounds = wws->energy_bounds().data();
×
1026
  *e_bounds_size = wws->energy_bounds().size();
1027
  return 0;
1028
}
1029

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
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())
×
1203
      continue;
1204

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

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

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

×
1217
  file_close(ww_file);
1218

1219
  return 0;
70✔
1220
}
1221

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

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

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

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

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

120✔
1244
  // Check that the file version is compatible
1245
  std::array<int, 2> file_version;
60✔
1246
  read_attribute(ww_file, "version", file_version);
60✔
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 "
60✔
1250
                  "expected version ({}).",
60✔
1251
        name, file_version, VERSION_WEIGHT_WINDOWS);
×
1252
    set_errmsg(err_msg);
1253
    return OPENMC_E_INVALID_ARGUMENT;
60✔
1254
  }
60✔
1255

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

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

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

60✔
1264
  close_group(weight_windows_group);
1265

60✔
1266
  file_close(ww_file);
1267

60✔
1268
  return 0;
60✔
1269
}
1270

×
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