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

openmc-dev / openmc / 21621721042

03 Feb 2026 07:51AM UTC coverage: 81.568% (-0.2%) from 81.763%
21621721042

Pull #3683

github

web-flow
Merge acf06fb0f into b41e22f68
Pull Request #3683: Using NJOY2016 to create derived photonuclear data libraries.

16759 of 23252 branches covered (72.08%)

Branch coverage included in aggregate %.

2 of 44 new or added lines in 1 file covered. (4.55%)

308 existing lines in 25 files now uncovered.

55049 of 64783 relevant lines covered (84.97%)

31755492.1 hits per line

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

84.79
/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/bank_io.h"
13
#include "openmc/capi.h"
14
#include "openmc/constants.h"
15
#include "openmc/eigenvalue.h"
16
#include "openmc/error.h"
17
#include "openmc/file_utils.h"
18
#include "openmc/hdf5_interface.h"
19
#include "openmc/mcpl_interface.h"
20
#include "openmc/mesh.h"
21
#include "openmc/message_passing.h"
22
#include "openmc/mgxs_interface.h"
23
#include "openmc/nuclide.h"
24
#include "openmc/output.h"
25
#include "openmc/particle_type.h"
26
#include "openmc/settings.h"
27
#include "openmc/simulation.h"
28
#include "openmc/tallies/derivative.h"
29
#include "openmc/tallies/filter.h"
30
#include "openmc/tallies/filter_mesh.h"
31
#include "openmc/tallies/tally.h"
32
#include "openmc/timer.h"
33
#include "openmc/vector.h"
34

