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

openmc-dev / openmc / 12385490469

18 Dec 2024 02:58AM UTC coverage: 82.673% (-2.2%) from 84.823%
12385490469

Pull #3087

github

web-flow
Merge 3317476f5 into 775c41512
Pull Request #3087: wheel building with scikit build core

106679 of 129038 relevant lines covered (82.67%)

12084526.77 hits per line

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

54.55
/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/search.h"
26
#include "openmc/settings.h"
27
#include "openmc/tallies/filter_energy.h"
28
#include "openmc/tallies/filter_mesh.h"
29
#include "openmc/tallies/filter_particle.h"
30
#include "openmc/tallies/tally.h"
31
#include "openmc/xml_interface.h"
32

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

36
namespace openmc {
37

38
//==============================================================================
39
// Global variables
40
//==============================================================================
41

42
namespace variance_reduction {
43

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

48
} // namespace variance_reduction
49

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

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

59
  // WW on photon and neutron only
60
  if (p.type() != ParticleType::neutron && p.type() != ParticleType::photon)
42,893,923✔
61
    return;
4,927,608✔
62

63
  // skip dead or no energy
64
  if (p.E() <= 0 || !p.alive())
37,966,315✔
65
    return;
719,154✔
66

67
  bool in_domain = false;
37,247,161✔
68
  // TODO: this is a linear search - should do something more clever
69
  WeightWindow weight_window;
37,247,161✔
70
  for (const auto& ww : variance_reduction::weight_windows) {
55,006,670✔
71
    weight_window = ww->get_weight_window(p);
41,883,349✔
72
    if (weight_window.is_valid())
41,883,349✔
73
      break;
24,123,840✔
74
  }
75
  // particle is not in any of the ww domains, do nothing
76
  if (!weight_window.is_valid())
37,247,161✔
77
    return;
13,123,321✔
78

79
  // get the paramters
80
  double weight = p.wgt();
24,123,840✔
81

82
  // first check to see if particle should be killed for weight cutoff
83
  if (p.wgt() < weight_window.weight_cutoff) {
24,123,840✔
84
    p.wgt() = 0.0;
×
85
    return;
×
86
  }
87

88
  // check if particle is far above current weight window
89
  // only do this if the factor is not already set on the particle and a
90
  // maximum lower bound ratio is specified
91
  if (p.ww_factor() == 0.0 && weight_window.max_lb_ratio > 1.0 &&
24,126,936✔
92
      p.wgt() > weight_window.lower_weight * weight_window.max_lb_ratio) {
3,096✔
93
    p.ww_factor() =
3,096✔
94
      p.wgt() / (weight_window.lower_weight * weight_window.max_lb_ratio);
3,096✔
95
  }
96

97
  // move weight window closer to the particle weight if needed
98
  if (p.ww_factor() > 1.0)
24,123,840✔
99
    weight_window.scale(p.ww_factor());
1,579,560✔
100

101
  // if particle's weight is above the weight window split until they are within
102
  // the window
103
  if (weight > weight_window.upper_weight) {
24,123,840✔
104
    // do not further split the particle if above the limit
105
    if (p.n_split() >= settings::max_history_splits)
4,283,594✔
106
      return;
4,018,073✔
107

108
    double n_split = std::ceil(weight / weight_window.upper_weight);
265,521✔
109
    double max_split = weight_window.max_split;
265,521✔
110
    n_split = std::min(n_split, max_split);
265,521✔
111

112
    p.n_split() += n_split;
265,521✔
113

114
    // Create secondaries and divide weight among all particles
115
    int i_split = std::round(n_split);
265,521✔
116
    for (int l = 0; l < i_split - 1; l++) {
1,108,452✔
117
      p.create_secondary(weight / n_split, p.u(), p.E(), p.type());
842,931✔
118
    }
119
    // remaining weight is applied to current particle
120
    p.wgt() = weight / n_split;
265,521✔
121

122
  } else if (weight <= weight_window.lower_weight) {
19,840,246✔
123
    // if the particle weight is below the window, play Russian roulette
124
    double weight_survive =
125
      std::min(weight * weight_window.max_split, weight_window.survival_weight);
751,169✔
126
    russian_roulette(p, weight_survive);
751,169✔
127
  } // else particle is in the window, continue as normal
128
}
129

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

136
//==============================================================================
137
// WeightWindowSettings implementation
138
//==============================================================================
139

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

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

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

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

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

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

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

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

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

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

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

210
  set_defaults();
61✔
211
}
61✔
212

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

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

