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

openmc-dev / openmc / 13591584831

28 Feb 2025 03:46PM UTC coverage: 85.051% (+0.3%) from 84.722%
13591584831

Pull #3067

github

web-flow
Merge 08055e996 into c26fde666
Pull Request #3067: Implement user-configurable random number stride

36 of 44 new or added lines in 8 files covered. (81.82%)

3588 existing lines in 111 files now uncovered.

51062 of 60037 relevant lines covered (85.05%)

32650986.73 hits per line

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

86.24
/src/output.cpp
1
#include "openmc/output.h"
2

3
#include <algorithm> // for transform, max
4
#include <cstdio>    // for stdout
5
#include <cstring>   // for strlen
6
#include <ctime>     // for time, localtime
7
#include <fstream>
8
#include <iomanip> // for setw, setprecision, put_time
9
#include <ios>     // for fixed, scientific, left
10
#include <iostream>
11
#include <sstream>
12
#include <unordered_map>
13
#include <utility> // for pair
14

15
#include <fmt/core.h>
16
#include <fmt/ostream.h>
17
#ifdef _OPENMP
18
#include <omp.h>
19
#endif
20
#include "xtensor/xview.hpp"
21

22
#include "openmc/capi.h"
23
#include "openmc/cell.h"
24
#include "openmc/constants.h"
25
#include "openmc/eigenvalue.h"
26
#include "openmc/error.h"
27
#include "openmc/geometry.h"
28
#include "openmc/lattice.h"
29
#include "openmc/math_functions.h"
30
#include "openmc/message_passing.h"
31
#include "openmc/mgxs_interface.h"
32
#include "openmc/nuclide.h"
33
#include "openmc/plot.h"
34
#include "openmc/random_ray/flat_source_domain.h"
35
#include "openmc/reaction.h"
36
#include "openmc/settings.h"
37
#include "openmc/simulation.h"
38
#include "openmc/surface.h"
39
#include "openmc/tallies/derivative.h"
40
#include "openmc/tallies/filter.h"
41
#include "openmc/tallies/tally.h"
42
#include "openmc/tallies/tally_scoring.h"
43
#include "openmc/timer.h"
44

