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

openmc-dev / openmc / 27780945043

18 Jun 2026 06:30PM UTC coverage: 81.097% (-0.2%) from 81.34%
27780945043

Pull #3911

github

web-flow
Merge c5ade9293 into 09ee8308d
Pull Request #3911: Creating a new HDF5 nuclear data library for UQ

18119 of 26286 branches covered (68.93%)

Branch coverage included in aggregate %.

310 of 599 new or added lines in 3 files covered. (51.75%)

2247 existing lines in 53 files now uncovered.

59544 of 69480 relevant lines covered (85.7%)

40971728.6 hits per line

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

81.15
/src/source.cpp
1
#include "openmc/source.h"
2

3
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
4
#define HAS_DYNAMIC_LINKING
5
#endif
6

7
#include <utility> // for move
8

9
#ifdef HAS_DYNAMIC_LINKING
10
#include <dlfcn.h> // for dlopen, dlsym, dlclose, dlerror
11
#endif
12

13
#include "openmc/tensor.h"
14
#include <fmt/core.h>
15

16
#include "openmc/bank.h"
17
#include "openmc/capi.h"
18
#include "openmc/cell.h"
19
#include "openmc/container_util.h"
20
#include "openmc/error.h"
21
#include "openmc/file_utils.h"
22
#include "openmc/geometry.h"
23
#include "openmc/hdf5_interface.h"
24
#include "openmc/material.h"
25
#include "openmc/mcpl_interface.h"
26
#include "openmc/memory.h"
27
#include "openmc/message_passing.h"
28
#include "openmc/mgxs_interface.h"
29
#include "openmc/nuclide.h"
30
#include "openmc/random_lcg.h"
31
#include "openmc/search.h"
32
#include "openmc/settings.h"
33
#include "openmc/simulation.h"
34
#include "openmc/state_point.h"
35
#include "openmc/string_utils.h"
36
#include "openmc/xml_interface.h"
37

