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

openmc-dev / openmc / 22210404096

20 Feb 2026 03:44AM UTC coverage: 81.804% (+0.08%) from 81.721%
22210404096

Pull #3809

github

web-flow
Merge d39f3220e into 53ce1910f
Pull Request #3809: Implement tally filter for filtering by reaction

17328 of 24423 branches covered (70.95%)

Branch coverage included in aggregate %.

125 of 149 new or added lines in 11 files covered. (83.89%)

1322 existing lines in 33 files now uncovered.

57670 of 67257 relevant lines covered (85.75%)

45506622.43 hits per line

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

86.27
/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 "openmc/tensor.h"
8
#include <fmt/core.h>
9

10
#include "openmc/bank.h"
11
#include "openmc/bank_io.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/particle_type.h"
25
#include "openmc/settings.h"
26
#include "openmc/simulation.h"
27
#include "openmc/tallies/derivative.h"
28
#include "openmc/tallies/filter.h"
29
#include "openmc/tallies/filter_mesh.h"
30
#include "openmc/tallies/tally.h"
31
#include "openmc/timer.h"
32
#include "openmc/vector.h"
33

34
namespace openmc {
35

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

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

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

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

61
  // Determine whether or not to write the source bank
62
  bool write_source_ = write_source ? *write_source : true;
7,304!
63

64
  // Write message
65
  write_message("Creating state point " + filename_ + "...", 5);
7,304✔
66

67
  hid_t file_id;
68
  if (mpi::master) {
7,304✔
69
    // Create statepoint file
70
    file_id = file_open(filename_, 'w');
6,328✔
71

72
    // Write file type
73
    write_attribute(file_id, "filetype", "statepoint");
6,328✔
74

75
    // Write revision number for state point file
76
    write_attribute(file_id, "version", VERSION_STATEPOINT);
6,328✔
77

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

84
    // Write current date and time
85
    write_attribute(file_id, "date_and_time", time_stamp());
6,328✔
86

87
    // Write path to input
88
    write_attribute(file_id, "path", settings::path_input);
6,328✔
89

90
    // Write out random number seed
91
    write_dataset(file_id, "seed", openmc_get_seed());
6,328✔
92

93
    // Write out random number stride
94
    write_dataset(file_id, "stride", openmc_get_stride());
6,328✔
95

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

113
    // Write out current batch number
114
    write_dataset(file_id, "current_batch", simulation::current_batch);
6,328✔
115

116
    // Indicate whether source bank is stored in statepoint
117
    write_attribute(file_id, "source_present", write_source_);
6,328✔
118

119
    // Write out information for eigenvalue run
120
    if (settings::run_mode == RunMode::EIGENVALUE)
6,328✔
121
      write_eigenvalue_hdf5(file_id);
3,884✔
122

123
    hid_t tallies_group = create_group(file_id, "tallies");
6,328✔
124

125
    // Write meshes
126
    meshes_to_hdf5(tallies_group);
6,328✔
127

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

153
    // Write information for filters
154
    hid_t filters_group = create_group(tallies_group, "filters");
6,328✔
155
    write_attribute(filters_group, "n_filters", model::tally_filters.size());
6,328✔
156
    if (!model::tally_filters.empty()) {
6,328✔
157
      // Write filter IDs
158
      vector<int32_t> filter_ids;
3,948✔
159
      filter_ids.reserve(model::tally_filters.size());
3,948✔
160
      for (const auto& filt : model::tally_filters)
14,216✔
161
        filter_ids.push_back(filt->id());
10,268✔
162
      write_attribute(filters_group, "ids", filter_ids);
3,948✔
163

164
      // Write info for each filter
165
      for (const auto& filt : model::tally_filters) {
14,216✔
166
        hid_t filter_group =
167
          create_group(filters_group, "filter " + std::to_string(filt->id()));
10,268✔
168
        filt->to_statepoint(filter_group);
10,268✔
169
        close_group(filter_group);
10,268✔
170
      }
171
    }
3,948✔
172
    close_group(filters_group);
6,328✔
173

174
    // Write information for tallies
175
    write_attribute(tallies_group, "n_tallies", model::tallies.size());
6,328✔
176
    if (!model::tallies.empty()) {
6,328✔
177
      // Write tally IDs
178
      vector<int32_t> tally_ids;
4,438✔
179
      tally_ids.reserve(model::tallies.size());
4,438✔
180
      for (const auto& tally : model::tallies)
24,502✔
181
        tally_ids.push_back(tally->id_);
20,064✔
182
      write_attribute(tallies_group, "ids", tally_ids);
4,438✔
183

184
      // Write all tally information except results
185
      for (const auto& tally : model::tallies) {
24,502✔
186
        hid_t tally_group =
187
          create_group(tallies_group, "tally " + std::to_string(tally->id_));
20,064✔
188

189
        write_dataset(tally_group, "name", tally->name_);
20,064✔
190

191
        if (tally->writable_) {
20,064✔
192
          write_attribute(tally_group, "internal", 0);
19,116✔
193
        } else {
194
          write_attribute(tally_group, "internal", 1);
948✔
195
          close_group(tally_group);
948✔
196
          continue;
948✔
197
        }
198

199
        if (tally->multiply_density()) {
19,116✔
200
          write_attribute(tally_group, "multiply_density", 1);
19,066✔
201
        } else {
202
          write_attribute(tally_group, "multiply_density", 0);
50✔
203
        }
204

205
        if (tally->higher_moments()) {
19,116✔
206
          write_attribute(tally_group, "higher_moments", 1);
10✔
207
        } else {
208
          write_attribute(tally_group, "higher_moments", 0);
19,106✔
209
        }
210

211
        if (tally->estimator_ == TallyEstimator::ANALOG) {
19,116✔
212
          write_dataset(tally_group, "estimator", "analog");
7,198✔
213
        } else if (tally->estimator_ == TallyEstimator::TRACKLENGTH) {
11,918✔
214
          write_dataset(tally_group, "estimator", "tracklength");
11,120✔
215
        } else if (tally->estimator_ == TallyEstimator::COLLISION) {
798!
216
          write_dataset(tally_group, "estimator", "collision");
798✔
217
        }
218

219
        write_dataset(tally_group, "n_realizations", tally->n_realizations_);
19,116✔
220

221
        // Write the ID of each filter attached to this tally
222
        write_dataset(tally_group, "n_filters", tally->filters().size());
19,116✔
223
        if (!tally->filters().empty()) {
19,116✔
224
          vector<int32_t> filter_ids;
18,036✔
225
          filter_ids.reserve(tally->filters().size());
18,036✔
226
          for (auto i_filt : tally->filters())
54,802✔
227
            filter_ids.push_back(model::tally_filters[i_filt]->id());
36,766✔
228
          write_dataset(tally_group, "filters", filter_ids);
18,036✔
229
        }
18,036✔
230

231
        // Write the nuclides this tally scores
232
        vector<std::string> nuclides;
19,116✔
233
        for (auto i_nuclide : tally->nuclides_) {
45,292✔
234
          if (i_nuclide == -1) {
26,176✔
235
            nuclides.push_back("total");
16,726✔
236
          } else {
237
            if (settings::run_CE) {
9,450✔
238
              nuclides.push_back(data::nuclides[i_nuclide]->name_);
9,350✔
239
            } else {
240
              nuclides.push_back(data::mg.nuclides_[i_nuclide].name);
100✔
241
            }
242
          }
243
        }
244
        write_dataset(tally_group, "nuclides", nuclides);
19,116✔
245

246
        if (tally->deriv_ != C_NONE)
19,116✔
247
          write_dataset(
200✔
248
            tally_group, "derivative", model::tally_derivs[tally->deriv_].id);
200✔
249

250
        // Write the tally score bins
251
        vector<std::string> scores;
19,116✔
252
        for (auto sc : tally->scores_)
47,166✔
253
          scores.push_back(reaction_name(sc));
28,050✔
254
        write_dataset(tally_group, "n_score_bins", scores.size());
19,116✔
255
        write_dataset(tally_group, "score_bins", scores);
19,116✔
256

257
        close_group(tally_group);
19,116✔
258
      }
19,116✔
259
    }
4,438✔
260

261
    if (settings::reduce_tallies) {
6,328✔
262
      // Write global tallies
263
      write_dataset(file_id, "global_tallies", simulation::global_tallies);
6,318✔
264

265
      // Write tallies
266
      if (model::active_tallies.size() > 0) {
6,318✔
267
        // Indicate that tallies are on
268
        write_attribute(file_id, "tallies_present", 1);
4,228✔
269

270
        // Write all tally results
271
        for (const auto& tally : model::tallies) {
24,082✔
272
          if (!tally->writable_)
19,854✔
273
            continue;
748✔
274

275
          // Write results for each bin
276
          std::string name = "tally " + std::to_string(tally->id_);
19,106✔
277
          hid_t tally_group = open_group(tallies_group, name.c_str());
19,106✔
278
          auto& results = tally->results_;
19,106✔
279
          write_tally_results(tally_group, results.shape(0), results.shape(1),
19,106✔
280
            results.shape(2), results.data());
19,106✔
281
          close_group(tally_group);
19,106✔
282
        }
19,106✔
283
      } else {
284
        // Indicate tallies are off
285
        write_attribute(file_id, "tallies_present", 0);
2,090✔
286
      }
287
    }
288

289
    close_group(tallies_group);
6,328✔
290
  }
291

292
  // Check for the no-tally-reduction method
293
  if (!settings::reduce_tallies) {
7,304✔
294
    // If using the no-tally-reduction method, we need to collect tally
295
    // results before writing them to the state point file.
296
    write_tally_results_nr(file_id);
14✔
297

298
  } else if (mpi::master) {
7,290✔
299
    // Write number of global realizations
300
    write_dataset(file_id, "n_realizations", simulation::n_realizations);
6,318✔
301
  }
302

303
  if (mpi::master) {
7,304✔
304
    // Write out the runtime metrics.
305
    using namespace simulation;
306
    hid_t runtime_group = create_group(file_id, "runtime");
6,328✔
307
    write_dataset(
6,328✔
308
      runtime_group, "total initialization", time_initialize.elapsed());
309
    write_dataset(
6,328✔
310
      runtime_group, "reading cross sections", time_read_xs.elapsed());
311
    write_dataset(runtime_group, "simulation",
6,328✔
312
      time_inactive.elapsed() + time_active.elapsed());
6,328✔
313
    write_dataset(runtime_group, "transport", time_transport.elapsed());
6,328✔
314
    if (settings::run_mode == RunMode::EIGENVALUE) {
6,328✔
315
      write_dataset(runtime_group, "inactive batches", time_inactive.elapsed());
3,884✔
316
    }
317
    write_dataset(runtime_group, "active batches", time_active.elapsed());
6,328✔
318
    if (settings::run_mode == RunMode::EIGENVALUE) {
6,328✔
319
      write_dataset(
3,884✔
320
        runtime_group, "synchronizing fission bank", time_bank.elapsed());
321
      write_dataset(
3,884✔
322
        runtime_group, "sampling source sites", time_bank_sample.elapsed());
323
      write_dataset(
3,884✔
324
        runtime_group, "SEND-RECV source sites", time_bank_sendrecv.elapsed());
325
    }
326
    write_dataset(
6,328✔
327
      runtime_group, "accumulating tallies", time_tallies.elapsed());
328
    write_dataset(runtime_group, "total", time_total.elapsed());
6,328✔
329
    write_dataset(
6,328✔
330
      runtime_group, "writing statepoints", time_statepoint.elapsed());
331
    close_group(runtime_group);
6,328✔
332

333
    file_close(file_id);
6,328✔
334
  }
335

336
#ifdef PHDF5
337
  bool parallel = true;
3,517✔
338
#else
339
  bool parallel = false;
3,787✔
340
#endif
341

342
  // Write the source bank if desired
343
  if (write_source_) {
7,304✔
344
    if (mpi::master || parallel)
3,601!
345
      file_id = file_open(filename_, 'a', true);
3,601✔
346
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
3,601✔
347
    if (mpi::master || parallel)
3,601!
348
      file_close(file_id);
3,601✔
349
  }
350

351
#if defined(OPENMC_LIBMESH_ENABLED) || defined(OPENMC_DAGMC_ENABLED)
352
  // write unstructured mesh tally files
353
  write_unstructured_mesh_results();
2,433✔
354
#endif
355

356
  simulation::time_statepoint.stop();
7,304✔
357

358
  return 0;
7,304✔
359
}
7,304✔
360

