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

openmc-dev / openmc / 21728712162

05 Feb 2026 09:13PM UTC coverage: 81.763% (-0.003%) from 81.766%
21728712162

Pull #3776

github

web-flow
Merge 06cb586bc into 1039b5d9f
Pull Request #3776: Modifications to C++ plots for interactive raytrace plots

17310 of 24268 branches covered (71.33%)

Branch coverage included in aggregate %.

90 of 94 new or added lines in 2 files covered. (95.74%)

309 existing lines in 26 files now uncovered.

55957 of 65341 relevant lines covered (85.64%)

50685327.01 hits per line

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

85.86
/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)
7,949✔
38
{
39
  simulation::time_statepoint.start();
7,949✔
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_;
7,949✔
44
  if (filename) {
7,949✔
45
    filename_ = filename;
797✔
46
  } else {
47
    // Determine width for zero padding
48
    int w = std::to_string(settings::n_max_batches).size();
7,152✔
49

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

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

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

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

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

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

79
    // Write OpenMC version
80
    write_attribute(file_id, "openmc_version", VERSION);
6,764✔
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());
6,764✔
87

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

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

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

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

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

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

120
    // Write out information for eigenvalue run
121
    if (settings::run_mode == RunMode::EIGENVALUE)
6,764✔
122
      write_eigenvalue_hdf5(file_id);
4,180✔
123

124
    hid_t tallies_group = create_group(file_id, "tallies");
6,764✔
125

126
    // Write meshes
127
    meshes_to_hdf5(tallies_group);
6,764✔
128

129
    // Write information for derivatives
130
    if (!model::tally_derivs.empty()) {
6,764✔
131
      hid_t derivs_group = create_group(tallies_group, "derivatives");
11✔
132
      for (const auto& deriv : model::tally_derivs) {
66✔
133
        hid_t deriv_group =
134
          create_group(derivs_group, "derivative " + std::to_string(deriv.id));
55✔
135
        write_dataset(deriv_group, "material", deriv.diff_material);
55✔
136
        if (deriv.variable == DerivativeVariable::DENSITY) {
55✔
137
          write_dataset(deriv_group, "independent variable", "density");
22✔
138
        } else if (deriv.variable == DerivativeVariable::NUCLIDE_DENSITY) {
33✔
139
          write_dataset(deriv_group, "independent variable", "nuclide_density");
22✔
140
          write_dataset(
22✔
141
            deriv_group, "nuclide", data::nuclides[deriv.diff_nuclide]->name_);
22✔
142
        } else if (deriv.variable == DerivativeVariable::TEMPERATURE) {
11!
143
          write_dataset(deriv_group, "independent variable", "temperature");
11✔
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);
55✔
150
      }
151
      close_group(derivs_group);
11✔
152
    }
153

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

165
      // Write info for each filter
166
      for (const auto& filt : model::tally_filters) {
14,810✔
167
        hid_t filter_group =
168
          create_group(filters_group, "filter " + std::to_string(filt->id()));
10,619✔
169
        filt->to_statepoint(filter_group);
10,619✔
170
        close_group(filter_group);
10,619✔
171
      }
172
    }
4,191✔
173
    close_group(filters_group);
6,764✔
174

175
    // Write information for tallies
176
    write_attribute(tallies_group, "n_tallies", model::tallies.size());
6,764✔
177
    if (!model::tallies.empty()) {
6,764✔
178
      // Write tally IDs
179
      vector<int32_t> tally_ids;
4,719✔
180
      tally_ids.reserve(model::tallies.size());
4,719✔
181
      for (const auto& tally : model::tallies)
26,158✔
182
        tally_ids.push_back(tally->id_);
21,439✔
183
      write_attribute(tallies_group, "ids", tally_ids);
4,719✔
184

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

190
        write_dataset(tally_group, "name", tally->name_);
21,439✔
191

192
        if (tally->writable_) {
21,439✔
193
          write_attribute(tally_group, "internal", 0);
20,401✔
194
        } else {
195
          write_attribute(tally_group, "internal", 1);
1,038✔
196
          close_group(tally_group);
1,038✔
197
          continue;
1,038✔
198
        }
199

200
        if (tally->multiply_density()) {
20,401✔
201
          write_attribute(tally_group, "multiply_density", 1);
20,346✔
202
        } else {
203
          write_attribute(tally_group, "multiply_density", 0);
55✔
204
        }
205

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

212
        if (tally->estimator_ == TallyEstimator::ANALOG) {
20,401✔
213
          write_dataset(tally_group, "estimator", "analog");
7,429✔
214
        } else if (tally->estimator_ == TallyEstimator::TRACKLENGTH) {
12,972✔
215
          write_dataset(tally_group, "estimator", "tracklength");
12,108✔
216
        } else if (tally->estimator_ == TallyEstimator::COLLISION) {
864!
217
          write_dataset(tally_group, "estimator", "collision");
864✔
218
        }
219

220
        write_dataset(tally_group, "n_realizations", tally->n_realizations_);
20,401✔
221

222
        // Write the ID of each filter attached to this tally
223
        write_dataset(tally_group, "n_filters", tally->filters().size());
20,401✔
224
        if (!tally->filters().empty()) {
20,401✔
225
          vector<int32_t> filter_ids;
19,224✔
226
          filter_ids.reserve(tally->filters().size());
19,224✔
227
          for (auto i_filt : tally->filters())
58,106✔
228
            filter_ids.push_back(model::tally_filters[i_filt]->id());
38,882✔
229
          write_dataset(tally_group, "filters", filter_ids);
19,224✔
230
        }
19,224✔
231

232
        // Write the nuclides this tally scores
233
        vector<std::string> nuclides;
20,401✔
234
        for (auto i_nuclide : tally->nuclides_) {
48,568✔
235
          if (i_nuclide == -1) {
28,167✔
236
            nuclides.push_back("total");
17,772✔
237
          } else {
238
            if (settings::run_CE) {
10,395✔
239
              nuclides.push_back(data::nuclides[i_nuclide]->name_);
10,285✔
240
            } else {
241
              nuclides.push_back(data::mg.nuclides_[i_nuclide].name);
110✔
242
            }
243
          }
244
        }
245
        write_dataset(tally_group, "nuclides", nuclides);
20,401✔
246

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

251
        // Write the tally score bins
252
        vector<std::string> scores;
20,401✔
253
        for (auto sc : tally->scores_)
49,807✔
254
          scores.push_back(reaction_name(sc));
29,406✔
255
        write_dataset(tally_group, "n_score_bins", scores.size());
20,401✔
256
        write_dataset(tally_group, "score_bins", scores);
20,401✔
257

258
        close_group(tally_group);
20,401✔
259
      }
20,401✔
260
    }
4,719✔
261

262
    if (settings::reduce_tallies) {
6,764✔
263
      // Write global tallies
264
      write_dataset(file_id, "global_tallies", simulation::global_tallies);
6,753✔
265

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

271
        // Write all tally results
272
        for (const auto& tally : model::tallies) {
25,696✔
273
          if (!tally->writable_)
21,208✔
274
            continue;
818✔
275

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

290
    close_group(tallies_group);
6,764✔
291
  }
292

293
  // Check for the no-tally-reduction method
294
  if (!settings::reduce_tallies) {
7,949✔
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);
16✔
298

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

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

334
    file_close(file_id);
6,764✔
335
  }
336

337
#ifdef PHDF5
338
  bool parallel = true;
4,264✔
339
#else
340
  bool parallel = false;
3,685✔
341
#endif
342

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

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

357
  simulation::time_statepoint.stop();
7,949✔
358

359
  return 0;
7,949✔
360
}
7,949✔
361

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

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

383
void statepoint_version_check(hid_t file_id)
65✔
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);
65✔
389
  if (version_array != VERSION_STATEPOINT) {
65!
390
    fatal_error(
×
391
      "State point version does not match current version in OpenMC.");
392
  }
393
}
65✔
394

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

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

407
  statepoint_version_check(file_id);
65✔
408

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

414
  // Read and overwrite random number stride
415
  uint64_t stride;
416
  read_dataset(file_id, "stride", stride);
65✔
417
  openmc_set_stride(stride);
65✔
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);
65✔
422
  if (word == "multi-group" && settings::run_CE) {
65!
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) {
65!
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);
65✔
432
  if (word == "fixed source") {
65!
433
    settings::run_mode = RunMode::FIXED_SOURCE;
×
434
  } else if (word == "eigenvalue") {
65!
435
    settings::run_mode = RunMode::EIGENVALUE;
65✔
436
  }
437
  read_attribute(file_id, "photon_transport", settings::photon_transport);
65✔
438
  read_dataset(file_id, "n_particles", settings::n_particles);
65✔
439
  int temp;
440
  read_dataset(file_id, "n_batches", temp);
65✔
441

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

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

448
  if (settings::restart_run &&
65!
449
      simulation::restart_batch >= settings::n_max_batches) {
65✔
450
    warning(fmt::format(
11✔
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);
65✔
460

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

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

469
    // Check to make sure source bank is present
470
    if (settings::path_sourcepoint == settings::path_statepoint &&
130!
471
        !source_present) {
65!
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);
65✔
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) {
65!
482
    restart_set_keff();
65✔
483
  }
484

485
  // Set current batch number
486
  simulation::current_batch = simulation::restart_batch;
65✔
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) {
30!
494
#endif
495
    // Read global tally data
496
    read_dataset_lowlevel(file_id, "global_tallies", H5T_NATIVE_DOUBLE, H5S_ALL,
65✔
497
      false, simulation::global_tallies.data());
65✔
498

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

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

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

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

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

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

534
    // Check if source was written out separately
535
    if (!source_present) {
65!
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);
65✔
550
  }
551

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

555
  return 0;
65✔
556
}
65✔
557

558
hid_t h5banktype(bool memory)
10,548✔
559
{
560
  // Create compound type for position
561
  hid_t postype = H5Tcreate(H5T_COMPOUND, sizeof(struct Position));
10,548✔
562
  H5Tinsert(postype, "x", HOFFSET(Position, x), H5T_NATIVE_DOUBLE);
10,548✔
563
  H5Tinsert(postype, "y", HOFFSET(Position, y), H5T_NATIVE_DOUBLE);
10,548✔
564
  H5Tinsert(postype, "z", HOFFSET(Position, z), H5T_NATIVE_DOUBLE);
10,548✔
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);
10,548✔
574
  if (!memory)
10,548✔
575
    n = 2 * sizeof(struct Position) + 3 * sizeof(double) + 3 * sizeof(int);
5,210✔
576
  hid_t banktype = H5Tcreate(H5T_COMPOUND, n);
10,548✔
577
  H5Tinsert(banktype, "r", HOFFSET(SourceSite, r), postype);
10,548✔
578
  H5Tinsert(banktype, "u", HOFFSET(SourceSite, u), postype);
10,548✔
579
  H5Tinsert(banktype, "E", HOFFSET(SourceSite, E), H5T_NATIVE_DOUBLE);
10,548✔
580
  H5Tinsert(banktype, "time", HOFFSET(SourceSite, time), H5T_NATIVE_DOUBLE);
10,548✔
581
  H5Tinsert(banktype, "wgt", HOFFSET(SourceSite, wgt), H5T_NATIVE_DOUBLE);
10,548✔
582
  H5Tinsert(banktype, "delayed_group", HOFFSET(SourceSite, delayed_group),
10,548✔
583
    H5T_NATIVE_INT);
10,548✔
584
  H5Tinsert(banktype, "surf_id", HOFFSET(SourceSite, surf_id), H5T_NATIVE_INT);
10,548✔
585
  H5Tinsert(
10,548✔
586
    banktype, "particle", HOFFSET(SourceSite, particle), H5T_NATIVE_INT);
10,548✔
587

588
  H5Tclose(postype);
10,548✔
589
  return banktype;
10,548✔
590
}
591

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

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

609
void write_h5_source_point(const char* filename, span<SourceSite> source_bank,
1,204✔
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;
587✔
618
#else
619
  bool parallel = false;
617✔
620
#endif
621

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

625
  std::string filename_(filename);
1,204✔
626
  const auto extension = get_file_extension(filename_);
1,204✔
627
  if (extension != "h5") {
1,204!
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) {
1,204!
634
    file_id = file_open(filename_.c_str(), 'w', true);
1,204✔
635
    write_attribute(file_id, "filetype", "source");
1,204✔
636
    write_attribute(file_id, "version", VERSION_STATEPOINT);
1,204✔
637
  }
638

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

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

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

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

660
  H5Tclose(membanktype);
5,210✔
661
  H5Tclose(filebanktype);
5,210✔
662
}
5,210✔
663

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

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

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

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

697
  // Make sure number of members matches
698
  hid_t dtype = H5Dget_type(dset);
128✔
699
  auto file_member_names = dtype_member_names(dtype);
128✔
700
  auto bank_member_names = dtype_member_names(banktype);
128✔
701
  if (file_member_names != bank_member_names) {
128✔
702
    fatal_error(fmt::format(
9✔
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);
119✔
710
  hsize_t n_sites;
711
  H5Sget_simple_extent_dims(dspace, &n_sites, nullptr);
119✔
712

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

718
  hid_t memspace;
719
  if (distribute) {
119✔
720
    if (simulation::work_index[mpi::n_procs] > n_sites) {
65!
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;
65✔
727
    memspace = H5Screate_simple(1, &n_sites_local, nullptr);
65✔
728

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

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

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

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

761
void write_unstructured_mesh_results()
2,369✔
762
{
763

764
  for (auto& tally : model::tallies) {
11,044✔
765

766
    vector<std::string> tally_scores;
8,675✔
767
    for (auto filter_idx : tally->filters()) {
25,409✔
768
      auto& filter = model::tally_filters[filter_idx];
16,734✔
769
      if (filter->type() != FilterType::MESH)
16,734!
770
        continue;
16,719✔
771

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

778
      if (!umesh)
1,942✔
779
        continue;
1,907✔
780

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

784
      if (umesh->library() == "moab") {
35!
UNCOV
785
        if (mpi::master)
20✔
UNCOV
786
          warning(fmt::format(
10!
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_));
10✔
UNCOV
791
        continue;
20✔
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) {
15!
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_;
15✔
804

805
      for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) {
30✔
806
        for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) {
30✔
807
          // combine the score and nuclide into a name for the value
808
          auto score_str = fmt::format("{}_{}", tally->score_name(score_idx),
30!
809
            tally->nuclide_name(nuc_idx));
30!
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);
15!
815
        }
15✔
816
      }
817

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

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

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

838
            // compute the standard deviation
839
            double sum_sq =
840
              tally->results_(j, nuc_score_idx, TallyResult::SUM_SQ);
146,784!
841
            double std_dev {0.0};
146,784✔
842
            if (n_realizations > 1) {
146,784!
843
              std_dev = sum_sq / n_realizations - mean * mean;
146,784✔
844
              std_dev = std::sqrt(std_dev / (n_realizations - 1));
146,784✔
845
            }
846
            std_dev_vec[j] = std_dev / volume;
146,784✔
847
          }
848
#ifdef OPENMC_MPI
849
          MPI_Bcast(
10!
850
            mean_vec.data(), mean_vec.size(), MPI_DOUBLE, 0, mpi::intracomm);
10✔
851
          MPI_Bcast(std_dev_vec.data(), std_dev_vec.size(), MPI_DOUBLE, 0,
10!
852
            mpi::intracomm);
853
#endif
854
          // set the data for this score
855
          umesh->set_score_data(score_str, mean_vec, std_dev_vec);
15!
856
        }
15✔
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()};
15!
862
      std::string filename = fmt::format("tally_{0}.{1:0{2}}", tally->id_,
15✔
863
        simulation::current_batch, batch_width);
×
864

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

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

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

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

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

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

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

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

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

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

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

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

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

929
    if (mpi::master) {
16✔
930
      // Open group for tally
931
      std::string groupname {"tally " + std::to_string(t->id_)};
11✔
932
      hid_t tally_group = open_group(tallies_group, groupname.c_str());
11✔
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,
5✔
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 ||
11!
944
          simulation::satisfy_triggers) {
945
        values_view = values;
11✔
946
      }
947

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

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

960
      close_group(tally_group);
11✔
961
    } else {
11✔
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,
5✔
965
        mpi::intracomm);
966
#endif
967
    }
968
  }
16✔
969

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

976
    close_group(tallies_group);
11✔
977
  }
978
}
16✔
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