45
namespace openmc {
46

47
//==============================================================================
48

49
void title()
5,652✔
50
{
51
  fmt::print("                                %%%%%%%%%%%%%%%\n"
4,700✔
52
             "                           %%%%%%%%%%%%%%%%%%%%%%%%\n"
53
             "                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
54
             "                      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
55
             "                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
56
             "                   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
57
             "                                    %%%%%%%%%%%%%%%%%%%%%%%%\n"
58
             "                                     %%%%%%%%%%%%%%%%%%%%%%%%\n"
59
             "                 ###############      %%%%%%%%%%%%%%%%%%%%%%%%\n"
60
             "                ##################     %%%%%%%%%%%%%%%%%%%%%%%\n"
61
             "                ###################     %%%%%%%%%%%%%%%%%%%%%%%\n"
62
             "                ####################     %%%%%%%%%%%%%%%%%%%%%%\n"
63
             "                #####################     %%%%%%%%%%%%%%%%%%%%%\n"
64
             "                ######################     %%%%%%%%%%%%%%%%%%%%\n"
65
             "                #######################     %%%%%%%%%%%%%%%%%%\n"
66
             "                 #######################     %%%%%%%%%%%%%%%%%\n"
67
             "                 ######################     %%%%%%%%%%%%%%%%%\n"
68
             "                  ####################     %%%%%%%%%%%%%%%%%\n"
69
             "                    #################     %%%%%%%%%%%%%%%%%\n"
70
             "                     ###############     %%%%%%%%%%%%%%%%\n"
71
             "                       ############     %%%%%%%%%%%%%%%\n"
72
             "                          ########     %%%%%%%%%%%%%%\n"
73
             "                                      %%%%%%%%%%%\n\n");
74

75
  // Write version information
76
  fmt::print(
4,700✔
77
    "                 | The OpenMC Monte Carlo Code\n"
78
    "       Copyright | 2011-2025 MIT, UChicago Argonne LLC, and contributors\n"
79
    "         License | https://docs.openmc.org/en/latest/license.html\n"
80
    "         Version | {}.{}.{}{}{}\n",
81
    VERSION_MAJOR, VERSION_MINOR, VERSION_RELEASE, VERSION_DEV ? "-dev" : "",
11,304✔
82
    VERSION_COMMIT_COUNT);
83
  fmt::print("     Commit Hash | {}\n", VERSION_COMMIT_HASH);
4,700✔
84

85
  // Write the date and time
86
  fmt::print("       Date/Time | {}\n", time_stamp());
11,304✔
87

88
#ifdef OPENMC_MPI
89
  // Write number of processors
90
  fmt::print("   MPI Processes | {}\n", mpi::n_procs);
1,912✔
91
#endif
92

93
#ifdef _OPENMP
94
  // Write number of OpenMP threads
95
  fmt::print("  OpenMP Threads | {}\n", omp_get_max_threads());
5,690✔
96
#endif
97
  fmt::print("\n");
5,652✔
98
  std::fflush(stdout);
5,652✔
99
}
5,652✔
100

101
//==============================================================================
102

103
std::string header(const char* msg)
35,750✔
104
{
105
  // Determine how many times to repeat the '=' character.
106
  int n_prefix = (63 - strlen(msg)) / 2;
35,750✔
107
  int n_suffix = n_prefix;
35,750✔
108
  if ((strlen(msg) % 2) == 0)
35,750✔
109
    ++n_suffix;
8,191✔
110

111
  // Convert to uppercase.
112
  std::string upper(msg);
35,750✔
113
  std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
35,750✔
114

115
  // Add ===>  <=== markers.
116
  std::stringstream out;
35,750✔
117
  out << ' ';
35,750✔
118
  for (int i = 0; i < n_prefix; i++)
923,733✔
119
    out << '=';
887,983✔
120
  out << ">     " << upper << "     <";
35,750✔
121
  for (int i = 0; i < n_suffix; i++)
931,924✔
122
    out << '=';
896,174✔
123

124
  return out.str();
71,500✔
125
}
35,750✔
126

127
std::string header(const std::string& msg)
19,819✔
128
{
129
  return header(msg.c_str());
19,819✔
130
}
131

132
void header(const char* msg, int level)
15,931✔
133
{
134
  auto out = header(msg);
15,931✔
135

136
  // Print header based on verbosity level.
137
  if (settings::verbosity >= level) {
15,931✔
138
    fmt::print("\n{}\n\n", out);
12,900✔
139
    std::fflush(stdout);
15,581✔
140
  }
141
}
15,931✔
142

143
//==============================================================================
144

145
std::string time_stamp()
17,223✔
146
{
147
  std::stringstream ts;
17,223✔
148
  std::time_t t = std::time(nullptr); // get time now
17,223✔
149
  ts << std::put_time(std::localtime(&t), "%Y-%m-%d %H:%M:%S");
17,223✔
150
  return ts.str();
34,446✔
151
}
17,223✔
152

153
//==============================================================================
154

155
void print_particle(Particle& p)
36✔
156
{
157
  // Display particle type and ID.
158
  switch (p.type()) {
36✔
159
  case ParticleType::neutron:
36✔
160
    fmt::print("Neutron ");
30✔
161
    break;
36✔
UNCOV
162
  case ParticleType::photon:
×
163
    fmt::print("Photon ");
×
164
    break;
×
165
  case ParticleType::electron:
×
166
    fmt::print("Electron ");
×
167
    break;
×
168
  case ParticleType::positron:
×
169
    fmt::print("Positron ");
×
170
    break;
×
171
  default:
×
172
    fmt::print("Unknown Particle ");
×
173
  }
174
  fmt::print("{}\n", p.id());
66✔
175

176
  // Display particle geometry hierarchy.
177
  for (auto i = 0; i < p.n_coord(); i++) {
72✔
178
    fmt::print("  Level {}\n", i);
30✔
179

180
    if (p.coord(i).cell != C_NONE) {
36✔
181
      const Cell& c {*model::cells[p.coord(i).cell]};
36✔
182
      fmt::print("    Cell             = {}\n", c.id_);
72✔
183
    }
184

185
    if (p.coord(i).universe != C_NONE) {
36✔
186
      const Universe& u {*model::universes[p.coord(i).universe]};
36✔
187
      fmt::print("    Universe         = {}\n", u.id_);
72✔
188
    }
189

190
    if (p.coord(i).lattice != C_NONE) {
36✔
UNCOV
191
      const Lattice& lat {*model::lattices[p.coord(i).lattice]};
×
192
      fmt::print("    Lattice          = {}\n", lat.id_);
×
193
      fmt::print("    Lattice position = ({},{},{})\n", p.coord(i).lattice_i[0],
×
194
        p.coord(i).lattice_i[1], p.coord(i).lattice_i[2]);
×
195
    }
196

197
    fmt::print("    r = {}\n", p.coord(i).r);
66✔
198
    fmt::print("    u = {}\n", p.coord(i).u);
72✔
199
  }
200

201
  // Display miscellaneous info.
202
  if (p.surface() != SURFACE_NONE) {
36✔
203
    // Surfaces identifiers are >= 1, but indices are >= 0 so we need -1
UNCOV
204
    const Surface& surf {*model::surfaces[p.surface_index()]};
×
205
    fmt::print("  Surface = {}\n", (p.surface() > 0) ? surf.id_ : -surf.id_);
×
206
  }
207
  fmt::print("  Weight = {}\n", p.wgt());
66✔
208
  if (settings::run_CE) {
36✔
209
    fmt::print("  Energy = {}\n", p.E());
72✔
210
  } else {
UNCOV
211
    fmt::print("  Energy Group = {}\n", p.g());
×
212
  }
213
  fmt::print("  Delayed Group = {}\n\n", p.delayed_group());
66✔
214
}
36✔
215

216
//==============================================================================
217

218
void print_plot()
288✔
219
{
220
  header("PLOTTING SUMMARY", 5);
288✔
221
  if (settings::verbosity < 5)
288✔
UNCOV
222
    return;
×
223

224
  for (const auto& pl : model::plots) {
864✔
225
    fmt::print("Plot ID: {}\n", pl->id());
1,056✔
226
    fmt::print("Plot file: {}\n", pl->path_plot());
1,056✔
227
    fmt::print("Universe depth: {}\n", pl->level());
1,056✔
228
    pl->print_info(); // prints type-specific plot info
576✔
229
    fmt::print("\n");
576✔
230
  }
231
}
232

233
//==============================================================================
234

UNCOV
235
void print_overlap_check()
×
236
{
237
#ifdef OPENMC_MPI
238
  vector<int64_t> temp(model::overlap_check_count);
239
  MPI_Reduce(temp.data(), model::overlap_check_count.data(),
240
    model::overlap_check_count.size(), MPI_INT64_T, MPI_SUM, 0, mpi::intracomm);
241
#endif
242

UNCOV
243
  if (mpi::master) {
×
244
    header("cell overlap check summary", 1);
×
245
    fmt::print(" Cell ID      No. Overlap Checks\n");
×
246

UNCOV
247
    vector<int32_t> sparse_cell_ids;
×
248
    for (int i = 0; i < model::cells.size(); i++) {
×
249
      fmt::print(
×
250
        " {:8} {:17}\n", model::cells[i]->id_, model::overlap_check_count[i]);
×
251
      if (model::overlap_check_count[i] < 10) {
×
252
        sparse_cell_ids.push_back(model::cells[i]->id_);
×
253
      }
254
    }
255

UNCOV
256
    fmt::print("\n There were {} cells with less than 10 overlap checks\n",
×
257
      sparse_cell_ids.size());
×
258
    for (auto id : sparse_cell_ids) {
×
259
      fmt::print(" {}", id);
×
260
    }
UNCOV
261
    fmt::print("\n");
×
262
  }
263
}
264

265
//==============================================================================
266

UNCOV
267
void print_usage()
×
268
{
UNCOV
269
  if (mpi::master) {
×
270
    fmt::print(
×
271
      "Usage: openmc [options] [path]\n\n"
272
      "Options:\n"
273
      "  -c, --volume           Run in stochastic volume calculation mode\n"
274
      "  -g, --geometry-debug   Run with geometry debugging on\n"
275
      "  -n, --particles        Number of particles per generation\n"
276
      "  -p, --plot             Run in plotting mode\n"
277
      "  -r, --restart          Restart a previous run from a state point\n"
278
      "                         or a particle restart file\n"
279
      "  -s, --threads          Number of OpenMP threads\n"
280
      "  -t, --track            Write tracks for all particles (up to "
281
      "max_tracks)\n"
282
      "  -e, --event            Run using event-based parallelism\n"
283
      "  -v, --version          Show version information\n"
284
      "  -h, --help             Show this message\n");
285
  }
286
}
287

288
//==============================================================================
289

290
void print_version()
12✔
291
{
292
  if (mpi::master) {
12✔
293
    fmt::print("OpenMC version {}.{}.{}{}{}\n", VERSION_MAJOR, VERSION_MINOR,
10✔
294
      VERSION_RELEASE, VERSION_DEV ? "-dev" : "", VERSION_COMMIT_COUNT);
24✔
295
    fmt::print("Commit hash: {}\n", VERSION_COMMIT_HASH);
12✔
296
    fmt::print("Copyright (c) 2011-2025 MIT, UChicago Argonne LLC, and "
12✔
297
               "contributors\nMIT/X license at "
298
               "<https://docs.openmc.org/en/latest/license.html>\n");
299
  }
300
}
12✔
301

302
//==============================================================================
303

304
void print_build_info()
12✔
305
{
306
  const std::string n("no");
12✔
307
  const std::string y("yes");
12✔
308

309
  std::string mpi(n);
12✔
310
  std::string phdf5(n);
12✔
311
  std::string dagmc(n);
12✔
312
  std::string libmesh(n);
12✔
313
  std::string png(n);
12✔
314
  std::string profiling(n);
12✔
315
  std::string coverage(n);
12✔
316
  std::string mcpl(n);
12✔
317
  std::string ncrystal(n);
12✔
318
  std::string uwuw(n);
12✔
319

320
#ifdef PHDF5
321
  phdf5 = y;
5✔
322
#endif
323
#ifdef OPENMC_MPI
324
  mpi = y;
5✔
325
#endif
326
#ifdef DAGMC
327
  dagmc = y;
1✔
328
#endif
329
#ifdef LIBMESH
330
  libmesh = y;
2✔
331
#endif
332
#ifdef OPENMC_MCPL
333
  mcpl = y;
12✔
334
#endif
335
#ifdef NCRYSTAL
336
  ncrystal = y;
1✔
337
#endif
338
#ifdef USE_LIBPNG
339
  png = y;
12✔
340
#endif
341
#ifdef PROFILINGBUILD
342
  profiling = y;
343
#endif
344
#ifdef COVERAGEBUILD
345
  coverage = y;
12✔
346
#endif
347
#ifdef OPENMC_UWUW
348
  uwuw = y;
1✔
349
#endif
350

351
  // Wraps macro variables in quotes
352
#define STRINGIFY(x) STRINGIFY2(x)
353
#define STRINGIFY2(x) #x
354

355
  if (mpi::master) {
12✔
356
    fmt::print("Build type:            {}\n", STRINGIFY(BUILD_TYPE));
12✔
357
    fmt::print("Compiler ID:           {} {}\n", STRINGIFY(COMPILER_ID),
12✔
358
      STRINGIFY(COMPILER_VERSION));
359
    fmt::print("MPI enabled:           {}\n", mpi);
12✔
360
    fmt::print("Parallel HDF5 enabled: {}\n", phdf5);
12✔
361
    fmt::print("PNG support:           {}\n", png);
12✔
362
    fmt::print("DAGMC support:         {}\n", dagmc);
12✔
363
    fmt::print("libMesh support:       {}\n", libmesh);
12✔
364
    fmt::print("MCPL support:          {}\n", mcpl);
12✔
365
    fmt::print("NCrystal support:      {}\n", ncrystal);
12✔
366
    fmt::print("Coverage testing:      {}\n", coverage);
12✔
367
    fmt::print("Profiling flags:       {}\n", profiling);
12✔
368
    fmt::print("UWUW support:          {}\n", uwuw);
12✔
369
  }
370
}
12✔
371

372
//==============================================================================
373

374
void print_columns()
2,874✔
375
{
376
  if (settings::entropy_on) {
2,874✔
377
    fmt::print("  Bat./Gen.      k       Entropy         Average k \n"
339✔
378
               "  =========   ========   ========   ====================\n");
379
  } else {
380
    fmt::print("  Bat./Gen.      k            Average k\n"
2,535✔
381
               "  =========   ========   ====================\n");
382
  }
383
}
2,874✔
384

385
//==============================================================================
386

387
void print_generation()
56,567✔
388
{
389
  // Determine overall generation index and number of active generations
390
  int idx = overall_generation() - 1;
56,567✔
391
  int n = simulation::current_batch > settings::n_inactive
113,134✔
392
            ? settings::gen_per_batch * simulation::n_realizations +
56,567✔
393
                simulation::current_gen
394
            : 0;
395

396
  // write out batch/generation and generation k-effective
397
  auto batch_and_gen = std::to_string(simulation::current_batch) + "/" +
113,134✔
398
                       std::to_string(simulation::current_gen);
113,134✔
399
  fmt::print("  {:>9}   {:8.5f}", batch_and_gen, simulation::k_generation[idx]);
103,417✔
400

401
  // write out entropy info
402
  if (settings::entropy_on) {
56,567✔
403
    fmt::print("   {:8.5f}", simulation::entropy[idx]);
20,370✔
404
  }
405

406
  if (n > 1) {
56,567✔
407
    fmt::print("   {:8.5f} +/-{:8.5f}", simulation::keff, simulation::keff_std);
42,734✔
408
  }
409
  fmt::print("\n");
46,850✔
410
  std::fflush(stdout);
56,567✔
411
}
56,567✔
412

413
//==============================================================================
414

415
void show_time(const char* label, double secs, int indent_level)
58,134✔
416
{
417
  int width = 33 - indent_level * 2;
58,134✔
418
  fmt::print("{0:{1}} {2:<{3}} = {4:>10.4e} seconds\n", "", 2 * indent_level,
106,357✔
419
    label, width, secs);
420
}
58,134✔
421

422
void show_rate(const char* label, double particles_per_sec)
6,608✔
423
{
424
  fmt::print(" {:<33} = {:.6} particles/second\n", label, particles_per_sec);
6,608✔
425
}
6,608✔
426

427
void print_runtime()
4,598✔
428
{
429
  using namespace simulation;
430

431
  // display header block
432
  header("Timing Statistics", 6);
4,598✔
433
  if (settings::verbosity < 6)
4,598✔
UNCOV
434
    return;
×
435

436
  // display time elapsed for various sections
437
  show_time("Total time for initialization", time_initialize.elapsed());
4,598✔
438
  show_time("Reading cross sections", time_read_xs.elapsed(), 1);
4,598✔
439
  show_time("Total time in simulation",
4,598✔
440
    time_inactive.elapsed() + time_active.elapsed());
4,598✔
441
  show_time("Time in transport only", time_transport.elapsed(), 1);
4,598✔
442
  if (settings::event_based) {
4,598✔
443
    show_time("Particle initialization", time_event_init.elapsed(), 2);
126✔
444
    show_time("XS lookups", time_event_calculate_xs.elapsed(), 2);
126✔
445
    show_time("Advancing", time_event_advance_particle.elapsed(), 2);
126✔
446
    show_time("Surface crossings", time_event_surface_crossing.elapsed(), 2);
126✔
447
    show_time("Collisions", time_event_collision.elapsed(), 2);
126✔
448
    show_time("Particle death", time_event_death.elapsed(), 2);
126✔
449
  }
450
  if (settings::run_mode == RunMode::EIGENVALUE) {
4,598✔
451
    show_time("Time in inactive batches", time_inactive.elapsed(), 1);
2,790✔
452
  }
453
  show_time("Time in active batches", time_active.elapsed(), 1);
4,598✔
454
  if (settings::run_mode == RunMode::EIGENVALUE) {
4,598✔
455
    show_time("Time synchronizing fission bank", time_bank.elapsed(), 1);
2,790✔
456
    show_time("Sampling source sites", time_bank_sample.elapsed(), 2);
2,790✔
457
    show_time("SEND/RECV source sites", time_bank_sendrecv.elapsed(), 2);
2,790✔
458
  }
459
  show_time("Time accumulating tallies", time_tallies.elapsed(), 1);
4,598✔
460
  show_time("Time writing statepoints", time_statepoint.elapsed(), 1);
4,598✔
461
  show_time("Total time for finalization", time_finalize.elapsed());
4,598✔
462
  show_time("Total time elapsed", time_total.elapsed());
4,598✔
463

464
  // Calculate particle rate in active/inactive batches
465
  int n_active = simulation::current_batch - settings::n_inactive;
4,598✔
466
  double speed_inactive = 0.0;
4,598✔
467
  double speed_active;
468
  if (settings::restart_run) {
4,598✔
469
    if (simulation::restart_batch < settings::n_inactive) {
37✔
UNCOV
470
      speed_inactive = (settings::n_particles *
×
UNCOV
471
                         (settings::n_inactive - simulation::restart_batch) *
×
UNCOV
472
                         settings::gen_per_batch) /
×
473
                       time_inactive.elapsed();
×
474
      speed_active =
×
475
        (settings::n_particles * n_active * settings::gen_per_batch) /
×
476
        time_active.elapsed();
×
477
    } else {
478
      speed_active = (settings::n_particles *
74✔
479
                       (settings::n_batches - simulation::restart_batch) *
37✔
480
                       settings::gen_per_batch) /
37✔
481
                     time_active.elapsed();
37✔
482
    }
483
  } else {
484
    if (settings::n_inactive > 0) {
4,561✔
485
      speed_inactive = (settings::n_particles * settings::n_inactive *
4,020✔
486
                         settings::gen_per_batch) /
2,010✔
487
                       time_inactive.elapsed();
2,010✔
488
    }
489
    speed_active =
4,561✔
490
      (settings::n_particles * n_active * settings::gen_per_batch) /
4,561✔
491
      time_active.elapsed();
4,561✔
492
  }
493

494
  // display calculation rate
495
  if (!(settings::restart_run &&
4,598✔
496
        (simulation::restart_batch >= settings::n_inactive)) &&
37✔
497
      settings::n_inactive > 0) {
4,561✔
498
    show_rate("Calculation Rate (inactive)", speed_inactive);
2,010✔
499
  }
500
  show_rate("Calculation Rate (active)", speed_active);
4,598✔
501
}
502

503
//==============================================================================
504

505
std::pair<double, double> mean_stdev(const double* x, int n)
14,811,669✔
506
{
507
  double mean = x[static_cast<int>(TallyResult::SUM)] / n;
14,811,669✔
508
  double stdev =
509
    n > 1 ? std::sqrt(std::max(0.0,
29,614,422✔
510
              (x[static_cast<int>(TallyResult::SUM_SQ)] / n - mean * mean) /
29,614,422✔
511
                (n - 1)))
14,802,753✔
512
          : 0.0;
14,811,669✔
513
  return {mean, stdev};
14,811,669✔
514
}
515

516
//==============================================================================
517

518
void print_results()
4,598✔
519
{
520
  // display header block for results
521
  header("Results", 4);
4,598✔
522
  if (settings::verbosity < 4)
4,598✔
UNCOV
523
    return;
×
524

525
  // Calculate t-value for confidence intervals
526
  int n = simulation::n_realizations;
4,598✔
527
  double alpha, t_n1, t_n3;
528
  if (settings::confidence_intervals) {
4,598✔
529
    alpha = 1.0 - CONFIDENCE_LEVEL;
12✔
530
    t_n1 = t_percentile(1.0 - alpha / 2.0, n - 1);
12✔
531
    t_n3 = t_percentile(1.0 - alpha / 2.0, n - 3);
12✔
532
  } else {
533
    t_n1 = 1.0;
4,586✔
534
    t_n3 = 1.0;
4,586✔
535
  }
536

537
  // write global tallies
538
  const auto& gt = simulation::global_tallies;
4,598✔
539
  double mean, stdev;
540
  if (n > 1) {
4,598✔
541
    if (settings::run_mode == RunMode::EIGENVALUE) {
4,463✔
542
      std::tie(mean, stdev) = mean_stdev(&gt(GlobalTally::K_COLLISION, 0), n);
2,754✔
543
      fmt::print(" k-effective (Collision)     = {:.5f} +/- {:.5f}\n", mean,
2,277✔
544
        t_n1 * stdev);
2,754✔
545
      std::tie(mean, stdev) = mean_stdev(&gt(GlobalTally::K_TRACKLENGTH, 0), n);
2,754✔
546
      fmt::print(" k-effective (Track-length)  = {:.5f} +/- {:.5f}\n", mean,
2,277✔
547
        t_n1 * stdev);
2,754✔
548
      std::tie(mean, stdev) = mean_stdev(&gt(GlobalTally::K_ABSORPTION, 0), n);
2,754✔
549
      fmt::print(" k-effective (Absorption)    = {:.5f} +/- {:.5f}\n", mean,
2,277✔
550
        t_n1 * stdev);
2,754✔
551
      if (n > 3) {
2,754✔
552
        double k_combined[2];
553
        openmc_get_keff(k_combined);
2,694✔
554
        fmt::print(" Combined k-effective        = {:.5f} +/- {:.5f}\n",
2,694✔
555
          k_combined[0], k_combined[1]);
556
      }
557
    }
558
    std::tie(mean, stdev) = mean_stdev(&gt(GlobalTally::LEAKAGE, 0), n);
4,463✔
559
    fmt::print(
3,690✔
560
      " Leakage Fraction            = {:.5f} +/- {:.5f}\n", mean, t_n1 * stdev);
8,926✔
561
  } else {
562
    if (mpi::master)
135✔
563
      warning("Could not compute uncertainties -- only one "
135✔
564
              "active batch simulated!");
565

566
    if (settings::run_mode == RunMode::EIGENVALUE) {
135✔
567
      fmt::print(" k-effective (Collision)    = {:.5f}\n",
30✔
568
        gt(GlobalTally::K_COLLISION, TallyResult::SUM) / n);
36✔
569
      fmt::print(" k-effective (Track-length) = {:.5f}\n",
30✔
570
        gt(GlobalTally::K_TRACKLENGTH, TallyResult::SUM) / n);
36✔
571
      fmt::print(" k-effective (Absorption)   = {:.5f}\n",
30✔
572
        gt(GlobalTally::K_ABSORPTION, TallyResult::SUM) / n);
72✔
573
    }
574
    fmt::print(" Leakage Fraction           = {:.5f}\n",
111✔
575
      gt(GlobalTally::LEAKAGE, TallyResult::SUM) / n);
270✔
576
  }
577
  fmt::print("\n");
3,801✔
578
  std::fflush(stdout);
4,598✔
579
}
580

581
//==============================================================================
582

583
const std::unordered_map<int, const char*> score_names = {
584
  {SCORE_FLUX, "Flux"},
585
  {SCORE_TOTAL, "Total Reaction Rate"},
586
  {SCORE_SCATTER, "Scattering Rate"},
587
  {SCORE_NU_SCATTER, "Scattering Production Rate"},
588
  {SCORE_ABSORPTION, "Absorption Rate"},
589
  {SCORE_FISSION, "Fission Rate"},
590
  {SCORE_NU_FISSION, "Nu-Fission Rate"},
591
  {SCORE_KAPPA_FISSION, "Kappa-Fission Rate"},
592
  {SCORE_EVENTS, "Events"},
593
  {SCORE_DECAY_RATE, "Decay Rate"},
594
  {SCORE_DELAYED_NU_FISSION, "Delayed-Nu-Fission Rate"},
595
  {SCORE_PROMPT_NU_FISSION, "Prompt-Nu-Fission Rate"},
596
  {SCORE_INVERSE_VELOCITY, "Flux-Weighted Inverse Velocity"},
597
  {SCORE_FISS_Q_PROMPT, "Prompt fission power"},
598
  {SCORE_FISS_Q_RECOV, "Recoverable fission power"},
599
  {SCORE_CURRENT, "Current"},
600
  {SCORE_PULSE_HEIGHT, "pulse-height"},
601
};
602

603
//! Create an ASCII output file showing all tally results.
604

605
void write_tallies()
5,164✔
606
{
607
  if (model::tallies.empty())
5,164✔
608
    return;
1,647✔
609

610
  // Set filename for tallies_out
611
  std::string filename = fmt::format("{}tallies.out", settings::path_output);
2,906✔
612

613
  // Open the tallies.out file.
614
  std::ofstream tallies_out;
3,517✔
615
  tallies_out.open(filename, std::ios::out | std::ios::trunc);
3,517✔
616

617
  // Loop over each tally.
618
  for (auto i_tally = 0; i_tally < model::tallies.size(); ++i_tally) {
23,336✔
619
    const auto& tally {*model::tallies[i_tally]};
19,819✔
620

621
    // Write header block.
622
    std::string tally_header("TALLY " + std::to_string(tally.id_));
19,819✔
623
    if (!tally.name_.empty())
19,819✔
624
      tally_header += ": " + tally.name_;
1,635✔
625
    fmt::print(tallies_out, "{}\n\n", header(tally_header));
39,638✔
626

627
    if (!tally.writable_) {
19,819✔
628
      fmt::print(tallies_out, " Internal\n\n");
368✔
629
      continue;
368✔
630
    }
631

632
    // Calculate t-value for confidence intervals
633
    double t_value = 1;
19,451✔
634
    if (settings::confidence_intervals) {
19,451✔
635
      auto alpha = 1 - CONFIDENCE_LEVEL;
12✔
636
      t_value = t_percentile(1 - alpha * 0.5, tally.n_realizations_ - 1);
12✔
637
    }
638

639
    // Write derivative information.
640
    if (tally.deriv_ != C_NONE) {
19,451✔
641
      const auto& deriv {model::tally_derivs[tally.deriv_]};
240✔
642
      switch (deriv.variable) {
240✔
643
      case DerivativeVariable::DENSITY:
96✔
644
        fmt::print(tallies_out, " Density derivative Material {}\n",
96✔
645
          deriv.diff_material);
96✔
646
        break;
96✔
647
      case DerivativeVariable::NUCLIDE_DENSITY:
96✔
648
        fmt::print(tallies_out,
96✔
649
          " Nuclide density derivative Material {} Nuclide {}\n",
650
          deriv.diff_material, data::nuclides[deriv.diff_nuclide]->name_);
96✔
651
        break;
96✔
652
      case DerivativeVariable::TEMPERATURE:
48✔
653
        fmt::print(tallies_out, " Temperature derivative Material {}\n",
48✔
654
          deriv.diff_material);
48✔
655
        break;
48✔
UNCOV
656
      default:
×
UNCOV
657
        fatal_error(fmt::format("Differential tally dependent variable for "
×
658
                                "tally {} not defined in output.cpp",
659
          tally.id_));
×
660
      }
661
    }
662

663
    // Initialize Filter Matches Object
664
    vector<FilterMatch> filter_matches;
38,902✔
665
    // Allocate space for tally filter matches
666
    filter_matches.resize(model::tally_filters.size());
19,451✔
667

668
    // Loop over all filter bin combinations.
669
    auto filter_iter = FilterBinIter(tally, false, &filter_matches);
19,451✔
670
    auto end = FilterBinIter(tally, true, &filter_matches);
19,451✔
671
    for (; filter_iter != end; ++filter_iter) {
10,127,423✔
672
      auto filter_index = filter_iter.index_;
10,107,972✔
673

674
      // Print info about this combination of filter bins.  The stride check
675
      // prevents redundant output.
676
      int indent = 0;
10,107,972✔
677
      for (auto i = 0; i < tally.filters().size(); ++i) {
31,790,860✔
678
        if (filter_index % tally.strides(i) == 0) {
21,682,888✔
679
          auto i_filt = tally.filters(i);
14,993,211✔
680
          const auto& filt {*model::tally_filters[i_filt]};
14,993,211✔
681
          auto& match {filter_matches[i_filt]};
14,993,211✔
682
          fmt::print(tallies_out, "{0:{1}}{2}\n", "", indent + 1,
29,986,422✔
683
            filt.text_label(match.i_bin_));
29,986,422✔
684
        }
685
        indent += 2;
21,682,888✔
686
      }
687

688
      // Loop over all nuclide and score combinations.
689
      int score_index = 0;
10,107,972✔
690
      for (auto i_nuclide : tally.nuclides_) {
21,774,024✔
691
        // Write label for this nuclide bin.
692
        if (i_nuclide == -1) {
11,666,052✔
693
          fmt::print(tallies_out, "{0:{1}}Total Material\n", "", indent + 1);
17,142,648✔
694
        } else {
695
          if (settings::run_CE) {
3,094,728✔
696
            fmt::print(tallies_out, "{0:{1}}{2}\n", "", indent + 1,
3,094,320✔
697
              data::nuclides[i_nuclide]->name_);
3,094,320✔
698
          } else {
699
            fmt::print(tallies_out, "{0:{1}}{2}\n", "", indent + 1,
408✔
700
              data::mg.nuclides_[i_nuclide].name);
408✔
701
          }
702
        }
703

704
        // Write the score, mean, and uncertainty.
705
        indent += 2;
11,666,052✔
706
        for (auto score : tally.scores_) {
26,464,996✔
707
          std::string score_name =
708
            score > 0 ? reaction_name(score) : score_names.at(score);
14,798,944✔
709
          double mean, stdev;
710
          std::tie(mean, stdev) =
14,798,944✔
711
            mean_stdev(&tally.results_(filter_index, score_index, 0),
14,798,944✔
712
              tally.n_realizations_);
29,597,888✔
713
          fmt::print(tallies_out, "{0:{1}}{2:<36} {3:.6} +/- {4:.6}\n", "",
14,798,944✔
714
            indent + 1, score_name, mean, t_value * stdev);
14,798,944✔
715
          score_index += 1;
14,798,944✔
716
        }
14,798,944✔
717
        indent -= 2;
11,666,052✔
718
      }
719
    }
720
  }
19,819✔
721
}
3,517✔
722

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