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

openmc-dev / openmc / 17774031490

16 Sep 2025 05:30PM UTC coverage: 85.099% (-0.1%) from 85.218%
17774031490

Pull #3454

github

web-flow
Merge f336385dd into afd9d0607
Pull Request #3454: Adding variance of variance and normality tests for tally statistics

213 of 339 new or added lines in 8 files covered. (62.83%)

4 existing lines in 2 files now uncovered.

53215 of 62533 relevant lines covered (85.1%)

38089589.12 hits per line

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

87.24
/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)
7,742✔
36
{
37
  simulation::time_statepoint.start();
7,742✔
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_;
7,742✔
42
  if (filename) {
7,742✔
43
    filename_ = filename;
1,170✔
44
  } else {
45
    // Determine width for zero padding
46
    int w = std::to_string(settings::n_max_batches).size();
6,572✔
47

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

53
  // If a file name was specified, ensure it has .h5 file extension
54
  const auto extension = get_file_extension(filename_);
7,742✔
55
  if (extension != "h5") {
7,742✔
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;
7,742✔
62

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

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

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

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

77
    // Write OpenMC version
78
    write_attribute(file_id, "openmc_version", VERSION);
6,687✔
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());
6,687✔
85

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

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

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

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

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

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

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

122
    hid_t tallies_group = create_group(file_id, "tallies");
6,687✔
123

124
    // Write meshes
125
    meshes_to_hdf5(tallies_group);
6,687✔
126

127
    // Write information for derivatives
128
    if (!model::tally_derivs.empty()) {
6,687✔
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");
6,687✔
154
    write_attribute(filters_group, "n_filters", model::tally_filters.size());
6,687✔
155
    if (!model::tally_filters.empty()) {
6,687✔
156
      // Write filter IDs
157
      vector<int32_t> filter_ids;
4,519✔
158
      filter_ids.reserve(model::tally_filters.size());
4,519✔
159
      for (const auto& filt : model::tally_filters)
15,533✔
160
        filter_ids.push_back(filt->id());
11,014✔
161
      write_attribute(filters_group, "ids", filter_ids);
4,519✔
162

163
      // Write info for each filter
164
      for (const auto& filt : model::tally_filters) {
15,533✔
165
        hid_t filter_group =
166
          create_group(filters_group, "filter " + std::to_string(filt->id()));
11,014✔
167
        filt->to_statepoint(filter_group);
11,014✔
168
        close_group(filter_group);
11,014✔
169
      }
170
    }
4,519✔
171
    close_group(filters_group);
6,687✔
172

173
    // Write information for tallies
174
    write_attribute(tallies_group, "n_tallies", model::tallies.size());
6,687✔
175
    if (!model::tallies.empty()) {
6,687✔
176
      // Write tally IDs
177
      vector<int32_t> tally_ids;
5,014✔
178
      tally_ids.reserve(model::tallies.size());
5,014✔
179
      for (const auto& tally : model::tallies)
26,751✔
180
        tally_ids.push_back(tally->id_);
21,737✔
181
      write_attribute(tallies_group, "ids", tally_ids);
5,014✔
182

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

188
        write_dataset(tally_group, "name", tally->name_);
21,737✔
189

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

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

204
        if (tally->vov_enabled()) {
19,950✔
205
          write_attribute(tally_group, "vov_enabled", 1);
11✔
206
        } else {
207
          write_attribute(tally_group, "vov_enabled", 0);
19,939✔
208
        }
209

210
        if (tally->estimator_ == TallyEstimator::ANALOG) {
19,950✔
211
          write_dataset(tally_group, "estimator", "analog");
6,888✔
212
        } else if (tally->estimator_ == TallyEstimator::TRACKLENGTH) {
13,062✔
213
          write_dataset(tally_group, "estimator", "tracklength");
12,360✔
214
        } else if (tally->estimator_ == TallyEstimator::COLLISION) {
702✔
215
          write_dataset(tally_group, "estimator", "collision");
702✔
216
        }
217

218
        write_dataset(tally_group, "n_realizations", tally->n_realizations_);
19,950✔
219

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

230
        // Write the nuclides this tally scores
231
        vector<std::string> nuclides;
19,950✔
232
        for (auto i_nuclide : tally->nuclides_) {
47,460✔
233
          if (i_nuclide == -1) {
27,510✔
234
            nuclides.push_back("total");
17,329✔
235
          } else {
236
            if (settings::run_CE) {
10,181✔
237
              nuclides.push_back(data::nuclides[i_nuclide]->name_);
10,071✔
238
            } else {
239
              nuclides.push_back(data::mg.nuclides_[i_nuclide].name);
110✔
240
            }
241
          }
242
        }
243
        write_dataset(tally_group, "nuclides", nuclides);
19,950✔
244

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

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

256
        close_group(tally_group);
19,950✔
257
      }
19,950✔
258
    }
5,014✔
259

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

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

269
        // Write all tally results
270
        for (const auto& tally : model::tallies) {
26,013✔
271
          if (!tally->writable_)
21,368✔
272
            continue;
1,418✔
273

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

288
    close_group(tallies_group);
6,687✔
289
  }
290

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

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

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

332
    file_close(file_id);
6,687✔
333
  }
334

335
#ifdef PHDF5
336
  bool parallel = true;
4,530✔
337
#else
338
  bool parallel = false;
3,212✔
339
#endif
340

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

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

355
  simulation::time_statepoint.stop();
7,742✔
356

357
  return 0;
7,742✔
358
}
7,742✔
359

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

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

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

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

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

