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

openmc-dev / openmc / 26052903817

18 May 2026 06:35PM UTC coverage: 81.382% (-0.007%) from 81.389%
26052903817

push

github

web-flow
Check for missing thread count argument for -s/--threads (#3940)

17751 of 25654 branches covered (69.19%)

Branch coverage included in aggregate %.

1 of 5 new or added lines in 1 file covered. (20.0%)

2 existing lines in 1 file now uncovered.

58753 of 68352 relevant lines covered (85.96%)

47201601.08 hits per line

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

74.77
/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,450✔
46
{
47
  using namespace openmc;
8,450✔
48

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

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

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

67
#ifdef OPENMC_LIBMESH_ENABLED
68
  const int n_threads = num_threads();
1,577✔
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,577!
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 =
906✔
78
      make_unique<libMesh::LibMeshInit>(argc, argv, comm, n_threads);
1,812✔
79
#else
80
    // pass command line args, empty MPI communicator, and number of threads
81
    settings::libmesh_init =
671✔
82
      make_unique<libMesh::LibMeshInit>(argc, argv, 0, n_threads);
1,342✔
83
#endif
84

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

88
#endif
89

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

94
#ifdef _OPENMP
95
  // If OMP_SCHEDULE is not set, default to a static schedule
96
  char* envvar = std::getenv("OMP_SCHEDULE");
4,792✔
97
  if (!envvar) {
4,792!
98
    omp_set_schedule(omp_sched_static, 0);
4,792✔
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,406✔
105
  openmc::openmc_set_stride(DEFAULT_STRIDE);
8,406✔
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,406✔
113
  if (std::setlocale(LC_ALL, "C") == NULL) {
8,406!
114
    fatal_error("Cannot set locale to C.");
×
115
  }
116

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

121
  if (!settings::properties_file.empty()) {
8,313✔
122
    openmc_properties_import(settings::properties_file.c_str());
11✔
123
  }
124

125
  // Reset locale to previous state
126
  if (std::setlocale(LC_ALL, prev_locale.c_str()) == NULL) {
8,313!
127
    fatal_error("Cannot reset locale.");
×
128
  }
129

130
  // Write some initial output under the header if needed
131
  initial_output();
8,313✔
132

133
  // Check for particle restart run
134
  if (settings::particle_restart_run)
8,313✔
135
    settings::run_mode = RunMode::PARTICLE;
41✔
136

137
  // Stop initialization timer
138
  simulation::time_initialize.stop();
8,313✔
139
  simulation::time_total.stop();
8,313✔
140

141
  return 0;
8,313✔
142
}
8,324✔
143

144
namespace openmc {
145

146
#ifdef OPENMC_MPI
147
void initialize_mpi(MPI_Comm intracomm)
3,711✔
148
{
149
  mpi::intracomm = intracomm;
3,711✔
150

151
  // Initialize MPI
152
  int flag;
3,711✔
153
  MPI_Initialized(&flag);
3,711✔
154
  if (!flag)
3,711✔
155
    MPI_Init(nullptr, nullptr);
3,027✔
156

157
  // Determine number of processes and rank for each
158
  MPI_Comm_size(intracomm, &mpi::n_procs);
3,711✔
159
  MPI_Comm_rank(intracomm, &mpi::rank);
3,711✔
160
  mpi::master = (mpi::rank == 0);
3,711✔
161

162
  // Create bank datatype
163
  SourceSite b;
3,711✔
164
  MPI_Aint disp[11];
3,711✔
165
  MPI_Get_address(&b.r, &disp[0]);
3,711✔
166
  MPI_Get_address(&b.u, &disp[1]);
3,711✔
167
  MPI_Get_address(&b.E, &disp[2]);
3,711✔
168
  MPI_Get_address(&b.time, &disp[3]);
3,711✔
169
  MPI_Get_address(&b.wgt, &disp[4]);
3,711✔
170
  MPI_Get_address(&b.delayed_group, &disp[5]);
3,711✔
171
  MPI_Get_address(&b.surf_id, &disp[6]);
3,711✔
172
  MPI_Get_address(&b.particle, &disp[7]);
3,711✔
173
  MPI_Get_address(&b.parent_nuclide, &disp[8]);
3,711✔
174
  MPI_Get_address(&b.parent_id, &disp[9]);
3,711✔
175
  MPI_Get_address(&b.progeny_id, &disp[10]);
3,711✔
176
  for (int i = 10; i >= 0; --i) {
44,532✔
177
    disp[i] -= disp[0];
40,821✔
178
  }
179

180
  int blocks[] {3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1};
3,711✔
181
  MPI_Datatype types[] {MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE,
3,711✔
182
    MPI_DOUBLE, MPI_INT, MPI_INT, MPI_INT, MPI_INT, MPI_LONG, MPI_LONG};
183
  MPI_Type_create_struct(11, blocks, disp, types, &mpi::source_site);
3,711✔
184
  MPI_Type_commit(&mpi::source_site);
3,711✔
185

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

208
  int blocksc[] = {3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
3,711✔
209
  MPI_Datatype typesc[] = {MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE,
3,711✔
210
    MPI_DOUBLE, MPI_DOUBLE, MPI_INT, MPI_INT, MPI_INT, MPI_INT, MPI_INT,
211
    MPI_INT, MPI_INT, MPI_INT, MPI_INT64_T, MPI_INT64_T};
212

213
  MPI_Type_create_struct(
3,711✔
214
    16, blocksc, dispc, typesc, &mpi::collision_track_site);
215
  MPI_Type_commit(&mpi::collision_track_site);
3,711✔
216
}
3,711✔
217
#endif // OPENMC_MPI
218

219
int parse_command_line(int argc, char* argv[])
8,450✔
220
{
221
  int last_flag = 0;
8,450✔
222
  for (int i = 1; i < argc; ++i) {
9,764✔
223
    std::string arg {argv[i]};
1,325✔
224
    if (arg[0] == '-') {
1,325✔
225
      if (arg == "-p" || arg == "--plot") {
2,325!
226
        settings::run_mode = RunMode::PLOTTING;
119✔
227
        settings::check_overlaps = true;
119✔
228

229
      } else if (arg == "-n" || arg == "--particles") {
2,206!
230
        i += 1;
×
231
        settings::n_particles = std::stoll(argv[i]);
×
232

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

242
      } else if (arg == "-e" || arg == "--event") {
1,999!
243
        settings::event_based = true;
207✔
244
      } else if (arg == "-r" || arg == "--restart") {
1,688!
245
        i += 1;
104✔
246
        // Check what type of file this is
247
        hid_t file_id = file_open(argv[i], 'r', true);
104✔
248
        std::string filetype;
104✔
249
        read_attribute(file_id, "filetype", filetype);
104✔
250
        file_close(file_id);
104✔
251

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

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

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

283
            // It is a source file
284
            settings::path_sourcepoint = argv[i + 1];
104!
285
            i += 1;
286

287
          } else {
288
            // Source is in statepoint file
289
            settings::path_sourcepoint = settings::path_statepoint;
×
290
          }
291

292
        } else {
293
          // Source is assumed to be in statepoint file
294
          settings::path_sourcepoint = settings::path_statepoint;
208✔
295
        }
296

297
      } else if (arg == "-g" || arg == "--geometry-debug") {
1,688!
298
        settings::check_overlaps = true;
×
299
      } else if (arg == "-c" || arg == "--volume") {
965✔
300
        settings::run_mode = RunMode::VOLUME;
701✔
301
      } else if (arg == "-s" || arg == "--threads") {
158!
302
        // Read number of threads
303
        if (i + 1 >= argc) {
24!
NEW
304
          std::string msg {"Number of threads not specified."};
×
NEW
305
          strcpy(openmc_err_msg, msg.c_str());
×
NEW
306
          return OPENMC_E_INVALID_ARGUMENT;
×
NEW
307
        }
×
308
        i += 1;
24✔
309

310
#ifdef _OPENMP
311
        // Read and set number of OpenMP threads
312
        int n_threads = std::stoi(argv[i]);
26✔
313
        if (n_threads < 1) {
13!
314
          std::string msg {"Number of threads must be positive."};
×
315
          strcpy(openmc_err_msg, msg.c_str());
316
          return OPENMC_E_INVALID_ARGUMENT;
317
        }
318
        omp_set_num_threads(n_threads);
13✔
319
#else
320
        if (mpi::master) {
11✔
321
          warning("Ignoring number of threads specified on command line.");
20✔
322
        }
323
#endif
324

325
      } else if (arg == "-?" || arg == "-h" || arg == "--help") {
201!
326
        print_usage();
×
327
        return OPENMC_E_UNASSIGNED;
×
328

329
      } else if (arg == "-v" || arg == "--version") {
123!
330
        print_version();
11✔
331
        print_build_info();
11✔
332
        return OPENMC_E_UNASSIGNED;
11✔
333

334
      } else if (arg == "-t" || arg == "--track") {
56!
335
        settings::write_all_tracks = true;
56✔
336

337
      } else {
338
        fmt::print(stderr, "Unknown option: {}\n", argv[i]);
×
339
        print_usage();
×
340
        return OPENMC_E_UNASSIGNED;
×
341
      }
342

343
      last_flag = i;
344
    }
345
  }
1,325✔
346

347
  // Determine directory where XML input files are
348
  if (argc > 1 && last_flag < argc - 1) {
8,439✔
349
    settings::path_input = std::string(argv[last_flag + 1]);
103✔
350

351
    // check that the path is either a valid directory or file
352
    if (!dir_exists(settings::path_input) &&
193✔
353
        !file_exists(settings::path_input)) {
90✔
354
      fatal_error(fmt::format(
39✔
355
        "The path specified to the OpenMC executable '{}' does not exist.",
356
        settings::path_input));
357
    }
358

359
    // Add slash at end of directory if it isn't there
360
    if (!ends_with(settings::path_input, "/") &&
210!
361
        dir_exists(settings::path_input)) {
70✔
362
      settings::path_input += "/";
8,417✔
363
    }
364
  }
365

366
  return 0;
367
}
368

369
bool read_model_xml()
8,406✔
370
{
371
  std::string model_filename = settings::path_input;
8,406✔
372

373
  // if the current filename is a directory, append the default model filename
374
  if (model_filename.empty() || dir_exists(model_filename))
8,406✔
375
    model_filename += "model.xml";
8,349✔
376

377
  // if this file doesn't exist, stop here
378
  if (!file_exists(model_filename))
8,406✔
379
    return false;
380

381
  // try to process the path input as an XML file
382
  pugi::xml_document doc;
7,024✔
383
  if (!doc.load_file(model_filename.c_str())) {
7,024!
384
    fatal_error(fmt::format(
×
385
      "Error reading from single XML input file '{}'", model_filename));
386
  }
387

388
  pugi::xml_node root = doc.document_element();
7,024✔
389

390
  // Read settings
391
  if (!check_for_node(root, "settings")) {
7,024!
392
    fatal_error("No <settings> node present in the model.xml file.");
×
393
  }
394
  auto settings_root = root.child("settings");
7,024✔
395

396
  // Verbosity
397
  if (check_for_node(settings_root, "verbosity") && settings::verbosity == -1) {
7,024!
398
    settings::verbosity = std::stoi(get_node_value(settings_root, "verbosity"));
60✔
399
  } else if (settings::verbosity == -1) {
6,994!
400
    settings::verbosity = 7;
6,994✔
401
  }
402

403
  // To this point, we haven't displayed any output since we didn't know what
404
  // the verbosity is. Now that we checked for it, show the title if necessary
405
  if (mpi::master) {
7,024✔
406
    if (settings::verbosity >= 2)
6,256✔
407
      title();
6,234✔
408
  }
409

410
  write_message(
7,024✔
411
    fmt::format("Reading model XML file '{}' ...", model_filename), 5);
8,339✔
412

413
  // Read chain data before settings so DecaySpectrum source distributions can
414
  // resolve nuclides while sources are constructed.
415
  read_chain_file_xml();
7,024✔
416

417
  read_settings_xml(settings_root);
7,024✔
418

419
  // If other XML files are present, display warning
420
  // that they will be ignored
421
  auto other_inputs = {"materials.xml", "geometry.xml", "settings.xml",
6,970✔
422
    "tallies.xml", "plots.xml"};
6,970✔
423
  for (const auto& input : other_inputs) {
41,026✔
424
    if (file_exists(settings::path_input + input)) {
34,246✔
425
      warning((fmt::format("Other XML file input(s) are present. These files "
225✔
426
                           "may be ignored in favor of the {} file.",
427
        model_filename)));
428
      break;
190✔
429
    }
430
  }
431

432
  // Read materials and cross sections
433
  if (!check_for_node(root, "materials")) {
6,970!
434
    fatal_error(fmt::format(
×
435
      "No <materials> node present in the {} file.", model_filename));
436
  }
437

438
  if (settings::run_mode != RunMode::PLOTTING) {
6,970✔
439
    read_cross_sections_xml(root.child("materials"));
6,884✔
440
  }
441
  read_materials_xml(root.child("materials"));
6,970✔
442

443
  // Read geometry
444
  if (!check_for_node(root, "geometry")) {
6,970!
445
    fatal_error(fmt::format(
×
446
      "No <geometry> node present in the {} file.", model_filename));
447
  }
448
  read_geometry_xml(root.child("geometry"));
6,970✔
449

450
  // Final geometry setup and assign temperatures
451
  finalize_geometry();
6,968✔
452

453
  // Finalize cross sections having assigned temperatures
454
  finalize_cross_sections();
6,968✔
455

456
  // Compute cell density multipliers now that material densities
457
  // have been finalized (from geometry_aux.h)
458
  finalize_cell_densities();
6,968✔
459

460
  if (check_for_node(root, "tallies"))
6,968✔
461
    read_tallies_xml(root.child("tallies"));
4,078✔
462

463
  // Initialize distribcell_filters
464
  prepare_distribcell();
6,950✔
465

466
  if (check_for_node(root, "plots")) {
6,950✔
467
    read_plots_xml(root.child("plots"));
365✔
468
  } else {
469
    // When no <plots> element is present in the model.xml file, check for a
470
    // regular plots.xml file
471
    std::string filename = settings::path_input + "plots.xml";
6,585✔
472
    if (file_exists(filename)) {
6,585!
473
      read_plots_xml();
×
474
    }
475
  }
6,585✔
476

477
  finalize_variance_reduction();
6,941✔
478

479
  return true;
6,941✔
480
}
15,264✔
481

482
void read_separate_xml_files()
1,382✔
483
{
484
  // Read chain data before settings so DecaySpectrum source distributions can
485
  // resolve nuclides while sources are constructed.
486
  read_chain_file_xml();
1,382✔
487

488
  read_settings_xml();
1,382✔
489
  if (settings::run_mode != RunMode::PLOTTING) {
1,372✔
490
    read_cross_sections_xml();
1,339✔
491
  }
492

493
  read_materials_xml();
1,372✔
494
  read_geometry_xml();
1,372✔
495

496
  // Final geometry setup and assign temperatures
497
  finalize_geometry();
1,372✔
498

499
  // Finalize cross sections having assigned temperatures
500
  finalize_cross_sections();
1,372✔
501

502
  // Compute cell density multipliers now that material densities
503
  // have been finalized (from geometry_aux.h)
504
  finalize_cell_densities();
1,372✔
505

506
  read_tallies_xml();
1,372✔
507

508
  // Initialize distribcell_filters
509
  prepare_distribcell();
1,372✔
510

511
  // Read the plots.xml regardless of plot mode in case plots are requested
512
  // via the API
513
  read_plots_xml();
1,372✔
514

515
  finalize_variance_reduction();
1,372✔
516
}
1,372✔
517

518
void initial_output()
8,313✔
519
{
520
  // write initial output
521
  if (settings::run_mode == RunMode::PLOTTING) {
8,313✔
522
    // Read plots.xml if it exists
523
    if (mpi::master && settings::verbosity >= 5)
110!
524
      print_plot();
88✔
525

526
  } else {
527
    // Write summary information
528
    if (mpi::master && settings::output_summary)
8,203✔
529
      write_summary();
6,911✔
530

531
    // Warn if overlap checking is on
532
    if (mpi::master && settings::check_overlaps) {
8,203!
533
      warning("Cell overlap checking is ON.");
×
534
    }
535
  }
536
}
8,313✔
537

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

© 2026 Coveralls, Inc