361
void restart_set_keff()
58✔
362
{
363
  if (simulation::restart_batch > settings::n_inactive) {
58!
364
    for (int i = settings::n_inactive; i < simulation::restart_batch; ++i) {
276✔
365
      simulation::k_sum[0] += simulation::k_generation[i];
218✔
366
      simulation::k_sum[1] += std::pow(simulation::k_generation[i], 2);
218✔
367
    }
368
    int n = settings::gen_per_batch * simulation::n_realizations;
58✔
369
    simulation::keff = simulation::k_sum[0] / n;
58✔
370
  } else {
UNCOV
371
    simulation::keff = simulation::k_generation.back();
×
372
  }
373
}
58✔
374

375
void load_state_point()
58✔
376
{
377
  write_message(
58✔
378
    fmt::format("Loading state point {}...", settings::path_statepoint_c), 5);
104✔
379
  openmc_statepoint_load(settings::path_statepoint.c_str());
58✔
380
}
58✔
381

382
void statepoint_version_check(hid_t file_id)
58✔
383
{
384
  // Read revision number for state point file and make sure it matches with
385
  // current version
386
  array<int, 2> version_array;
387
  read_attribute(file_id, "version", version_array);
58✔
388
  if (version_array != VERSION_STATEPOINT) {
58!
UNCOV
389
    fatal_error(
×
390
      "State point version does not match current version in OpenMC.");
391
  }
392
}
58✔
393