405
  statepoint_version_check(file_id);
67✔
406

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

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

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

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

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

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

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

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

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

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

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

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

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

483
  // Set current batch number
484
  simulation::current_batch = simulation::restart_batch;
67✔
485

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

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

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

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

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

521
          read_dataset(tally_group, "n_realizations", tally->n_realizations_);
166✔
522
          close_group(tally_group);
166✔
523
        }
524
      }
166✔
525
      close_group(tallies_group);
67✔
526
    }
527
  }
528

529
  // Read source if in eigenvalue mode
530
  if (settings::run_mode == RunMode::EIGENVALUE) {
67✔
531

532
    // Check if source was written out separately
533
    if (!source_present) {
67✔
534

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

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

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

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

550
  // Close file
551
  file_close(file_id);
67✔
552

553
  return 0;
67✔
554
}
67✔
555

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

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

583
  H5Tclose(postype);
4,974✔
584
  return banktype;
4,974✔
585
}
586

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

594
  // Dispatch to appropriate function based on file type
595
  if (use_mcpl) {
1,243✔
596
    filename.append(".mcpl");
38✔
597
    write_mcpl_source_point(filename.c_str(), source_bank, bank_index);
38✔
598
  } else {
599
    filename.append(".h5");
1,205✔
600
    write_h5_source_point(filename.c_str(), source_bank, bank_index);
1,205✔
601
  }
602
}
1,243✔
603

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

617
  if (!filename)
1,205✔
618
    fatal_error("write_source_point filename needs a nonempty name.");
×
619

620
  std::string filename_(filename);
1,205✔
621
  const auto extension = get_file_extension(filename_);
1,205✔
622
  if (extension != "h5") {
1,205✔
623
    warning("write_source_point was passed a file extension differing "
×
624
            "from .h5, but an hdf5 file will be written.");
625
  }
626

627
  hid_t file_id;
628
  if (mpi::master || parallel) {
1,205✔
629
    file_id = file_open(filename_.c_str(), 'w', true);
1,205✔
630
    write_attribute(file_id, "filetype", "source");
1,205✔
631
  }
632

633
  // Get pointer to source bank and write to file
634
  write_source_bank(file_id, source_bank, bank_index);
1,205✔
635

636
  if (mpi::master || parallel)
1,205✔
637
    file_close(file_id);