35
namespace openmc {
36

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

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

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

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

62
  // Determine whether or not to write the source bank
63
  bool write_source_ = write_source ? *write_source : true;
4,133!
64

65
  // Write message
66
  write_message("Creating state point " + filename_ + "...", 5);
4,133✔
67

68
  hid_t file_id;
69
  if (mpi::master) {
4,133✔
70
    // Create statepoint file
71
    file_id = file_open(filename_, 'w');
3,667✔
72

73
    // Write file type
74
    write_attribute(file_id, "filetype", "statepoint");
3,667✔
75

76
    // Write revision number for state point file
77
    write_attribute(file_id, "version", VERSION_STATEPOINT);
3,667✔
78

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

85
    // Write current date and time
86
    write_attribute(file_id, "date_and_time", time_stamp());
3,667✔
87

88
    // Write path to input
89
    write_attribute(file_id, "path", settings::path_input);
3,667✔
90

91
    // Write out random number seed
92
    write_dataset(file_id, "seed", openmc_get_seed());
3,667✔
93

94
    // Write out random number stride
95
    write_dataset(file_id, "stride", openmc_get_stride());
3,667✔
96

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

114
    // Write out current batch number
115
    write_dataset(file_id, "current_batch", simulation::current_batch);
3,667✔
116

117
    // Indicate whether source bank is stored in statepoint
118
    write_attribute(file_id, "source_present", write_source_);
3,667✔
119

120
    // Write out information for eigenvalue run
121
    if (settings::run_mode == RunMode::EIGENVALUE)
3,667✔
122
      write_eigenvalue_hdf5(file_id);
2,268✔
123

124
    hid_t tallies_group = create_group(file_id, "tallies");
3,667✔
125

126
    // Write meshes
127
    meshes_to_hdf5(tallies_group);
3,667✔
128

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

154
    // Write information for filters
155
    hid_t filters_group = create_group(tallies_group, "filters");
3,667✔
156
    write_attribute(filters_group, "n_filters", model::tally_filters.size());
3,667✔
157
    if (!model::tally_filters.empty()) {
3,667✔
158
      // Write filter IDs
159
      vector<int32_t> filter_ids;
2,281✔
160
      filter_ids.reserve(model::tally_filters.size());
2,281✔
161
      for (const auto& filt : model::tally_filters)
8,059✔
162
        filter_ids.push_back(filt->id());
5,778✔
163
      write_attribute(filters_group, "ids", filter_ids);
2,281✔
164

165
      // Write info for each filter
166
      for (const auto& filt : model::tally_filters) {
8,059✔
167
        hid_t filter_group =
168
          create_group(filters_group, "filter " + std::to_string(filt->id()));
5,778✔
169
        filt->to_statepoint(filter_group);
5,778✔
170
        close_group(filter_group);
5,778✔
171
      }
172
    }
2,281✔
173
    close_group(filters_group);
3,667✔
174

175
    // Write information for tallies
176
    write_attribute(tallies_group, "n_tallies", model::tallies.size());
3,667✔
177
    if (!model::tallies.empty()) {
3,667✔
178
      // Write tally IDs
179
      vector<int32_t> tally_ids;
2,569✔
180
      tally_ids.reserve(model::tallies.size());
2,569✔
181
      for (const auto& tally : model::tallies)
14,251✔
182
        tally_ids.push_back(tally->id_);
11,682✔
183
      write_attribute(tallies_group, "ids", tally_ids);
2,569✔
184

185
      // Write all tally information except results
186
      for (const auto& tally : model::tallies) {
14,251✔
187
        hid_t tally_group =
188
          create_group(tallies_group, "tally " + std::to_string(tally->id_));
11,682✔
189

190
        write_dataset(tally_group, "name", tally->name_);
11,682✔
191

192
        if (tally->writable_) {
11,682✔
193
          write_attribute(tally_group, "internal", 0);
11,110✔
194
        } else {
195
          write_attribute(tally_group, "internal", 1);
572✔
196
          close_group(tally_group);
572✔
197
          continue;
572✔
198
        }
199

200
        if (tally->multiply_density()) {
11,110✔
201
          write_attribute(tally_group, "multiply_density", 1);
11,080✔
202
        } else {
203
          write_attribute(tally_group, "multiply_density", 0);
30✔
204
        }
205

206
        if (tally->higher_moments()) {
11,110✔
207
          write_attribute(tally_group, "higher_moments", 1);
6✔
208
        } else {
209
          write_attribute(tally_group, "higher_moments", 0);
11,104✔
210
        }
211

212
        if (tally->estimator_ == TallyEstimator::ANALOG) {
11,110✔
213
          write_dataset(tally_group, "estimator", "analog");
4,050✔
214
        } else if (tally->estimator_ == TallyEstimator::TRACKLENGTH) {
7,060✔
215
          write_dataset(tally_group, "estimator", "tracklength");
6,594✔
216
        } else if (tally->estimator_ == TallyEstimator::COLLISION) {
466!
217
          write_dataset(tally_group, "estimator", "collision");
466✔
218
        }
219

220
        write_dataset(tally_group, "n_realizations", tally->n_realizations_);
11,110✔
221

222
        // Write the ID of each filter attached to this tally
223
        write_dataset(tally_group, "n_filters", tally->filters().size());
11,110✔
224
        if (!tally->filters().empty()) {
11,110✔
225
          vector<int32_t> filter_ids;
10,468✔
226
          filter_ids.reserve(tally->filters().size());
10,468✔
227
          for (auto i_filt : tally->filters())
31,652✔
228
            filter_ids.push_back(model::tally_filters[i_filt]->id());
21,184✔
229
          write_dataset(tally_group, "filters", filter_ids);
10,468✔
230
        }
10,468✔
231

232
        // Write the nuclides this tally scores
233
        vector<std::string> nuclides;
11,110✔
234
        for (auto i_nuclide : tally->nuclides_) {
26,456✔
235
          if (i_nuclide == -1) {
15,346✔
236
            nuclides.push_back("total");
9,676✔
237
          } else {
238
            if (settings::run_CE) {
5,670✔
239
              nuclides.push_back(data::nuclides[i_nuclide]->name_);
5,610✔
240
            } else {
241
              nuclides.push_back(data::mg.nuclides_[i_nuclide].name);
60✔
242
            }
243
          }
244
        }
245
        write_dataset(tally_group, "nuclides", nuclides);
11,110✔
246

247
        if (tally->deriv_ != C_NONE)
11,110✔
248
          write_dataset(
120✔
249
            tally_group, "derivative", model::tally_derivs[tally->deriv_].id);
120✔
250

251
        // Write the tally score bins
252
        vector<std::string> scores;
11,110✔
253
        for (auto sc : tally->scores_)
27,128✔
254
          scores.push_back(reaction_name(sc));
16,018✔
255
        write_dataset(tally_group, "n_score_bins", scores.size());
11,110✔
256
        write_dataset(tally_group, "score_bins", scores);
11,110✔
257

258
        close_group(tally_group);
11,110✔
259
      }
11,110✔
260
    }
2,569✔
261

262
    if (settings::reduce_tallies) {
3,667✔
263
      // Write global tallies
264
      write_dataset(file_id, "global_tallies", simulation::global_tallies);
3,661✔
265

266
      // Write tallies
267
      if (model::active_tallies.size() > 0) {
3,661✔
268
        // Indicate that tallies are on
269
        write_attribute(file_id, "tallies_present", 1);
2,443✔
270

271
        // Write all tally results
272
        for (const auto& tally : model::tallies) {
13,999✔
273
          if (!tally->writable_)
11,556✔
274
            continue;
452✔
275

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

290
    close_group(tallies_group);
3,667✔
291
  }
292

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

299
  } else if (mpi::master) {
4,125✔
300
    // Write number of global realizations
301
    write_dataset(file_id, "n_realizations", simulation::n_realizations);
3,661✔
302
  }
303

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

334
    file_close(file_id);
3,667✔
335
  }
336

337
#ifdef PHDF5
338
  bool parallel = true;
1,680✔
339
#else
340
  bool parallel = false;
2,453✔
341
#endif
342

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

352
#if defined(OPENMC_LIBMESH_ENABLED) || defined(OPENMC_DAGMC_ENABLED)
353
  // write unstructured mesh tally files
354
  write_unstructured_mesh_results();
625✔
355
#endif
356

357
  simulation::time_statepoint.stop();
4,133✔
358

359
  return 0;
4,133✔
360
}
4,133✔
361

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

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

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

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

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

407
  statepoint_version_check(file_id);
34✔
408

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

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

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

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

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

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

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

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

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

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

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

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

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

485
  // Set current batch number
486
  simulation::current_batch = simulation::restart_batch;
34✔
487

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

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

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

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

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

523
          read_dataset(tally_group, "n_realizations", tally->n_realizations_);
84✔
524
          close_group(tally_group);
84✔
525
        }
526
      }
84✔
527
      close_group(tallies_group);
34✔
528
    }
529
  }
530

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

534
    // Check if source was written out separately
535
    if (!source_present) {
34!
536

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

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

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

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

552
  // Close file
553
  file_close(file_id);
34✔
554

555
  return 0;
34✔
556
}
34✔
557

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

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

588
  H5Tclose(postype);
5,463✔
589
  return banktype;
5,463✔
590
}
591

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

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

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

622
  if (!filename)
635!
623
    fatal_error("write_source_point filename needs a nonempty name.");
×
624

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

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

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

642
  if (mpi::master || parallel)
635!
643
    file_close(file_id);
635✔
644
}
635✔
645

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

652
#ifdef OPENMC_MPI
653
  write_bank_dataset("source_bank", group_id, source_bank, bank_index,
1,108✔
654
    membanktype, filebanktype, mpi::source_site);
655
#else
656
  write_bank_dataset("source_bank", group_id, source_bank, bank_index,
1,590✔
657
    membanktype, filebanktype);
658
#endif
659

660
  H5Tclose(membanktype);
2,698✔
661
  H5Tclose(filebanktype);
2,698✔
662
}
2,698✔
663

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

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

692
  hid_t banktype = h5banktype(true);
67✔
693

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

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

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

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

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

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

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

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

747
  // Close all ids
748
  H5Sclose(dspace);
62✔
749
  if (distribute)
62✔
750
    H5Sclose(memspace);