394
extern "C" int openmc_statepoint_load(const char* filename)
58✔
395
{
396
  // Open file for reading
397
  hid_t file_id = file_open(filename, 'r', true);
58✔
398

399
  // Read filetype
400
  std::string word;
58✔
401
  read_attribute(file_id, "filetype", word);
58✔
402
  if (word != "statepoint") {
58!
UNCOV
403
    fatal_error("OpenMC tried to restart from a non-statepoint file.");
×
404
  }
405

406
  statepoint_version_check(file_id);
58✔
407

408
  // Read and overwrite random number seed
409
  int64_t seed;
410
  read_dataset(file_id, "seed", seed);
58✔
411
  openmc_set_seed(seed);
58✔
412

413
  // Read and overwrite random number stride
414
  uint64_t stride;
415
  read_dataset(file_id, "stride", stride);
58✔
416
  openmc_set_stride(stride);
58✔
417

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

429
  // Read and overwrite run information except number of batches
430
  read_dataset(file_id, "run_mode", word);
58✔
431
  if (word == "fixed source") {
58!
UNCOV
432
    settings::run_mode = RunMode::FIXED_SOURCE;
×
433
  } else if (word == "eigenvalue") {
58!
434
    settings::run_mode = RunMode::EIGENVALUE;
58✔
435
  }
436
  read_attribute(file_id, "photon_transport", settings::photon_transport);
58✔
437
  read_dataset(file_id, "n_particles", settings::n_particles);
58✔
438
  int temp;
439
  read_dataset(file_id, "n_batches", temp);
58✔
440

441
  // Take maximum of statepoint n_batches and input n_batches
442
  settings::n_batches = std::max(settings::n_batches, temp);
58✔
443

444
  // Read batch number to restart at
445
  read_dataset(file_id, "current_batch", simulation::restart_batch);
58✔
446

447
  if (settings::restart_run &&
58!
448
      simulation::restart_batch >= settings::n_max_batches) {
58✔
449
    warning(fmt::format(
10✔
450
      "The number of batches specified for simulation ({}) is smaller "
451
      "than or equal to the number of batches in the restart statepoint file "
452
      "({})",
453
      settings::n_max_batches, simulation::restart_batch));
454
  }
455

456
  // Logical flag for source present in statepoint file
457
  bool source_present;
458
  read_attribute(file_id, "source_present", source_present);
58✔
459

460
  // Read information specific to eigenvalue run
461
  if (settings::run_mode == RunMode::EIGENVALUE) {
58!
462
    read_dataset(file_id, "n_inactive", temp);
58✔
463
    read_eigenvalue_hdf5(file_id);
58✔
464

465
    // Take maximum of statepoint n_inactive and input n_inactive
466
    settings::n_inactive = std::max(settings::n_inactive, temp);
58✔
467

468
    // Check to make sure source bank is present
469
    if (settings::path_sourcepoint == settings::path_statepoint &&
116!
470
        !source_present) {
58!
UNCOV
471
      fatal_error("Source bank must be contained in statepoint restart file");
×
472
    }
473
  }
474

475
  // Read number of realizations for global tallies
476
  read_dataset(file_id, "n_realizations", simulation::n_realizations);
58✔
477

478
  // Set k_sum, keff, and current_batch based on whether restart file is part
479
  // of active cycle or inactive cycle
480
  if (settings::run_mode == RunMode::EIGENVALUE) {
58!
481
    restart_set_keff();
58✔
482
  }
483

484
  // Set current batch number
485
  simulation::current_batch = simulation::restart_batch;
58✔
486

487
  // Read tallies to master. If we are using Parallel HDF5, all processes
488
  // need to be included in the HDF5 calls.
489
#ifdef PHDF5
490
  if (true) {
491
#else
492
  if (mpi::master) {
30!
493
#endif
494
    // Read global tally data
495
    read_dataset_lowlevel(file_id, "global_tallies", H5T_NATIVE_DOUBLE, H5S_ALL,
58✔
496
      false, simulation::global_tallies.data());
58✔
497

498
    // Check if tally results are present
499
    bool present;
500
    read_attribute(file_id, "tallies_present", present);
58✔
501

502
    // Read in sum and sum squared
503
    if (present) {
58!
504
      hid_t tallies_group = open_group(file_id, "tallies");
58✔
505

506
      for (auto& tally : model::tallies) {
200✔
507
        // Read sum, sum_sq, and N for each bin
508
        std::string name = "tally " + std::to_string(tally->id_);
142✔
509
        hid_t tally_group = open_group(tallies_group, name.c_str());
142✔
510

511
        int internal = 0;
142✔
512
        if (attribute_exists(tally_group, "internal")) {
142!
513
          read_attribute(tally_group, "internal", internal);
142✔
514
        }
515
        if (internal) {
142!
UNCOV
516
          tally->writable_ = false;
×
517
        } else {
518
          auto& results = tally->results_;
142✔
519
          read_tally_results(tally_group, results.shape(0), results.shape(1),
284✔
520
            results.shape(2), results.data());
142✔
521

522
          read_dataset(tally_group, "n_realizations", tally->n_realizations_);
142✔
523
          close_group(tally_group);
142✔
524
        }
525
      }
142✔
526
      close_group(tallies_group);
58✔
527
    }
528
  }
529

530
  // Read source if in eigenvalue mode
531
  if (settings::run_mode == RunMode::EIGENVALUE) {
58!
532

533
    // Check if source was written out separately
534
    if (!source_present) {
58!
535

536
      // Close statepoint file
UNCOV
537
      file_close(file_id);
×
538

539
      // Write message
UNCOV
540
      write_message(
×
541
        "Loading source file " + settings::path_sourcepoint + "...", 5);
×
542

543
      // Open source file
UNCOV
544
      file_id = file_open(settings::path_sourcepoint.c_str(), 'r', true);
×
545
    }
546

547
    // Read source
548
    read_source_bank(file_id, simulation::source_bank, true);
58✔
549
  }
550

551
  // Close file
552
  file_close(file_id);
58✔
553

554
  return 0;
58✔
555
}
58✔
556

557
hid_t h5banktype(bool memory)
9,494✔
558
{
559
  // Create compound type for position
560
  hid_t postype = H5Tcreate(H5T_COMPOUND, sizeof(struct Position));
9,494✔
561
  H5Tinsert(postype, "x", HOFFSET(Position, x), H5T_NATIVE_DOUBLE);
9,494✔
562
  H5Tinsert(postype, "y", HOFFSET(Position, y), H5T_NATIVE_DOUBLE);
9,494✔
563
  H5Tinsert(postype, "z", HOFFSET(Position, z), H5T_NATIVE_DOUBLE);
9,494✔
564

565
  // Create bank datatype
566
  //
567
  // If you make changes to the compound datatype here, make sure you update:
568
  // - openmc/source.py
569
  // - openmc/statepoint.py
570
  // - docs/source/io_formats/statepoint.rst
571
  // - docs/source/io_formats/source.rst
572
  auto n = sizeof(SourceSite);
9,494✔
573
  if (!memory)
9,494✔
574
    n = 2 * sizeof(struct Position) + 3 * sizeof(double) + 3 * sizeof(int);
4,690✔
575
  hid_t banktype = H5Tcreate(H5T_COMPOUND, n);
9,494✔
576
  H5Tinsert(banktype, "r", HOFFSET(SourceSite, r), postype);
9,494✔
577
  H5Tinsert(banktype, "u", HOFFSET(SourceSite, u), postype);
9,494✔
578
  H5Tinsert(banktype, "E", HOFFSET(SourceSite, E), H5T_NATIVE_DOUBLE);
9,494✔
579
  H5Tinsert(banktype, "time", HOFFSET(SourceSite, time), H5T_NATIVE_DOUBLE);
9,494✔
580
  H5Tinsert(banktype, "wgt", HOFFSET(SourceSite, wgt), H5T_NATIVE_DOUBLE);
9,494✔
581
  H5Tinsert(banktype, "delayed_group", HOFFSET(SourceSite, delayed_group),
9,494✔
582
    H5T_NATIVE_INT);
9,494✔
583
  H5Tinsert(banktype, "surf_id", HOFFSET(SourceSite, surf_id), H5T_NATIVE_INT);
9,494✔
584
  H5Tinsert(
9,494✔
585
    banktype, "particle", HOFFSET(SourceSite, particle), H5T_NATIVE_INT);
9,494✔
586

587
  H5Tclose(postype);
9,494✔
588
  return banktype;
9,494✔
589
}
590

591
void write_source_point(std::string filename, span<SourceSite> source_bank,
1,123✔
592
  const vector<int64_t>& bank_index, bool use_mcpl)
593
{
594
  std::string ext = use_mcpl ? "mcpl" : "h5";
1,123✔
595
  write_message("Creating source file {}.{} with {} particles ...", filename,
1,123✔
596
    ext, source_bank.size(), 5);
1,123✔
597

598
  // Dispatch to appropriate function based on file type
599
  if (use_mcpl) {
1,123✔
600
    filename.append(".mcpl");
34✔
601
    write_mcpl_source_point(filename.c_str(), source_bank, bank_index);
34✔
602
  } else {
603
    filename.append(".h5");
1,089✔
604
    write_h5_source_point(filename.c_str(), source_bank, bank_index);
1,089✔
605
  }
606
}
1,123✔
607

608
void write_h5_source_point(const char* filename, span<SourceSite> source_bank,
1,089✔
609
  const vector<int64_t>& bank_index)
610
{
611
  // When using parallel HDF5, the file is written to collectively by all
612
  // processes. With MPI-only, the file is opened and written by the master
613
  // (note that the call to write_source_bank is by all processes since slave
614
  // processes need to send source bank data to the master.
615
#ifdef PHDF5
616
  bool parallel = true;
472✔
617
#else
618
  bool parallel = false;
617✔
619
#endif
620

621
  if (!filename)
1,089!
UNCOV
622
    fatal_error("write_source_point filename needs a nonempty name.");
×
623

624
  std::string filename_(filename);
1,089✔
625
  const auto extension = get_file_extension(filename_);
1,089✔
626
  if (extension != "h5") {
1,089!
UNCOV
627
    warning("write_source_point was passed a file extension differing "
×
628
            "from .h5, but an hdf5 file will be written.");
629
  }
630

631
  hid_t file_id;
632
  if (mpi::master || parallel) {
1,089!
633
    file_id = file_open(filename_.c_str(), 'w', true);
1,089✔
634
    write_attribute(file_id, "filetype", "source");
1,089✔
635
    write_attribute(file_id, "version", VERSION_STATEPOINT);
1,089✔
636
  }
637

638
  // Get pointer to source bank and write to file
639
  write_source_bank(file_id, source_bank, bank_index);
1,089✔
640

641
  if (mpi::master || parallel)
1,089!
642
    file_close(file_id);
1,089✔
643
}
1,089✔
644

645
void write_source_bank(hid_t group_id, span<SourceSite> source_bank,
4,690✔
646
  const vector<int64_t>& bank_index)
647
{
648
  hid_t membanktype = h5banktype(true);
4,690✔
649
  hid_t filebanktype = h5banktype(false);
4,690✔
650

651
#ifdef OPENMC_MPI
652
  write_bank_dataset("source_bank", group_id, source_bank, bank_index,
2,268✔
653
    membanktype, filebanktype, mpi::source_site);
654
#else
655
  write_bank_dataset("source_bank", group_id, source_bank, bank_index,
2,422✔
656
    membanktype, filebanktype);
657
#endif
658

659
  H5Tclose(membanktype);
4,690✔
660
  H5Tclose(filebanktype);
4,690✔
661
}
4,690✔
662

663
// Determine member names of a compound HDF5 datatype
664
std::string dtype_member_names(hid_t dtype_id)
228✔
665
{
666
  int nmembers = H5Tget_nmembers(dtype_id);
228✔
667
  std::string names;
228✔
668
  for (int i = 0; i < nmembers; i++) {
2,012✔
669
    char* name = H5Tget_member_name(dtype_id, i);
1,784✔
670
    names = names.append(name);
1,784✔
671
    H5free_memory(name);
1,784✔
672
    if (i < nmembers - 1)
1,784✔
673
      names += ", ";
1,556✔
674
  }
675
  return names;
228✔
UNCOV
676
}
×
677

678
void read_source_bank(
114✔
679
  hid_t group_id, vector<SourceSite>& sites, bool distribute)
680
{
681
  bool legacy_particle_codes = true;
114✔
682
  if (attribute_exists(group_id, "version")) {
114✔
683
    array<int, 2> version;
684
    read_attribute(group_id, "version", version);
106✔
685
    if (version[0] > VERSION_STATEPOINT[0] ||
212!
686
        (version[0] == VERSION_STATEPOINT[0] && version[1] >= 2)) {
106!
687
      legacy_particle_codes = false;
106✔
688
    }
689
  }
690

691
  hid_t banktype = h5banktype(true);
114✔
692

693
  // Open the dataset
694
  hid_t dset = H5Dopen(group_id, "source_bank", H5P_DEFAULT);
114✔
695

696
  // Make sure number of members matches
697
  hid_t dtype = H5Dget_type(dset);
114✔
698
  auto file_member_names = dtype_member_names(dtype);
114✔
699
  auto bank_member_names = dtype_member_names(banktype);
114✔
700
  if (file_member_names != bank_member_names) {
114✔
701
    fatal_error(fmt::format(
8✔
702
      "Source site attributes in file do not match what is "
703
      "expected for this version of OpenMC. File attributes = ({}). Expected "
704
      "attributes = ({})",
705
      file_member_names, bank_member_names));
706
  }
707

708
  hid_t dspace = H5Dget_space(dset);
106✔
709
  hsize_t n_sites;
710
  H5Sget_simple_extent_dims(dspace, &n_sites, nullptr);
106✔
711

712
  // Make sure vector is big enough in case where we're reading entire source on
713
  // each process
714
  if (!distribute)
106✔
715
    sites.resize(n_sites);
48✔
716

717
  hid_t memspace;
718
  if (distribute) {
106✔
719
    if (simulation::work_index[mpi::n_procs] > n_sites) {
58!
UNCOV
720
      fatal_error("Number of source sites in source file is less "
×
721
                  "than number of source particles per generation.");
722
    }
723

724
    // Create another data space but for each proc individually
725
    hsize_t n_sites_local = simulation::work_per_rank;
58✔
726
    memspace = H5Screate_simple(1, &n_sites_local, nullptr);
58✔
727

728
    // Select hyperslab for each process
729
    hsize_t offset = simulation::work_index[mpi::rank];
58✔
730
    H5Sselect_hyperslab(
58✔
731
      dspace, H5S_SELECT_SET, &offset, nullptr, &n_sites_local, nullptr);
732
  } else {
733
    memspace = H5S_ALL;
48✔
734
  }
735

736
#ifdef PHDF5
737
  // Read data in parallel
738
  hid_t plist = H5Pcreate(H5P_DATASET_XFER);
52✔
739
  H5Pset_dxpl_mpio(plist, H5FD_MPIO_COLLECTIVE);
52✔
740
  H5Dread(dset, banktype, memspace, dspace, plist, sites.data());
52✔
741
  H5Pclose(plist);
52✔
742
#else
743
  H5Dread(dset, banktype, memspace, dspace, H5P_DEFAULT, sites.data());
54✔
744
#endif
745

746
  // Close all ids
747
  H5Sclose(dspace);
106✔
748
  if (distribute)
106✔
749
    H5Sclose(memspace);
58✔
750
  H5Dclose(dset);
106✔
751
  H5Tclose(banktype);
106✔
752

753
  if (legacy_particle_codes) {
106!
UNCOV
754
    for (auto& site : sites) {
×
755
      site.particle = legacy_particle_index_to_type(site.particle.pdg_number());
×
756
    }
757
  }
758
}
106✔
759

760
void write_unstructured_mesh_results()
2,433✔
761
{
762

763
  for (auto& tally : model::tallies) {
11,291✔
764

765
    vector<std::string> tally_scores;
8,858✔
766
    for (auto filter_idx : tally->filters()) {
26,045✔
767
      auto& filter = model::tally_filters[filter_idx];
17,187✔
768
      if (filter->type() != FilterType::MESH)
17,187!
769
        continue;
17,172✔
770

771
      // check if the filter uses an unstructured mesh
772
      auto mesh_filter = dynamic_cast<MeshFilter*>(filter.get());
1,952!
773
      auto mesh_idx = mesh_filter->mesh();
1,952!
774
      auto umesh =
775
        dynamic_cast<UnstructuredMesh*>(model::meshes[mesh_idx].get());
1,952!
776

777
      if (!umesh)
1,952✔
778
        continue;
1,917✔
779

780
      if (!umesh->output_)
35!
UNCOV
781
        continue;
×
782

783
      if (umesh->library() == "moab") {
35!
784
        if (mpi::master)
20✔
785
          warning(fmt::format(
10!
786
            "Output for a MOAB mesh (mesh {}) was "
787
            "requested but will not be written. Please use the Python "
788
            "API to generated the desired VTK tetrahedral mesh.",
789
            umesh->id_));
10✔
790
        continue;
20✔
791
      }
792

793
      // if this tally has more than one filter, print
794
      // warning and skip writing the mesh
795
      if (tally->filters().size() > 1) {
15!
UNCOV
796
        warning(fmt::format("Skipping unstructured mesh writing for tally "
×
797
                            "{}. More than one filter is present on the tally.",
UNCOV
798
          tally->id_));
×
799
        break;
×
800
      }
801

802
      int n_realizations = tally->n_realizations_;
15✔
803

804
      for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) {
30✔
805
        for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) {
30✔
806
          // combine the score and nuclide into a name for the value
807
          auto score_str = fmt::format("{}_{}", tally->score_name(score_idx),
30!
808
            tally->nuclide_name(nuc_idx));
30!
809
          // add this score to the mesh
810
          // (this is in a separate loop because all variables need to be added
811
          //  to libMesh's equation system before any are initialized, which
812
          //  happens in set_score_data)
813
          umesh->add_score(score_str);
15!
814
        }
15✔
815
      }
816

817
      for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) {
30✔
818
        for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) {
30✔
819
          // combine the score and nuclide into a name for the value
820
          auto score_str = fmt::format("{}_{}", tally->score_name(score_idx),
30!
821
            tally->nuclide_name(nuc_idx));
30!
822

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

826
          // construct result vectors
827
          vector<double> mean_vec(umesh->n_bins()),
15!
828
            std_dev_vec(umesh->n_bins());
15!
829
          for (int j = 0; j < tally->results_.shape(0); j++) {
146,799✔
830
            // get the volume for this bin
831
            double volume = umesh->volume(j);
146,784!
832
            // compute the mean
833
            double mean = tally->results_(j, nuc_score_idx, TallyResult::SUM) /
146,784✔
834
                          n_realizations;
146,784✔
835
            mean_vec.at(j) = mean / volume;
146,784!
836

837
            // compute the standard deviation
838
            double sum_sq =
839
              tally->results_(j, nuc_score_idx, TallyResult::SUM_SQ);
146,784✔
840
            double std_dev {0.0};
146,784✔
841
            if (n_realizations > 1) {
146,784!
842
              std_dev = sum_sq / n_realizations - mean * mean;
146,784✔
843
              std_dev = std::sqrt(std_dev / (n_realizations - 1));
146,784✔
844
            }
845
            std_dev_vec[j] = std_dev / volume;
146,784✔
846
          }
847
#ifdef OPENMC_MPI
848
          MPI_Bcast(
10!
849
            mean_vec.data(), mean_vec.size(), MPI_DOUBLE, 0, mpi::intracomm);
10✔
850
          MPI_Bcast(std_dev_vec.data(), std_dev_vec.size(), MPI_DOUBLE, 0,
10!
851
            mpi::intracomm);
852
#endif
853
          // set the data for this score
854
          umesh->set_score_data(score_str, mean_vec, std_dev_vec);
15!
855
        }
15✔
856
      }
857

858
      // Generate a file name based on the tally id
859
      // and the current batch number
860
      size_t batch_width {std::to_string(settings::n_max_batches).size()};
15!
861
      std::string filename = fmt::format("tally_{0}.{1:0{2}}", tally->id_,
15✔
UNCOV
862
        simulation::current_batch, batch_width);
×
863

864
      // Write the unstructured mesh and data to file
865
      umesh->write(filename);
15!
866

867
      // remove score data added for this mesh write
868
      umesh->remove_scores();
15!
869
    }
15✔
870
  }
8,858✔
871
}
2,433✔
872

873
void write_tally_results_nr(hid_t file_id)
14✔
874
{
875
  // ==========================================================================
876
  // COLLECT AND WRITE GLOBAL TALLIES
877

878
  hid_t tallies_group;
879
  if (mpi::master) {
14✔
880
    // Write number of realizations
881
    write_dataset(file_id, "n_realizations", simulation::n_realizations);
10✔
882

883
    tallies_group = open_group(file_id, "tallies");
10✔
884
  }
885

886
  // Get global tallies
887
  auto& gt = simulation::global_tallies;
14✔
888

889
#ifdef OPENMC_MPI
890
  // Reduce global tallies
891
  tensor::Tensor<double> gt_reduced({N_GLOBAL_TALLIES, 3});
8✔
892
  MPI_Reduce(gt.data(), gt_reduced.data(), gt.size(), MPI_DOUBLE, MPI_SUM, 0,
8✔
893
    mpi::intracomm);
894

895
  // Transfer values to value on master
896
  if (mpi::master) {
8✔
897
    if (simulation::current_batch == settings::n_max_batches ||
4!
898
        simulation::satisfy_triggers) {
899
      std::copy(gt_reduced.begin(), gt_reduced.end(), gt.begin());
4✔
900
    }
901
  }
902
#endif
903

904
  // Write out global tallies sum and sum_sq
905
  if (mpi::master) {
14✔
906
    write_dataset(file_id, "global_tallies", gt);
10✔
907
  }
908

909
  for (const auto& t : model::tallies) {
28✔
910
    // Skip any tallies that are not active
911
    if (!t->active_)
14!
UNCOV
912
      continue;
×
913
    if (!t->writable_)
14!
UNCOV
914
      continue;
×
915

916
    if (mpi::master && !attribute_exists(file_id, "tallies_present")) {
14!
917
      write_attribute(file_id, "tallies_present", 1);
10✔
918
    }
919

920
    // Copy the SUM and SUM_SQ columns from the tally results into a
921
    // contiguous array for MPI reduction
922
    const int r_start = static_cast<int>(TallyResult::SUM);
14✔
923
    const int r_end = static_cast<int>(TallyResult::SUM_SQ) + 1;
14✔
924
    const size_t r_count = r_end - r_start;
14✔
925
    const size_t ni = t->results_.shape(0);
14✔
926
    const size_t nj = t->results_.shape(1);
14✔
927
    tensor::Tensor<double> values({ni, nj, r_count});
14✔
928
    for (size_t i = 0; i < ni; i++)
28✔
929
      for (size_t j = 0; j < nj; j++)
28✔
930
        for (size_t r = 0; r < r_count; r++)
42✔
931
          values(i, j, r) = t->results_(i, j, r_start + r);
28✔
932

933
    if (mpi::master) {
14✔
934
      // Open group for tally
935
      std::string groupname {"tally " + std::to_string(t->id_)};
10✔
936
      hid_t tally_group = open_group(tallies_group, groupname.c_str());
10✔
937

938
      // The MPI_IN_PLACE specifier allows the master to copy values into
939
      // a receive buffer without having a temporary variable
940
#ifdef OPENMC_MPI
941
      MPI_Reduce(MPI_IN_PLACE, values.data(), values.size(), MPI_DOUBLE,
4✔
942
        MPI_SUM, 0, mpi::intracomm);
943
#endif
944

945
      // At the end of the simulation, store the reduced results back
946
      // into the tally results array
947
      if (simulation::current_batch == settings::n_max_batches ||
10!
948
          simulation::satisfy_triggers) {
949
        for (size_t i = 0; i < ni; i++)
20✔
950
          for (size_t j = 0; j < nj; j++)
20✔
951
            for (size_t r = 0; r < r_count; r++)
30✔
952
              t->results_(i, j, r_start + r) = values(i, j, r);
20✔
953
      }
954

955
      // Put reduced values into a full-sized copy for writing to HDF5
956
      tensor::Tensor<double> results_copy = tensor::zeros_like(t->results_);
10✔
957
      for (size_t i = 0; i < ni; i++)
20✔
958
        for (size_t j = 0; j < nj; j++)
20✔
959
          for (size_t r = 0; r < r_count; r++)
30✔
960
            results_copy(i, j, r_start + r) = values(i, j, r);
20✔
961

962
      // Write reduced tally results to file
963
      auto shape = results_copy.shape();
10✔
964
      write_tally_results(
10✔
965
        tally_group, shape[0], shape[1], shape[2], results_copy.data());
10✔
966

967
      close_group(tally_group);
10✔
968
    } else {
10✔
969
      // Receive buffer not significant at other processors
970
#ifdef OPENMC_MPI
971
      MPI_Reduce(values.data(), nullptr, values.size(), MPI_DOUBLE, MPI_SUM, 0,
4✔
972
        mpi::intracomm);
973
#endif
974
    }
975
  }
14✔
976

977
  if (mpi::master) {
14✔
978
    if (!object_exists(file_id, "tallies_present")) {
10!
979
      // Indicate that tallies are off
980
      write_dataset(file_id, "tallies_present", 0);
10✔
981
    }
982

983
    close_group(tallies_group);
10✔
984
  }
985
}
14✔
986

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

© 2026 Coveralls, Inc