1,205✔
638
}
1,205✔
639

640
void write_source_bank(hid_t group_id, span<SourceSite> source_bank,
4,843✔
641
  const vector<int64_t>& bank_index)
642
{
643
  hid_t banktype = h5banktype();
4,843✔
644

645
  // Set total and individual process dataspace sizes for source bank
646
  int64_t dims_size = bank_index.back();
4,843✔
647
  int64_t count_size = bank_index[mpi::rank + 1] - bank_index[mpi::rank];
4,843✔
648

649
#ifdef PHDF5
650
  // Set size of total dataspace for all procs and rank
651
  hsize_t dims[] {static_cast<hsize_t>(dims_size)};
2,702✔
652
  hid_t dspace = H5Screate_simple(1, dims, nullptr);
2,702✔
653
  hid_t dset = H5Dcreate(group_id, "source_bank", banktype, dspace, H5P_DEFAULT,
2,702✔
654
    H5P_DEFAULT, H5P_DEFAULT);
655

656
  // Create another data space but for each proc individually
657
  hsize_t count[] {static_cast<hsize_t>(count_size)};
2,702✔
658
  hid_t memspace = H5Screate_simple(1, count, nullptr);
2,702✔
659

660
  // Select hyperslab for this dataspace
661
  hsize_t start[] {static_cast<hsize_t>(bank_index[mpi::rank])};
2,702✔
662
  H5Sselect_hyperslab(dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
2,702✔
663

664
  // Set up the property list for parallel writing
665
  hid_t plist = H5Pcreate(H5P_DATASET_XFER);
2,702✔
666
  H5Pset_dxpl_mpio(plist, H5FD_MPIO_COLLECTIVE);
2,702✔
667

668
  // Write data to file in parallel
669
  H5Dwrite(dset, banktype, memspace, dspace, plist, source_bank.data());
2,702✔
670

671
  // Free resources
672
  H5Sclose(dspace);
2,702✔
673
  H5Sclose(memspace);
2,702✔
674
  H5Dclose(dset);
2,702✔
675
  H5Pclose(plist);
2,702✔
676

677
#else
678

679
  if (mpi::master) {
2,141✔
680
    // Create dataset big enough to hold all source sites
681
    hsize_t dims[] {static_cast<hsize_t>(dims_size)};
2,141✔
682
    hid_t dspace = H5Screate_simple(1, dims, nullptr);
2,141✔
683
    hid_t dset = H5Dcreate(group_id, "source_bank", banktype, dspace,
2,141✔
684
      H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
685

686
    // Save source bank sites since the array is overwritten below
687
#ifdef OPENMC_MPI
688
    vector<SourceSite> temp_source {source_bank.begin(), source_bank.end()};
689
#endif
690

691
    for (int i = 0; i < mpi::n_procs; ++i) {
4,282✔
692
      // Create memory space
693
      hsize_t count[] {static_cast<hsize_t>(bank_index[i + 1] - bank_index[i])};
2,141✔
694
      hid_t memspace = H5Screate_simple(1, count, nullptr);
2,141✔
695

696
#ifdef OPENMC_MPI
697
      // Receive source sites from other processes
698
      if (i > 0)
699
        MPI_Recv(source_bank.data(), count[0], mpi::source_site, i, i,
700
          mpi::intracomm, MPI_STATUS_IGNORE);
701
#endif
702

703
      // Select hyperslab for this dataspace
704
      dspace = H5Dget_space(dset);
2,141✔
705
      hsize_t start[] {static_cast<hsize_t>(bank_index[i])};
2,141✔
706
      H5Sselect_hyperslab(
2,141✔
707
        dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
708

709
      // Write data to hyperslab
710
      H5Dwrite(
2,141✔
711
        dset, banktype, memspace, dspace, H5P_DEFAULT, source_bank.data());
2,141✔
712

713
      H5Sclose(memspace);
2,141✔
714
      H5Sclose(dspace);
2,141✔
715
    }
716

717
    // Close all ids
718
    H5Dclose(dset);
2,141✔
719

720
#ifdef OPENMC_MPI
721
    // Restore state of source bank
722
    std::copy(temp_source.begin(), temp_source.end(), source_bank.begin());
723
#endif
724
  } else {
725
#ifdef OPENMC_MPI
726
    MPI_Send(source_bank.data(), count_size, mpi::source_site, 0, mpi::rank,
727
      mpi::intracomm);
728
#endif
729
  }
730
#endif
731

732
  H5Tclose(banktype);
4,843✔
733
}
4,843✔
734

735
// Determine member names of a compound HDF5 datatype
736
std::string dtype_member_names(hid_t dtype_id)
262✔
737
{
738
  int nmembers = H5Tget_nmembers(dtype_id);
262✔
739
  std::string names;
262✔
740
  for (int i = 0; i < nmembers; i++) {
2,313✔
741
    char* name = H5Tget_member_name(dtype_id, i);
2,051✔
742
    names = names.append(name);
2,051✔
743
    H5free_memory(name);
2,051✔
744
    if (i < nmembers - 1)
2,051✔
745
      names += ", ";
1,789✔
746
  }
747
  return names;
262✔
748
}
×
749

750
void read_source_bank(
131✔
751
  hid_t group_id, vector<SourceSite>& sites, bool distribute)
752
{
753
  hid_t banktype = h5banktype();
131✔
754

755
  // Open the dataset
756
  hid_t dset = H5Dopen(group_id, "source_bank", H5P_DEFAULT);
131✔
757

758
  // Make sure number of members matches
759
  hid_t dtype = H5Dget_type(dset);
131✔
760
  auto file_member_names = dtype_member_names(dtype);
131✔
761
  auto bank_member_names = dtype_member_names(banktype);
131✔
762
  if (file_member_names != bank_member_names) {
131✔
763
    fatal_error(fmt::format(
9✔
764
      "Source site attributes in file do not match what is "
765
      "expected for this version of OpenMC. File attributes = ({}). Expected "
766
      "attributes = ({})",
767
      file_member_names, bank_member_names));
768
  }
769

770
  hid_t dspace = H5Dget_space(dset);
122✔
771
  hsize_t n_sites;
772
  H5Sget_simple_extent_dims(dspace, &n_sites, nullptr);
122✔
773

774
  // Make sure vector is big enough in case where we're reading entire source on
775
  // each process
776
  if (!distribute)
122✔
777
    sites.resize(n_sites);
55✔
778

779
  hid_t memspace;
780
  if (distribute) {
122✔
781
    if (simulation::work_index[mpi::n_procs] > n_sites) {
67✔
782
      fatal_error("Number of source sites in source file is less "
×
783
                  "than number of source particles per generation.");
784
    }
785

786
    // Create another data space but for each proc individually
787
    hsize_t n_sites_local = simulation::work_per_rank;
67✔
788
    memspace = H5Screate_simple(1, &n_sites_local, nullptr);
67✔
789

790
    // Select hyperslab for each process
791
    hsize_t offset = simulation::work_index[mpi::rank];
67✔
792
    H5Sselect_hyperslab(
67✔
793
      dspace, H5S_SELECT_SET, &offset, nullptr, &n_sites_local, nullptr);
794
  } else {
795
    memspace = H5S_ALL;
55✔
796
  }
797

798
#ifdef PHDF5
799
  // Read data in parallel
800
  hid_t plist = H5Pcreate(H5P_DATASET_XFER);
68✔
801
  H5Pset_dxpl_mpio(plist, H5FD_MPIO_COLLECTIVE);
68✔
802
  H5Dread(dset, banktype, memspace, dspace, plist, sites.data());
68✔
803
  H5Pclose(plist);
68✔
804
#else
805
  H5Dread(dset, banktype, memspace, dspace, H5P_DEFAULT, sites.data());
54✔
806
#endif
807

808
  // Close all ids
809
  H5Sclose(dspace);
122✔
810
  if (distribute)
122✔
811
    H5Sclose(memspace);
67✔
812
  H5Dclose(dset);
122✔
813
  H5Tclose(banktype);
122✔
814
}
122✔
815

816
void write_unstructured_mesh_results()
2,446✔
817
{
818

819
  for (auto& tally : model::tallies) {
11,461✔
820

821
    vector<std::string> tally_scores;
9,015✔
822
    for (auto filter_idx : tally->filters()) {
25,753✔
823
      auto& filter = model::tally_filters[filter_idx];
16,738✔
824
      if (filter->type() != FilterType::MESH)
16,738✔
825
        continue;
16,723✔
826

827
      // check if the filter uses an unstructured mesh
828
      auto mesh_filter = dynamic_cast<MeshFilter*>(filter.get());
1,918✔
829
      auto mesh_idx = mesh_filter->mesh();
1,918✔
830
      auto umesh =
831
        dynamic_cast<UnstructuredMesh*>(model::meshes[mesh_idx].get());
1,918✔
832

833
      if (!umesh)
1,918✔
834
        continue;
1,884✔
835

836
      if (!umesh->output_)
34✔
837
        continue;
×
838

839
      if (umesh->library() == "moab") {
34✔
840
        if (mpi::master)
19✔
841
          warning(fmt::format(
9✔
842
            "Output for a MOAB mesh (mesh {}) was "
843
            "requested but will not be written. Please use the Python "
844
            "API to generated the desired VTK tetrahedral mesh.",
845
            umesh->id_));
9✔
846
        continue;
19✔
847
      }
848

849
      // if this tally has more than one filter, print
850
      // warning and skip writing the mesh
851
      if (tally->filters().size() > 1) {
15✔
852
        warning(fmt::format("Skipping unstructured mesh writing for tally "
×
853
                            "{}. More than one filter is present on the tally.",
854
          tally->id_));
×
855
        break;
×
856
      }
857

858
      int n_realizations = tally->n_realizations_;
15✔
859

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

873
      for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) {
30✔
874
        for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) {
30✔
875
          // combine the score and nuclide into a name for the value
876
          auto score_str = fmt::format("{}_{}", tally->score_name(score_idx),
30✔
877
            tally->nuclide_name(nuc_idx));
30✔
878

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

882
          // construct result vectors
883
          vector<double> mean_vec(umesh->n_bins()),
15✔
884
            std_dev_vec(umesh->n_bins());
15✔
885
          for (int j = 0; j < tally->results_.shape()[0]; j++) {
146,799✔
886
            // get the volume for this bin
887
            double volume = umesh->volume(j);
146,784✔
888
            // compute the mean
889
            double mean = tally->results_(j, nuc_score_idx, TallyResult::SUM) /
146,784✔
890
                          n_realizations;
146,784✔
891
            mean_vec.at(j) = mean / volume;
146,784✔
892

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

914
      // Generate a file name based on the tally id
915
      // and the current batch number
916
      size_t batch_width {std::to_string(settings::n_max_batches).size()};
15✔
917
      std::string filename = fmt::format("tally_{0}.{1:0{2}}", tally->id_,
15✔
918
        simulation::current_batch, batch_width);
×
919

920
      // Write the unstructured mesh and data to file
921
      umesh->write(filename);
15✔
922

923
      // remove score data added for this mesh write
924
      umesh->remove_scores();
15✔
925
    }
15✔
926
  }
9,015✔
927
}
2,446✔
928

929
void write_tally_results_nr(hid_t file_id)
×
930
{
931
  // ==========================================================================
932
  // COLLECT AND WRITE GLOBAL TALLIES
933

934
  hid_t tallies_group;
935
  if (mpi::master) {
×
936
    // Write number of realizations
937
    write_dataset(file_id, "n_realizations", simulation::n_realizations);
×
938

939
    tallies_group = open_group(file_id, "tallies");
×
940
  }
941

942
  // Get global tallies
943
  auto& gt = simulation::global_tallies;
×
944

945
#ifdef OPENMC_MPI
946
  // Reduce global tallies
947
  xt::xtensor<double, 2> gt_reduced = xt::empty_like(gt);
948
  MPI_Reduce(gt.data(), gt_reduced.data(), gt.size(), MPI_DOUBLE, MPI_SUM, 0,
949
    mpi::intracomm);
950

951
  // Transfer values to value on master
952
  if (mpi::master) {
953
    if (simulation::current_batch == settings::n_max_batches ||
954
        simulation::satisfy_triggers) {
955
      std::copy(gt_reduced.begin(), gt_reduced.end(), gt.begin());
956
    }
957
  }
958
#endif
959

960
  // Write out global tallies sum and sum_sq
961
  if (mpi::master) {
×
962
    write_dataset(file_id, "global_tallies", gt);
×
963
  }
964

965
  for (const auto& t : model::tallies) {
×
966
    // Skip any tallies that are not active
967
    if (!t->active_)
×
968
      continue;
×
969
    if (!t->writable_)
×
970
      continue;
×
971

972
    if (mpi::master && !attribute_exists(file_id, "tallies_present")) {
×
973
      write_attribute(file_id, "tallies_present", 1);
×
974
    }
975

976
    // Get view of accumulated tally values
977
    auto values_view = xt::view(t->results_, xt::all(), xt::all(),
×
978
      xt::range(static_cast<int>(TallyResult::SUM),
×
979
        static_cast<int>(TallyResult::SUM_SQ) + 1));
980

981
    // Make copy of tally values in contiguous array
982
    xt::xtensor<double, 3> values = values_view;
×
983

984
    if (mpi::master) {
×
985
      // Open group for tally
986
      std::string groupname {"tally " + std::to_string(t->id_)};
×
987
      hid_t tally_group = open_group(tallies_group, groupname.c_str());
×
988

989
      // The MPI_IN_PLACE specifier allows the master to copy values into
990
      // a receive buffer without having a temporary variable
991
#ifdef OPENMC_MPI
992
      MPI_Reduce(MPI_IN_PLACE, values.data(), values.size(), MPI_DOUBLE,
993
        MPI_SUM, 0, mpi::intracomm);
994
#endif
995

996
      // At the end of the simulation, store the results back in the
997
      // regular TallyResults array
998
      if (simulation::current_batch == settings::n_max_batches ||
×
999
          simulation::satisfy_triggers) {
1000
        values_view = values;
×
1001
      }
1002

1003
      // Put in temporary tally result
1004
      xt::xtensor<double, 3> results_copy = xt::zeros_like(t->results_);
×
1005
      auto copy_view = xt::view(results_copy, xt::all(), xt::all(),
×
1006
        xt::range(static_cast<int>(TallyResult::SUM),
×
1007
          static_cast<int>(TallyResult::SUM_SQ) + 1));
1008
      copy_view = values;
×
1009

1010
      // Write reduced tally results to file
1011
      auto shape = results_copy.shape();
×
NEW
1012
      write_tally_results(
×
NEW
1013
        tally_group, shape[0], shape[1], shape[2], results_copy.data());
×
1014

1015
      close_group(tally_group);
×
1016
    } else {
×
1017
      // Receive buffer not significant at other processors
1018
#ifdef OPENMC_MPI
1019
      MPI_Reduce(values.data(), nullptr, values.size(), MPI_DOUBLE, MPI_SUM, 0,
1020
        mpi::intracomm);
1021
#endif
1022
    }
1023
  }
1024

1025
  if (mpi::master) {
×
1026
    if (!object_exists(file_id, "tallies_present")) {
×
1027
      // Indicate that tallies are off
1028
      write_dataset(file_id, "tallies_present", 0);
×
1029
    }
1030

1031
    close_group(tallies_group);
×
1032
  }
1033
}
1034

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