38
namespace openmc {
39

40
std::atomic<int64_t> source_n_accept {0};
41
std::atomic<int64_t> source_n_reject {0};
42

43
namespace {
44

45
void validate_particle_type(ParticleType type, const std::string& context)
44,874✔
46
{
47
  if (type.is_transportable())
44,874!
48
    return;
44,874✔
49

50
  fatal_error(
×
51
    fmt::format("Unsupported source particle type '{}' (PDG {}) in {}.",
×
52
      type.str(), type.pdg_number(), context));
×
53
}
54

55
} // namespace
56

57
//==============================================================================
58
// Global variables
59
//==============================================================================
60

61
namespace model {
62

63
vector<unique_ptr<Source>> external_sources;
64

65
vector<unique_ptr<Source>> adjoint_sources;
66

67
DiscreteIndex external_sources_probability;
68

69
} // namespace model
70

71
//==============================================================================
72
// Source implementation
73
//==============================================================================
74

75
Source::Source(pugi::xml_node node)
2,550✔
76
{
77
  // Check for source strength
78
  if (check_for_node(node, "strength")) {
2,550✔
79
    strength_ = std::stod(get_node_value(node, "strength"));
4,830✔
80
    if (strength_ < 0.0) {
2,415!
UNCOV
81
      fatal_error("Source strength is negative.");
×
82
    }
83
  }
84

85
  // Check for additional defined constraints
86
  read_constraints(node);
2,550✔
87
}
2,550✔
88

89
unique_ptr<Source> Source::create(pugi::xml_node node)
2,550✔
90
{
91
  // if the source type is present, use it to determine the type
92
  // of object to create
93
  if (check_for_node(node, "type")) {
2,550✔
94
    std::string source_type = get_node_value(node, "type");
2,361✔
95
    if (source_type == "independent") {
2,361✔
96
      return make_unique<IndependentSource>(node);
2,292✔
97
    } else if (source_type == "file") {
69✔
98
      return make_unique<FileSource>(node);
9✔
99
    } else if (source_type == "compiled") {
60✔
100
      return make_unique<CompiledSourceWrapper>(node);
6✔
101
    } else if (source_type == "mesh") {
54!
102
      return make_unique<MeshSource>(node);
54✔
103
    } else {
UNCOV
104
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
105
    }
106
  } else {
2,358✔
107
    // support legacy source format
108
    if (check_for_node(node, "file")) {
189✔
109
      return make_unique<FileSource>(node);
6✔
110
    } else if (check_for_node(node, "library")) {
183!
UNCOV
111
      return make_unique<CompiledSourceWrapper>(node);
×
112
    } else {
113
      return make_unique<IndependentSource>(node);
183✔
114
    }
115
  }
116
}
117

118
void Source::read_constraints(pugi::xml_node node)
2,550✔
119
{
120
  // Check for constraints node. For backwards compatibility, if no constraints
121
  // node is given, still try searching for domain constraints from top-level
122
  // node.
123
  pugi::xml_node constraints_node = node.child("constraints");
2,550✔
124
  if (constraints_node) {
2,550✔
125
    node = constraints_node;
498✔
126
  }
127

128
  // Check for domains to reject from
129
  if (check_for_node(node, "domain_type")) {
2,550✔
130
    std::string domain_type = get_node_value(node, "domain_type");
117✔
131
    if (domain_type == "cell") {
117✔
132
      domain_type_ = DomainType::CELL;
27✔
133
    } else if (domain_type == "material") {
90✔
134
      domain_type_ = DomainType::MATERIAL;
15✔
135
    } else if (domain_type == "universe") {
75!
136
      domain_type_ = DomainType::UNIVERSE;
75✔
137
    } else {
UNCOV
138
      fatal_error(
×
UNCOV
139
        std::string("Unrecognized domain type for constraint: " + domain_type));
×
140
    }
141

142
    auto ids = get_node_array<int>(node, "domain_ids");
117✔
143
    domain_ids_.insert(ids.begin(), ids.end());
117✔
144
  }
117✔
145

146
  if (check_for_node(node, "time_bounds")) {
2,550✔
147
    auto ids = get_node_array<double>(node, "time_bounds");
3✔
148
    if (ids.size() != 2) {
3!
UNCOV
149
      fatal_error("Time bounds must be represented by two numbers.");
×
150
    }
151
    time_bounds_ = std::make_pair(ids[0], ids[1]);
3✔
152
  }
3✔
153
  if (check_for_node(node, "energy_bounds")) {
2,550✔
154
    auto ids = get_node_array<double>(node, "energy_bounds");
3✔
155
    if (ids.size() != 2) {
3!
UNCOV
156
      fatal_error("Energy bounds must be represented by two numbers.");
×
157
    }
158
    energy_bounds_ = std::make_pair(ids[0], ids[1]);
3✔
159
  }
3✔
160

161
  if (check_for_node(node, "fissionable")) {
2,550✔
162
    only_fissionable_ = get_node_value_bool(node, "fissionable");
378✔
163
  }
164

165
  // Check for how to handle rejected particles
166
  if (check_for_node(node, "rejection_strategy")) {
2,550!
167
    std::string rejection_strategy = get_node_value(node, "rejection_strategy");
×
168
    if (rejection_strategy == "kill") {
×
169
      rejection_strategy_ = RejectionStrategy::KILL;
×
UNCOV
170
    } else if (rejection_strategy == "resample") {
×
171
      rejection_strategy_ = RejectionStrategy::RESAMPLE;
×
172
    } else {
UNCOV
173
      fatal_error(std::string(
×
174
        "Unrecognized strategy source rejection: " + rejection_strategy));
175
    }
UNCOV
176
  }
×
177
}
2,550✔
178

179
void check_rejection_fraction(int64_t n_reject, int64_t n_accept)
9,391,506✔
180
{
181
  // Don't check unless we've hit a minimum number of total sites rejected
182
  if (n_reject < EXTSRC_REJECT_THRESHOLD)
9,391,506✔
183
    return;
184

185
  // Compute fraction of accepted sites and compare against minimum
186
  double fraction = static_cast<double>(n_accept) / n_reject;
359,463✔
187
  if (fraction <= settings::source_rejection_fraction) {
359,463✔
188
    fatal_error(fmt::format(
3✔
189
      "Too few source sites satisfied the constraints (minimum source "
190
      "rejection fraction = {}). Please check your source definition or "
191
      "set a lower value of Settings.source_rejection_fraction.",
192
      settings::source_rejection_fraction));
193
  }
194
}
195

196
SourceSite Source::sample_with_constraints(uint64_t* seed) const
9,391,506✔
197
{
198
  bool accepted = false;
9,391,506✔
199
  int64_t n_local_reject = 0;
9,391,506✔
200
  SourceSite site {};
9,391,506✔
201

202
  while (!accepted) {
28,535,966✔
203
    // Sample a source site without considering constraints yet
204
    site = this->sample(seed);
9,752,954✔
205

206
    if (constraints_applied()) {
9,752,954✔
207
      accepted = true;
208
    } else {
209
      // Check whether sampled site satisfies constraints
210
      accepted = satisfies_spatial_constraints(site.r) &&
10,672,245✔
211
                 satisfies_energy_constraints(site.E) &&
730,529✔
212
                 satisfies_time_constraints(site.time);
185,991✔
213
      if (!accepted) {
361,448✔
214
        ++n_local_reject;
361,448✔
215

216
        // Check per-particle rejection limit
217
        if (n_local_reject >= MAX_SOURCE_REJECTIONS_PER_SAMPLE) {
361,448!
UNCOV
218
          fatal_error("Exceeded maximum number of source rejections per "
×
219
                      "sample. Please check your source definition.");
220
        }
221

222
        // For the "kill" strategy, accept particle but set weight to 0 so that
223
        // it is terminated immediately
224
        if (rejection_strategy_ == RejectionStrategy::KILL) {
361,448!
UNCOV
225
          accepted = true;
×
UNCOV
226
          site.wgt = 0.0;
×
227
        }
228
      }
229
    }
230
  }
231

232
  // Flush local rejection count, update accept counter, and check overall
233
  // rejection fraction
234
  if (n_local_reject > 0) {
9,391,506✔
235
    source_n_reject += n_local_reject;
5,202✔
236
  }
237
  ++source_n_accept;
9,391,506✔
238
  check_rejection_fraction(source_n_reject, source_n_accept);
9,391,506✔
239

240
  return site;
9,391,503✔
241
}
242

243
bool Source::satisfies_energy_constraints(double E) const
9,400,079✔
244
{
245
  return E > energy_bounds_.first && E < energy_bounds_.second;
9,400,079!
246
}
247

248
bool Source::satisfies_time_constraints(double time) const
185,991✔
249
{
250
  return time > time_bounds_.first && time < time_bounds_.second;
185,991✔
251
}
252

253
bool Source::satisfies_spatial_constraints(Position r) const
10,830,690✔
254
{
255
  GeometryState geom_state;
10,830,690✔
256
  geom_state.r() = r;
10,830,690✔
257
  geom_state.u() = {0.0, 0.0, 1.0};
10,830,690✔
258

259
  // Reject particle if it's not in the geometry at all
260
  bool found = exhaustive_find_cell(geom_state);
10,830,690✔
261
  if (!found)
10,830,690✔
262
    return false;
263

264
  // Check the geometry state against specified domains
265
  bool accepted = true;
10,695,618✔
266
  if (!domain_ids_.empty()) {
10,695,618✔
267
    if (domain_type_ == DomainType::MATERIAL) {
693,298✔
268
      auto mat_index = geom_state.material();
60,000✔
269
      if (mat_index == MATERIAL_VOID) {
60,000!
270
        accepted = false;
271
      } else {
272
        accepted = contains(domain_ids_, model::materials[mat_index]->id());
120,000✔
273
      }
274
    } else {
275
      for (int i = 0; i < geom_state.n_coord(); i++) {
1,224,173✔
276
        auto id =
633,298✔
277
          (domain_type_ == DomainType::CELL)
278
            ? model::cells[geom_state.coord(i).cell()].get()->id_
633,298!
UNCOV
279
            : model::universes[geom_state.coord(i).universe()].get()->id_;
×
280
        if ((accepted = contains(domain_ids_, id)))
1,266,596✔
281
          break;
282
      }
283
    }
284
  }
285

286
  // Check if spatial site is in fissionable material
287
  if (accepted && only_fissionable_) {
10,695,618✔
288
    // Determine material
289
    auto mat_index = geom_state.material();
295,173✔
290
    if (mat_index == MATERIAL_VOID) {
295,173!
291
      accepted = false;
292
    } else {
293
      accepted = model::materials[mat_index]->fissionable();
295,173✔
294
    }
295
  }
296

297
  return accepted;
298
}
10,830,690✔
299

300
//==============================================================================
301
// IndependentSource implementation
302
//==============================================================================
303

304
IndependentSource::IndependentSource(
546✔
305
  UPtrSpace space, UPtrAngle angle, UPtrDist energy, UPtrDist time)
546✔
306
  : space_ {std::move(space)}, angle_ {std::move(angle)},
546✔
307
    energy_ {std::move(energy)}, time_ {std::move(time)}
546✔
308
{}
546✔
309

310
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
2,475✔
311
{
312
  // Check for particle type
313
  if (check_for_node(node, "particle")) {
2,475✔
314
    auto temp_str = get_node_value(node, "particle", false, true);
2,292✔
315
    particle_ = ParticleType(temp_str);
2,292✔
316
    if (particle_ == ParticleType::photon() ||
2,292✔
317
        particle_ == ParticleType::electron() ||
2,292✔
318
        particle_ == ParticleType::positron()) {
2,226!
319
      settings::photon_transport = true;
66✔
320
    }
321
  }
2,292✔
322
  validate_particle_type(particle_, "IndependentSource");
2,475✔
323

324
  // Check for external source file
325
  if (check_for_node(node, "file")) {
2,475!
326

327
  } else {
328

329
    // Spatial distribution for external source
330
    if (check_for_node(node, "space")) {
2,475✔
331
      space_ = SpatialDistribution::create(node.child("space"));
1,887✔
332
    } else {
333
      // If no spatial distribution specified, make it a point source
334
      space_ = UPtrSpace {new SpatialPoint()};
588✔
335
    }
336

337
    // For backwards compatibility, check for only fissionable setting on box
338
    // source
339
    auto space_box = dynamic_cast<SpatialBox*>(space_.get());
2,475!
340
    if (space_box) {
2,475✔
341
      if (!only_fissionable_) {
969✔
342
        only_fissionable_ = space_box->only_fissionable();
591✔
343
      }
344
    }
345

346
    // Determine external source angular distribution
347
    if (check_for_node(node, "angle")) {
2,475✔
348
      angle_ = UnitSphereDistribution::create(node.child("angle"));
915✔
349
    } else {
350
      angle_ = UPtrAngle {new Isotropic()};
1,560✔
351
    }
352

353
    // Determine external source energy distribution
354
    if (check_for_node(node, "energy")) {
2,475✔
355
      pugi::xml_node node_dist = node.child("energy");
1,296✔
356
      energy_ = distribution_from_xml(node_dist);
1,296✔
357

358
      // For decay photon sources, use the absolute photon emission rate in
359
      // [photons/s] as the source strength
360
      if (dynamic_cast<DecaySpectrum*>(energy_.get())) {
1,296!
361
        if (strength_ != 1.0) {
15!
UNCOV
362
          warning(fmt::format(
×
363
            "Source strength of {} is ignored because the source uses a "
364
            "DecaySpectrum energy distribution. The source strength will be "
365
            "set from the DecaySpectrum emission rate.",
UNCOV
366
            strength_));
×
367
        }
368
        strength_ = energy_->integral();
15✔
369
      }
370
    } else {
371
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
372
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
1,179✔
373
    }
374

375
    // Determine external source time distribution
376
    if (check_for_node(node, "time")) {
2,475✔
377
      pugi::xml_node node_dist = node.child("time");
9✔
378
      time_ = distribution_from_xml(node_dist);
9✔
379
    } else {
380
      // Default to a Constant time T=0
381
      double T[] {0.0};
2,466✔
382
      double p[] {1.0};
2,466✔
383
      time_ = UPtrDist {new Discrete {T, p, 1}};
2,466✔
384
    }
385
  }
386
}
2,475✔
387

388
SourceSite IndependentSource::sample(uint64_t* seed) const
9,828,216✔
389
{
390
  SourceSite site {};
9,828,216✔
391
  site.particle = particle_;
9,828,216✔
392
  double r_wgt = 1.0;
9,828,216✔
393
  double E_wgt = 1.0;
9,828,216✔
394

395
  // Repeat sampling source location until a good site has been accepted
396
  bool accepted = false;
9,828,216✔
397
  int64_t n_local_reject = 0;
9,828,216✔
398

399
  while (!accepted) {
20,114,368✔
400

401
    // Sample spatial distribution
402
    auto [r, r_wgt_temp] = space_->sample(seed);
10,286,152✔
403
    site.r = r;
10,286,152✔
404
    r_wgt = r_wgt_temp;
10,286,152✔
405

406
    // Check if sampled position satisfies spatial constraints
407
    accepted = satisfies_spatial_constraints(site.r);
10,286,152✔
408

409
    // Check for rejection
410
    if (!accepted) {
10,286,152✔
411
      ++n_local_reject;
457,936✔
412
      if (n_local_reject >= MAX_SOURCE_REJECTIONS_PER_SAMPLE) {
457,936!
UNCOV
413
        fatal_error("Exceeded maximum number of source rejections per "
×
414
                    "sample. Please check your source definition.");
415
      }
416
    }
417
  }
418

419
  // Sample angle
420
  auto [u, u_wgt] = angle_->sample(seed);
9,828,216✔
421
  site.u = u;
9,828,216✔
422

423
  site.wgt = r_wgt * u_wgt;
9,828,216✔
424

425
  // Sample energy and time for neutron and photon sources
426
  if (settings::solver_type != SolverType::RANDOM_RAY) {
9,828,216✔
427
    // Check for monoenergetic source above maximum particle energy
428
    auto p = particle_.transport_index();
9,208,416✔
429
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
9,208,416!
430
    auto decay_spectrum = dynamic_cast<DecaySpectrum*>(energy_.get());
9,208,416!
431
    if (energy_ptr) {
9,208,416✔
432
      auto energies =
4,781,256✔
433
        tensor::Tensor<double>(energy_ptr->x().data(), energy_ptr->x().size());
4,781,256✔
434
      if ((energies > data::energy_max[p]).any()) {
14,343,768!
435
        fatal_error("Source energy above range of energies of at least "
×
436
                    "one cross section table");
437
      }
438
    }
4,781,256✔
439

440
    while (true) {
9,208,416✔
441
      // Sample energy spectrum. For decay photon sources, also get the parent
442
      // nuclide index to store in the source site for tallying purposes.
443
      if (decay_spectrum) {
9,208,416✔
444
        auto sample = decay_spectrum->sample_with_parent(seed);
105,000✔
445
        site.E = sample.energy;
105,000✔
446
        E_wgt = sample.weight;
105,000✔
447
        site.parent_nuclide = sample.parent_nuclide;
105,000✔
448
      } else {
449
        auto [E, E_wgt_temp] = energy_->sample(seed);
9,103,416✔
450
        site.E = E;
9,103,416✔
451
        E_wgt = E_wgt_temp;
9,103,416✔
452
      }
453

454
      // Resample if energy falls above maximum particle energy
455
      if (site.E < data::energy_max[p] &&
18,416,832!
456
          (satisfies_energy_constraints(site.E)))
9,208,416✔
457
        break;
458

UNCOV
459
      ++n_local_reject;
×
UNCOV
460
      if (n_local_reject >= MAX_SOURCE_REJECTIONS_PER_SAMPLE) {
×
UNCOV
461
        fatal_error("Exceeded maximum number of source rejections per "
×
462
                    "sample. Please check your source definition.");
463
      }
464
    }
465

466
    // Sample particle creation time
467
    auto [time, time_wgt] = time_->sample(seed);
9,208,416✔
468
    site.time = time;
9,208,416✔
469

470
    site.wgt *= (E_wgt * time_wgt);
9,208,416✔
471
  }
472

473
  // Flush local rejection count into global counter
474
  if (n_local_reject > 0) {
9,828,216✔
475
    source_n_reject += n_local_reject;
98,106✔
476
  }
477

478
  return site;
9,828,216✔
479
}
480

481
//==============================================================================
482
// FileSource implementation
483
//==============================================================================
484

485
FileSource::FileSource(pugi::xml_node node) : Source(node)
15✔
486
{
487
  auto path = get_node_value(node, "file", false, true);
15✔
488
  load_sites_from_file(path);
15✔
489
}
12✔
490

491
FileSource::FileSource(const std::string& path)
6✔
492
{
493
  load_sites_from_file(path);
6✔
494
}
6✔
495

496
void FileSource::load_sites_from_file(const std::string& path)
21✔
497
{
498
  // If MCPL file, use the dedicated file reader
499
  if (ends_with(path, ".mcpl") || ends_with(path, ".mcpl.gz")) {
36!
500
    sites_ = mcpl_source_sites(path);
6✔
501
  } else {
502
    // Check if source file exists
503
    if (!file_exists(path)) {
15!
UNCOV
504
      fatal_error(fmt::format("Source file '{}' does not exist.", path));
×
505
    }
506

507
    write_message(6, "Reading source file from {}...", path);
15✔
508

509
    // Open the binary file
510
    hid_t file_id = file_open(path, 'r', true);
15✔
511

512
    // Check to make sure this is a source file
513
    std::string filetype;
15✔
514
    read_attribute(file_id, "filetype", filetype);
15✔
515
    if (filetype != "source" && filetype != "statepoint") {
15!
UNCOV
516
      fatal_error("Specified starting source file not a source file type.");
×
517
    }
518

519
    // Read in the source particles
520
    read_source_bank(file_id, sites_, false);
15✔
521

522
    // Close file
523
    file_close(file_id);
12✔
524
  }
12✔
525

526
  // Make sure particles in source file have valid types
527
  for (const auto& site : this->sites_) {
42,021✔
528
    validate_particle_type(site.particle, "FileSource");
84,006✔
529
  }
530
}
18✔
531

532
SourceSite FileSource::sample(uint64_t* seed) const
77,663✔
533
{
534
  // Sample a particle randomly from list
535
  size_t i_site = sites_.size() * prn(seed);
77,663✔
536
  return sites_[i_site];
77,663✔
537
}
538

539
//==============================================================================
540
// CompiledSourceWrapper implementation
541
//==============================================================================
542

543
CompiledSourceWrapper::CompiledSourceWrapper(pugi::xml_node node) : Source(node)
6✔
544
{
545
  // Get shared library path and parameters
546
  auto path = get_node_value(node, "library", false, true);
6✔
547
  std::string parameters;
6✔
548
  if (check_for_node(node, "parameters")) {
6✔
549
    parameters = get_node_value(node, "parameters", false, true);
3✔
550
  }
551
  setup(path, parameters);
6✔
552
}
6✔
553

554
void CompiledSourceWrapper::setup(
6✔
555
  const std::string& path, const std::string& parameters)
556
{
557
#ifdef HAS_DYNAMIC_LINKING
558
  // Open the library
559
  shared_library_ = dlopen(path.c_str(), RTLD_LAZY);
6✔
560
  if (!shared_library_) {
6!
UNCOV
561
    fatal_error("Couldn't open source library " + path);
×
562
  }
563

564
  // reset errors
565
  dlerror();
6✔
566

567
  // get the function to create the custom source from the library
568
  auto create_compiled_source = reinterpret_cast<create_compiled_source_t*>(
6✔
569
    dlsym(shared_library_, "openmc_create_source"));
6✔
570

571
  // check for any dlsym errors
572
  auto dlsym_error = dlerror();
6✔
573
  if (dlsym_error) {
6!
UNCOV
574
    std::string error_msg = fmt::format(
×
UNCOV
575
      "Couldn't open the openmc_create_source symbol: {}", dlsym_error);
×
UNCOV
576
    dlclose(shared_library_);
×
UNCOV
577
    fatal_error(error_msg);
×
UNCOV
578
  }
×
579

580
  // create a pointer to an instance of the custom source
581
  compiled_source_ = create_compiled_source(parameters);
6✔
582

583
#else
584
  fatal_error("Custom source libraries have not yet been implemented for "
585
              "non-POSIX systems");
586
#endif
587
}
6✔
588

589
CompiledSourceWrapper::~CompiledSourceWrapper()
12✔
590
{
591
  // Make sure custom source is cleared before closing shared library
592
  if (compiled_source_.get())
6!
593
    compiled_source_.reset();
6✔
594

595
#ifdef HAS_DYNAMIC_LINKING
596
  dlclose(shared_library_);
6✔
597
#else
598
  fatal_error("Custom source libraries have not yet been implemented for "
599
              "non-POSIX systems");
600
#endif
601
}
12✔
602

603
//==============================================================================
604
// MeshElementSpatial implementation
605
//==============================================================================
606

607
std::pair<Position, double> MeshElementSpatial::sample(uint64_t* seed) const
411,129✔
608
{
609
  return {model::meshes[mesh_index_]->sample_element(elem_index_, seed), 1.0};
411,129✔
610
}
611

612
//==============================================================================
613
// MeshSource implementation
614
//==============================================================================
615

616
MeshSource::MeshSource(pugi::xml_node node) : Source(node)
54✔
617
{
618
  int32_t mesh_id = stoi(get_node_value(node, "mesh"));
108✔
619
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
54✔
620
  const auto& mesh = model::meshes[mesh_idx];
54✔
621

622
  std::vector<double> strengths;
54✔
623
  // read all source distributions and populate strengths vector for MeshSpatial
624
  // object
625
  for (auto source_node : node.children("source")) {
450✔
626
    auto src = Source::create(source_node);
396✔
627
    if (auto ptr = dynamic_cast<IndependentSource*>(src.get())) {
396!
628
      src.release();
396✔
629
      sources_.emplace_back(ptr);
396✔
630
    } else {
UNCOV
631
      fatal_error(
×
632
        "The source assigned to each element must be an IndependentSource.");
633
    }
634
    strengths.push_back(sources_.back()->strength());
396✔
635
  }
396✔
636

637
  // Set spatial distributions for each mesh element
638
  for (int elem_index = 0; elem_index < sources_.size(); ++elem_index) {
450✔
639
    sources_[elem_index]->set_space(
396✔
640
      std::make_unique<MeshElementSpatial>(mesh_idx, elem_index));
792✔
641
  }
642

643
  // Make sure sources use valid particle types
644
  for (const auto& src : sources_) {
450✔
645
    validate_particle_type(src->particle_type(), "MeshSource");
792✔
646
  }
647

648
  // the number of source distributions should either be one or equal to the
649
  // number of mesh elements
650
  if (sources_.size() > 1 && sources_.size() != mesh->n_bins()) {
54!
UNCOV
651
    fatal_error(fmt::format("Incorrect number of source distributions ({}) for "
×
652
                            "mesh source with {} elements.",
UNCOV
653
      sources_.size(), mesh->n_bins()));
×
654
  }
655

656
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
54✔
657
}
54✔
658

659
SourceSite MeshSource::sample(uint64_t* seed) const
406,875✔
660
{
661
  // Sample a mesh element based on the relative strengths
662
  int32_t element = space_->sample_element_index(seed);
406,875✔
663

664
  // Sample the distribution for the specific mesh element; note that the
665
  // spatial distribution has been set for each element using MeshElementSpatial
666
  return source(element)->sample_with_constraints(seed);
813,750!
667
}
668

669
//==============================================================================
670
// Non-member functions
671
//==============================================================================
672

673
void initialize_source()
948✔
674
{
675
  write_message("Initializing source particles...", 5);
948✔
676

677
// Generation source sites from specified distribution in user input
678
#pragma omp parallel for
679
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
774,267✔
680
    // initialize random number seed
681
    int64_t id = simulation::total_gen * settings::n_particles +
773,319✔
682
                 simulation::work_index[mpi::rank] + i + 1;
773,319✔
683
    uint64_t seed = init_seed(id, STREAM_SOURCE);
773,319✔
684

685
    // sample external source distribution
686
    simulation::source_bank[i] = sample_external_source(&seed);
773,319✔
687
  }
688

689
  // Write out initial source
690
  if (settings::write_initial_source) {
948!
UNCOV
691
    write_message("Writing out initial source...", 5);
×
UNCOV
692
    std::string filename = settings::path_output + "initial_source.h5";
×
UNCOV
693
    hid_t file_id = file_open(filename, 'w', true);
×
UNCOV
694
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
×
UNCOV
695
    file_close(file_id);
×
UNCOV
696
  }
×
697
}
948✔
698

699
SourceSite sample_external_source(uint64_t* seed)
8,984,631✔
700
{
701
  // Sample from among multiple source distributions
702
  int i = 0;
8,984,631✔
703
  int n_sources = model::external_sources.size();
8,984,631✔
704
  if (n_sources > 1) {
8,984,631✔
705
    if (settings::uniform_source_sampling) {
969,900✔
706
      i = prn(seed) * n_sources;
600✔
707
    } else {
708
      i = model::external_sources_probability.sample(seed);
969,300✔
709
    }
710
  }
711

712
  // Sample source site from i-th source distribution
713
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
8,984,631✔
714

715
  // For uniform source sampling, multiply the weight by the ratio of the actual
716
  // probability of sampling source i to the biased probability of sampling
717
  // source i, which is (strength_i / total_strength) / (1 / n)
718
  if (n_sources > 1 && settings::uniform_source_sampling) {
8,984,628✔
719
    double total_strength = model::external_sources_probability.integral();
600✔
720
    site.wgt *=
1,200✔
721
      model::external_sources[i]->strength() * n_sources / total_strength;
600✔
722
  }
723

724
  // If running in MG, convert site.E to group
725
  if (!settings::run_CE) {
8,984,628✔
726
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
476,190✔
727
      data::mg.rev_energy_bins_.end(), site.E);
728
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
476,190✔
729
  }
