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

openmc-dev / openmc / 13703779155

06 Mar 2025 04:45PM UTC coverage: 85.674% (+0.5%) from 85.129%
13703779155

Pull #3087

github

web-flow
Merge 20c292e2a into e360cb467
Pull Request #3087: wheel building with scikit build core

47261 of 55164 relevant lines covered (85.67%)

29624867.19 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 <cassert>
5
#include <cmath>
6
#include <set>
7
#include <string>
8

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

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

35
#include <fmt/core.h>
36

37
namespace openmc {
38

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

43
namespace variance_reduction {
44

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

49
} // namespace variance_reduction
50

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

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

60
  // WW on photon and neutron only
61
  if (p.type() != ParticleType::neutron && p.type() != ParticleType::photon)
53,333,332✔
62
    return;
8,349,359✔
63

64
  // skip dead or no energy
65
  if (p.E() <= 0 || !p.alive())
44,983,973✔
66
    return;
6,209,713✔
67

68
  bool in_domain = false;
38,774,260✔
69
  // TODO: this is a linear search - should do something more clever
70
  WeightWindow weight_window;
38,774,260✔
71
  for (const auto& ww : variance_reduction::weight_windows) {
55,246,254✔
72
    weight_window = ww->get_weight_window(p);
43,024,099✔
73
    if (weight_window.is_valid())
43,024,099✔
74
      break;
26,552,105✔
75
  }
76
  // particle is not in any of the ww domains, do nothing
77
  if (!weight_window.is_valid())
38,774,260✔
78
    return;
12,222,155✔
79

80
  // get the paramters
81
  double weight = p.wgt();
26,552,105✔
82

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

98
  // move weight window closer to the particle weight if needed
99
  if (p.ww_factor() > 1.0)
26,552,105✔
100
    weight_window.scale(p.ww_factor());
1,447,930✔
101

102
  // if particle's weight is above the weight window split until they are within
103
  // the window
104
  if (weight > weight_window.upper_weight) {
26,552,105✔
105
    // do not further split the particle if above the limit
106
    if (p.n_split() >= settings::max_history_splits)
4,955,202✔
107
      return;
3,683,263✔
108

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

113
    p.n_split() += n_split;
1,271,939✔
114

115
    // Create secondaries and divide weight among all particles
116
    int i_split = std::round(n_split);
1,271,939✔
117
    for (int l = 0; l < i_split - 1; l++) {
7,182,673✔
118
      p.split(weight / n_split);
5,910,734✔
119
    }
120
    // remaining weight is applied to current particle
121
    p.wgt() = weight / n_split;
1,271,939✔
122

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

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

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

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

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

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

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

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

175
  // get the survival value - optional
176
  if (check_for_node(node, "survival_ratio")) {
68✔
177
    survival_ratio_ = std::stod(get_node_value(node, "survival_ratio"));
68✔
178
    if (survival_ratio_ <= 1)
68✔
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")) {
68✔
185
    max_lb_ratio_ = std::stod(get_node_value(node, "max_lower_bound_ratio"));
32✔
186
    if (max_lb_ratio_ < 1.0) {
32✔
187
      fatal_error("Maximum lower bound ratio must be larger than 1");
×
188
    }
189
  }
190

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

373
  // particle energy
374
  double E = p.E();
39,011,211✔
375

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

664
    xt::noalias(new_bounds) = new_bounds / (2.0 * max_val);
353✔
665
  }
706✔
666

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

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

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

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

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

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

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

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

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

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

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

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

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

754
  close_group(ww_group);
755
}
353✔
756

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

49✔
923
//==============================================================================
49✔
924
// C API
98✔
925
//==============================================================================
49✔
926

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

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

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

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

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

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

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

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

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

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

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

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

×
987
  return 0;
×
988
}
×
989

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1216
  file_close(ww_file);
1217

1218
  return 0;
65✔
1219
}
1220

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

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

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

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

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

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

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

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

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

55✔
1263
  close_group(weight_windows_group);
1264

55✔
1265
  file_close(ww_file);
1266

55✔
1267
  return 0;
55✔
1268
}
1269

×
1270
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc