• 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

81.22
/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()
6,293✔
50
{
51
  fmt::print("                                %%%%%%%%%%%%%%%\n"
5,160✔
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(
5,160✔
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" : "",
12,586✔
82
    VERSION_COMMIT_COUNT);
83
  fmt::print("     Commit Hash | {}\n", VERSION_COMMIT_HASH);
5,160✔
84

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

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

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

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

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

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

115
  // Add ===>  <=== markers.
116
  std::stringstream out;
36,955✔
117
  out << ' ';
36,955✔
118
  for (int i = 0; i < n_prefix; i++)
944,789✔
119
    out << '=';
907,834✔
120
  out << ">     " << upper << "     <";
36,955✔
121
  for (int i = 0; i < n_suffix; i++)
952,504✔
122
    out << '=';
915,549✔
123

124
  return out.str();
73,910✔
125
}
36,955✔
126

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

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

136
  // Print header based on verbosity level.
137
  if (settings::verbosity >= level) {
17,498✔
138
    fmt::print("\n{}\n\n", out);
13,984✔
139
    std::fflush(stdout);
17,195✔
140
  }
141
}
17,498✔
142

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

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

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

155
void print_particle(Particle& p)
33✔
156
{
157
  // Display particle type and ID.
158
  switch (p.type()) {
33!
159
  case ParticleType::neutron:
33✔
160
    fmt::print("Neutron ");
27✔
161
    break;
33✔
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());
60✔
175

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

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

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

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

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

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

217
//==============================================================================
218

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

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

234
//==============================================================================
235

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

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

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

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

266
//==============================================================================
267

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

289
//==============================================================================
290

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

303
//==============================================================================
304

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

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

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

348
  // Wraps macro variables in quotes
349
#define STRINGIFY(x) STRINGIFY2(x)
350
#define STRINGIFY2(x) #x
351

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

368
//==============================================================================
369

370
void print_columns()
3,002✔
371
{
372
  if (settings::entropy_on) {
3,002✔
373
    fmt::print("  Bat./Gen.      k       Entropy         Average k \n"
370✔
374
               "  =========   ========   ========   ====================\n");
375
  } else {
376
    fmt::print("  Bat./Gen.      k            Average k\n"
2,632✔
377
               "  =========   ========   ====================\n");
378
  }
379
}
3,002✔
380

381
//==============================================================================
382

383
void print_generation()
62,229✔
384
{
385
  // Determine overall generation index and number of active generations
386
  int idx = overall_generation() - 1;
62,229✔
387
  int n = simulation::current_batch > settings::n_inactive
124,458✔
388
            ? settings::gen_per_batch * simulation::n_realizations +
62,229✔
389
                simulation::current_gen
390
            : 0;
391

392
  // write out batch/generation and generation k-effective
393
  auto batch_and_gen = std::to_string(simulation::current_batch) + "/" +
124,458✔
394
                       std::to_string(simulation::current_gen);
124,458✔
395
  fmt::print("  {:>9}   {:8.5f}", batch_and_gen, simulation::k_generation[idx]);
113,200✔
396

397
  // write out entropy info
398
  if (settings::entropy_on) {
62,229✔
399
    fmt::print("   {:8.5f}", simulation::entropy[idx]);
20,640✔
400
  }
401

402
  if (n > 1) {
62,229✔
403
    fmt::print("   {:8.5f} +/-{:8.5f}", simulation::keff, simulation::keff_std);
44,701✔
404
  }
405
  fmt::print("\n");
50,971✔
406
  std::fflush(stdout);
62,229✔
407
}
62,229✔
408

409
//==============================================================================
410

411
void show_time(const char* label, double secs, int indent_level)
62,717✔
412
{
413
  int width = 33 - indent_level * 2;
62,717✔
414
  fmt::print("{0:{1}} {2:<{3}} = {4:>10.4e} seconds\n", "", 2 * indent_level,
113,879✔
415
    label, width, secs);
416
}
62,717✔
417

418
void show_rate(const char* label, double particles_per_sec)
7,099✔
419
{
420
  fmt::print(" {:<33} = {:.6} particles/second\n", label, particles_per_sec);
7,099✔
421
}
7,099✔
422

423
void print_runtime()
4,981✔
424
{
425
  using namespace simulation;
426

427
  // display header block
428
  header("Timing Statistics", 6);
4,981✔
429
  if (settings::verbosity < 6)
4,981!
430
    return;
×
431

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

460
  // Calculate particle rate in active/inactive batches
461
  int n_active = simulation::current_batch - settings::n_inactive;
4,981✔
462
  double speed_inactive = 0.0;
4,981✔
463
  double speed_active;
464
  if (settings::restart_run) {
4,981✔
465
    if (simulation::restart_batch < settings::n_inactive) {
34!
466
      speed_inactive = (settings::n_particles *
×
467
                         (settings::n_inactive - simulation::restart_batch) *
×
468
                         settings::gen_per_batch) /
×
469
                       time_inactive.elapsed();
×
470
      speed_active =
×
471
        (settings::n_particles * n_active * settings::gen_per_batch) /
×
472
        time_active.elapsed();
×
473
    } else {
474
      speed_active = (settings::n_particles *
68✔
475
                       (settings::n_batches - simulation::restart_batch) *
34✔
476
                       settings::gen_per_batch) /
34✔
477
                     time_active.elapsed();
34✔
478
    }
479
  } else {
480
    if (settings::n_inactive > 0) {
4,947✔
481
      speed_inactive = (settings::n_particles * settings::n_inactive *
4,236✔
482
                         settings::gen_per_batch) /
2,118✔
483
                       time_inactive.elapsed();
2,118✔
484
    }
485
    speed_active =
4,947✔
486
      (settings::n_particles * n_active * settings::gen_per_batch) /
4,947✔
487
      time_active.elapsed();
4,947✔
488
  }
489

490
  // display calculation rate
491
  if (!(settings::restart_run &&
4,981✔
492
        (simulation::restart_batch >= settings::n_inactive)) &&
34!
493
      settings::n_inactive > 0) {
4,947✔
494
    show_rate("Calculation Rate (inactive)", speed_inactive);
2,118✔
495
  }
496
  show_rate("Calculation Rate (active)", speed_active);
4,981✔
497
}
498

499
//==============================================================================
500

501
std::pair<double, double> mean_stdev(const double* x, int n)
14,053,841✔
502
{
503
  double mean = x[static_cast<int>(TallyResult::SUM)] / n;
14,053,841✔
504
  double stdev =
505
    n > 1 ? std::sqrt(std::max(0.0,
28,099,266✔
506
              (x[static_cast<int>(TallyResult::SUM_SQ)] / n - mean * mean) /
28,099,266✔
507
                (n - 1)))
14,045,425✔
508
          : 0.0;
14,053,841✔
509
  return {mean, stdev};
14,053,841✔
510
}
511

512
//==============================================================================
513

514
void print_results()
4,981✔
515
{
516
  // display header block for results
517
  header("Results", 4);
4,981✔
518
  if (settings::verbosity < 4)
4,981!
519
    return;
×
520

521
  // Calculate t-value for confidence intervals
522
  int n = simulation::n_realizations;
4,981✔
523
  double alpha, t_n1, t_n3;
524
  if (settings::confidence_intervals) {
4,981✔
525
    alpha = 1.0 - CONFIDENCE_LEVEL;
11✔
526
    t_n1 = t_percentile(1.0 - alpha / 2.0, n - 1);
11✔
527
    t_n3 = t_percentile(1.0 - alpha / 2.0, n - 3);
11✔
528
  } else {
529
    t_n1 = 1.0;
4,970✔
530
    t_n3 = 1.0;
4,970✔
531
  }
532

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

562
    if (settings::run_mode == RunMode::EIGENVALUE) {
232✔
563
      fmt::print(" k-effective (Collision)    = {:.5f}\n",
27✔
564
        gt(GlobalTally::K_COLLISION, TallyResult::SUM) / n);
33✔
565
      fmt::print(" k-effective (Track-length) = {:.5f}\n",
27✔
566
        gt(GlobalTally::K_TRACKLENGTH, TallyResult::SUM) / n);
33✔
567
      fmt::print(" k-effective (Absorption)   = {:.5f}\n",
27✔
568
        gt(GlobalTally::K_ABSORPTION, TallyResult::SUM) / n);
66✔
569
    }
570
    fmt::print(" Leakage Fraction           = {:.5f}\n",
189✔
571
      gt(GlobalTally::LEAKAGE, TallyResult::SUM) / n);
464✔
572
  }
573
  fmt::print("\n");
4,042✔
574
  std::fflush(stdout);
4,981✔
575
}
576

577
//==============================================================================
578

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

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

604
void write_tallies()
5,581✔
605
{
606
  if (model::tallies.empty())
5,581✔
607
    return;
1,763✔
608

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

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

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

620
    // Write header block.
621
    std::string tally_header("TALLY " + std::to_string(tally.id_));
19,457✔
622
    if (!tally.name_.empty())
19,457✔
623
      tally_header += ": " + tally.name_;
2,133✔
624
    fmt::print(tallies_out, "{}\n\n", header(tally_header));
38,914✔
625

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

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

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

662
    // Initialize Filter Matches Object
663
    vector<FilterMatch> filter_matches;
37,646✔
664
    // Allocate space for tally filter matches
665
    filter_matches.resize(model::tally_filters.size());
18,823✔
666

667
    // Loop over all filter bin combinations.
668
    auto filter_iter = FilterBinIter(tally, false, &filter_matches);
18,823✔
669
    auto end = FilterBinIter(tally, true, &filter_matches);
18,823✔
670
    for (; filter_iter != end; ++filter_iter) {
9,760,716✔
671
      auto filter_index = filter_iter.index_;
9,741,893✔
672

673
      // Print info about this combination of filter bins.  The stride check
674
      // prevents redundant output.
675
      int indent = 0;
9,741,893✔
676
      for (auto i = 0; i < tally.filters().size(); ++i) {
30,881,187✔
677
        if (filter_index % tally.strides(i) == 0) {
21,139,294✔
678
          auto i_filt = tally.filters(i);
14,679,362✔
679
          const auto& filt {*model::tally_filters[i_filt]};
14,679,362✔
680
          auto& match {filter_matches[i_filt]};
14,679,362✔
681
          fmt::print(tallies_out, "{0:{1}}{2}\n", "", indent + 1,
29,358,724✔
682
            filt.text_label(match.i_bin_));
29,358,724✔
683
        }
684
        indent += 2;
21,139,294✔
685
      }
686

687
      // Loop over all nuclide and score combinations.
688
      int score_index = 0;
9,741,893✔
689
      for (auto i_nuclide : tally.nuclides_) {
20,910,931✔
690
        // Write label for this nuclide bin.
691
        if (i_nuclide == -1) {
11,169,038✔
692
          fmt::print(tallies_out, "{0:{1}}Total Material\n", "", indent + 1);
16,666,632✔
693
        } else {
694
          if (settings::run_CE) {
2,835,722✔
695
            fmt::print(tallies_out, "{0:{1}}{2}\n", "", indent + 1,
2,835,348✔
696
              data::nuclides[i_nuclide]->name_);
2,835,348✔
697
          } else {
698
            fmt::print(tallies_out, "{0:{1}}{2}\n", "", indent + 1,
374✔
699
              data::mg.nuclides_[i_nuclide].name);
374✔
700
          }
701
        }
702

703
        // Write the score, mean, and uncertainty.
704
        indent += 2;
11,169,038✔
705
        for (auto score : tally.scores_) {
25,209,619✔
706
          std::string score_name =
707
            score > 0 ? reaction_name(score) : score_names.at(score);
14,040,581!
708
          double mean, stdev;
709
          std::tie(mean, stdev) =
14,040,581✔
710
            mean_stdev(&tally.results_(filter_index, score_index, 0),
14,040,581✔
711
              tally.n_realizations_);
28,081,162✔
712
          fmt::print(tallies_out, "{0:{1}}{2:<36} {3:.6} +/- {4:.6}\n", "",
14,040,581✔
713
            indent + 1, score_name, mean, t_value * stdev);
14,040,581✔
714
          score_index += 1;
14,040,581✔
715
        }
14,040,581✔
716
        indent -= 2;
11,169,038✔
717
      }
718
    }
719
  }
19,457✔
720
}
3,818✔
721

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