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

openmc-dev / openmc / 18538152141

15 Oct 2025 06:02PM UTC coverage: 81.97% (-3.2%) from 85.194%
18538152141

Pull #3417

github

web-flow
Merge 4604e1321 into e9077b137
Pull Request #3417: Addition of a collision tracking feature

16794 of 23357 branches covered (71.9%)

Branch coverage included in aggregate %.

480 of 522 new or added lines in 13 files covered. (91.95%)

457 existing lines in 53 files now uncovered.

54128 of 63165 relevant lines covered (85.69%)

42776927.64 hits per line

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

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

34
namespace openmc {
35

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

164
      // Write info for each filter
165
      for (const auto& filt : model::tally_filters) {
15,411✔
166
        hid_t filter_group =
167
          create_group(filters_group, "filter " + std::to_string(filt->id()));
10,959✔
168
        filt->to_statepoint(filter_group);
10,959✔
169
        close_group(filter_group);
10,959✔
170
      }
171
    }
4,452✔
172
    close_group(filters_group);
6,775✔
173

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

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

189
        write_dataset(tally_group, "name", tally->name_);
21,770✔
190

191
        if (tally->writable_) {
21,770✔
192
          write_attribute(tally_group, "internal", 0);
20,130✔
193
        } else {
194
          write_attribute(tally_group, "internal", 1);
1,640✔
195
          close_group(tally_group);
1,640✔
196
          continue;
1,640✔
197
        }
198

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

205
        if (tally->estimator_ == TallyEstimator::ANALOG) {
20,130✔
206
          write_dataset(tally_group, "estimator", "analog");
6,888✔
207
        } else if (tally->estimator_ == TallyEstimator::TRACKLENGTH) {
13,242✔
208
          write_dataset(tally_group, "estimator", "tracklength");
12,361✔
209
        } else if (tally->estimator_ == TallyEstimator::COLLISION) {
881!
210
          write_dataset(tally_group, "estimator", "collision");
881✔
211
        }
212

213
        write_dataset(tally_group, "n_realizations", tally->n_realizations_);
20,130✔
214

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

225
        // Write the nuclides this tally scores
226
        vector<std::string> nuclides;
20,130✔
227
        for (auto i_nuclide : tally->nuclides_) {
47,834✔
228
          if (i_nuclide == -1) {
27,704✔
229
            nuclides.push_back("total");
17,495✔
230
          } else {
231
            if (settings::run_CE) {
10,209✔
232
              nuclides.push_back(data::nuclides[i_nuclide]->name_);
10,099✔
233
            } else {
234
              nuclides.push_back(data::mg.nuclides_[i_nuclide].name);
110✔
235
            }
236
          }
237
        }
238
        write_dataset(tally_group, "nuclides", nuclides);
20,130✔
239

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

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

251
        close_group(tally_group);
20,130✔
252
      }
20,130✔
253
    }
4,969✔
254

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

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

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

282
    close_group(tallies_group);
6,775✔
283
  }
284

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

291
  } else if (mpi::master) {
7,865✔
292
    // Write number of global realizations
293
    write_dataset(file_id, "n_realizations", simulation::n_realizations);
6,775✔
294
  }
295

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

326
    file_close(file_id);
6,775✔
327
  }
328

329
#ifdef PHDF5
330
  bool parallel = true;
4,546✔
331
#else
332
  bool parallel = false;
3,319✔
333
#endif
334

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

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

349
  simulation::time_statepoint.stop();
7,865✔
350

351
  return 0;
7,865✔
352
}
7,865✔
353

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

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

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

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

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

399
  statepoint_version_check(file_id);
68✔
400

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

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

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

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

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

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

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

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

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

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

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

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

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

477
  // Set current batch number
478
  simulation::current_batch = simulation::restart_batch;
68✔
479

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

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

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

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

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

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

525
    // Check if source was written out separately
526
    if (!source_present) {
68!
527

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

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

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

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

543
  // Close file
544
  file_close(file_id);
68✔
545

546
  return 0;
68✔
547
}
68✔
548

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

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

576
  H5Tclose(postype);
5,139✔
577
  return banktype;
5,139✔
578
}
579

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

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

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

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

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

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

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

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

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

638
#ifdef OPENMC_MPI
639
  write_bank_dataset("source_bank", group_id, source_bank, bank_index, banktype,
2,783✔
640
    mpi::source_site);
