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

openmc-dev / openmc / 22500302709

27 Feb 2026 07:16PM UTC coverage: 81.512% (-0.3%) from 81.826%
22500302709

Pull #3830

github

web-flow
Merge 25fbb4266 into b3788f11e
Pull Request #3830: Parallelize sampling external sources and threadsafe rejection counters

17488 of 25193 branches covered (69.42%)

Branch coverage included in aggregate %.

59 of 66 new or added lines in 6 files covered. (89.39%)

841 existing lines in 44 files now uncovered.

57726 of 67081 relevant lines covered (86.05%)

44920080.48 hits per line

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

80.98
/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)
78,784✔
46
{
47
  if (type.is_transportable())
78,784!
48
    return;
78,784✔
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
DiscreteIndex external_sources_probability;
66

67
} // namespace model
68

69
//==============================================================================
70
// Source implementation
71
//==============================================================================
72

73
Source::Source(pugi::xml_node node)
4,248✔
74
{
75
  // Check for source strength
76
  if (check_for_node(node, "strength")) {
4,248✔
77
    strength_ = std::stod(get_node_value(node, "strength"));
7,980✔
78
    if (strength_ < 0.0) {
3,990!
79
      fatal_error("Source strength is negative.");
×
80
    }
81
  }
82

83
  // Check for additional defined constraints
84
  read_constraints(node);
4,248✔
85
}
4,248✔
86

87
unique_ptr<Source> Source::create(pugi::xml_node node)
4,248✔
88
{
89
  // if the source type is present, use it to determine the type
90
  // of object to create
91
  if (check_for_node(node, "type")) {
4,248✔
92
    std::string source_type = get_node_value(node, "type");
3,897✔
93
    if (source_type == "independent") {
3,897✔
94
      return make_unique<IndependentSource>(node);
3,780✔
95
    } else if (source_type == "file") {
117✔
96
      return make_unique<FileSource>(node);
15✔
97
    } else if (source_type == "compiled") {
102✔
98
      return make_unique<CompiledSourceWrapper>(node);
12✔
99
    } else if (source_type == "mesh") {
90!
100
      return make_unique<MeshSource>(node);
90✔
101
    } else {
102
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
103
    }
104
  } else {
3,892✔
105
    // support legacy source format
106
    if (check_for_node(node, "file")) {
351✔
107
      return make_unique<FileSource>(node);
12✔
108
    } else if (check_for_node(node, "library")) {
339!
109
      return make_unique<CompiledSourceWrapper>(node);
×
110
    } else {
111
      return make_unique<IndependentSource>(node);
339✔
112
    }
113
  }
114
}
115

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

126
  // Check for domains to reject from
127
  if (check_for_node(node, "domain_type")) {
4,248✔
128
    std::string domain_type = get_node_value(node, "domain_type");
194✔
129
    if (domain_type == "cell") {
194✔
130
      domain_type_ = DomainType::CELL;
44✔
131
    } else if (domain_type == "material") {
150✔
132
      domain_type_ = DomainType::MATERIAL;
12✔
133
    } else if (domain_type == "universe") {
138!
134
      domain_type_ = DomainType::UNIVERSE;
138✔
135
    } else {
136
      fatal_error(
×
137
        std::string("Unrecognized domain type for constraint: " + domain_type));
×
138
    }
139

140
    auto ids = get_node_array<int>(node, "domain_ids");
194✔
141
    domain_ids_.insert(ids.begin(), ids.end());
194✔
142
  }
194✔
143

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

159
  if (check_for_node(node, "fissionable")) {
4,248✔
160
    only_fissionable_ = get_node_value_bool(node, "fissionable");
607✔
161
  }
162

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

