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

openmc-dev / openmc / 22551281114

01 Mar 2026 07:52PM UTC coverage: 81.508% (-0.3%) from 81.806%
22551281114

push

github

web-flow
Speed up Docker build (#3841)

Co-authored-by: Jonathan Shimwell <drshimwell@gmail.com>

17477 of 25177 branches covered (69.42%)

Branch coverage included in aggregate %.

57682 of 67034 relevant lines covered (86.05%)

44970568.33 hits per line

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

75.43
/src/initialize.cpp
1
#include "openmc/initialize.h"
2

3
#include <clocale>
4
#include <cstddef>
5
#include <cstdlib> // for getenv
6
#include <cstring>
7
#include <string>
8

9
#ifdef _OPENMP
10
#include <omp.h>
11
#endif
12
#include <fmt/core.h>
13

14
#include "openmc/capi.h"
15
#include "openmc/chain.h"
16
#include "openmc/constants.h"
17
#include "openmc/cross_sections.h"
18
#include "openmc/error.h"
19
#include "openmc/file_utils.h"
20
#include "openmc/geometry_aux.h"
21
#include "openmc/hdf5_interface.h"
22
#include "openmc/material.h"
23
#include "openmc/memory.h"
24
#include "openmc/message_passing.h"
25
#include "openmc/mgxs_interface.h"
26
#include "openmc/nuclide.h"
27
#include "openmc/openmp_interface.h"
28
#include "openmc/output.h"
29
#include "openmc/plot.h"
30
#include "openmc/random_lcg.h"
31
#include "openmc/settings.h"
32
#include "openmc/simulation.h"
33
#include "openmc/string_utils.h"
34
#include "openmc/summary.h"
35
#include "openmc/tallies/tally.h"
36
#include "openmc/thermal.h"
37
#include "openmc/timer.h"
38
#include "openmc/vector.h"
39
#include "openmc/weight_windows.h"
40

41
#ifdef OPENMC_LIBMESH_ENABLED
42
#include "libmesh/libmesh.h"
43
#endif
44

45
int openmc_init(int argc, char* argv[], const void* intracomm)
8,185 ✔
46
{
47
  using namespace openmc;
8,185 ✔
48

49
#ifdef OPENMC_MPI
50
  // Check if intracomm was passed
51
  MPI_Comm comm;
3,607 ✔
52
  if (intracomm) {
3,607 ✔
53
    comm = *static_cast<const MPI_Comm*>(intracomm);
3,409 ✔
54
  } else {
55
    comm = MPI_COMM_WORLD;
47 ✔
56
  }
57

58
  // Initialize MPI for C++
59
  initialize_mpi(comm);
3,607 ✔
60
#endif
61

62
  // Parse command-line arguments
63
  int err = parse_command_line(argc, argv);
8,185 ✔
64
  if (err)
8,152 ✔
65
    return err;
66

67
#ifdef OPENMC_LIBMESH_ENABLED
68
  const int n_threads = num_threads();
1,528 ✔
69
  // initialize libMesh if it hasn't been initialized already
70
  // (if initialized externally, the libmesh_init object needs to be provided
71
  // also)
72
  if (!settings::libmesh_init && !libMesh::initialized()) {
1,528 !
73
#ifdef OPENMC_MPI
74
    // pass command line args, empty MPI communicator, and number of threads.
75
    // Because libMesh was not initialized, we assume that OpenMC is the primary
76
    // application and that its main MPI comm should be used.
77
    settings::libmesh_init =
880 ✔
78
      make_unique<libMesh::LibMeshInit>(argc, argv, comm, n_threads);
1,760 ✔
79
#else
80
    // pass command line args, empty MPI communicator, and number of threads
81
    settings::libmesh_init =
648 ✔
82
      make_unique<libMesh::LibMeshInit>(argc, argv, 0, n_threads);
1,296 ✔
83
#endif
84

85
    settings::libmesh_comm = &(settings::libmesh_init->comm());
1,528 ✔
86
  }
87

88
#endif
89

90
  // Start total and initialization timer
91
  simulation::time_total.start();
8,141 ✔
92
  simulation::time_initialize.start();
8,141 ✔
93

94
#ifdef _OPENMP
95
  // If OMP_SCHEDULE is not set, default to a static schedule
96
  char* envvar = std::getenv("OMP_SCHEDULE");
4,645 ✔
97
  if (!envvar) {
4,645 !
98
    omp_set_schedule(omp_sched_static, 0);
4,645 ✔
99
  }
100
#endif
101

102
  // Initialize random number generator -- if the user specifies a seed and/or
103
  // stride, it will be re-initialized later
104
  openmc::openmc_set_seed(DEFAULT_SEED);
8,141 ✔
105
  openmc::openmc_set_stride(DEFAULT_STRIDE);
8,141 ✔
106

107
  // Copy previous locale and set locale to C. This is a workaround for an issue
108
  // whereby when openmc_init is called from the plotter, the Qt application
109
  // framework first calls std::setlocale, which affects how pugixml reads
110
  // floating point numbers due to a bug:
111
  // https://github.com/zeux/pugixml/issues/469
112
  std::string prev_locale = std::setlocale(LC_ALL, nullptr);
8,141 ✔
113
  if (std::setlocale(LC_ALL, "C") == NULL) {
8,141 !
114
    fatal_error("Cannot set locale to C.");
×
115
  }
116

117
  // Read XML input files
118
  if (!read_model_xml())
8,141 ✔
119
    read_separate_xml_files();
1,349 ✔
120

121
  // Reset locale to previous state
122
  if (std::setlocale(LC_ALL, prev_locale.c_str()) == NULL) {
8,048 !
123
    fatal_error("Cannot reset locale.");
×
124
  }
125

126
  // Write some initial output under the header if needed
127
  initial_output();
8,048 ✔
128

129
  // Check for particle restart run
130
  if (settings::particle_restart_run)
8,048 ✔
131
    settings::run_mode = RunMode::PARTICLE;
41 ✔
132

133
  // Stop initialization timer
134
  simulation::time_initialize.stop();
8,048 ✔
135
  simulation::time_total.stop();
8,048 ✔
136

137
  return 0;
8,048 ✔
138
}
8,059 ✔
139

140
namespace openmc {
141

142
#ifdef OPENMC_MPI
143
void initialize_mpi(MPI_Comm intracomm)
3,607 ✔
144
{
145
  mpi::intracomm = intracomm;
3,607 ✔
146

147
  // Initialize MPI
148
  int flag;
3,607 ✔
149
  MPI_Initialized(&flag);
3,607 ✔
150
  if (!flag)
3,607 ✔
151
    MPI_Init(nullptr, nullptr);
2,967 ✔
152

153
  // Determine number of processes and rank for each
154
  MPI_Comm_size(intracomm, &mpi::n_procs);
3,607 ✔
155
  MPI_Comm_rank(intracomm, &mpi::rank);
3,607 ✔
156
  mpi::master = (mpi::rank == 0);
3,607 ✔
157

158
  // Create bank datatype
159
  SourceSite b;
3,607 ✔
160
  MPI_Aint disp[11];
3,607 ✔
161
  MPI_Get_address(&b.r, &disp[0]);
3,607 ✔
162
  MPI_Get_address(&b.u, &disp[1]);
3,607 ✔
163
  MPI_Get_address(&b.E, &disp[2]);
3,607 ✔
164
  MPI_Get_address(&b.time, &disp[3]);
3,607 ✔
165
  MPI_Get_address(&b.wgt, &disp[4]);
3,607 ✔
166
  MPI_Get_address(&b.delayed_group, &disp[5]);
3,607 ✔
167
  MPI_Get_address(&b.surf_id, &disp[6]);
3,607 ✔
168
  MPI_Get_address(&b.particle, &disp[7]);
3,607 ✔
169
  MPI_Get_address(&b.parent_nuclide, &disp[8]);
3,607 ✔
170
  MPI_Get_address(&b.parent_id, &disp[9]);
3,607 ✔
171
  MPI_Get_address(&b.progeny_id, &disp[10]);
3,607 ✔
172
  for (int i = 10; i >= 0; --i) {
43,284 ✔
173
    disp[i] -= disp[0];
39,677 ✔
174
  }
175

176
  int blocks[] {3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1};
3,607 ✔
177
  MPI_Datatype types[] {MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE,
3,607 ✔
178
    MPI_DOUBLE, MPI_INT, MPI_INT, MPI_INT, MPI_INT, MPI_LONG, MPI_LONG};
179
  MPI_Type_create_struct(11, blocks, disp, types, &mpi::source_site);
3,607 ✔
180
  MPI_Type_commit(&mpi::source_site);
3,607 ✔
181

182
  CollisionTrackSite bc;
3,607 ✔
183
  MPI_Aint dispc[16];
3,607 ✔
184
  MPI_Get_address(&bc.r, &dispc[0]);             // double
3,607 ✔
185
  MPI_Get_address(&bc.u, &dispc[1]);             // double
3,607 ✔
186
  MPI_Get_address(&bc.E, &dispc[2]);             // double
3,607 ✔
187
  MPI_Get_address(&bc.dE, &dispc[3]);            // double
3,607 ✔
188
  MPI_Get_address(&bc.time, &dispc[4]);          // double
3,607 ✔
189
  MPI_Get_address(&bc.wgt, &dispc[5]);           // double
3,607 ✔
190
  MPI_Get_address(&bc.event_mt, &dispc[6]);      // int
3,607 ✔
191
  MPI_Get_address(&bc.delayed_group, &dispc[7]); // int
3,607 ✔
192
  MPI_Get_address(&bc.cell_id, &dispc[8]);       // int
3,607 ✔
193
  MPI_Get_address(&bc.nuclide_id, &dispc[9]);    // int
3,607 ✔
194
  MPI_Get_address(&bc.material_id, &dispc[10]);  // int
3,607 ✔
195
  MPI_Get_address(&bc.universe_id, &dispc[11]);  // int
3,607 ✔
196
  MPI_Get_address(&bc.n_collision, &dispc[12]);  // int
3,607 ✔
197
  MPI_Get_address(&bc.particle, &dispc[13]);     // int
3,607 ✔
198
  MPI_Get_address(&bc.parent_id, &dispc[14]);    // int64_t
3,607 ✔
199
  MPI_Get_address(&bc.progeny_id, &dispc[15]);   // int64_t
3,607 ✔
200
  for (int i = 15; i >= 0; --i) {
61,319 ✔
201
    dispc[i] -= dispc[0];
57,712 ✔
202
  }
203

204
  int blocksc[] = {3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
3,607 ✔
205
  MPI_Datatype typesc[] = {MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE,
3,607 ✔
206
    MPI_DOUBLE, MPI_DOUBLE, MPI_INT, MPI_INT, MPI_INT, MPI_INT, MPI_INT,
207
    MPI_INT, MPI_INT, MPI_INT, MPI_INT64_T, MPI_INT64_T};
208

209
  MPI_Type_create_struct(
3,607 ✔
210
    16, blocksc, dispc, typesc, &mpi::collision_track_site);
211
  MPI_Type_commit(&mpi::collision_track_site);
3,607 ✔
212
}
3,607 ✔
213
#endif // OPENMC_MPI
214

215
int parse_command_line(int argc, char* argv[])
8,185 ✔
216
{
217
  int last_flag = 0;
8,185 ✔
218
  for (int i = 1; i < argc; ++i) {
9,474 ✔
219
    std::string arg {argv[i]};
1,300 ✔
220
    if (arg[0] == '-') {
1,300 ✔
221
      if (arg == "-p" || arg == "--plot") {
2,275 !
222
        settings::run_mode = RunMode::PLOTTING;
119 ✔
223
        settings::check_overlaps = true;
119 ✔
224

225
      } else if (arg == "-n" || arg == "--particles") {
2,156 !
226
        i += 1;
×
227
        settings::n_particles = std::stoll(argv[i]);
×
228

229
      } else if (arg == "-q" || arg == "--verbosity") {
2,156 !
230
        i += 1;
×
231
        settings::verbosity = std::stoi(argv[i]);
×
232
        if (settings::verbosity > 10 || settings::verbosity < 1) {
×
233
          auto msg = fmt::format("Invalid verbosity: {}.", settings::verbosity);
×
234
          strcpy(openmc_err_msg, msg.c_str());
×
235
          return OPENMC_E_INVALID_ARGUMENT;
×
236
        }
×
237

238
      } else if (arg == "-e" || arg == "--event") {
1,952 !
239
        settings::event_based = true;
204 ✔
240
      } else if (arg == "-r" || arg == "--restart") {
1,644 !
241
        i += 1;
104 ✔
242
        // Check what type of file this is
243
        hid_t file_id = file_open(argv[i], 'r', true);
104 ✔
244
        std::string filetype;
104 ✔
245
        read_attribute(file_id, "filetype", filetype);
104 ✔
246
        file_close(file_id);
104 ✔
247

248
        // Set path and flag for type of run
249
        if (filetype == "statepoint") {
104 ✔
250
          settings::path_statepoint = argv[i];
63 ✔
251
          settings::path_statepoint_c = settings::path_statepoint.c_str();
63 ✔
252
          settings::restart_run = true;
63 ✔
253
        } else if (filetype == "particle restart") {
41 !
254
          settings::path_particle_restart = argv[i];
41 ✔
255
          settings::particle_restart_run = true;
41 ✔
256
        } else {
257
          auto msg =
×
258
            fmt::format("Unrecognized file after restart flag: {}.", filetype);
×
259
          strcpy(openmc_err_msg, msg.c_str());
×
260
          return OPENMC_E_INVALID_ARGUMENT;
×
261
        }
×
262

263
        // If its a restart run check for additional source file
264
        if (settings::restart_run && i + 1 < argc) {
104 !
265
          // Check if it has extension we can read
266
          if (ends_with(argv[i + 1], ".h5")) {
×
267

268
            // Check file type is a source file
269
            file_id = file_open(argv[i + 1], 'r', true);
×
270
            read_attribute(file_id, "filetype", filetype);
×
271
            file_close(file_id);
×
272
            if (filetype != "source") {
×
273
              std::string msg {
×
274
                "Second file after restart flag must be a source file"};
×
275
              strcpy(openmc_err_msg, msg.c_str());
×
276
              return OPENMC_E_INVALID_ARGUMENT;
×
277
            }
×
278

279
            // It is a source file
280
            settings::path_sourcepoint = argv[i + 1];
104 !
281
            i += 1;
282

283
          } else {
284
            // Source is in statepoint file
285
            settings::path_sourcepoint = settings::path_statepoint;
×
286
          }
287

288
        } else {
289
          // Source is assumed to be in statepoint file
290
          settings::path_sourcepoint = settings::path_statepoint;
208 ✔
291
        }
292

293
      } else if (arg == "-g" || arg == "--geometry-debug") {
1,644 !
294
        settings::check_overlaps = true;
×
295
      } else if (arg == "-c" || arg == "--volume") {
943 ✔
296
        settings::run_mode = RunMode::VOLUME;
679 ✔
297
      } else if (arg == "-s" || arg == "--threads") {
158 !
298
        // Read number of threads
299
        i += 1;
24 ✔
300

301
#ifdef _OPENMP
302
        // Read and set number of OpenMP threads
303
        int n_threads = std::stoi(argv[i]);
26 ✔
304
        if (n_threads < 1) {
13 !
305
          std::string msg {"Number of threads must be positive."};
×
306
          strcpy(openmc_err_msg, msg.c_str());
307
          return OPENMC_E_INVALID_ARGUMENT;
308
        }
309
        omp_set_num_threads(n_threads);
13 ✔
310
#else
311
        if (mpi::master) {
11 ✔
312
          warning("Ignoring number of threads specified on command line.");
20 ✔
313
        }
314
#endif
315

316
      } else if (arg == "-?" || arg == "-h" || arg == "--help") {
201 !
317
        print_usage();
×
318
        return OPENMC_E_UNASSIGNED;
×
319

320
      } else if (arg == "-v" || arg == "--version") {
123 !
321
        print_version();
11 ✔
322
        print_build_info();
11 ✔
323
        return OPENMC_E_UNASSIGNED;
11 ✔
324

325
      } else if (arg == "-t" || arg == "--track") {
56 !
326
        settings::write_all_tracks = true;
56 ✔
327

328
      } else {
329
        fmt::print(stderr, "Unknown option: {}\n", argv[i]);
×
330
        print_usage();
×
331
        return OPENMC_E_UNASSIGNED;
×
332
      }
333

334
      last_flag = i;
335
    }
336
  }
1,300 ✔
337

338
  // Determine directory where XML input files are
339
  if (argc > 1 && last_flag < argc - 1) {
8,174 ✔
340
    settings::path_input = std::string(argv[last_flag + 1]);
103 ✔
341

342
    // check that the path is either a valid directory or file
343
    if (!dir_exists(settings::path_input) &&
193 ✔
344
        !file_exists(settings::path_input)) {
90 ✔
345
      fatal_error(fmt::format(
39 ✔
346
        "The path specified to the OpenMC executable '{}' does not exist.",
347
        settings::path_input));
348
    }
349

350
    // Add slash at end of directory if it isn't there
351
    if (!ends_with(settings::path_input, "/") &&
210 !
352
        dir_exists(settings::path_input)) {
70 ✔
353
      settings::path_input += "/";
8,152 ✔
354
    }
355
  }
356

357
  return 0;
358
}
359

360
bool read_model_xml()
8,141 ✔
361
{
362
  std::string model_filename = settings::path_input;
8,141 ✔
363

364
  // if the current filename is a directory, append the default model filename
365
  if (model_filename.empty() || dir_exists(model_filename))
8,141 ✔
366
    model_filename += "model.xml";
8,084 ✔
367

368
  // if this file doesn't exist, stop here
369
  if (!file_exists(model_filename))
8,141 ✔
370
    return false;
371

372
  // try to process the path input as an XML file
373
  pugi::xml_document doc;
6,792 ✔
374
  if (!doc.load_file(model_filename.c_str())) {
6,792 !
375
    fatal_error(fmt::format(
×
376
      "Error reading from single XML input file '{}'", model_filename));
377
  }
378

379
  pugi::xml_node root = doc.document_element();
6,792 ✔
380

381
  // Read settings
382
  if (!check_for_node(root, "settings")) {
6,792 !
383
    fatal_error("No <settings> node present in the model.xml file.");
×
384
  }
385
  auto settings_root = root.child("settings");
6,792 ✔
386

387
  // Verbosity
388
  if (check_for_node(settings_root, "verbosity") && settings::verbosity == -1) {
6,792 !
389
    settings::verbosity = std::stoi(get_node_value(settings_root, "verbosity"));
60 ✔
390
  } else if (settings::verbosity == -1) {
6,762 !
391
    settings::verbosity = 7;
6,762 ✔
392
  }
393

394
  // To this point, we haven't displayed any output since we didn't know what
395
  // the verbosity is. Now that we checked for it, show the title if necessary
396
  if (mpi::master) {
6,792 ✔
397
    if (settings::verbosity >= 2)
6,036 ✔
398
      title();
6,014 ✔
399
  }
400

401
  write_message(
6,792 ✔
402
    fmt::format("Reading model XML file '{}' ...", model_filename), 5);
8,064 ✔
403

404
  read_settings_xml(settings_root);
6,792 ✔
405

406
  // If other XML files are present, display warning
407
  // that they will be ignored
408
  auto other_inputs = {"materials.xml", "geometry.xml", "settings.xml",
6,738 ✔
409
    "tallies.xml", "plots.xml"};
6,738 ✔
410
  for (const auto& input : other_inputs) {
39,634 ✔
411
    if (file_exists(settings::path_input + input)) {
33,086 ✔
412
      warning((fmt::format("Other XML file input(s) are present. These files "
225 ✔
413
                           "may be ignored in favor of the {} file.",
414
        model_filename)));
415
      break;
190 ✔
416
    }
417
  }
418

419
  // Read data from chain file
420
  read_chain_file_xml();
6,738 ✔
421

422
  // Read materials and cross sections
423
  if (!check_for_node(root, "materials")) {
6,738 !
424
    fatal_error(fmt::format(
×
425
      "No <materials> node present in the {} file.", model_filename));
426
  }
427

428
  if (settings::run_mode != RunMode::PLOTTING) {
6,738 ✔
429
    read_cross_sections_xml(root.child("materials"));
6,652 ✔
430
  }
431
  read_materials_xml(root.child("materials"));
6,738 ✔
432

433
  // Read geometry
434
  if (!check_for_node(root, "geometry")) {
6,738 !
435
    fatal_error(fmt::format(
×
436
      "No <geometry> node present in the {} file.", model_filename));
437
  }
438
  read_geometry_xml(root.child("geometry"));
6,738 ✔
439

440
  // Final geometry setup and assign temperatures
441
  finalize_geometry();
6,736 ✔
442

443
  // Finalize cross sections having assigned temperatures
444
  finalize_cross_sections();
6,736 ✔
445

446
  // Compute cell density multipliers now that material densities
447
  // have been finalized (from geometry_aux.h)
448
  finalize_cell_densities();
6,736 ✔
449

450
  if (check_for_node(root, "tallies"))
6,736 ✔
451
    read_tallies_xml(root.child("tallies"));
3,901 ✔
452

453
  // Initialize distribcell_filters
454
  prepare_distribcell();
6,718 ✔
455

456
  if (check_for_node(root, "plots")) {
6,718 ✔
457
    read_plots_xml(root.child("plots"));
343 ✔
458
  } else {
459
    // When no <plots> element is present in the model.xml file, check for a
460
    // regular plots.xml file
461
    std::string filename = settings::path_input + "plots.xml";
6,375 ✔
462
    if (file_exists(filename)) {
6,375 !
463
      read_plots_xml();
×
464
    }
465
  }
6,375 ✔
466

467
  finalize_variance_reduction();
6,709 ✔
468

469
  return true;
6,709 ✔
470
}
14,767 ✔
471

472
void read_separate_xml_files()
1,349 ✔
473
{
474
  read_settings_xml();
1,349 ✔
475
  if (settings::run_mode != RunMode::PLOTTING) {
1,339 ✔
476
    read_cross_sections_xml();
1,306 ✔
477
  }
478

479
  // Read data from chain file
480
  read_chain_file_xml();
1,339 ✔
481

482
  read_materials_xml();
1,339 ✔
483
  read_geometry_xml();
1,339 ✔
484

485
  // Final geometry setup and assign temperatures
486
  finalize_geometry();
1,339 ✔
487

488
  // Finalize cross sections having assigned temperatures
489
  finalize_cross_sections();
1,339 ✔
490

491
  // Compute cell density multipliers now that material densities
492
  // have been finalized (from geometry_aux.h)
493
  finalize_cell_densities();
1,339 ✔
494

495
  read_tallies_xml();
1,339 ✔
496

497
  // Initialize distribcell_filters
498
  prepare_distribcell();
1,339 ✔
499

500
  // Read the plots.xml regardless of plot mode in case plots are requested
501
  // via the API
502
  read_plots_xml();
1,339 ✔
503

504
  finalize_variance_reduction();
1,339 ✔
505
}
1,339 ✔
506

507
void initial_output()
8,048 ✔
508
{
509
  // write initial output
510
  if (settings::run_mode == RunMode::PLOTTING) {
8,048 ✔
511
    // Read plots.xml if it exists
512
    if (mpi::master && settings::verbosity >= 5)
110 !
513
      print_plot();
88 ✔
514

515
  } else {
516
    // Write summary information
517
    if (mpi::master && settings::output_summary)
7,938 ✔
518
      write_summary();
6,680 ✔
519

520
    // Warn if overlap checking is on
521
    if (mpi::master && settings::check_overlaps) {
7,938 !
522
      warning("Cell overlap checking is ON.");
×
523
    }
524
  }
525
}
8,048 ✔
526

527
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc