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

openmc-dev / openmc / 20197979645

13 Dec 2025 09:16PM UTC coverage: 82.118% (+0.008%) from 82.11%
20197979645

Pull #3675

github

web-flow
Merge 3fafce82c into bbfa18d72
Pull Request #3675: Extend level scattering to support incident photons

17013 of 23594 branches covered (72.11%)

Branch coverage included in aggregate %.

55 of 76 new or added lines in 4 files covered. (72.37%)

193 existing lines in 7 files now uncovered.

55125 of 64253 relevant lines covered (85.79%)

43453609.56 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,357✔
50
{
51
  fmt::print("                                %%%%%%%%%%%%%%%\n"
5,216✔
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,216✔
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,714✔
82
    VERSION_COMMIT_COUNT);
83
  fmt::print("     Commit Hash | {}\n", VERSION_COMMIT_HASH);
5,216✔
84

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

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

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

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

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

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

115
  // Add ===>  <=== markers.
116
  std::stringstream out;
36,699✔
117
  out << ' ';
36,699✔
118
  for (int i = 0; i < n_prefix; i++)
937,301✔
119
    out << '=';
900,602✔
120
  out << ">     " << upper << "     <";
36,699✔
121
  for (int i = 0; i < n_suffix; i++)
945,225✔
122
    out << '=';
908,526✔
123

124
  return out.str();
73,398✔
125
}
36,699✔
126

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

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

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

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

145
std::string time_stamp()
19,127✔
146
{
147
  std::stringstream ts;
19,127✔
148
  std::time_t t = std::time(nullptr); // get time now
19,127✔
149
  ts << std::put_time(std::localtime(&t), "%Y-%m-%d %H:%M:%S");
19,127✔
150
  return ts.str();
38,254✔
151
}
19,127✔
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()
245✔
220
{
221
  header("PLOTTING SUMMARY", 5);
245✔
222
  if (settings::verbosity < 5)
245!
223
    return;
×
224

225
  for (const auto& pl : model::plots) {
644✔
226
    fmt::print("Plot ID: {}\n", pl->id());
726✔
227
    fmt::print("Plot file: {}\n", pl->path_plot());
726✔
228
    fmt::print("Universe depth: {}\n", pl->level());
726✔
229
    pl->print_info(); // prints type-specific plot info
399✔
230
    fmt::print("\n");
399✔
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");
×
263
  }
×
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
      "  -q, --verbosity        Output verbosity\n"
285
      "  -v, --version          Show version information\n"
286
      "  -h, --help             Show this message\n");
287
  }
UNCOV
288
}
×
289

290
//==============================================================================
291

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

304
//==============================================================================
305

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

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

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

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

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

369
//==============================================================================
370

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

382
//==============================================================================
383

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

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

398
  // write out entropy info
399
  if (settings::entropy_on) {
65,336✔
400
    fmt::print("   {:8.5f}", simulation::entropy[idx]);
20,350✔
401
  }
402

403
  if (n > 1) {
65,336✔
404
    fmt::print("   {:8.5f} +/-{:8.5f}", simulation::keff, simulation::keff_std);
48,097✔
405
  }
406
  fmt::print("\n");
53,454✔
407
  std::fflush(stdout);
65,336✔
408
}
65,336✔
409

410
//==============================================================================
411

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

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

424
void print_runtime()
5,042✔
425
{
426
  using namespace simulation;
427

428
  // display header block
429
  header("Timing Statistics", 6);
5,042✔
430
  if (settings::verbosity < 6)
5,042!
UNCOV
431
    return;
×
432

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

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

491
  // display calculation rate
492
  if (!(settings::restart_run &&
5,042✔
493
        (simulation::restart_batch >= settings::n_inactive)) &&
33!
494
      settings::n_inactive > 0) {
5,009✔
495
    show_rate("Calculation Rate (inactive)", speed_inactive);
2,136✔
496
  }
497
  show_rate("Calculation Rate (active)", speed_active);
5,042✔
498
}
499

500
//==============================================================================
501