177
void check_rejection_fraction(int64_t n_reject, int64_t n_accept)
15,274,773✔
178
{
179
  // Don't check unless we've hit a minimum number of total sites rejected
180
  if (n_reject < EXTSRC_REJECT_THRESHOLD)
15,274,773✔
181
    return;
182

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

194
SourceSite Source::sample_with_constraints(uint64_t* seed) const
15,274,773✔
195
{
196
  bool accepted = false;
15,274,773✔
197
  int64_t n_local_reject = 0;
15,274,773✔
198
  SourceSite site {};
15,274,773✔
199

200
  while (!accepted) {
46,441,049✔
201
    // Sample a source site without considering constraints yet
202
    site = this->sample(seed);
15,891,503✔
203

204
    if (constraints_applied()) {
15,891,503✔
205
      accepted = true;
206
    } else {
207
      // Check whether sampled site satisfies constraints
208
      accepted = satisfies_spatial_constraints(site.r) &&
17,439,209✔
209
                 satisfies_energy_constraints(site.E) &&
1,232,213✔
210
                 satisfies_time_constraints(site.time);
310,333✔
211
      if (!accepted) {
616,730✔
212
        ++n_local_reject;
616,730✔
213

214
        // Check per-particle rejection limit
215
        if (n_local_reject >= settings::max_source_rejections_per_sample) {
616,730!
NEW
216
          fatal_error("Exceeded maximum number of source rejections per "
×
217
                      "sample. Please check your source definition or increase "
218
                      "Settings.max_source_rejections_per_sample.");
219
        }
220

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

231
  // Flush local rejection count, update accept counter, and check overall
232
  // rejection fraction
233
  if (n_local_reject > 0) {
15,274,773✔
234
    source_n_reject += n_local_reject;
8,765✔
235
  }
236
  ++source_n_accept;
15,274,773✔
237
  check_rejection_fraction(source_n_reject, source_n_accept);
15,274,773✔
238

239
  return site;
15,274,769✔
240
}
241

242
bool Source::satisfies_energy_constraints(double E) const
15,290,299✔
243
{
244
  return E > energy_bounds_.first && E < energy_bounds_.second;
15,290,299!
245
}
246

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

252
bool Source::satisfies_spatial_constraints(Position r) const
17,531,886✔
253
{
254
  GeometryState geom_state;
17,531,886✔
255
  geom_state.r() = r;
17,531,886✔
256
  geom_state.u() = {0.0, 0.0, 1.0};
17,531,886✔
257

258
  // Reject particle if it's not in the geometry at all
259
  bool found = exhaustive_find_cell(geom_state);
17,531,886✔
260
  if (!found)
17,531,886✔
261
    return false;
262

263
  // Check the geometry state against specified domains
264
  bool accepted = true;
17,309,151✔
265
  if (!domain_ids_.empty()) {
17,309,151✔
266
    if (domain_type_ == DomainType::MATERIAL) {
991,141!
267
      auto mat_index = geom_state.material();
×
268
      if (mat_index == MATERIAL_VOID) {
×
269
        accepted = false;
270
      } else {
271
        accepted = contains(domain_ids_, model::materials[mat_index]->id());
×
272
      }
273
    } else {
274
      for (int i = 0; i < geom_state.n_coord(); i++) {
1,912,718✔
275
        auto id =
991,141✔
276
          (domain_type_ == DomainType::CELL)
277
            ? model::cells[geom_state.coord(i).cell()].get()->id_
991,141!
278
            : model::universes[geom_state.coord(i).universe()].get()->id_;
×
279
        if ((accepted = contains(domain_ids_, id)))
1,982,282✔
280
          break;
281
      }
282
    }
283
  }
284

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

296
  return accepted;
297
}
17,531,886✔
298

299
//==============================================================================
300
// IndependentSource implementation
301
//==============================================================================
302

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

309
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
4,119✔
310
{
311
  // Check for particle type
312
  if (check_for_node(node, "particle")) {
4,119✔
313
    auto temp_str = get_node_value(node, "particle", false, true);
3,780✔
314
    particle_ = ParticleType(temp_str);
3,780✔
315
    if (particle_ == ParticleType::photon() ||
3,780✔
316
        particle_ == ParticleType::electron() ||
3,780✔
317
        particle_ == ParticleType::positron()) {
3,711!
318
      settings::photon_transport = true;
69✔
319
    }
320
  }
3,780✔
321
  validate_particle_type(particle_, "IndependentSource");
4,119✔
322

323
  // Check for external source file
324
  if (check_for_node(node, "file")) {
4,119!
325

326
  } else {
327

328
    // Spatial distribution for external source
329
    if (check_for_node(node, "space")) {
4,119✔
330
      space_ = SpatialDistribution::create(node.child("space"));
3,186✔
331
    } else {
332
      // If no spatial distribution specified, make it a point source
333
      space_ = UPtrSpace {new SpatialPoint()};
933✔
334
    }
335

336
    // For backwards compatibility, check for only fissionable setting on box
337
    // source
338
    auto space_box = dynamic_cast<SpatialBox*>(space_.get());
4,119!
339
    if (space_box) {
4,119✔
340
      if (!only_fissionable_) {
1,677✔
341
        only_fissionable_ = space_box->only_fissionable();
1,070✔
342
      }
343
    }
344

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

352
    // Determine external source energy distribution
353
    if (check_for_node(node, "energy")) {
4,119✔
354
      pugi::xml_node node_dist = node.child("energy");
2,098✔
355
      energy_ = distribution_from_xml(node_dist);
2,098✔
356
    } else {
357
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
358
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
2,021✔
359
    }
360

361
    // Determine external source time distribution
362
    if (check_for_node(node, "time")) {
4,119✔
363
      pugi::xml_node node_dist = node.child("time");
17✔
364
      time_ = distribution_from_xml(node_dist);
17✔
365
    } else {
366
      // Default to a Constant time T=0
367
      double T[] {0.0};
4,102✔
368
      double p[] {1.0};
4,102✔
369
      time_ = UPtrDist {new Discrete {T, p, 1}};
4,102✔
370
    }
371
  }
372
}
4,119✔
373

374
SourceSite IndependentSource::sample(uint64_t* seed) const
15,927,623✔
375
{
376
  SourceSite site {};
15,927,623✔
377
  site.particle = particle_;
15,927,623✔
378
  double r_wgt = 1.0;
15,927,623✔
379
  double E_wgt = 1.0;
15,927,623✔
380

381
  // Repeat sampling source location until a good site has been accepted
382
  bool accepted = false;
15,927,623✔
383
  int64_t n_local_reject = 0;
15,927,623✔
384

385
  while (!accepted) {
32,537,629✔
386

387
    // Sample spatial distribution
388
    auto [r, r_wgt_temp] = space_->sample(seed);
16,610,006✔
389
    site.r = r;
16,610,006✔
390
    r_wgt = r_wgt_temp;
16,610,006✔
391

392
    // Check if sampled position satisfies spatial constraints
393
    accepted = satisfies_spatial_constraints(site.r);
16,610,006✔
394

395
    // Check for rejection
396
    if (!accepted) {
16,610,006✔
397
      ++n_local_reject;
682,383✔
398
      if (n_local_reject >= settings::max_source_rejections_per_sample) {
682,383!
NEW
399
        fatal_error("Exceeded maximum number of source rejections per "
×
400
                    "sample. Please check your source definition or increase "
401
                    "Settings.max_source_rejections_per_sample.");
402
      }
403
    }
404
  }
405

406
  // Sample angle
407
  auto [u, u_wgt] = angle_->sample(seed);
15,927,623✔
408
  site.u = u;
15,927,623✔
409

410
  site.wgt = r_wgt * u_wgt;
15,927,623✔
411

412
  // Sample energy and time for neutron and photon sources
413
  if (settings::solver_type != SolverType::RANDOM_RAY) {
15,927,623✔
414
    // Check for monoenergetic source above maximum particle energy
415
    auto p = particle_.transport_index();
14,969,623✔
416
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
14,969,623!
417
    if (energy_ptr) {
14,969,623✔
418
      auto energies =
7,885,455✔
419
        tensor::Tensor<double>(energy_ptr->x().data(), energy_ptr->x().size());
7,885,455✔
420
      if ((energies > data::energy_max[p]).any()) {
23,656,365!
421
        fatal_error("Source energy above range of energies of at least "
×
422
                    "one cross section table");
423
      }
424
    }
7,885,455✔
425

426
    while (true) {
14,969,623✔
427
      // Sample energy spectrum
428
      auto [E, E_wgt_temp] = energy_->sample(seed);
14,969,623✔
429
      site.E = E;
14,969,623✔
430
      E_wgt = E_wgt_temp;
14,969,623✔
431

432
      // Resample if energy falls above maximum particle energy
433
      if (site.E < data::energy_max[p] &&
29,939,246!
434
          (satisfies_energy_constraints(site.E)))
14,969,623✔
435
        break;
436

NEW
437
      ++n_local_reject;
×
NEW
438
      if (n_local_reject >= settings::max_source_rejections_per_sample) {
×
NEW
439
        fatal_error("Exceeded maximum number of source rejections per "
×
440
                    "sample. Please check your source definition or increase "
441
                    "Settings.max_source_rejections_per_sample.");
442
      }
UNCOV
443
    }
×
444

445
    // Sample particle creation time
446
    auto [time, time_wgt] = time_->sample(seed);
14,969,623✔
447
    site.time = time;
14,969,623✔
448

449
    site.wgt *= (E_wgt * time_wgt);
14,969,623✔
450
  }
451

452
  // Flush local rejection count into global counter
453
  if (n_local_reject > 0) {
15,927,623✔
454
    source_n_reject += n_local_reject;
160,357✔
455
  }
456

457
  return site;
15,927,623✔
458
}
459

460
//==============================================================================
461
// FileSource implementation
462
//==============================================================================
463

464
FileSource::FileSource(pugi::xml_node node) : Source(node)
27✔
465
{
466
  auto path = get_node_value(node, "file", false, true);
27✔
467
  load_sites_from_file(path);
27✔
468
}
22✔
469

470
FileSource::FileSource(const std::string& path)
12✔
471
{
472
  load_sites_from_file(path);
12✔
473
}
12✔
474

475
void FileSource::load_sites_from_file(const std::string& path)
39✔
476
{
477
  // If MCPL file, use the dedicated file reader
478
  if (ends_with(path, ".mcpl") || ends_with(path, ".mcpl.gz")) {
66!
479
    sites_ = mcpl_source_sites(path);
12✔
480
  } else {
481
    // Check if source file exists
482
    if (!file_exists(path)) {
27!
483
      fatal_error(fmt::format("Source file '{}' does not exist.", path));
×
484
    }
485

486
    write_message(6, "Reading source file from {}...", path);
27✔
487

488
    // Open the binary file
489
    hid_t file_id = file_open(path, 'r', true);
27✔
490

491
    // Check to make sure this is a source file
492
    std::string filetype;
27✔
493
    read_attribute(file_id, "filetype", filetype);
27✔
494
    if (filetype != "source" && filetype != "statepoint") {
27!
495
      fatal_error("Specified starting source file not a source file type.");
×
496
    }
497

498
    // Read in the source particles
499
    read_source_bank(file_id, sites_, false);
27✔
500

501
    // Close file
502
    file_close(file_id);
22✔
503
  }
22✔
504

505
  // Make sure particles in source file have valid types
506
  for (const auto& site : this->sites_) {
74,039✔
507
    validate_particle_type(site.particle, "FileSource");
148,010✔
508
  }
509
}
34✔
510

511
SourceSite FileSource::sample(uint64_t* seed) const
130,676✔
512
{
513
  // Sample a particle randomly from list
514
  size_t i_site = sites_.size() * prn(seed);
130,676✔
515
  return sites_[i_site];
130,676✔
516
}
517

518
//==============================================================================
519
// CompiledSourceWrapper implementation
520
//==============================================================================
521

522
CompiledSourceWrapper::CompiledSourceWrapper(pugi::xml_node node) : Source(node)
12✔
523
{
524
  // Get shared library path and parameters
525
  auto path = get_node_value(node, "library", false, true);
12✔
526
  std::string parameters;
12✔
527
  if (check_for_node(node, "parameters")) {
12✔
528
    parameters = get_node_value(node, "parameters", false, true);
6✔
529
  }
530
  setup(path, parameters);
12✔
531
}
12✔
532

533
void CompiledSourceWrapper::setup(
12✔
534
  const std::string& path, const std::string& parameters)
535
{
536
#ifdef HAS_DYNAMIC_LINKING
537
  // Open the library
538
  shared_library_ = dlopen(path.c_str(), RTLD_LAZY);
12✔
539
  if (!shared_library_) {
12!
540
    fatal_error("Couldn't open source library " + path);
×
541
  }
542

543
  // reset errors
544
  dlerror();
12✔
545

546
  // get the function to create the custom source from the library
547
  auto create_compiled_source = reinterpret_cast<create_compiled_source_t*>(
12✔
548
    dlsym(shared_library_, "openmc_create_source"));
12✔
549

550
  // check for any dlsym errors
551
  auto dlsym_error = dlerror();
12✔
552
  if (dlsym_error) {
12!
UNCOV
553
    std::string error_msg = fmt::format(
×
554
      "Couldn't open the openmc_create_source symbol: {}", dlsym_error);
×
555
    dlclose(shared_library_);
×
556
    fatal_error(error_msg);
×
557
  }
×
558

559
  // create a pointer to an instance of the custom source
560
  compiled_source_ = create_compiled_source(parameters);
12✔
561

562
#else
563
  fatal_error("Custom source libraries have not yet been implemented for "
564
              "non-POSIX systems");
565
#endif
566
}
12✔
567

568
CompiledSourceWrapper::~CompiledSourceWrapper()
24✔
569
{
570
  // Make sure custom source is cleared before closing shared library
571
  if (compiled_source_.get())
12!
572
    compiled_source_.reset();
12✔
573

574
#ifdef HAS_DYNAMIC_LINKING
575
  dlclose(shared_library_);
12✔
576
#else
577
  fatal_error("Custom source libraries have not yet been implemented for "
578
              "non-POSIX systems");
579
#endif
580
}
24✔
581

582
//==============================================================================
583
// MeshElementSpatial implementation
584
//==============================================================================
585

586
std::pair<Position, double> MeshElementSpatial::sample(uint64_t* seed) const
697,359✔
587
{
588
  return {model::meshes[mesh_index_]->sample_element(elem_index_, seed), 1.0};
697,359✔
589
}
590

591
//==============================================================================
592
// MeshSource implementation
593
//==============================================================================
594

595
MeshSource::MeshSource(pugi::xml_node node) : Source(node)
90✔
596
{
597
  int32_t mesh_id = stoi(get_node_value(node, "mesh"));
180✔
598
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
90✔
599
  const auto& mesh = model::meshes[mesh_idx];
90✔
600

601
  std::vector<double> strengths;
90✔
602
  // read all source distributions and populate strengths vector for MeshSpatial
603
  // object
604
  for (auto source_node : node.children("source")) {
750✔
605
    auto src = Source::create(source_node);
660✔
606
    if (auto ptr = dynamic_cast<IndependentSource*>(src.get())) {
660!
607
      src.release();
660✔
608
      sources_.emplace_back(ptr);
660✔
609
    } else {
610
      fatal_error(
×
611
        "The source assigned to each element must be an IndependentSource.");
612
    }
613
    strengths.push_back(sources_.back()->strength());
660✔
614
  }
660✔
615

616
  // Set spatial distributions for each mesh element
617
  for (int elem_index = 0; elem_index < sources_.size(); ++elem_index) {
750✔
618
    sources_[elem_index]->set_space(
660✔
619
      std::make_unique<MeshElementSpatial>(mesh_idx, elem_index));
1,320✔
620
  }
621

622
  // Make sure sources use valid particle types
623
  for (const auto& src : sources_) {
750✔
624
    validate_particle_type(src->particle_type(), "MeshSource");
1,320✔
625
  }
626

627
  // the number of source distributions should either be one or equal to the
628
  // number of mesh elements
629
  if (sources_.size() > 1 && sources_.size() != mesh->n_bins()) {
90!
630
    fatal_error(fmt::format("Incorrect number of source distributions ({}) for "
×
631
                            "mesh source with {} elements.",
632
      sources_.size(), mesh->n_bins()));
×
633
  }
634

635
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
90✔
636
}
90✔
637

638
SourceSite MeshSource::sample(uint64_t* seed) const
691,204✔
639
{
640
  // Sample a mesh element based on the relative strengths
641
  int32_t element = space_->sample_element_index(seed);
691,204✔
642

643
  // Sample the distribution for the specific mesh element; note that the
644
  // spatial distribution has been set for each element using MeshElementSpatial
645
  return source(element)->sample_with_constraints(seed);
1,382,408!
646
}
647

648
//==============================================================================
649
// Non-member functions
650
//==============================================================================
651

652
void initialize_source()
1,630✔
653
{
654
  write_message("Initializing source particles...", 5);
1,630✔
655

656
// Generation source sites from specified distribution in user input
657
#pragma omp parallel for
658
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
1,205,295✔
659
    // initialize random number seed
660
    int64_t id = simulation::total_gen * settings::n_particles +
1,203,665✔
661
                 simulation::work_index[mpi::rank] + i + 1;
1,203,665✔
662
    uint64_t seed = init_seed(id, STREAM_SOURCE);
1,203,665✔
663

664
    // sample external source distribution
665
    simulation::source_bank[i] = sample_external_source(&seed);
1,203,665✔
666
  }
667

668
  // Write out initial source
669
  if (settings::write_initial_source) {
1,630!
670
    write_message("Writing out initial source...", 5);
×
671
    std::string filename = settings::path_output + "initial_source.h5";
×
672
    hid_t file_id = file_open(filename, 'w', true);
×
673
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
×
674
    file_close(file_id);
×
675
  }
×
676
}
1,630✔
677

678
SourceSite sample_external_source(uint64_t* seed)
14,583,569✔
679
{
680
  // Sample from among multiple source distributions
681
  int i = 0;
14,583,569✔
682
  int n_sources = model::external_sources.size();
14,583,569✔
683
  if (n_sources > 1) {
14,583,569✔
684
    if (settings::uniform_source_sampling) {
1,616,500✔
685
      i = prn(seed) * n_sources;
1,000✔
686
    } else {
687
      i = model::external_sources_probability.sample(seed);
1,615,500✔
688
    }
689
  }
690

691
  // Sample source site from i-th source distribution
692
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
14,583,569✔
693

694
  // For uniform source sampling, multiply the weight by the ratio of the actual
695
  // probability of sampling source i to the biased probability of sampling
696
  // source i, which is (strength_i / total_strength) / (1 / n)
697
  if (n_sources > 1 && settings::uniform_source_sampling) {
14,583,565✔
698
    double total_strength = model::external_sources_probability.integral();
1,000✔
699
    site.wgt *=
2,000✔
700
      model::external_sources[i]->strength() * n_sources / total_strength;
1,000✔
701
  }
702

703
  // If running in MG, convert site.E to group
704
  if (!settings::run_CE) {
14,583,565✔
705
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
792,000✔
706
      data::mg.rev_energy_bins_.end(), site.E);
707
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
792,000✔
708
  }
709

710
  return site;
14,583,565✔
711
}
712

713
void free_memory_source()
3,507✔
714
{
715
  model::external_sources.clear();
3,507✔
716
  reset_source_rejection_counters();
3,507✔
717
}
3,507✔
718

719
void reset_source_rejection_counters()
6,536✔
720
{
721
  source_n_accept = 0;
6,536✔
722
  source_n_reject = 0;
6,536✔
723
}
6,536✔
724

725
//==============================================================================
726
// C API
727
//==============================================================================
728

729
extern "C" int openmc_sample_external_source(
165✔
730
  size_t n, uint64_t* seed, void* sites)
731
{
732
  if (!sites || !seed) {
165!
733
    set_errmsg("Received null pointer.");
×
734
    return OPENMC_E_INVALID_ARGUMENT;
×
735
  }
736

737
  if (model::external_sources.empty()) {
165!
738
    set_errmsg("No external sources have been defined.");
×
739
    return OPENMC_E_OUT_OF_BOUNDS;
×
740
  }
741

742
  auto sites_array = static_cast<SourceSite*>(sites);
165✔
743

744
  // Derive independent per-particle seeds from the base seed so that
745
  // each iteration has its own RNG state for thread-safe parallel sampling.
746
  uint64_t base_seed = *seed;
165✔
747

748
#pragma omp parallel for schedule(static)
749
  for (size_t i = 0; i < n; ++i) {
1,071,485✔
750
    uint64_t particle_seed = init_seed(base_seed + i, STREAM_SOURCE);
1,071,320✔
751
    sites_array[i] = sample_external_source(&particle_seed);
1,071,320✔
752
  }
753
  return 0;
754
}
755

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