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

openmc-dev / openmc / 14503681639

16 Apr 2025 10:18PM UTC coverage: 85.44% (+0.03%) from 85.414%
14503681639

Pull #3363

github

web-flow
Merge 2b00af0af into 47ca2916a
Pull Request #3363: Figure of Merit implementation

19 of 21 new or added lines in 1 file covered. (90.48%)

41 existing lines in 1 file now uncovered.

52426 of 61360 relevant lines covered (85.44%)

37551049.33 hits per line

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

87.32
/src/state_point.cpp
1
#include "openmc/state_point.h"
2

3
#include <algorithm>
4
#include <cstdint> // for int64_t
5
#include <string>
6

7
#include "xtensor/xbuilder.hpp" // for empty_like
8
#include "xtensor/xview.hpp"
9
#include <fmt/core.h>
10

11
#include "openmc/bank.h"
12
#include "openmc/capi.h"
13
#include "openmc/constants.h"
14
#include "openmc/eigenvalue.h"
15
#include "openmc/error.h"
16
#include "openmc/file_utils.h"
17
#include "openmc/hdf5_interface.h"
18
#include "openmc/mcpl_interface.h"
19
#include "openmc/mesh.h"
20
#include "openmc/message_passing.h"
21
#include "openmc/mgxs_interface.h"
22
#include "openmc/nuclide.h"
23
#include "openmc/output.h"
24
#include "openmc/settings.h"
25
#include "openmc/simulation.h"
26
#include "openmc/tallies/derivative.h"
27
#include "openmc/tallies/filter.h"
28
#include "openmc/tallies/filter_mesh.h"
29
#include "openmc/tallies/tally.h"
30
#include "openmc/timer.h"
31
#include "openmc/vector.h"
32

33
namespace openmc {
34

35
extern "C" int openmc_statepoint_write(const char* filename, bool* write_source)
6,689✔
36
{
37
  simulation::time_statepoint.start();
6,689✔
38

39
  // If a nullptr is passed in, we assume that the user
40
  // wants a default name for this, of the form like output/statepoint.20.h5
41
  std::string filename_;
6,689✔
42
  if (filename) {
6,689✔
43
    filename_ = filename;
674✔
44
  } else {
45
    // Determine width for zero padding
46
    int w = std::to_string(settings::n_max_batches).size();
6,015✔
47

48
    // Set filename for state point
49
    filename_ = fmt::format("{0}statepoint.{1:0{2}}.h5", settings::path_output,
10,905✔
50
      simulation::current_batch, w);
6,015✔
51
  }
52

53
  // If a file name was specified, ensure it has .h5 file extension
54
  const auto extension = get_file_extension(filename_);
6,689✔
55
  if (extension != "h5") {
6,689✔
56
    warning("openmc_statepoint_write was passed a file extension differing "
×
57
            "from .h5, but an hdf5 file will be written.");
58
  }
59

60
  // Determine whether or not to write the source bank
61
  bool write_source_ = write_source ? *write_source : true;
6,689✔
62

63
  // Write message
64
  write_message("Creating state point " + filename_ + "...", 5);
6,689✔
65

66
  hid_t file_id;
67
  if (mpi::master) {
6,689✔
68
    // Create statepoint file
69
    file_id = file_open(filename_, 'w');
5,649✔
70

71
    // Write file type
72
    write_attribute(file_id, "filetype", "statepoint");
5,649✔
73

74
    // Write revision number for state point file
75
    write_attribute(file_id, "version", VERSION_STATEPOINT);
5,649✔
76

77
    // Write OpenMC version
78
    write_attribute(file_id, "openmc_version", VERSION);
5,649✔
79
#ifdef GIT_SHA1
80
    write_attribute(file_id, "git_sha1", GIT_SHA1);
81
#endif
82

83
    // Write current date and time
84
    write_attribute(file_id, "date_and_time", time_stamp());
5,649✔
85

86
    // Write path to input
87
    write_attribute(file_id, "path", settings::path_input);
5,649✔
88

89
    // Write out random number seed
90
    write_dataset(file_id, "seed", openmc_get_seed());
5,649✔
91

92
    // Write out random number stride
93
    write_dataset(file_id, "stride", openmc_get_stride());
5,649✔
94

95
    // Write run information
96
    write_dataset(file_id, "energy_mode",
5,649✔
97
      settings::run_CE ? "continuous-energy" : "multi-group");
98
    switch (settings::run_mode) {
5,649✔
99
    case RunMode::FIXED_SOURCE:
2,154✔
100
      write_dataset(file_id, "run_mode", "fixed source");
2,154✔
101
      break;
2,154✔
102
    case RunMode::EIGENVALUE:
3,495✔
103
      write_dataset(file_id, "run_mode", "eigenvalue");
3,495✔
104
      break;
3,495✔
105
    default:
×
106
      break;
×
107
    }
108
    write_attribute(file_id, "photon_transport", settings::photon_transport);
5,649✔
109
    write_dataset(file_id, "n_particles", settings::n_particles);
5,649✔
110
    write_dataset(file_id, "n_batches", settings::n_batches);
5,649✔
111

112
    // Write out current batch number
113
    write_dataset(file_id, "current_batch", simulation::current_batch);
5,649✔
114

115
    // Indicate whether source bank is stored in statepoint
116
    write_attribute(file_id, "source_present", write_source_);
5,649✔
117

118
    // Write out information for eigenvalue run
119
    if (settings::run_mode == RunMode::EIGENVALUE)
5,649✔
120
      write_eigenvalue_hdf5(file_id);
3,495✔
121

122
    hid_t tallies_group = create_group(file_id, "tallies");
5,649✔
123

124
    // Write meshes
125
    meshes_to_hdf5(tallies_group);
5,649✔
126

127
    // Write information for derivatives
128
    if (!model::tally_derivs.empty()) {
5,649✔
129
      hid_t derivs_group = create_group(tallies_group, "derivatives");
11✔
130
      for (const auto& deriv : model::tally_derivs) {
66✔
131
        hid_t deriv_group =
132
          create_group(derivs_group, "derivative " + std::to_string(deriv.id));
55✔
133
        write_dataset(deriv_group, "material", deriv.diff_material);
55✔
134
        if (deriv.variable == DerivativeVariable::DENSITY) {
55✔
135
          write_dataset(deriv_group, "independent variable", "density");
22✔
136
        } else if (deriv.variable == DerivativeVariable::NUCLIDE_DENSITY) {
33✔
137
          write_dataset(deriv_group, "independent variable", "nuclide_density");
22✔
138
          write_dataset(
22✔
139
            deriv_group, "nuclide", data::nuclides[deriv.diff_nuclide]->name_);
22✔
140
        } else if (deriv.variable == DerivativeVariable::TEMPERATURE) {
11✔
141
          write_dataset(deriv_group, "independent variable", "temperature");
11✔
142
        } else {
143
          fatal_error("Independent variable for derivative " +
×
144
                      std::to_string(deriv.id) +
×
145
                      " not defined in state_point.cpp");
146
        }
147
        close_group(deriv_group);
55✔
148
      }
149
      close_group(derivs_group);
11✔
150
    }
151

152
    // Write information for filters
153
    hid_t filters_group = create_group(tallies_group, "filters");
5,649✔
154
    write_attribute(filters_group, "n_filters", model::tally_filters.size());
5,649✔
155
    if (!model::tally_filters.empty()) {
5,649✔
156
      // Write filter IDs
157
      vector<int32_t> filter_ids;
3,556✔
158
      filter_ids.reserve(model::tally_filters.size());
3,556✔
159
      for (const auto& filt : model::tally_filters)
12,795✔
160
        filter_ids.push_back(filt->id());
9,239✔
161
      write_attribute(filters_group, "ids", filter_ids);
3,556✔
162

163
      // Write info for each filter
164
      for (const auto& filt : model::tally_filters) {
12,795✔
165
        hid_t filter_group =
166
          create_group(filters_group, "filter " + std::to_string(filt->id()));
9,239✔
167
        filt->to_statepoint(filter_group);
9,239✔
168
        close_group(filter_group);
9,239✔
169
      }
170
    }
3,556✔
171
    close_group(filters_group);
5,649✔
172

173
    // Write information for tallies
174
    write_attribute(tallies_group, "n_tallies", model::tallies.size());
5,649✔
175
    if (!model::tallies.empty()) {
5,649✔
176
      // Write tally IDs
177
      vector<int32_t> tally_ids;
4,029✔
178
      tally_ids.reserve(model::tallies.size());
4,029✔
179
      for (const auto& tally : model::tallies)
23,971✔
180
        tally_ids.push_back(tally->id_);
19,942✔
181
      write_attribute(tallies_group, "ids", tally_ids);
4,029✔
182

183
      // Write all tally information except results
184
      for (const auto& tally : model::tallies) {
23,971✔
185
        hid_t tally_group =
186
          create_group(tallies_group, "tally " + std::to_string(tally->id_));
19,942✔
187

188
        write_dataset(tally_group, "name", tally->name_);
19,942✔
189

190
        if (tally->writable_) {
19,942✔
191
          write_attribute(tally_group, "internal", 0);
19,095✔
192
        } else {
193
          write_attribute(tally_group, "internal", 1);
847✔
194
          close_group(tally_group);
847✔
195
          continue;
847✔
196
        }
197

198
        if (tally->multiply_density()) {
19,095✔
199
          write_attribute(tally_group, "multiply_density", 1);
19,062✔
200
        } else {
201
          write_attribute(tally_group, "multiply_density", 0);
33✔
202
        }
203

204
        if (tally->estimator_ == TallyEstimator::ANALOG) {
19,095✔
205
          write_dataset(tally_group, "estimator", "analog");
6,809✔
206
        } else if (tally->estimator_ == TallyEstimator::TRACKLENGTH) {
12,286✔
207
          write_dataset(tally_group, "estimator", "tracklength");
11,642✔
208
        } else if (tally->estimator_ == TallyEstimator::COLLISION) {
644✔
209
          write_dataset(tally_group, "estimator", "collision");
644✔
210
        }
211

212
        write_dataset(tally_group, "n_realizations", tally->n_realizations_);
19,095✔
213

214
        // Write the ID of each filter attached to this tally
215
        write_dataset(tally_group, "n_filters", tally->filters().size());
19,095✔
216
        if (!tally->filters().empty()) {
19,095✔
217
          vector<int32_t> filter_ids;
18,094✔
218
          filter_ids.reserve(tally->filters().size());
18,094✔
219
          for (auto i_filt : tally->filters())
54,569✔
220
            filter_ids.push_back(model::tally_filters[i_filt]->id());
36,475✔
221
          write_dataset(tally_group, "filters", filter_ids);
18,094✔
222
        }
18,094✔
223

224
        // Write the nuclides this tally scores
225
        vector<std::string> nuclides;
19,095✔
226
        for (auto i_nuclide : tally->nuclides_) {
45,923✔
227
          if (i_nuclide == -1) {
26,828✔
228
            nuclides.push_back("total");
16,499✔
229
          } else {
230
            if (settings::run_CE) {
10,329✔
231
              nuclides.push_back(data::nuclides[i_nuclide]->name_);
10,219✔
232
            } else {
233
              nuclides.push_back(data::mg.nuclides_[i_nuclide].name);
110✔
234
            }
235
          }
236
        }
237
        write_dataset(tally_group, "nuclides", nuclides);
19,095✔
238

239
        if (tally->deriv_ != C_NONE)
19,095✔
240
          write_dataset(
220✔
241
            tally_group, "derivative", model::tally_derivs[tally->deriv_].id);
220✔
242

243
        // Write the tally score bins
244
        vector<std::string> scores;
19,095✔
245
        for (auto sc : tally->scores_)
45,978✔
246
          scores.push_back(reaction_name(sc));
26,883✔
247
        write_dataset(tally_group, "n_score_bins", scores.size());
19,095✔
248
        write_dataset(tally_group, "score_bins", scores);
19,095✔
249

250
        close_group(tally_group);
19,095✔
251
      }
19,095✔
252
    }
4,029✔
253

254
    if (settings::reduce_tallies) {
5,649✔
255
      // Write global tallies
256
      write_dataset(file_id, "global_tallies", simulation::global_tallies);
5,649✔
257

258
      // Write tallies
259
      if (model::active_tallies.size() > 0) {
5,649✔
260
        // Indicate that tallies are on
261
        write_attribute(file_id, "tallies_present", 1);
3,864✔
262

263
        // Write all tally results
264
        for (const auto& tally : model::tallies) {
23,641✔
265
          if (!tally->writable_)
19,777✔
266
            continue;
682✔
267
          // Write sum and sum_sq for each bin
268
          std::string name = "tally " + std::to_string(tally->id_);
19,095✔
269
          hid_t tally_group = open_group(tallies_group, name.c_str());
19,095✔
270
          auto& results = tally->results_;
19,095✔
271
          write_tally_results(tally_group, results.shape()[0],
19,095✔
272
            results.shape()[1], results.data());
19,095✔
273
          close_group(tally_group);
19,095✔
274
        }
19,095✔
275
      } else {
276
        // Indicate tallies are off
277
        write_attribute(file_id, "tallies_present", 0);
1,785✔
278
      }
279
    }
280

281
    close_group(tallies_group);
5,649✔
282
  }
283

284
  // Check for the no-tally-reduction method
285
  if (!settings::reduce_tallies) {
6,689✔
286
    // If using the no-tally-reduction method, we need to collect tally
287
    // results before writing them to the state point file.
288
    write_tally_results_nr(file_id);
×
289

290
  } else if (mpi::master) {
6,689✔
291
    // Write number of global realizations
292
    write_dataset(file_id, "n_realizations", simulation::n_realizations);
5,649✔
293
  }
294

295
  if (mpi::master) {
6,689✔
296
    // Write out the runtime metrics.
297
    using namespace simulation;
298
    hid_t runtime_group = create_group(file_id, "runtime");
5,649✔
299
    write_dataset(
5,649✔
300
      runtime_group, "total initialization", time_initialize.elapsed());
301
    write_dataset(
5,649✔
302
      runtime_group, "reading cross sections", time_read_xs.elapsed());
303
    write_dataset(runtime_group, "simulation",
5,649✔
304
      time_inactive.elapsed() + time_active.elapsed());
5,649✔
305
    write_dataset(runtime_group, "transport", time_transport.elapsed());
5,649✔
306
    if (settings::run_mode == RunMode::EIGENVALUE) {
5,649✔
307
      write_dataset(runtime_group, "inactive batches", time_inactive.elapsed());
3,495✔
308
    }
309
    write_dataset(runtime_group, "active batches", time_active.elapsed());
5,649✔
310
    if (settings::run_mode == RunMode::EIGENVALUE) {
5,649✔
311
      write_dataset(
3,495✔
312
        runtime_group, "synchronizing fission bank", time_bank.elapsed());
313
      write_dataset(
3,495✔
314
        runtime_group, "sampling source sites", time_bank_sample.elapsed());
315
      write_dataset(
3,495✔
316
        runtime_group, "SEND-RECV source sites", time_bank_sendrecv.elapsed());
317
    }
318
    write_dataset(
5,649✔
319
      runtime_group, "accumulating tallies", time_tallies.elapsed());
320
    write_dataset(runtime_group, "total", time_total.elapsed());
5,649✔
321
    write_dataset(
5,649✔
322
      runtime_group, "writing statepoints", time_statepoint.elapsed());
323
    // Write out number of threads used
324

325
    close_group(runtime_group);
5,649✔
326

327
    file_close(file_id);
5,649✔
328
  }
329

330
#ifdef PHDF5
331
  bool parallel = true;
3,633✔
332
#else
333
  bool parallel = false;
3,056✔
334
#endif
335

336
  // Write the source bank if desired
337
  if (write_source_) {
6,689✔
338
    if (mpi::master || parallel)
3,473✔
339
      file_id = file_open(filename_, 'a', true);
3,473✔
340
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
3,473✔
341
    if (mpi::master || parallel)
3,473✔
342
      file_close(file_id);
3,473✔
343
  }
344

345
#if defined(LIBMESH) || defined(DAGMC)
346
  // write unstructured mesh tally files
347
  write_unstructured_mesh_results();
2,008✔
348
#endif
349

350
  simulation::time_statepoint.stop();
6,689✔
351

352
  return 0;
6,689✔
353
}
6,689✔
354

355
void restart_set_keff()
65✔
356
{
357
  if (simulation::restart_batch > settings::n_inactive) {
65✔
358
    for (int i = settings::n_inactive; i < simulation::restart_batch; ++i) {
309✔
359
      simulation::k_sum[0] += simulation::k_generation[i];
244✔
360
      simulation::k_sum[1] += std::pow(simulation::k_generation[i], 2);
244✔
361
    }
362
    int n = settings::gen_per_batch * simulation::n_realizations;
65✔
363
    simulation::keff = simulation::k_sum[0] / n;
65✔
364
  } else {
UNCOV
365
    simulation::keff = simulation::k_generation.back();
×
366
  }
367
}
65✔
368

369
void load_state_point()
65✔
370
{
371
  write_message(
65✔
372
    fmt::format("Loading state point {}...", settings::path_statepoint_c), 5);
118✔
373
  openmc_statepoint_load(settings::path_statepoint.c_str());
65✔
374
}
65✔
375

376
void statepoint_version_check(hid_t file_id)
65✔
377
{
378
  // Read revision number for state point file and make sure it matches with
379
  // current version
380
  array<int, 2> version_array;
381
  read_attribute(file_id, "version", version_array);
65✔
382
  if (version_array != VERSION_STATEPOINT) {
65✔
UNCOV
383
    fatal_error(
×
384
      "State point version does not match current version in OpenMC.");
385
  }
386
}
65✔
387

388
extern "C" int openmc_statepoint_load(const char* filename)
65✔
389
{
390
  // Open file for reading
391
  hid_t file_id = file_open(filename, 'r', true);
65✔
392

393
  // Read filetype
394
  std::string word;
65✔
395
  read_attribute(file_id, "filetype", word);
65✔
396
  if (word != "statepoint") {
65✔
UNCOV
397
    fatal_error("OpenMC tried to restart from a non-statepoint file.");
×
398
  }
399

400
  statepoint_version_check(file_id);
65✔
401

402
  // Read and overwrite random number seed
403
  int64_t seed;
404
  read_dataset(file_id, "seed", seed);
65✔
405
  openmc_set_seed(seed);
65✔
406

407
  // Read and overwrite random number stride
408
  uint64_t stride;
409
  read_dataset(file_id, "stride", stride);
65✔
410
  openmc_set_stride(stride);
65✔
411

412
  // It is not impossible for a state point to be generated from a CE run but
413
  // to be loaded in to an MG run (or vice versa), check to prevent that.
414
  read_dataset(file_id, "energy_mode", word);
65✔
415
  if (word == "multi-group" && settings::run_CE) {
65✔
UNCOV
416
    fatal_error("State point file is from multigroup run but current run is "
×
417
                "continous energy.");
418
  } else if (word == "continuous-energy" && !settings::run_CE) {
65✔
UNCOV
419
    fatal_error("State point file is from continuous-energy run but current "
×
420
                "run is multigroup!");
421
  }
422

423
  // Read and overwrite run information except number of batches
424
  read_dataset(file_id, "run_mode", word);
65✔
425
  if (word == "fixed source") {
65✔
UNCOV
426
    settings::run_mode = RunMode::FIXED_SOURCE;
×
427
  } else if (word == "eigenvalue") {
65✔
428
    settings::run_mode = RunMode::EIGENVALUE;
65✔
429
  }
430
  read_attribute(file_id, "photon_transport", settings::photon_transport);
65✔
431
  read_dataset(file_id, "n_particles", settings::n_particles);
65✔
432
  int temp;
433
  read_dataset(file_id, "n_batches", temp);
65✔
434

435
  // Take maximum of statepoint n_batches and input n_batches
436
  settings::n_batches = std::max(settings::n_batches, temp);
65✔
437

438
  // Read batch number to restart at
439
  read_dataset(file_id, "current_batch", simulation::restart_batch);
65✔
440

441
  if (simulation::restart_batch >= settings::n_max_batches) {
65✔
442
    warning(fmt::format(
11✔
443
      "The number of batches specified for simulation ({}) is smaller "
444
      "than or equal to the number of batches in the restart statepoint file "
445
      "({})",
446
      settings::n_max_batches, simulation::restart_batch));
447
  }
448

449
  // Logical flag for source present in statepoint file
450
  bool source_present;
451
  read_attribute(file_id, "source_present", source_present);
65✔
452

453
  // Read information specific to eigenvalue run
454
  if (settings::run_mode == RunMode::EIGENVALUE) {
65✔
455
    read_dataset(file_id, "n_inactive", temp);
65✔
456
    read_eigenvalue_hdf5(file_id);
65✔
457

458
    // Take maximum of statepoint n_inactive and input n_inactive
459
    settings::n_inactive = std::max(settings::n_inactive, temp);
65✔
460

461
    // Check to make sure source bank is present
462
    if (settings::path_sourcepoint == settings::path_statepoint &&
130✔
463
        !source_present) {
65✔
UNCOV
464
      fatal_error("Source bank must be contained in statepoint restart file");
×
465
    }
466
  }
467

468
  // Read number of realizations for global tallies
469
  read_dataset(file_id, "n_realizations", simulation::n_realizations);
65✔
470

471
  // Set k_sum, keff, and current_batch based on whether restart file is part
472
  // of active cycle or inactive cycle
473
  if (settings::run_mode == RunMode::EIGENVALUE) {
65✔
474
    restart_set_keff();
65✔
475
  }
476

477
  // Set current batch number
478
  simulation::current_batch = simulation::restart_batch;
65✔
479

480
  // Read tallies to master. If we are using Parallel HDF5, all processes
481
  // need to be included in the HDF5 calls.
482
#ifdef PHDF5
483
  if (true) {
484
#else
485
  if (mpi::master) {
30✔
486
#endif
487
    // Read global tally data
488
    read_dataset_lowlevel(file_id, "global_tallies", H5T_NATIVE_DOUBLE, H5S_ALL,
65✔
489
      false, simulation::global_tallies.data());
65✔
490

491
    // Check if tally results are present
492
    bool present;
493
    read_attribute(file_id, "tallies_present", present);
65✔
494

495
    // Read in sum and sum squared
496
    if (present) {
65✔
497
      hid_t tallies_group = open_group(file_id, "tallies");
65✔
498

499
      for (auto& tally : model::tallies) {
223✔
500
        // Read sum, sum_sq, and N for each bin
501
        std::string name = "tally " + std::to_string(tally->id_);
158✔
502
        hid_t tally_group = open_group(tallies_group, name.c_str());
158✔
503

504
        int internal = 0;
158✔
505
        if (attribute_exists(tally_group, "internal")) {
158✔
506
          read_attribute(tally_group, "internal", internal);
158✔
507
        }
508
        if (internal) {
158✔
UNCOV
509
          tally->writable_ = false;
×
510
        } else {
511
          auto& results = tally->results_;
158✔
512
          read_tally_results(tally_group, results.shape()[0],
316✔
513
            results.shape()[1], results.data());
158✔
514
          read_dataset(tally_group, "n_realizations", tally->n_realizations_);
158✔
515
          close_group(tally_group);
158✔
516
        }
517
      }
158✔
518
      close_group(tallies_group);
65✔
519
    }
520
  }
521

522
  // Read source if in eigenvalue mode
523
  if (settings::run_mode == RunMode::EIGENVALUE) {
65✔
524

525
    // Check if source was written out separately
526
    if (!source_present) {
65✔
527

528
      // Close statepoint file
UNCOV
529
      file_close(file_id);
×
530

531
      // Write message
UNCOV
532
      write_message(
×
UNCOV
533
        "Loading source file " + settings::path_sourcepoint + "...", 5);
×
534

535
      // Open source file
UNCOV
536
      file_id = file_open(settings::path_sourcepoint.c_str(), 'r', true);
×
537
    }
538

539
    // Read source
540
    read_source_bank(file_id, simulation::source_bank, true);
65✔
541
  }
542

543
  // Close file
544
  file_close(file_id);
65✔
545

546
  return 0;
65✔
547
}
65✔
548

549
hid_t h5banktype()
4,429✔
550
{
551
  // Create compound type for position
552
  hid_t postype = H5Tcreate(H5T_COMPOUND, sizeof(struct Position));
4,429✔
553
  H5Tinsert(postype, "x", HOFFSET(Position, x), H5T_NATIVE_DOUBLE);
4,429✔
554
  H5Tinsert(postype, "y", HOFFSET(Position, y), H5T_NATIVE_DOUBLE);
4,429✔
555
  H5Tinsert(postype, "z", HOFFSET(Position, z), H5T_NATIVE_DOUBLE);
4,429✔
556

557
  // Create bank datatype
558
  //
559
  // If you make changes to the compound datatype here, make sure you update:
560
  // - openmc/source.py
561
  // - openmc/statepoint.py
562
  // - docs/source/io_formats/statepoint.rst
563
  // - docs/source/io_formats/source.rst
564
  hid_t banktype = H5Tcreate(H5T_COMPOUND, sizeof(struct SourceSite));
4,429✔
565
  H5Tinsert(banktype, "r", HOFFSET(SourceSite, r), postype);
4,429✔
566
  H5Tinsert(banktype, "u", HOFFSET(SourceSite, u), postype);
4,429✔
567
  H5Tinsert(banktype, "E", HOFFSET(SourceSite, E), H5T_NATIVE_DOUBLE);
4,429✔
568
  H5Tinsert(banktype, "time", HOFFSET(SourceSite, time), H5T_NATIVE_DOUBLE);
4,429✔
569
  H5Tinsert(banktype, "wgt", HOFFSET(SourceSite, wgt), H5T_NATIVE_DOUBLE);
4,429✔
570
  H5Tinsert(banktype, "delayed_group", HOFFSET(SourceSite, delayed_group),
4,429✔
571
    H5T_NATIVE_INT);
4,429✔
572
  H5Tinsert(banktype, "surf_id", HOFFSET(SourceSite, surf_id), H5T_NATIVE_INT);
4,429✔
573
  H5Tinsert(
4,429✔
574
    banktype, "particle", HOFFSET(SourceSite, particle), H5T_NATIVE_INT);
4,429✔
575

576
  H5Tclose(postype);
4,429✔
577
  return banktype;
4,429✔
578
}
579

580
void write_source_point(std::string filename, span<SourceSite> source_bank,
833✔
581
  const vector<int64_t>& bank_index, bool use_mcpl)
582
{
583
  std::string ext = use_mcpl ? "mcpl" : "h5";
833✔
584
  write_message("Creating source file {}.{} with {} particles ...", filename,
833✔
585
    ext, source_bank.size(), 5);
833✔
586

587
  // Dispatch to appropriate function based on file type
588
  if (use_mcpl) {
833✔
589
    filename.append(".mcpl");
16✔
590
    write_mcpl_source_point(filename.c_str(), source_bank, bank_index);
16✔
591
  } else {
592
    filename.append(".h5");
817✔
593
    write_h5_source_point(filename.c_str(), source_bank, bank_index);
817✔
594
  }
595
}
833✔
596

597
void write_h5_source_point(const char* filename, span<SourceSite> source_bank,
817✔
598
  const vector<int64_t>& bank_index)
599
{
600
  // When using parallel HDF5, the file is written to collectively by all
601
  // processes. With MPI-only, the file is opened and written by the master
602
  // (note that the call to write_source_bank is by all processes since slave
603
  // processes need to send source bank data to the master.
604
#ifdef PHDF5
605
  bool parallel = true;
422✔
606
#else
607
  bool parallel = false;
395✔
608
#endif
609

610
  if (!filename)
817✔
UNCOV
611
    fatal_error("write_source_point filename needs a nonempty name.");
×
612

613
  std::string filename_(filename);
817✔
614
  const auto extension = get_file_extension(filename_);
817✔
615
  if (extension != "h5") {
817✔
UNCOV
616
    warning("write_source_point was passed a file extension differing "
×
617
            "from .h5, but an hdf5 file will be written.");
618
  }
619

620
  hid_t file_id;
621
  if (mpi::master || parallel) {
817✔
622
    file_id = file_open(filename_.c_str(), 'w', true);
817✔
623
    write_attribute(file_id, "filetype", "source");
817✔
624
  }
625

626
  // Get pointer to source bank and write to file
627
  write_source_bank(file_id, source_bank, bank_index);
817✔
628

629
  if (mpi::master || parallel)
817✔
630
    file_close(file_id);
817✔
631
}
817✔
632

633
void write_source_bank(hid_t group_id, span<SourceSite> source_bank,
4,290✔
634
  const vector<int64_t>& bank_index)
635
{
636
  hid_t banktype = h5banktype();
4,290✔
637

638
  // Set total and individual process dataspace sizes for source bank
639
  int64_t dims_size = bank_index.back();
4,290✔
640
  int64_t count_size = bank_index[mpi::rank + 1] - bank_index[mpi::rank];
4,290✔
641

642
#ifdef PHDF5
643
  // Set size of total dataspace for all procs and rank
644
  hsize_t dims[] {static_cast<hsize_t>(dims_size)};
2,371✔
645
  hid_t dspace = H5Screate_simple(1, dims, nullptr);
2,371✔
646
  hid_t dset = H5Dcreate(group_id, "source_bank", banktype, dspace, H5P_DEFAULT,
2,371✔
647
    H5P_DEFAULT, H5P_DEFAULT);
648

649
  // Create another data space but for each proc individually
650
  hsize_t count[] {static_cast<hsize_t>(count_size)};
2,371✔
651
  hid_t memspace = H5Screate_simple(1, count, nullptr);
2,371✔
652

653
  // Select hyperslab for this dataspace
654
  hsize_t start[] {static_cast<hsize_t>(bank_index[mpi::rank])};
2,371✔
655
  H5Sselect_hyperslab(dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
2,371✔
656

657
  // Set up the property list for parallel writing
658
  hid_t plist = H5Pcreate(H5P_DATASET_XFER);
2,371✔
659
  H5Pset_dxpl_mpio(plist, H5FD_MPIO_COLLECTIVE);
2,371✔
660

661
  // Write data to file in parallel
662
  H5Dwrite(dset, banktype, memspace, dspace, plist, source_bank.data());
2,371✔
663

664
  // Free resources
665
  H5Sclose(dspace);
2,371✔
666
  H5Sclose(memspace);
2,371✔
667
  H5Dclose(dset);
2,371✔
668
  H5Pclose(plist);
2,371✔
669

670
#else
671

672
  if (mpi::master) {
1,919✔
673
    // Create dataset big enough to hold all source sites
674
    hsize_t dims[] {static_cast<hsize_t>(dims_size)};
1,919✔
675
    hid_t dspace = H5Screate_simple(1, dims, nullptr);
1,919✔
676
    hid_t dset = H5Dcreate(group_id, "source_bank", banktype, dspace,
1,919✔
677
      H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
678

679
    // Save source bank sites since the array is overwritten below
680
#ifdef OPENMC_MPI
681
    vector<SourceSite> temp_source {source_bank.begin(), source_bank.end()};
682
#endif
683

684
    for (int i = 0; i < mpi::n_procs; ++i) {
3,838✔
685
      // Create memory space
686
      hsize_t count[] {static_cast<hsize_t>(bank_index[i + 1] - bank_index[i])};
1,919✔
687
      hid_t memspace = H5Screate_simple(1, count, nullptr);
1,919✔
688

689
#ifdef OPENMC_MPI
690
      // Receive source sites from other processes
691
      if (i > 0)
692
        MPI_Recv(source_bank.data(), count[0], mpi::source_site, i, i,
693
          mpi::intracomm, MPI_STATUS_IGNORE);
694
#endif
695

696
      // Select hyperslab for this dataspace
697
      dspace = H5Dget_space(dset);
1,919✔
698
      hsize_t start[] {static_cast<hsize_t>(bank_index[i])};
1,919✔
699
      H5Sselect_hyperslab(
1,919✔
700
        dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
701

702
      // Write data to hyperslab
703
      H5Dwrite(
1,919✔
704
        dset, banktype, memspace, dspace, H5P_DEFAULT, source_bank.data());
1,919✔
705

706
      H5Sclose(memspace);
1,919✔
707
      H5Sclose(dspace);
1,919✔
708
    }
709

710
    // Close all ids
711
    H5Dclose(dset);
1,919✔
712

713
#ifdef OPENMC_MPI
714
    // Restore state of source bank
715
    std::copy(temp_source.begin(), temp_source.end(), source_bank.begin());
716
#endif
717
  } else {
718
#ifdef OPENMC_MPI
719
    MPI_Send(source_bank.data(), count_size, mpi::source_site, 0, mpi::rank,
720
      mpi::intracomm);
721
#endif
722
  }
723
#endif
724

725
  H5Tclose(banktype);
4,290✔
726
}
4,290✔
727

728
// Determine member names of a compound HDF5 datatype
729
std::string dtype_member_names(hid_t dtype_id)
278✔
730
{
731
  int nmembers = H5Tget_nmembers(dtype_id);
278✔
732
  std::string names;
278✔
733
  for (int i = 0; i < nmembers; i++) {
2,457✔
734
    char* name = H5Tget_member_name(dtype_id, i);
2,179✔
735
    names = names.append(name);
2,179✔
736
    H5free_memory(name);
2,179✔
737
    if (i < nmembers - 1)
2,179✔
738
      names += ", ";
1,901✔
739
  }
740
  return names;
278✔
UNCOV
741
}
×
742

743
void read_source_bank(
139✔
744
  hid_t group_id, vector<SourceSite>& sites, bool distribute)
745
{
746
  hid_t banktype = h5banktype();
139✔
747

748
  // Open the dataset
749
  hid_t dset = H5Dopen(group_id, "source_bank", H5P_DEFAULT);
139✔
750

751
  // Make sure number of members matches
752
  hid_t dtype = H5Dget_type(dset);
139✔
753
  auto file_member_names = dtype_member_names(dtype);
139✔
754
  auto bank_member_names = dtype_member_names(banktype);
139✔
755
  if (file_member_names != bank_member_names) {
139✔
756
    fatal_error(fmt::format(
9✔
757
      "Source site attributes in file do not match what is "
758
      "expected for this version of OpenMC. File attributes = ({}). Expected "
759
      "attributes = ({})",
760
      file_member_names, bank_member_names));
761
  }
762

763
  hid_t dspace = H5Dget_space(dset);
130✔
764
  hsize_t n_sites;
765
  H5Sget_simple_extent_dims(dspace, &n_sites, nullptr);
130✔
766

767
  // Make sure vector is big enough in case where we're reading entire source on
768
  // each process
769
  if (!distribute)
130✔
770
    sites.resize(n_sites);
65✔
771

772
  hid_t memspace;
773
  if (distribute) {
130✔
774
    if (simulation::work_index[mpi::n_procs] > n_sites) {
65✔
UNCOV
775
      fatal_error("Number of source sites in source file is less "
×
776
                  "than number of source particles per generation.");
777
    }
778

779
    // Create another data space but for each proc individually
780
    hsize_t n_sites_local = simulation::work_per_rank;
65✔
781
    memspace = H5Screate_simple(1, &n_sites_local, nullptr);
65✔
782

783
    // Select hyperslab for each process
784
    hsize_t offset = simulation::work_index[mpi::rank];
65✔
785
    H5Sselect_hyperslab(
65✔
786
      dspace, H5S_SELECT_SET, &offset, nullptr, &n_sites_local, nullptr);
787
  } else {
788
    memspace = H5S_ALL;
65✔
789
  }
790

791
#ifdef PHDF5
792
  // Read data in parallel
793
  hid_t plist = H5Pcreate(H5P_DATASET_XFER);
70✔
794
  H5Pset_dxpl_mpio(plist, H5FD_MPIO_COLLECTIVE);
70✔
795
  H5Dread(dset, banktype, memspace, dspace, plist, sites.data());
70✔
796
  H5Pclose(plist);
70✔
797
#else
798
  H5Dread(dset, banktype, memspace, dspace, H5P_DEFAULT, sites.data());
60✔
799
#endif
800

801
  // Close all ids
802
  H5Sclose(dspace);
130✔
803
  if (distribute)
130✔
804
    H5Sclose(memspace);
65✔
805
  H5Dclose(dset);
130✔
806
  H5Tclose(banktype);
130✔
807
}
130✔
808

809
void write_unstructured_mesh_results()
2,008✔
810
{
811

812
  for (auto& tally : model::tallies) {
10,234✔
813

814
    vector<std::string> tally_scores;
8,226✔
815
    for (auto filter_idx : tally->filters()) {
24,206✔
816
      auto& filter = model::tally_filters[filter_idx];
15,980✔
817
      if (filter->type() != FilterType::MESH)
15,980✔
818
        continue;
15,965✔
819

820
      // check if the filter uses an unstructured mesh
821
      auto mesh_filter = dynamic_cast<MeshFilter*>(filter.get());
1,898✔
822
      auto mesh_idx = mesh_filter->mesh();
1,898✔
823
      auto umesh =
824
        dynamic_cast<UnstructuredMesh*>(model::meshes[mesh_idx].get());
1,898✔
825

826
      if (!umesh)
1,898✔
827
        continue;
1,864✔
828

829
      if (!umesh->output_)
34✔
UNCOV
830
        continue;
×
831

832
      if (umesh->library() == "moab") {
34✔
833
        if (mpi::master)
19✔
834
          warning(fmt::format(
9✔
835
            "Output for a MOAB mesh (mesh {}) was "
836
            "requested but will not be written. Please use the Python "
837
            "API to generated the desired VTK tetrahedral mesh.",
838
            umesh->id_));
9✔
839
        continue;
19✔
840
      }
841

842
      // if this tally has more than one filter, print
843
      // warning and skip writing the mesh
844
      if (tally->filters().size() > 1) {
15✔
845
        warning(fmt::format("Skipping unstructured mesh writing for tally "
×
846
                            "{}. More than one filter is present on the tally.",
UNCOV
847
          tally->id_));
×
UNCOV
848
        break;
×
849
      }
850

851
      int n_realizations = tally->n_realizations_;
15✔
852

853
      for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) {
30✔
854
        for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) {
30✔
855
          // combine the score and nuclide into a name for the value
856
          auto score_str = fmt::format("{}_{}", tally->score_name(score_idx),
30✔
857
            tally->nuclide_name(nuc_idx));
30✔
858
          // add this score to the mesh
859
          // (this is in a separate loop because all variables need to be added
860
          //  to libMesh's equation system before any are initialized, which
861
          //  happens in set_score_data)
862
          umesh->add_score(score_str);
15✔
863
        }
15✔
864
      }
865

866
      for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) {
30✔
867
        for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) {
30✔
868
          // combine the score and nuclide into a name for the value
869
          auto score_str = fmt::format("{}_{}", tally->score_name(score_idx),
30✔
870
            tally->nuclide_name(nuc_idx));
30✔
871

872
          // index for this nuclide and score
873
          int nuc_score_idx = score_idx + nuc_idx * tally->scores_.size();
15✔
874

875
          // construct result vectors
876
          vector<double> mean_vec(umesh->n_bins()),
15✔
877
            std_dev_vec(umesh->n_bins());
15✔
878
          for (int j = 0; j < tally->results_.shape()[0]; j++) {
146,799✔
879
            // get the volume for this bin
880
            double volume = umesh->volume(j);
146,784✔
881
            // compute the mean
882
            double mean = tally->results_(j, nuc_score_idx, TallyResult::SUM) /
146,784✔
883
                          n_realizations;
146,784✔
884
            mean_vec.at(j) = mean / volume;
146,784✔
885

886
            // compute the standard deviation
887
            double sum_sq =
888
              tally->results_(j, nuc_score_idx, TallyResult::SUM_SQ);
146,784✔
889
            double std_dev {0.0};
146,784✔
890
            if (n_realizations > 1) {
146,784✔
891
              std_dev = sum_sq / n_realizations - mean * mean;
146,784✔
892
              std_dev = std::sqrt(std_dev / (n_realizations - 1));
146,784✔
893
            }
894
            std_dev_vec[j] = std_dev / volume;
146,784✔
895
          }
896
#ifdef OPENMC_MPI
897
          MPI_Bcast(
10✔
898
            mean_vec.data(), mean_vec.size(), MPI_DOUBLE, 0, mpi::intracomm);
10✔
899
          MPI_Bcast(std_dev_vec.data(), std_dev_vec.size(), MPI_DOUBLE, 0,
10✔
900
            mpi::intracomm);
901
#endif
902
          // set the data for this score
903
          umesh->set_score_data(score_str, mean_vec, std_dev_vec);
15✔
904
        }
15✔
905
      }
906

907
      // Generate a file name based on the tally id
908
      // and the current batch number
909
      size_t batch_width {std::to_string(settings::n_max_batches).size()};
15✔
910
      std::string filename = fmt::format("tally_{0}.{1:0{2}}", tally->id_,
15✔
UNCOV
911
        simulation::current_batch, batch_width);
×
912

913
      // Write the unstructured mesh and data to file
914
      umesh->write(filename);
15✔
915

916
      // remove score data added for this mesh write
917
      umesh->remove_scores();
15✔
918
    }
15✔
919
  }
8,226✔
920
}
2,008✔
921

UNCOV
922
void write_tally_results_nr(hid_t file_id)
×
923
{
924
  // ==========================================================================
925
  // COLLECT AND WRITE GLOBAL TALLIES
926

927
  hid_t tallies_group;
928
  if (mpi::master) {
×
929
    // Write number of realizations
930
    write_dataset(file_id, "n_realizations", simulation::n_realizations);
×
931

UNCOV
932
    tallies_group = open_group(file_id, "tallies");
×
933
  }
934

935
  // Get global tallies
UNCOV
936
  auto& gt = simulation::global_tallies;
×
937

938
#ifdef OPENMC_MPI
939
  // Reduce global tallies
940
  xt::xtensor<double, 2> gt_reduced = xt::empty_like(gt);
941
  MPI_Reduce(gt.data(), gt_reduced.data(), gt.size(), MPI_DOUBLE, MPI_SUM, 0,
942
    mpi::intracomm);
943

944
  // Transfer values to value on master
945
  if (mpi::master) {
946
    if (simulation::current_batch == settings::n_max_batches ||
947
        simulation::satisfy_triggers) {
948
      std::copy(gt_reduced.begin(), gt_reduced.end(), gt.begin());
949
    }
950
  }
951
#endif
952

953
  // Write out global tallies sum and sum_sq
UNCOV
954
  if (mpi::master) {
×
UNCOV
955
    write_dataset(file_id, "global_tallies", gt);
×
956
  }
957

958
  for (const auto& t : model::tallies) {
×
959
    // Skip any tallies that are not active
960
    if (!t->active_)
×
961
      continue;
×
UNCOV
962
    if (!t->writable_)
×
963
      continue;
×
964

UNCOV
965
    if (mpi::master && !attribute_exists(file_id, "tallies_present")) {
×
UNCOV
966
      write_attribute(file_id, "tallies_present", 1);
×
967
    }
968

969
    // Get view of accumulated tally values
UNCOV
970
    auto values_view = xt::view(t->results_, xt::all(), xt::all(),
×
UNCOV
971
      xt::range(static_cast<int>(TallyResult::SUM),
×
972
        static_cast<int>(TallyResult::SUM_SQ) + 1));
973

974
    // Make copy of tally values in contiguous array
975
    xt::xtensor<double, 3> values = values_view;
×
976

977
    if (mpi::master) {
×
978
      // Open group for tally
UNCOV
979
      std::string groupname {"tally " + std::to_string(t->id_)};
×
UNCOV
980
      hid_t tally_group = open_group(tallies_group, groupname.c_str());
×
981

982
      // The MPI_IN_PLACE specifier allows the master to copy values into
983
      // a receive buffer without having a temporary variable
984
#ifdef OPENMC_MPI
985
      MPI_Reduce(MPI_IN_PLACE, values.data(), values.size(), MPI_DOUBLE,
986
        MPI_SUM, 0, mpi::intracomm);
987
#endif
988

989
      // At the end of the simulation, store the results back in the
990
      // regular TallyResults array
991
      if (simulation::current_batch == settings::n_max_batches ||
×
992
          simulation::satisfy_triggers) {
UNCOV
993
        values_view = values;
×
994
      }
995

996
      // Put in temporary tally result
997
      xt::xtensor<double, 3> results_copy = xt::zeros_like(t->results_);
×
UNCOV
998
      auto copy_view = xt::view(results_copy, xt::all(), xt::all(),
×
999
        xt::range(static_cast<int>(TallyResult::SUM),
×
1000
          static_cast<int>(TallyResult::SUM_SQ) + 1));
UNCOV
1001
      copy_view = values;
×
1002

1003
      // Write reduced tally results to file
UNCOV
1004
      auto shape = results_copy.shape();
×
1005
      write_tally_results(tally_group, shape[0], shape[1], results_copy.data());
×
1006

UNCOV
1007
      close_group(tally_group);
×
UNCOV
1008
    } else {
×
1009
      // Receive buffer not significant at other processors
1010
#ifdef OPENMC_MPI
1011
      MPI_Reduce(values.data(), nullptr, values.size(), MPI_DOUBLE, MPI_SUM, 0,
1012
        mpi::intracomm);
1013
#endif
1014
    }
1015
  }
1016

UNCOV
1017
  if (mpi::master) {
×
1018
    if (!object_exists(file_id, "tallies_present")) {
×
1019
      // Indicate that tallies are off
UNCOV
1020
      write_dataset(file_id, "tallies_present", 0);
×
1021
    }
1022

UNCOV
1023
    close_group(tallies_group);
×
1024
  }
1025
}
1026

1027
} // 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