34✔
751
  H5Dclose(dset);
62✔
752
  H5Tclose(banktype);
62✔
753

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

761
void write_unstructured_mesh_results()
625✔
762
{
763

764
  for (auto& tally : model::tallies) {
2,583✔
765

766
    vector<std::string> tally_scores;
1,958✔
767
    for (auto filter_idx : tally->filters()) {
5,611✔
768
      auto& filter = model::tally_filters[filter_idx];
3,653✔
769
      if (filter->type() != FilterType::MESH)
3,653!
770
        continue;
3,648✔
771

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

778
      if (!umesh)
456✔
779
        continue;
451✔
780

781
      if (!umesh->output_)
5!
782
        continue;
×
783

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

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

803
      int n_realizations = tally->n_realizations_;
5✔
804

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

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

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

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

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

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

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

868
      // remove score data added for this mesh write
869
      umesh->remove_scores();
5!
870
    }
5✔
871
  }
1,958✔
872
}
625✔
873

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

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

884
    tallies_group = open_group(file_id, "tallies");
6✔
885
  }
886

887
  // Get global tallies
888
  auto& gt = simulation::global_tallies;
8✔
889

890
#ifdef OPENMC_MPI
891
  // Reduce global tallies
892
  xt::xtensor<double, 2> gt_reduced = xt::empty_like(gt);
4✔
893
  MPI_Reduce(gt.data(), gt_reduced.data(), gt.size(), MPI_DOUBLE, MPI_SUM, 0,
4✔
894
    mpi::intracomm);
895

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

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

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

917
    if (mpi::master && !attribute_exists(file_id, "tallies_present")) {
8!
918
      write_attribute(file_id, "tallies_present", 1);
6✔
919
    }
920

921
    // Get view of accumulated tally values
922
    auto values_view = xt::view(t->results_, xt::all(), xt::all(),
8✔
923
      xt::range(static_cast<int>(TallyResult::SUM),
8✔
924
        static_cast<int>(TallyResult::SUM_SQ) + 1));
8✔
925

926
    // Make copy of tally values in contiguous array
927
    xt::xtensor<double, 3> values = values_view;
8✔
928

929
    if (mpi::master) {
8✔
930
      // Open group for tally
931
      std::string groupname {"tally " + std::to_string(t->id_)};
6✔
932
      hid_t tally_group = open_group(tallies_group, groupname.c_str());
6✔
933

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

941
      // At the end of the simulation, store the results back in the
942
      // regular TallyResults array
943
      if (simulation::current_batch == settings::n_max_batches ||
6!
944
          simulation::satisfy_triggers) {
945
        values_view = values;
6✔
946
      }
947

948
      // Put in temporary tally result
949
      xt::xtensor<double, 3> results_copy = xt::zeros_like(t->results_);
6✔
950
      auto copy_view = xt::view(results_copy, xt::all(), xt::all(),
6✔
951
        xt::range(static_cast<int>(TallyResult::SUM),
6✔
952
          static_cast<int>(TallyResult::SUM_SQ) + 1));
6✔
953
      copy_view = values;
6✔
954

955
      // Write reduced tally results to file
956
      auto shape = results_copy.shape();
6✔
957
      write_tally_results(
6✔
958
        tally_group, shape[0], shape[1], shape[2], results_copy.data());
6✔
959

960
      close_group(tally_group);
6✔
961
    } else {
6✔
962
      // Receive buffer not significant at other processors
963
#ifdef OPENMC_MPI
964
      MPI_Reduce(values.data(), nullptr, values.size(), MPI_DOUBLE, MPI_SUM, 0,
2✔
965
        mpi::intracomm);
966
#endif
967
    }
968
  }
8✔
969

970
  if (mpi::master) {
8✔
971
    if (!object_exists(file_id, "tallies_present")) {
6!
972
      // Indicate that tallies are off
973
      write_dataset(file_id, "tallies_present", 0);
6✔
974
    }
975

976
    close_group(tallies_group);
6✔
977
  }
978
}
8✔
979

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