502
std::pair<double, double> mean_stdev(const double* x, int n)
13,764,135✔
503
{
504
  double mean = x[static_cast<int>(TallyResult::SUM)] / n;
13,764,135✔
505
  double stdev =
506
    n > 1 ? std::sqrt(std::max(0.0,
27,520,383✔
507
              (x[static_cast<int>(TallyResult::SUM_SQ)] / n - mean * mean) /
27,520,383✔
508
                (n - 1)))
13,756,248✔
509
          : 0.0;
13,764,135✔
510
  return {mean, stdev};
13,764,135✔
511
}
512

513
//==============================================================================
514

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

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

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

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

578
//==============================================================================
579

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

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

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

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

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

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

621
    // Write header block.
622
    std::string tally_header("TALLY " + std::to_string(tally.id_));
18,922✔
623
    if (!tally.name_.empty())
18,922✔
624
      tally_header += ": " + tally.name_;
1,986✔
625
    fmt::print(tallies_out, "{}\n\n", header(tally_header));
37,844✔
626

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

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

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

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

668
    // Loop over all filter bin combinations.
669
    auto filter_iter = FilterBinIter(tally, false, &filter_matches);
18,524✔
670
    auto end = FilterBinIter(tally, true, &filter_matches);
18,524✔
671
    for (; filter_iter != end; ++filter_iter) {
9,468,377✔
672
      auto filter_index = filter_iter.index_;
9,449,853✔
673

674
      // Print info about this combination of filter bins.  The stride check
675
      // prevents redundant output.
676
      int indent = 0;
9,449,853✔
677
      for (auto i = 0; i < tally.filters().size(); ++i) {
29,815,424✔
678
        if (filter_index % tally.strides(i) == 0) {
20,365,571✔
679
          auto i_filt = tally.filters(i);
14,226,900✔
680
          const auto& filt {*model::tally_filters[i_filt]};
14,226,900✔
681
          auto& match {filter_matches[i_filt]};
14,226,900✔
682
          fmt::print(tallies_out, "{0:{1}}{2}\n", "", indent + 1,
28,453,800✔
683
            filt.text_label(match.i_bin_));
28,453,800✔
684
        }
685
        indent += 2;
20,365,571✔
686
      }
687

688
      // Loop over all nuclide and score combinations.
689
      int score_index = 0;
9,449,853✔
690
      for (auto i_nuclide : tally.nuclides_) {
20,327,231✔
691
        // Write label for this nuclide bin.
692
        if (i_nuclide == -1) {
10,877,378✔
693
          fmt::print(tallies_out, "{0:{1}}Total Material\n", "", indent + 1);
16,082,584✔
694
        } else {
695
          if (settings::run_CE) {
2,836,086✔
696
            fmt::print(tallies_out, "{0:{1}}{2}\n", "", indent + 1,
2,835,712✔
697
              data::nuclides[i_nuclide]->name_);
2,835,712✔
698
          } else {
699
            fmt::print(tallies_out, "{0:{1}}{2}\n", "", indent + 1,
374✔
700
              data::mg.nuclides_[i_nuclide].name);
374✔
701
          }
702
        }
703

704
        // Write the score, mean, and uncertainty.
705
        indent += 2;
10,877,378✔
706
        for (auto score : tally.scores_) {
24,627,912✔
707
          std::string score_name =
708
            score > 0 ? reaction_name(score) : score_names.at(score);
13,750,534!
709
          double mean, stdev;
710
          std::tie(mean, stdev) =
13,750,534✔
711
            mean_stdev(&tally.results_(filter_index, score_index, 0),
13,750,534✔
712
              tally.n_realizations_);
27,501,068✔
713
          fmt::print(tallies_out, "{0:{1}}{2:<36} {3:.6} +/- {4:.6}\n", "",
13,750,534✔
714
            indent + 1, score_name, mean, t_value * stdev);
13,750,534✔
715
          score_index += 1;
13,750,534✔
716
        }
13,750,534✔
717
        indent -= 2;
10,877,378✔
718
      }
719
    }
720
  }
18,922✔
721
}
3,647✔
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