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

openmc-dev / openmc / 18299973882

07 Oct 2025 02:14AM UTC coverage: 81.92% (-3.3%) from 85.194%
18299973882

push

github

web-flow
Switch to using coveralls github action for reporting (#3594)

16586 of 23090 branches covered (71.83%)

Branch coverage included in aggregate %.

53703 of 62712 relevant lines covered (85.63%)

43428488.21 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

188
        write_dataset(tally_group, "name", tally->name_);
22,473✔
189

190
        if (tally->writable_) {
22,473✔
191
          write_attribute(tally_group, "internal", 0);
20,520✔
192
        } else {
193
          write_attribute(tally_group, "internal", 1);
1,953✔
194
          close_group(tally_group);
1,953✔
195
          continue;
1,953✔
196
        }
197

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

204
        if (tally->estimator_ == TallyEstimator::ANALOG) {
20,520✔
205
          write_dataset(tally_group, "estimator", "analog");
6,952✔
206
        } else if (tally->estimator_ == TallyEstimator::TRACKLENGTH) {
13,568✔
207
          write_dataset(tally_group, "estimator", "tracklength");
12,659✔
208
        } else if (tally->estimator_ == TallyEstimator::COLLISION) {
909!
209
          write_dataset(tally_group, "estimator", "collision");
909✔
210
        }
211

212
        write_dataset(tally_group, "n_realizations", tally->n_realizations_);
20,520✔
213

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

224
        // Write the nuclides this tally scores
225
        vector<std::string> nuclides;
20,520✔
226
        for (auto i_nuclide : tally->nuclides_) {
48,642✔
227
          if (i_nuclide == -1) {
28,122✔
228
            nuclides.push_back("total");
17,857✔
229
          } else {
230
            if (settings::run_CE) {
10,265✔
231
              nuclides.push_back(data::nuclides[i_nuclide]->name_);
10,155✔
232
            } else {
233
              nuclides.push_back(data::mg.nuclides_[i_nuclide].name);
110✔
234
            }
235
          }
236
        }
237
        write_dataset(tally_group, "nuclides", nuclides);
20,520✔
238

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

243
        // Write the tally score bins
244
        vector<std::string> scores;
20,520✔
245
        for (auto sc : tally->scores_)
49,090✔
246
          scores.push_back(reaction_name(sc));
28,570✔
247
        write_dataset(tally_group, "n_score_bins", scores.size());
20,520✔
248
        write_dataset(tally_group, "score_bins", scores);
20,520✔
249

250
        close_group(tally_group);
20,520✔
251
      }
20,520✔
252
    }
5,300✔
253

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

258
      // Write tallies
259
      if (model::active_tallies.size() > 0) {
6,990✔
260
        // Indicate that tallies are on
261
        write_attribute(file_id, "tallies_present", 1);
4,891✔
262

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

281
    close_group(tallies_group);
6,990✔
282
  }
283

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

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

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

325
    file_close(file_id);
6,990✔
326
  }
327

328
#ifdef PHDF5
329
  bool parallel = true;
4,791✔
330
#else
331
  bool parallel = false;
3,254✔
332
#endif
333

334
  // Write the source bank if desired
335
  if (write_source_) {
8,045✔
336
    if (mpi::master || parallel)
3,759!
337
      file_id = file_open(filename_, 'a', true);
3,759✔
338
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
3,759✔
339
    if (mpi::master || parallel)
3,759!
340
      file_close(file_id);
3,759✔
341
  }
342

343
#if defined(OPENMC_LIBMESH_ENABLED) || defined(OPENMC_DAGMC_ENABLED)
344
  // write unstructured mesh tally files
345
  write_unstructured_mesh_results();
2,395✔
346
#endif
347

348
  simulation::time_statepoint.stop();
8,045✔
349

350
  return 0;
8,045✔
351
}
8,045✔
352

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

367
void load_state_point()
71✔
368
{
369
  write_message(
71✔
370
    fmt::format("Loading state point {}...", settings::path_statepoint_c), 5);
130✔
371
  openmc_statepoint_load(settings::path_statepoint.c_str());
71✔
372
}
71✔
373

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

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

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

398
  statepoint_version_check(file_id);
71✔
399

400
  // Read and overwrite random number seed
401
  int64_t seed;
402
  read_dataset(file_id, "seed", seed);
71✔
403
  openmc_set_seed(seed);
71✔
404

405
  // Read and overwrite random number stride
406
  uint64_t stride;
407
  read_dataset(file_id, "stride", stride);
71✔
408
  openmc_set_stride(stride);
71✔
409

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

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

433
  // Take maximum of statepoint n_batches and input n_batches
434
  settings::n_batches = std::max(settings::n_batches, temp);
71✔
435

436
  // Read batch number to restart at
437
  read_dataset(file_id, "current_batch", simulation::restart_batch);
71✔
438

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

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

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

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

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

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

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

476
  // Set current batch number
477
  simulation::current_batch = simulation::restart_batch;
71✔
478

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

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

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

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

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

521
  // Read source if in eigenvalue mode
522
  if (settings::run_mode == RunMode::EIGENVALUE) {
71!
523

524
    // Check if source was written out separately
525
    if (!source_present) {
71!
526

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

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

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

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

542
  // Close file
543
  file_close(file_id);
71✔
544

545
  return 0;
71✔
546
}
71✔
547

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

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

575
  H5Tclose(postype);
5,136✔
576
  return banktype;
5,136✔
577
}
578

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

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

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

609
  if (!filename)
1,241!
610
    fatal_error("write_source_point filename needs a nonempty name.");
×
611

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

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

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

628
  if (mpi::master || parallel)
1,241!
629
    file_close(file_id);
1,241✔
630
}
1,241✔
631

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

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

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

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

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

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

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

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

669
#else
670

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

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

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

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

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

701
      // Write data to hyperslab
702
      H5Dwrite(
2,177✔
703
        dset, banktype, memspace, dspace, H5P_DEFAULT, source_bank.data());
2,177✔
704

705
      H5Sclose(memspace);
2,177✔
706
      H5Sclose(dspace);
2,177✔
707
    }
708

709
    // Close all ids
710
    H5Dclose(dset);
2,177✔
711

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

724
  H5Tclose(banktype);
5,000✔
725
}
5,000✔
726

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

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

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

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

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

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

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

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

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

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

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

808
void write_unstructured_mesh_results()
2,395✔
809
{
810

811
  for (auto& tally : model::tallies) {
11,331✔
812

813
    vector<std::string> tally_scores;
8,936✔
814
    for (auto filter_idx : tally->filters()) {
25,564✔
815
      auto& filter = model::tally_filters[filter_idx];
16,628✔
816
      if (filter->type() != FilterType::MESH)
16,628!
817
        continue;
16,613✔
818

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

825
      if (!umesh)
1,918✔
826
        continue;
1,884✔
827

828
      if (!umesh->output_)
34!
829
        continue;
×
830

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

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

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

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

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

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

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

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

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

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

915
      // remove score data added for this mesh write
916
      umesh->remove_scores();
15!
917
    }
15✔
918
  }
8,936✔
919
}
2,395✔
920

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1022
    close_group(tallies_group);
×
1023
  }
1024
}
×
1025

1026
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc