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

openmc-dev / openmc / 22509916028

28 Feb 2026 01:03AM UTC coverage: 81.503%. First build
22509916028

Pull #3830

github

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

17484 of 25188 branches covered (69.41%)

Branch coverage included in aggregate %.

50 of 63 new or added lines in 4 files covered. (79.37%)

57715 of 67077 relevant lines covered (86.04%)

44921609.46 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,786✔
46
{
47
  if (type.is_transportable())
78,786!
48
    return;
78,786✔
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,250✔
74
{
75
  // Check for source strength
76
  if (check_for_node(node, "strength")) {
4,250✔
77
    strength_ = std::stod(get_node_value(node, "strength"));
7,984✔
78
    if (strength_ < 0.0) {
3,992!
79
      fatal_error("Source strength is negative.");
×
80
    }
81
  }
82

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

87
unique_ptr<Source> Source::create(pugi::xml_node node)
4,250✔
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,250✔
92
    std::string source_type = get_node_value(node, "type");
3,899✔
93
    if (source_type == "independent") {
3,899✔
94
      return make_unique<IndependentSource>(node);
3,782✔
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,894✔
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,250✔
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,250✔
122
  if (constraints_node) {
4,250✔
123
    node = constraints_node;
806✔
124
  }
125

126
  // Check for domains to reject from
127
  if (check_for_node(node, "domain_type")) {
4,250✔
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,250✔
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,250✔
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,250✔
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,250!
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,250✔
176

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

183
  // Compute fraction of accepted sites and compare against minimum
184
  double fraction = static_cast<double>(n_accept) / n_reject;
596,366✔
185
  if (fraction <= settings::source_rejection_fraction) {
596,366✔
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,295,244✔
195
{
196
  bool accepted = false;
15,295,244✔
197
  int64_t n_local_reject = 0;
15,295,244✔
198
  SourceSite site {};
15,295,244✔
199

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

204
    if (constraints_applied()) {
15,901,503✔
205
      accepted = true;
206
    } else {
207
      // Check whether sampled site satisfies constraints
208
      accepted = satisfies_spatial_constraints(site.r) &&
17,438,146✔
209
                 satisfies_energy_constraints(site.E) &&
1,221,451✔
210
                 satisfies_time_constraints(site.time);
310,042✔
211
      if (!accepted) {
606,259✔
212
        ++n_local_reject;
606,259✔
213

214
        // Check per-particle rejection limit
215
        if (n_local_reject >= MAX_SOURCE_REJECTIONS_PER_SAMPLE) {
606,259!
NEW
216
          fatal_error("Exceeded maximum number of source rejections per "
×
217
                      "sample. Please check your source definition.");
218
        }
219

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

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

238
  return site;
15,295,240✔
239
}
240

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

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

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

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

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

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

295
  return accepted;
296
}
17,541,884✔
297

298
//==============================================================================
299
// IndependentSource implementation
300
//==============================================================================
301

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

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

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

325
  } else {
326

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

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

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

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

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

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

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

384
  while (!accepted) {
32,578,569✔
385

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

391
    // Check if sampled position satisfies spatial constraints
392
    accepted = satisfies_spatial_constraints(site.r);
16,630,475✔
393

394
    // Check for rejection
395
    if (!accepted) {
16,630,475✔
396
      ++n_local_reject;
682,381✔
397
      if (n_local_reject >= MAX_SOURCE_REJECTIONS_PER_SAMPLE) {
682,381!
NEW
398
        fatal_error("Exceeded maximum number of source rejections per "
×
399
                    "sample. Please check your source definition.");
400
      }
401
    }
402
  }
403

404
  // Sample angle
405
  auto [u, u_wgt] = angle_->sample(seed);
15,948,094✔
406
  site.u = u;
15,948,094✔
407

408
  site.wgt = r_wgt * u_wgt;
15,948,094✔
409

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

424
    while (true) {
14,990,094✔
425
      // Sample energy spectrum
426
      auto [E, E_wgt_temp] = energy_->sample(seed);
14,990,094✔
427
      site.E = E;
14,990,094✔
428
      E_wgt = E_wgt_temp;
14,990,094✔
429

430
      // Resample if energy falls above maximum particle energy
431
      if (site.E < data::energy_max[p] &&
29,980,188!
432
          (satisfies_energy_constraints(site.E)))
14,990,094✔
433
        break;
434

NEW
435
      ++n_local_reject;
×
NEW
436
      if (n_local_reject >= MAX_SOURCE_REJECTIONS_PER_SAMPLE) {
×
NEW
437
        fatal_error("Exceeded maximum number of source rejections per "
×
438
                    "sample. Please check your source definition.");
439
      }
440
    }
×
441

442
    // Sample particle creation time
443
    auto [time, time_wgt] = time_->sample(seed);
14,990,094✔
444
    site.time = time;
14,990,094✔
445

446
    site.wgt *= (E_wgt * time_wgt);
14,990,094✔
447
  }
448

449
  // Flush local rejection count into global counter
450
  if (n_local_reject > 0) {
15,948,094✔
451
    source_n_reject += n_local_reject;
160,411✔
452
  }
453

454
  return site;
15,948,094✔
455
}
456

457
//==============================================================================
458
// FileSource implementation
459
//==============================================================================
460

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

467
FileSource::FileSource(const std::string& path)
12✔
468
{
469
  load_sites_from_file(path);
12✔
470
}
12✔
471

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

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

485
    // Open the binary file
486
    hid_t file_id = file_open(path, 'r', true);
27✔
487

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

495
    // Read in the source particles
496
    read_source_bank(file_id, sites_, false);
27✔
497

498
    // Close file
499
    file_close(file_id);
22✔
500
  }
22✔
501

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

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

515
//==============================================================================
516
// CompiledSourceWrapper implementation
517
//==============================================================================
518

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

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

540
  // reset errors
541
  dlerror();
12✔
542

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

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

556
  // create a pointer to an instance of the custom source
557
  compiled_source_ = create_compiled_source(parameters);
12✔
558

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

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

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

579
//==============================================================================
580
// MeshElementSpatial implementation
581
//==============================================================================
582

583
std::pair<Position, double> MeshElementSpatial::sample(uint64_t* seed) const
687,563✔
584
{
585
  return {model::meshes[mesh_index_]->sample_element(elem_index_, seed), 1.0};
687,563✔
586
}
587

588
//==============================================================================
589
// MeshSource implementation
590
//==============================================================================
591

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

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

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

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

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

632
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
90✔
633
}
90✔
634

635
SourceSite MeshSource::sample(uint64_t* seed) const
681,325✔
636
{
637
  // Sample a mesh element based on the relative strengths
638
  int32_t element = space_->sample_element_index(seed);
681,325✔
639

640
  // Sample the distribution for the specific mesh element; note that the
641
  // spatial distribution has been set for each element using MeshElementSpatial
642
  return source(element)->sample_with_constraints(seed);
1,362,650!
643
}
644

645
//==============================================================================
646
// Non-member functions
647
//==============================================================================
648

649
void initialize_source()
1,630✔
650
{
651
  write_message("Initializing source particles...", 5);
1,630✔
652

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

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

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

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

688
  // Sample source site from i-th source distribution
689
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
14,613,919✔
690

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

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

707
  return site;
14,613,915✔
708
}
709

710
void free_memory_source()
3,509✔
711
{
712
  model::external_sources.clear();
3,509✔
713
  reset_source_rejection_counters();
3,509✔
714
}
3,509✔
715

716
void reset_source_rejection_counters()
6,541✔
717
{
718
  source_n_accept = 0;
6,541✔
719
  source_n_reject = 0;
6,541✔
720
}
6,541✔
721

722
//==============================================================================
723
// C API
724
//==============================================================================
725

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

734
  if (model::external_sources.empty()) {
195!
735
    set_errmsg("No external sources have been defined.");
×
736
    return OPENMC_E_OUT_OF_BOUNDS;
×
737
  }
738

739
  auto sites_array = static_cast<SourceSite*>(sites);
195✔
740

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

745
#pragma omp parallel for schedule(static)
746
  for (size_t i = 0; i < n; ++i) {
1,071,865✔
747
    uint64_t particle_seed = init_seed(base_seed + i, STREAM_SOURCE);
1,071,670✔
748
    sites_array[i] = sample_external_source(&particle_seed);
1,071,670✔
749
  }
750
  return 0;
751
}
752

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