227
WeightWindows* WeightWindows::from_hdf5(
×
228
  hid_t wws_group, const std::string& group_name)
229
{
230
  // collect ID from the name of this group
231
  hid_t ww_group = open_group(wws_group, group_name);
×
232

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

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

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

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

244
  if (model::mesh_map.count(mesh_id) == 0) {
×
245
    fatal_error(
×
246
      fmt::format("Mesh {} used in weight windows does not exist.", mesh_id));
×
247
  }
248
  wws->set_mesh(model::mesh_map[mesh_id]);
×
249

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

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

260
  close_group(ww_group);
×
261

262
  return wws;
×
263
}
264

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

275
void WeightWindows::allocate_ww_bounds()
109✔
276
{
277
  auto shape = bounds_size();
109✔
278
  if (shape[0] * shape[1] == 0) {
109✔
279
    auto msg = fmt::format(
280
      "Size of weight window bounds is zero for WeightWindows {}", id());
×
281
    warning(msg);
×
282
  }
283
  lower_ww_ = xt::empty<double>(shape);
109✔
284
  lower_ww_.fill(-1);
109✔
285
  upper_ww_ = xt::empty<double>(shape);
109✔
286
  upper_ww_.fill(-1);
109✔
287
}
109✔
288

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

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

299
  // Ensure no other mesh has the same ID
300
  if (variance_reduction::ww_map.find(id) != variance_reduction::ww_map.end()) {
85✔
301
    throw std::runtime_error {
×
302
      fmt::format("Two weight windows have the same ID: {}", id)};
×
303
  }
304

305
  // If no ID is specified, auto-assign the next ID in the sequence
306
  if (id == C_NONE) {
85✔
307
    id = 0;
24✔
308
    for (const auto& m : variance_reduction::weight_windows) {
24✔
309
      id = std::max(id, m->id_);
×
310
    }
311
    ++id;
24✔
312
  }
313

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

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

328
void WeightWindows::set_particle_type(ParticleType p_type)
24✔
329
{
330
  if (p_type != ParticleType::neutron && p_type != ParticleType::photon)
24✔
331
    fatal_error(
×
332
      fmt::format("Particle type '{}' cannot be applied to weight windows.",
×
333
        particle_type_to_str(p_type)));
×
334
  particle_type_ = p_type;
24✔
335
}
24✔
336

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

342
  mesh_idx_ = mesh_idx;
85✔
343
  model::meshes[mesh_idx_]->prepare_for_point_location();
85✔
344
  allocate_ww_bounds();
85✔
345
}
85✔
346

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

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

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

364
  // Get mesh index for particle's position
365
  const auto& mesh = this->mesh();
37,505,653✔
366
  int mesh_bin = mesh->get_bin(p.r());
37,505,653✔
367

368
  // particle is outside the weight window mesh
369
  if (mesh_bin < 0)
37,505,653✔
370
    return {};
×
371

372
  // particle energy
373
  double E = p.E();
37,505,653✔
374

375
  // check to make sure energy is in range, expects sorted energy values
376
  if (E < energy_bounds_.front() || E > energy_bounds_.back())
37,505,653✔
377
    return {};
58,224✔
378

379
  // get the mesh bin in energy group
380
  int energy_bin =
381
    lower_bound_index(energy_bounds_.begin(), energy_bounds_.end(), E);
37,447,429✔
382

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

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

403
template<class T>
404
void WeightWindows::check_bounds(const T& lower, const T& upper) const
61✔
405
{
406
  // make sure that the upper and lower bounds have the same size
407
  if (lower.size() != upper.size()) {
61✔
408
    auto msg = fmt::format("The upper and lower weight window lengths do not "
×
409
                           "match.\n Lower size: {}\n Upper size: {}",
410
      lower.size(), upper.size());
×
411
    fatal_error(msg);
×
412
  }
×
413
  this->check_bounds(lower);
61✔
414
}
61✔
415

61✔
416
template<class T>
417
void WeightWindows::check_bounds(const T& bounds) const
418
{
61✔
419
  // check that the number of weight window entries is correct
×
420
  auto dims = this->bounds_size();
421
  if (bounds.size() != dims[0] * dims[1]) {
×
422
    auto err_msg =
×
423
      fmt::format("In weight window domain {} the number of spatial "
×
424
                  "energy/spatial bins ({}) does not match the number "
61✔
425
                  "of weight bins ({})",
61✔
426
        id_, dims, bounds.size());
×
427
    fatal_error(err_msg);
428
  }
429
}
×
430

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

×
435
  this->check_bounds(lower_bounds, upper_bounds);
×
436

437
  // set new weight window values
438
  lower_ww_ = lower_bounds;
439
  upper_ww_ = upper_bounds;
61✔
440
}
441

442
void WeightWindows::set_bounds(
61✔
443
  const xt::xtensor<double, 2>& lower_bounds, double ratio)
61✔
444
{
×
445
  this->check_bounds(lower_bounds);
446

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

61✔
453
void WeightWindows::set_bounds(
454
  gsl::span<const double> lower_bounds, gsl::span<const double> upper_bounds)
455
{
61✔
456
  check_bounds(lower_bounds, upper_bounds);
61✔
457
  auto shape = this->bounds_size();
×
458
  lower_ww_ = xt::empty<double>(shape);
459
  upper_ww_ = xt::empty<double>(shape);
460

461
  // set new weight window values
×
462
  xt::view(lower_ww_, xt::all()) =
×
463
    xt::adapt(lower_bounds.data(), lower_ww_.shape());
×
464
  xt::view(upper_ww_, xt::all()) =
61✔
465
    xt::adapt(upper_bounds.data(), upper_ww_.shape());
×
466
}
467

468
void WeightWindows::set_bounds(
×
469
  gsl::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_magic(
486
  const Tally* tally, const std::string& value, double threshold, double ratio)
×
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));
61✔
502
  }
503

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

122✔
513
  ///////////////////////////
183✔
514
  // Extract tally data
61✔
515
  //
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};
24✔
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))
24✔
540
    filter_types.push_back(FilterType::PARTICLE);
541

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

545
  // particle axis mapping
120✔
546
  transpose[0] =
24✔
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();
24✔
554

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

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

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

24✔
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(),
24✔
595
    score_index, static_cast<int>(TallyResult::SUM_SQ));
24✔
596
  int n = tally->n_realizations_;
24✔
597

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

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

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

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

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

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

626
  int e_bins = new_bounds.shape()[0];
627
  for (int e = 0; e < e_bins; e++) {
24✔
628
    // select all
629
    auto group_view = xt::view(new_bounds, e);
630

×
631
    // divide by volume of mesh elements
×
632
    for (int i = 0; i < group_view.size(); i++) {
×
633
      group_view[i] /= mesh_vols[i];
×
634
    }
635

636
    double group_max = *std::max_element(group_view.begin(), group_view.end());
24✔
637
    // normalize values in this energy group by the maximum value for this
638
    // group
639
    if (group_max > 0.0)
640
      group_view /= 2.0 * group_max;
24✔
641
  }
48✔
642

24✔
643
  // make sure that values where the mean is zero are set s.t. the weight window
48✔
644
  // value will be ignored
24✔
645
  xt::filter(new_bounds, sum <= 0.0).fill(-1.0);
646

647
  // make sure the weight windows are ignored for any locations where the
648
  // relative error is higher than the specified relative error threshold
649
  xt::filter(new_bounds, rel_err > threshold).fill(-1.0);
650

651
  // update the bounds of this weight window class
652
  // noalias avoids additional memory allocation
653
  xt::noalias(upper_ww_) = ratio * lower_ww_;
654
}
655

656
void WeightWindows::check_tally_update_compatibility(const Tally* tally)
657
{
658
  // define the set of allowed filters for the tally
24✔
659
  const std::set<FilterType> allowed_filters = {
24✔
660
    FilterType::MESH, FilterType::ENERGY, FilterType::PARTICLE};
661

662
  // retrieve a mapping of filter type to filter index for the tally
24✔
663
  auto filter_indices = tally->filter_indices();
664

24✔
665
  // a mesh filter is required for a tally used to update weight windows
48✔
666
  if (!filter_indices.count(FilterType::MESH)) {
24✔
667
    fatal_error(
668
      "A mesh filter is required for a tally to update weight window bounds");
24✔
669
  }
12✔
670

671
  // ensure the mesh filter is using the same mesh as this weight window object
672
  auto mesh_filter = tally->get_filter<MeshFilter>();
24✔
673

674
  // make sure that all of the filters present on the tally are allowed
24✔
675
  for (auto filter_pair : filter_indices) {
1,680✔
676
    if (allowed_filters.find(filter_pair.first) == allowed_filters.end()) {
677
      fatal_error(fmt::format("Invalid filter type '{}' found on tally "
1,656✔
678
                              "used for weight window generation.",
679
        model::tally_filters[tally->filters(filter_pair.second)]->type_str()));
680
    }
1,657,656✔
681
  }
1,656,000✔
682

683
  if (mesh_filter->mesh() != mesh_idx_) {
684
    int32_t mesh_filter_id = model::meshes[mesh_filter->mesh()]->id();
1,656✔
685
    int32_t ww_mesh_id = model::meshes[this->mesh_idx_]->id();
686
    fatal_error(fmt::format("Mesh filter {} uses a different mesh ({}) than "
687
                            "weight window {} mesh ({})",
1,656✔
688
      mesh_filter->id(), mesh_filter_id, id_, ww_mesh_id));
1,656✔
689
  }
1,656✔
690

691
  // if an energy filter exists, make sure the energy grid matches that of this
692
  // weight window object
693
  if (auto energy_filter = tally->get_filter<EnergyFilter>()) {
24✔
694
    std::vector<double> filter_bins = energy_filter->bins();
695
    std::set<double> filter_e_bounds(
696
      energy_filter->bins().begin(), energy_filter->bins().end());
697
    if (filter_e_bounds.size() != energy_bounds().size()) {
24✔
698
      fatal_error(
699
        fmt::format("Energy filter {} does not have the same number of energy "
700
                    "bounds ({}) as weight window object {} ({})",
701
          energy_filter->id(), filter_e_bounds.size(), id_,
24✔
702
          energy_bounds().size()));
24✔
703
    }
704

24✔
705
    for (auto e : energy_bounds()) {
706
      if (filter_e_bounds.count(e) == 0) {
707
        fatal_error(fmt::format(
708
          "Energy bounds of filter {} and weight windows {} do not match",
24✔
709
          energy_filter->id(), id_));
710
      }
711
    }
24✔
712
  }
713
}
714

24✔
715
void WeightWindows::to_hdf5(hid_t group) const
×
716
{
717
  hid_t ww_group = create_group(group, fmt::format("weight_windows_{}", id()));
718

719
  write_dataset(ww_group, "mesh", this->mesh()->id());
720
  write_dataset(
24✔
721
    ww_group, "particle_type", openmc::particle_type_to_str(particle_type_));
722
  write_dataset(ww_group, "energy_bounds", energy_bounds_);
723
  write_dataset(ww_group, "lower_ww_bounds", lower_ww_);
96✔
724
  write_dataset(ww_group, "upper_ww_bounds", upper_ww_);
72✔
725
  write_dataset(ww_group, "survival_ratio", survival_ratio_);
×
726
  write_dataset(ww_group, "max_lower_bound_ratio", max_lb_ratio_);
727
  write_dataset(ww_group, "max_split", max_split_);
×
728
  write_dataset(ww_group, "weight_cutoff", weight_cutoff_);
729

730
  close_group(ww_group);
731
}
24✔
732

×
733
WeightWindowsGenerator::WeightWindowsGenerator(pugi::xml_node node)
×
734
{
×
735
  // read information from the XML node
736
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh"));
×
737
  int32_t mesh_idx = model::mesh_map[mesh_id];
738
  max_realizations_ = std::stoi(get_node_value(node, "max_realizations"));
739

740
  int active_batches = settings::n_batches - settings::n_inactive;
741
  if (max_realizations_ > active_batches) {
24✔
742
    auto msg =
24✔
743
      fmt::format("The maximum number of specified tally realizations ({}) is "
744
                  "greater than the number of active batches ({}).",
24✔
745
        max_realizations_, active_batches);
24✔
746
    warning(msg);
×
747
  }
×
748
  auto tmp_str = get_node_value(node, "particle_type", true, true);
749
  auto particle_type = str_to_particle_type(tmp_str);
×
750

×
751
  update_interval_ = std::stoi(get_node_value(node, "update_interval"));
752
  on_the_fly_ = get_node_value_bool(node, "on_the_fly");
753

1,704✔
754
  std::vector<double> e_bounds;
1,680✔
755
  if (check_for_node(node, "energy_bounds")) {
×
756
    e_bounds = get_node_array<double>(node, "energy_bounds");
757
  } else {
×
758
    int p_type = static_cast<int>(particle_type);
759
    e_bounds.push_back(data::energy_min[p_type]);
760
    e_bounds.push_back(data::energy_max[p_type]);
24✔
761
  }
24✔
762

763
  // set method and parameters for updates
24✔
764
  method_ = get_node_value(node, "method");
765
  if (method_ == "magic") {
48✔
766
    // parse non-default update parameters if specified
767
    if (check_for_node(node, "update_parameters")) {
24✔
768
      pugi::xml_node params_node = node.child("update_parameters");
24✔
769
      if (check_for_node(params_node, "value"))
48✔
770
        tally_value_ = get_node_value(params_node, "value");
24✔
771
      if (check_for_node(params_node, "threshold"))
24✔
772
        threshold_ = std::stod(get_node_value(params_node, "threshold"));
24✔
773
      if (check_for_node(params_node, "ratio")) {
24✔
774
        ratio_ = std::stod(get_node_value(params_node, "ratio"));
24✔
775
      }
24✔
776
    }
24✔
777
    // check update parameter values
778
    if (tally_value_ != "mean" && tally_value_ != "rel_err") {
24✔
779
      fatal_error(fmt::format("Unsupported tally value '{}' specified for "
24✔
780
                              "weight window generation.",
781
        tally_value_));
24✔
782
    }
783
    if (threshold_ <= 0.0)
784
      fatal_error(fmt::format("Invalid relative error threshold '{}' (<= 0.0) "
24✔
785
                              "specified for weight window generation",
24✔
786
        ratio_));
24✔
787
    if (ratio_ <= 1.0)
788
      fatal_error(fmt::format("Invalid weight window ratio '{}' (<= 1.0) "
24✔
789
                              "specified for weight window generation"));
24✔
790
  } else {
791
    fatal_error(fmt::format(
792
      "Unknown weight window update method '{}' specified", method_));
793
  }
×
794

×
795
  // create a matching weight windows object
796
  auto wws = WeightWindows::create();
24✔
797
  ww_idx_ = wws->index();
24✔
798
  wws->set_mesh(mesh_idx);
799
  if (e_bounds.size() > 0)
24✔
800
    wws->set_energy_bounds(e_bounds);
24✔
801
  wws->set_particle_type(particle_type);
802
  wws->set_defaults();
24✔
803
}
24✔
804

24✔
805
void WeightWindowsGenerator::create_tally()
806
{
×
807
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
×
808

×
809
  // create a tally based on the WWG information
810
  Tally* ww_tally = Tally::create();
811
  tally_idx_ = model::tally_map[ww_tally->id()];
812
  ww_tally->set_scores({"flux"});
24✔
813

24✔
814
  int32_t mesh_id = wws->mesh()->id();
815
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
24✔
816
  // see if there's already a mesh filter using this mesh
24✔
817
  bool found_mesh_filter = false;
24✔
818
  for (const auto& f : model::tally_filters) {
24✔
819
    if (f->type() == FilterType::MESH) {
24✔
820
      const auto* mesh_filter = dynamic_cast<MeshFilter*>(f.get());
24✔
821
      if (mesh_filter->mesh() == mesh_idx && !mesh_filter->translated()) {
24✔
822
        ww_tally->add_filter(f.get());
24✔
823
        found_mesh_filter = true;
824
        break;
825
      }
826
    }
24✔
827
  }
×
828

829
  if (!found_mesh_filter) {
×
830
    auto mesh_filter = Filter::create("mesh");
831
    openmc_mesh_filter_set_mesh(mesh_filter->index(), model::mesh_map[mesh_id]);
24✔
832
    ww_tally->add_filter(mesh_filter);
×
833
  }
834

×
835
  const auto& e_bounds = wws->energy_bounds();
24✔
836
  if (e_bounds.size() > 0) {
×
837
    auto energy_filter = Filter::create("energy");
838
    openmc_energy_filter_set_bins(
839
      energy_filter->index(), e_bounds.size(), e_bounds.data());
×
840
    ww_tally->add_filter(energy_filter);
×
841
  }
842

843
  // add a particle filter
844
  auto particle_type = wws->particle_type();
24✔
845
  auto particle_filter = Filter::create("particle");
24✔
846
  auto pf = dynamic_cast<ParticleFilter*>(particle_filter);
24✔
847
  pf->set_particles({&particle_type, 1});
24✔
848
  ww_tally->add_filter(particle_filter);
24✔
849
}
24✔
850

24✔
851
void WeightWindowsGenerator::update() const
24✔
852
{
853
  const auto& wws = variance_reduction::weight_windows[ww_idx_];
24✔
854

855
  Tally* tally = model::tallies[tally_idx_].get();
24✔
856

857
  // if we're beyond the number of max realizations or not at the corrrect
858
  // update interval, skip the update
24✔
859
  if (max_realizations_ < tally->n_realizations_ ||
24✔
860
      tally->n_realizations_ % update_interval_ != 0)
48✔
861
    return;
862

24✔
863
  wws->update_magic(tally, tally_value_, threshold_, ratio_);
24✔
864

865
  // if we're not doing on the fly generation, reset the tally results once
24✔
866
  // we're done with the update
48✔
867
  if (!on_the_fly_)
24✔
868
    tally->reset();
×
869

×
870
  // TODO: deactivate or remove tally once weight window generation is
×
871
  // complete
×
872
}
×
873

874
//==============================================================================
875
// Non-member functions
876
//==============================================================================
877

24✔
878
void finalize_variance_reduction()
24✔
879
{
24✔
880
  for (const auto& wwg : variance_reduction::weight_windows_generators) {
24✔
881
    wwg->create_tally();
882
  }
883
}
24✔
884

24✔
885
//==============================================================================
24✔
886
// C API
48✔
887
//==============================================================================
24✔
888

24✔
889
int verify_ww_index(int32_t index)
890
{
891
  if (index < 0 || index >= variance_reduction::weight_windows.size()) {
892
    set_errmsg(fmt::format("Index '{}' for weight windows is invalid", index));
24✔
893
    return OPENMC_E_OUT_OF_BOUNDS;
24✔
894
  }
24✔
895
  return 0;
24✔
896
}
24✔
897

24✔
898
extern "C" int openmc_get_weight_windows_index(int32_t id, int32_t* idx)
899
{
120✔
900
  auto it = variance_reduction::ww_map.find(id);
901
  if (it == variance_reduction::ww_map.end()) {
120✔
902
    set_errmsg(fmt::format("No weight windows exist with ID={}", id));
903
    return OPENMC_E_INVALID_ID;
120✔
904
  }
905

906
  *idx = it->second;
907
  return 0;
120✔
908
}
24✔
909

96✔
910
extern "C" int openmc_weight_windows_get_id(int32_t index, int32_t* id)
911
{
24✔
912
  if (int err = verify_ww_index(index))
913
    return err;
914

915
  const auto& wws = variance_reduction::weight_windows.at(index);
24✔
916
  *id = wws->id();
×
917
  return 0;
918
}
919

920
extern "C" int openmc_weight_windows_set_id(int32_t index, int32_t id)
921
{
922
  if (int err = verify_ww_index(index))
923
    return err;
924

925
  const auto& wws = variance_reduction::weight_windows.at(index);
926
  wws->set_id(id);
5,401✔
927
  return 0;
928
}
5,425✔
929

24✔
930
extern "C" int openmc_weight_windows_update_magic(int32_t ww_idx,
931
  int32_t tally_idx, const char* value, double threshold, double ratio)
5,401✔
932
{
933
  if (int err = verify_ww_index(ww_idx))
934
    return err;
935

936
  if (tally_idx < 0 || tally_idx >= model::tallies.size()) {
937
    set_errmsg(fmt::format("Index '{}' for tally is invalid", tally_idx));
×
938
    return OPENMC_E_OUT_OF_BOUNDS;
939
  }
×
940

×
941
  // get the requested tally
×
942
  const Tally* tally = model::tallies.at(tally_idx).get();
943

×
944
  // get the WeightWindows object
945
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
946

×
947
  wws->update_magic(tally, value, threshold, ratio);
948

×
949
  return 0;
×
950
}
×
951

×
952
extern "C" int openmc_weight_windows_set_mesh(int32_t ww_idx, int32_t mesh_idx)
953
{
954
  if (int err = verify_ww_index(ww_idx))
×
955
    return err;
×
956
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
957
  wws->set_mesh(mesh_idx);
958
  return 0;
×
959
}
960

×
961
extern "C" int openmc_weight_windows_get_mesh(int32_t ww_idx, int32_t* mesh_idx)
×
962
{
963
  if (int err = verify_ww_index(ww_idx))
×
964
    return err;
×
965
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
×
966
  *mesh_idx = model::mesh_map.at(wws->mesh()->id());
967
  return 0;
968
}
×
969

970
extern "C" int openmc_weight_windows_set_energy_bounds(
×
971
  int32_t ww_idx, double* e_bounds, size_t e_bounds_size)
×
972
{
973
  if (int err = verify_ww_index(ww_idx))
×
974
    return err;
×
975
  const auto& wws = variance_reduction::weight_windows.at(ww_idx);
×
976
  wws->set_energy_bounds({e_bounds, e_bounds_size});
977
  return 0;
978
}
×
979

980
extern "C" int openmc_weight_windows_get_energy_bounds(
981
  int32_t ww_idx, const double** e_bounds, size_t* e_bounds_size)
×
982
{
×
983
  if (int err = verify_ww_index(ww_idx))
984
    return err;
×
985
  const auto& wws = variance_reduction::weight_windows[ww_idx].get();
×
986
  *e_bounds = wws->energy_bounds().data();
×
987
  *e_bounds_size = wws->energy_bounds().size();
988
  return 0;
989
}
990

×
991
extern "C" int openmc_weight_windows_set_particle(int32_t index, int particle)
992
{
993
  if (int err = verify_ww_index(index))
×
994
    return err;
995

×
996
  const auto& wws = variance_reduction::weight_windows.at(index);
997
  wws->set_particle_type(static_cast<ParticleType>(particle));
×
998
  return 0;
999
}
1000

×
1001
extern "C" int openmc_weight_windows_get_particle(int32_t index, int* particle)
1002
{
×
1003
  if (int err = verify_ww_index(index))
×
1004
    return err;
×
1005

×
1006
  const auto& wws = variance_reduction::weight_windows.at(index);
×
1007
  *particle = static_cast<int>(wws->particle_type());
1008
  return 0;
1009
}
×
1010

1011
extern "C" int openmc_weight_windows_get_bounds(int32_t index,
×
1012
  const double** lower_bounds, const double** upper_bounds, size_t* size)
×
1013
{
×
1014
  if (int err = verify_ww_index(index))
×
1015
    return err;
×
1016

1017
  const auto& wws = variance_reduction::weight_windows[index];
1018
  *size = wws->lower_ww_bounds().size();
×
1019
  *lower_bounds = wws->lower_ww_bounds().data();
1020
  *upper_bounds = wws->upper_ww_bounds().data();
1021
  return 0;
×
1022
}
×
1023

×
1024
extern "C" int openmc_weight_windows_set_bounds(int32_t index,
×
1025
  const double* lower_bounds, const double* upper_bounds, size_t size)
×
1026
{
1027
  if (int err = verify_ww_index(index))
1028
    return err;
×
1029

1030
  const auto& wws = variance_reduction::weight_windows[index];
1031
  wws->set_bounds({lower_bounds, size}, {upper_bounds, size});
×
1032
  return 0;
×
1033
}
×
1034

×
1035
extern "C" int openmc_weight_windows_get_survival_ratio(
×
1036
  int32_t index, double* ratio)
×
1037
{
1038
  if (int err = verify_ww_index(index))
1039
    return err;
×
1040
  const auto& wws = variance_reduction::weight_windows[index];
1041
  *ratio = wws->survival_ratio();
×
1042
  return 0;
×
1043
}
1044

×
1045
extern "C" int openmc_weight_windows_set_survival_ratio(
×
1046
  int32_t index, double ratio)
×
1047
{
1048
  if (int err = verify_ww_index(index))
1049
    return err;
×
1050
  const auto& wws = variance_reduction::weight_windows[index];
1051
  wws->survival_ratio() = ratio;
×
1052
  std::cout << "Survival ratio: " << wws->survival_ratio() << std::endl;
×
1053
  return 0;
1054
}
×
1055

×
1056
extern "C" int openmc_weight_windows_get_max_lower_bound_ratio(
×
1057
  int32_t index, double* lb_ratio)
1058
{
1059
  if (int err = verify_ww_index(index))
×
1060
    return err;
1061
  const auto& wws = variance_reduction::weight_windows[index];
1062
  *lb_ratio = wws->max_lower_bound_ratio();
×
1063
  return 0;
×
1064
}
1065

×
1066
extern "C" int openmc_weight_windows_set_max_lower_bound_ratio(
×
1067
  int32_t index, double lb_ratio)
×
1068
{
×
1069
  if (int err = verify_ww_index(index))
×
1070
    return err;
1071
  const auto& wws = variance_reduction::weight_windows[index];
1072
  wws->max_lower_bound_ratio() = lb_ratio;
×
1073
  return 0;
1074
}
1075

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

1086
extern "C" int openmc_weight_windows_set_weight_cutoff(
×
1087
  int32_t index, double cutoff)
×
1088
{
×
1089
  if (int err = verify_ww_index(index))
×
1090
    return err;
×
1091
  const auto& wws = variance_reduction::weight_windows[index];
1092
  wws->weight_cutoff() = cutoff;
1093
  return 0;
×
1094
}
1095

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

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

×
1115
extern "C" int openmc_extend_weight_windows(
1116
  int32_t n, int32_t* index_start, int32_t* index_end)
1117
{
×
1118
  if (index_start)
×
1119
    *index_start = variance_reduction::weight_windows.size();
×
1120
  if (index_end)
×
1121
    *index_end = variance_reduction::weight_windows.size() + n - 1;
×
1122
  for (int i = 0; i < n; ++i)
1123
    variance_reduction::weight_windows.push_back(make_unique<WeightWindows>());
1124
  return 0;
×
1125
}
1126

1127
extern "C" size_t openmc_weight_windows_size()
×
1128
{
×
1129
  return variance_reduction::weight_windows.size();
×
1130
}
×
1131

×
1132
extern "C" int openmc_weight_windows_export(const char* filename)
1133
{
1134

×
1135
  if (!mpi::master)
1136
    return 0;
1137

×
1138
  std::string name = filename ? filename : "weight_windows.h5";
×
1139

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

×
1142
  hid_t ww_file = file_open(name, 'w');
1143

1144
  // Write file type
×
1145
  write_attribute(ww_file, "filetype", "weight_windows");
1146

1147
  // Write revisiion number for state point file
×
1148
  write_attribute(ww_file, "version", VERSION_WEIGHT_WINDOWS);
×
1149

×
1150
  hid_t weight_windows_group = create_group(ww_file, "weight_windows");
×
1151

×
1152
  hid_t mesh_group = create_group(ww_file, "meshes");
1153

1154
  std::vector<int32_t> mesh_ids;
×
1155
  std::vector<int32_t> ww_ids;
1156
  for (const auto& ww : variance_reduction::weight_windows) {
×
1157

×
1158
    ww->to_hdf5(weight_windows_group);
×
1159
    ww_ids.push_back(ww->id());
×
1160

×
1161
    // if the mesh has already been written, move on
1162
    int32_t mesh_id = ww->mesh()->id();
1163
    if (std::find(mesh_ids.begin(), mesh_ids.end(), mesh_id) != mesh_ids.end())
×
1164
      continue;
1165

1166
    mesh_ids.push_back(mesh_id);
×
1167
    ww->mesh()->to_hdf5(mesh_group);
×
1168
  }
×
1169

×
1170
  write_attribute(mesh_group, "n_meshes", mesh_ids.size());
×
1171
  write_attribute(mesh_group, "ids", mesh_ids);
×
1172
  close_group(mesh_group);
×
1173

1174
  write_attribute(weight_windows_group, "n_weight_windows", ww_ids.size());
1175
  write_attribute(weight_windows_group, "ids", ww_ids);
×
1176
  close_group(weight_windows_group);
1177

×
1178
  file_close(ww_file);
1179

1180
  return 0;
24✔
1181
}
1182

1183
extern "C" int openmc_weight_windows_import(const char* filename)
24✔
1184
{
×
1185
  std::string name = filename ? filename : "weight_windows.h5";
1186

48✔
1187
  if (mpi::master)
1188
    write_message(fmt::format("Importing weight windows from {}...", name), 5);
24✔
1189

1190
  if (!file_exists(name)) {
24✔
1191
    set_errmsg(fmt::format("File '{}' does not exist", name));
1192
  }
1193

24✔
1194
  hid_t ww_file = file_open(name, 'r');
1195

1196
  // Check that filetype is correct
24✔
1197
  std::string filetype;
1198
  read_attribute(ww_file, "filetype", filetype);
24✔
1199
  if (filetype != "weight_windows") {
1200
    file_close(ww_file);
24✔
1201
    set_errmsg(fmt::format("File '{}' is not a weight windows file.", name));
1202
    return OPENMC_E_INVALID_ARGUMENT;
24✔
1203
  }
24✔
1204

48✔
1205
  // Check that the file version is compatible
1206
  std::array<int, 2> file_version;
24✔
1207
  read_attribute(ww_file, "version", file_version);
24✔
1208
  if (file_version[0] != VERSION_WEIGHT_WINDOWS[0]) {
1209
    std::string err_msg =
1210
      fmt::format("File '{}' has version {} which is incompatible with the "
24✔
1211
                  "expected version ({}).",
24✔
1212
        name, file_version, VERSION_WEIGHT_WINDOWS);
×
1213
    set_errmsg(err_msg);
1214
    return OPENMC_E_INVALID_ARGUMENT;
24✔
1215
  }
24✔
1216

1217
  hid_t weight_windows_group = open_group(ww_file, "weight_windows");
1218

24✔
1219
  std::vector<std::string> names = group_names(weight_windows_group);
24✔
1220

24✔
1221
  for (const auto& name : names) {
1222
    WeightWindows::from_hdf5(weight_windows_group, name);
24✔
1223
  }
24✔
1224

24✔
1225
  close_group(weight_windows_group);
1226

24✔
1227
  file_close(ww_file);
1228

24✔
1229
  return 0;
24✔
1230
}
1231

×
1232
} // 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