641
#else
642
  write_bank_dataset(
2,224✔
643
    "source_bank", group_id, source_bank, bank_index, banktype);
644
#endif
645

646
  H5Tclose(banktype);
5,007✔
647
}
5,007✔
648

649
// Determine member names of a compound HDF5 datatype
650
std::string dtype_member_names(hid_t dtype_id)
264✔
651
{
652
  int nmembers = H5Tget_nmembers(dtype_id);
264✔
653
  std::string names;
264✔
654
  for (int i = 0; i < nmembers; i++) {
2,331✔
655
    char* name = H5Tget_member_name(dtype_id, i);
2,067✔
656
    names = names.append(name);
2,067✔
657
    H5free_memory(name);
2,067✔
658
    if (i < nmembers - 1)
2,067✔
659
      names += ", ";
1,803✔
660
  }
661
  return names;
264✔
662
}
×
663

664
void read_source_bank(
132✔
665
  hid_t group_id, vector<SourceSite>& sites, bool distribute)
666
{
667
  hid_t banktype = h5banktype();
132✔
668

669
  // Open the dataset
670
  hid_t dset = H5Dopen(group_id, "source_bank", H5P_DEFAULT);
132✔
671

672
  // Make sure number of members matches
673
  hid_t dtype = H5Dget_type(dset);
132✔
674
  auto file_member_names = dtype_member_names(dtype);
132✔
675
  auto bank_member_names = dtype_member_names(banktype);
132✔
676
  if (file_member_names != bank_member_names) {
132✔
677
    fatal_error(fmt::format(
9✔
678
      "Source site attributes in file do not match what is "
679
      "expected for this version of OpenMC. File attributes = ({}). Expected "
680
      "attributes = ({})",
681
      file_member_names, bank_member_names));
682
  }
683

684
  hid_t dspace = H5Dget_space(dset);
123✔
685
  hsize_t n_sites;
686
  H5Sget_simple_extent_dims(dspace, &n_sites, nullptr);
123✔
687

688
  // Make sure vector is big enough in case where we're reading entire source on
689
  // each process
690
  if (!distribute)
123✔
691
    sites.resize(n_sites);
55✔
692

693
  hid_t memspace;
694
  if (distribute) {
123✔
695
    if (simulation::work_index[mpi::n_procs] > n_sites) {
68!
696
      fatal_error("Number of source sites in source file is less "
×
697
                  "than number of source particles per generation.");
698
    }
699

700
    // Create another data space but for each proc individually
701
    hsize_t n_sites_local = simulation::work_per_rank;
68✔
702
    memspace = H5Screate_simple(1, &n_sites_local, nullptr);
68✔
703

704
    // Select hyperslab for each process
705
    hsize_t offset = simulation::work_index[mpi::rank];
68✔
706
    H5Sselect_hyperslab(
68✔
707
      dspace, H5S_SELECT_SET, &offset, nullptr, &n_sites_local, nullptr);
708
  } else {
709
    memspace = H5S_ALL;
55✔
710
  }
711

712
#ifdef PHDF5
713
  // Read data in parallel
714
  hid_t plist = H5Pcreate(H5P_DATASET_XFER);
69✔
715
  H5Pset_dxpl_mpio(plist, H5FD_MPIO_COLLECTIVE);
69✔
716
  H5Dread(dset, banktype, memspace, dspace, plist, sites.data());
69✔
717
  H5Pclose(plist);
69✔
718
#else
719
  H5Dread(dset, banktype, memspace, dspace, H5P_DEFAULT, sites.data());
54✔
720
#endif
721

722
  // Close all ids
723
  H5Sclose(dspace);
123✔
724
  if (distribute)
123✔
725
    H5Sclose(memspace);
68✔
726
  H5Dclose(dset);
123✔
727
  H5Tclose(banktype);
123✔
728
}
123✔
729

730
void write_unstructured_mesh_results()
2,414✔
731
{
732

733
  for (auto& tally : model::tallies) {
11,294✔
734

735
    vector<std::string> tally_scores;
8,880✔
736
    for (auto filter_idx : tally->filters()) {
25,456✔
737
      auto& filter = model::tally_filters[filter_idx];
16,576✔
738
      if (filter->type() != FilterType::MESH)
16,576!
739
        continue;
16,561✔
740

741
      // check if the filter uses an unstructured mesh
742
      auto mesh_filter = dynamic_cast<MeshFilter*>(filter.get());
1,918!
743
      auto mesh_idx = mesh_filter->mesh();
1,918!
744
      auto umesh =
745
        dynamic_cast<UnstructuredMesh*>(model::meshes[mesh_idx].get());
1,918!
746

747
      if (!umesh)
1,918✔
748
        continue;
1,884✔
749

750
      if (!umesh->output_)
34!
751
        continue;
×
752

753
      if (umesh->library() == "moab") {
34!
754
        if (mpi::master)
19✔
755
          warning(fmt::format(
9!
756
            "Output for a MOAB mesh (mesh {}) was "
757
            "requested but will not be written. Please use the Python "
758
            "API to generated the desired VTK tetrahedral mesh.",
759
            umesh->id_));
9✔
760
        continue;
19✔
761
      }
762

763
      // if this tally has more than one filter, print
764
      // warning and skip writing the mesh
765
      if (tally->filters().size() > 1) {
15!
766
        warning(fmt::format("Skipping unstructured mesh writing for tally "
×
767
                            "{}. More than one filter is present on the tally.",
768
          tally->id_));
×
769
        break;
×
770
      }
771

772
      int n_realizations = tally->n_realizations_;
15✔
773

774
      for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) {
30✔
775
        for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) {
30✔
776
          // combine the score and nuclide into a name for the value
777
          auto score_str = fmt::format("{}_{}", tally->score_name(score_idx),
30!
778
            tally->nuclide_name(nuc_idx));
30!
779
          // add this score to the mesh
780
          // (this is in a separate loop because all variables need to be added
781
          //  to libMesh's equation system before any are initialized, which
782
          //  happens in set_score_data)
783
          umesh->add_score(score_str);
15!
784
        }
15✔
785
      }
786

787
      for (int score_idx = 0; score_idx < tally->scores_.size(); score_idx++) {
30✔
788
        for (int nuc_idx = 0; nuc_idx < tally->nuclides_.size(); nuc_idx++) {
30✔
789
          // combine the score and nuclide into a name for the value
790
          auto score_str = fmt::format("{}_{}", tally->score_name(score_idx),
30!
791
            tally->nuclide_name(nuc_idx));
30!
792

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

796
          // construct result vectors
797
          vector<double> mean_vec(umesh->n_bins()),
15!
798
            std_dev_vec(umesh->n_bins());
15!
799
          for (int j = 0; j < tally->results_.shape()[0]; j++) {
146,799✔
800
            // get the volume for this bin
801
            double volume = umesh->volume(j);
146,784!
802
            // compute the mean
803
            double mean = tally->results_(j, nuc_score_idx, TallyResult::SUM) /
146,784!
804
                          n_realizations;
146,784✔
805
            mean_vec.at(j) = mean / volume;
146,784!
806

807
            // compute the standard deviation
808
            double sum_sq =
809
              tally->results_(j, nuc_score_idx, TallyResult::SUM_SQ);
146,784!
810
            double std_dev {0.0};
146,784✔
811
            if (n_realizations > 1) {
146,784!
812
              std_dev = sum_sq / n_realizations - mean * mean;
146,784✔
813
              std_dev = std::sqrt(std_dev / (n_realizations - 1));
146,784✔
814
            }
815
            std_dev_vec[j] = std_dev / volume;
146,784✔
816
          }
817
#ifdef OPENMC_MPI
818
          MPI_Bcast(
10!
819
            mean_vec.data(), mean_vec.size(), MPI_DOUBLE, 0, mpi::intracomm);
10✔
820
          MPI_Bcast(std_dev_vec.data(), std_dev_vec.size(), MPI_DOUBLE, 0,
10!
821
            mpi::intracomm);
822
#endif
823
          // set the data for this score
824
          umesh->set_score_data(score_str, mean_vec, std_dev_vec);
15!
825
        }
15✔
826
      }
827

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

834
      // Write the unstructured mesh and data to file
835
      umesh->write(filename);
15!
836

837
      // remove score data added for this mesh write
838
      umesh->remove_scores();
15!
839
    }
15✔
840
  }
8,880✔
841
}
2,414✔
842

843
void write_tally_results_nr(hid_t file_id)
×
844
{
845
  // ==========================================================================
846
  // COLLECT AND WRITE GLOBAL TALLIES
847

848
  hid_t tallies_group;
849
  if (mpi::master) {
×
850
    // Write number of realizations
851
    write_dataset(file_id, "n_realizations", simulation::n_realizations);
×
852

853
    tallies_group = open_group(file_id, "tallies");
×
854
  }
855

856
  // Get global tallies
857
  auto& gt = simulation::global_tallies;
×
858

859
#ifdef OPENMC_MPI
860
  // Reduce global tallies
861
  xt::xtensor<double, 2> gt_reduced = xt::empty_like(gt);
×
862
  MPI_Reduce(gt.data(), gt_reduced.data(), gt.size(), MPI_DOUBLE, MPI_SUM, 0,
×
863
    mpi::intracomm);
864

865
  // Transfer values to value on master
866
  if (mpi::master) {
×
867
    if (simulation::current_batch == settings::n_max_batches ||
×
868
        simulation::satisfy_triggers) {
869
      std::copy(gt_reduced.begin(), gt_reduced.end(), gt.begin());
×
870
    }
871
  }
872
#endif
873

874
  // Write out global tallies sum and sum_sq
875
  if (mpi::master) {
×
876
    write_dataset(file_id, "global_tallies", gt);
×
877
  }
878

879
  for (const auto& t : model::tallies) {
×
880
    // Skip any tallies that are not active
881
    if (!t->active_)
×
882
      continue;
×
883
    if (!t->writable_)
×
884
      continue;
×
885

886
    if (mpi::master && !attribute_exists(file_id, "tallies_present")) {
×
887
      write_attribute(file_id, "tallies_present", 1);
×
888
    }
889

890
    // Get view of accumulated tally values
891
    auto values_view = xt::view(t->results_, xt::all(), xt::all(),
×
892
      xt::range(static_cast<int>(TallyResult::SUM),
×
UNCOV
893
        static_cast<int>(TallyResult::SUM_SQ) + 1));
×
894

895
    // Make copy of tally values in contiguous array
896
    xt::xtensor<double, 3> values = values_view;
×
897

898
    if (mpi::master) {
×
899
      // Open group for tally
900
      std::string groupname {"tally " + std::to_string(t->id_)};
×
901
      hid_t tally_group = open_group(tallies_group, groupname.c_str());
×
902

903
      // The MPI_IN_PLACE specifier allows the master to copy values into
904
      // a receive buffer without having a temporary variable
905
#ifdef OPENMC_MPI
906
      MPI_Reduce(MPI_IN_PLACE, values.data(), values.size(), MPI_DOUBLE,
×
907
        MPI_SUM, 0, mpi::intracomm);
908
#endif
909

910
      // At the end of the simulation, store the results back in the
911
      // regular TallyResults array
912
      if (simulation::current_batch == settings::n_max_batches ||
×
913
          simulation::satisfy_triggers) {
914
        values_view = values;
×
915
      }
916

917
      // Put in temporary tally result
918
      xt::xtensor<double, 3> results_copy = xt::zeros_like(t->results_);
×
919
      auto copy_view = xt::view(results_copy, xt::all(), xt::all(),
×
920
        xt::range(static_cast<int>(TallyResult::SUM),
×
UNCOV
921
          static_cast<int>(TallyResult::SUM_SQ) + 1));
×
922
      copy_view = values;
×
923

924
      // Write reduced tally results to file
925
      auto shape = results_copy.shape();
×
926
      write_tally_results(tally_group, shape[0], shape[1], results_copy.data());
×
927

928
      close_group(tally_group);
×
929
    } else {
×
930
      // Receive buffer not significant at other processors
931
#ifdef OPENMC_MPI
932
      MPI_Reduce(values.data(), nullptr, values.size(), MPI_DOUBLE, MPI_SUM, 0,
×
933
        mpi::intracomm);
934
#endif
935
    }
UNCOV
936
  }
×
937

938
  if (mpi::master) {
×
939
    if (!object_exists(file_id, "tallies_present")) {
×
940
      // Indicate that tallies are off
941
      write_dataset(file_id, "tallies_present", 0);
×
942
    }
943

944
    close_group(tallies_group);
×
945
  }
UNCOV
946
}
×
947

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