730

731
  return site;
8,984,628✔
732
}
733

734
void free_memory_source()
2,127✔
735
{
736
  model::external_sources.clear();
2,127✔
737
  model::adjoint_sources.clear();
2,127✔
738
  reset_source_rejection_counters();
2,127✔
739
}
2,127✔
740

741
void reset_source_rejection_counters()
3,957✔
742
{
743
  source_n_accept = 0;
3,957✔
744
  source_n_reject = 0;
3,957✔
745
}
3,957✔
746

747
//==============================================================================
748
// C API
749
//==============================================================================
750

751
extern "C" int openmc_sample_external_source(
99✔
752
  size_t n, uint64_t* seed, void* sites)
753
{
754
  if (!sites || !seed) {
99!
UNCOV
755
    set_errmsg("Received null pointer.");
×
UNCOV
756
    return OPENMC_E_INVALID_ARGUMENT;
×
757
  }
758

759
  if (model::external_sources.empty()) {
99!
UNCOV
760
    set_errmsg("No external sources have been defined.");
×
UNCOV
761
    return OPENMC_E_OUT_OF_BOUNDS;
×
762
  }
763

764
  auto sites_array = static_cast<SourceSite*>(sites);
99✔
765

766
  // Derive independent per-particle seeds from the base seed so that
767
  // each iteration has its own RNG state for thread-safe parallel sampling.
768
  uint64_t base_seed = *seed;
99✔
769

770
#pragma omp parallel for schedule(static)
771
  for (size_t i = 0; i < n; ++i) {
642,891✔
772
    uint64_t particle_seed = init_seed(base_seed + i, STREAM_SOURCE);
642,792✔
773
    sites_array[i] = sample_external_source(&particle_seed);
642,792✔
774
  }
775
  return 0;
776
}
777

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