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

openmc-dev / openmc / 25559632448

08 May 2026 01:57PM UTC coverage: 80.844% (-0.5%) from 81.374%
25559632448

Pull #3757

github

web-flow
Merge 8d3b14a6d into f3e1066d4
Pull Request #3757: Testing point detectors

17721 of 25776 branches covered (68.75%)

Branch coverage included in aggregate %.

51 of 406 new or added lines in 25 files covered. (12.56%)

210 existing lines in 5 files now uncovered.

58617 of 68650 relevant lines covered (85.39%)

47081885.26 hits per line

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

80.79
/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/tallies/next_event_scoring.h"
37
#include "openmc/tallies/tally_scoring.h"
38
#include "openmc/xml_interface.h"
39

40
namespace openmc {
41

42
std::atomic<int64_t> source_n_accept {0};
43
std::atomic<int64_t> source_n_reject {0};
44

45
namespace {
46

47
void validate_particle_type(ParticleType type, const std::string& context)
253,205✔
48
{
49
  if (type.is_transportable())
253,205!
50
    return;
253,205✔
51

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

57
} // namespace
58

59
//==============================================================================
60
// Global variables
61
//==============================================================================
62

63
namespace model {
64

65
vector<unique_ptr<Source>> external_sources;
66

67
vector<unique_ptr<Source>> adjoint_sources;
68

69
DiscreteIndex external_sources_probability;
70

71
} // namespace model
72

73
//==============================================================================
74
// Source implementation
75
//==============================================================================
76

77
Source::Source(pugi::xml_node node)
46,034✔
78
{
79
  // Check for source strength
80
  if (check_for_node(node, "strength")) {
46,034✔
81
    strength_ = std::stod(get_node_value(node, "strength"));
90,778✔
82
    if (strength_ < 0.0) {
45,389!
83
      fatal_error("Source strength is negative.");
×
84
    }
85
  }
86

87
  // Check for additional defined constraints
88
  read_constraints(node);
46,034✔
89
}
46,034✔
90

91
unique_ptr<Source> Source::create(pugi::xml_node node)
46,034✔
92
{
93
  // if the source type is present, use it to determine the type
94
  // of object to create
95
  if (check_for_node(node, "type")) {
46,034✔
96
    std::string source_type = get_node_value(node, "type");
45,179✔
97
    if (source_type == "independent") {
45,179✔
98
      return make_unique<IndependentSource>(node);
44,917✔
99
    } else if (source_type == "file") {
262✔
100
      return make_unique<FileSource>(node);
31✔
101
    } else if (source_type == "compiled") {
231✔
102
      return make_unique<CompiledSourceWrapper>(node);
30✔
103
    } else if (source_type == "mesh") {
201!
104
      return make_unique<MeshSource>(node);
201✔
105
    } else {
106
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
107
    }
108
  } else {
45,169✔
109
    // support legacy source format
110
    if (check_for_node(node, "file")) {
855✔
111
      return make_unique<FileSource>(node);
30✔
112
    } else if (check_for_node(node, "library")) {
825!
113
      return make_unique<CompiledSourceWrapper>(node);
×
114
    } else {
115
      return make_unique<IndependentSource>(node);
825✔
116
    }
117
  }
118
}
119

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

130
  // Check for domains to reject from
131
  if (check_for_node(node, "domain_type")) {
46,034✔
132
    std::string domain_type = get_node_value(node, "domain_type");
512✔
133
    if (domain_type == "cell") {
512✔
134
      domain_type_ = DomainType::CELL;
107✔
135
    } else if (domain_type == "material") {
405✔
136
      domain_type_ = DomainType::MATERIAL;
30✔
137
    } else if (domain_type == "universe") {
375!
138
      domain_type_ = DomainType::UNIVERSE;
375✔
139
    } else {
140
      fatal_error(
×
141
        std::string("Unrecognized domain type for constraint: " + domain_type));
×
142
    }
143

144
    auto ids = get_node_array<int>(node, "domain_ids");
512✔
145
    domain_ids_.insert(ids.begin(), ids.end());
512✔
146
  }
512✔
147

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

163
  if (check_for_node(node, "fissionable")) {
46,034✔
164
    only_fissionable_ = get_node_value_bool(node, "fissionable");
1,430✔
165
  }
166

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

181
void check_rejection_fraction(int64_t n_reject, int64_t n_accept)
34,940,901✔
182
{
183
  // Don't check unless we've hit a minimum number of total sites rejected
184
  if (n_reject < EXTSRC_REJECT_THRESHOLD)
34,940,901✔
185
    return;
186

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

198
SourceSite Source::sample_with_constraints(uint64_t* seed) const
34,940,901✔
199
{
200
  bool accepted = false;
34,940,901✔
201
  int64_t n_local_reject = 0;
34,940,901✔
202
  SourceSite site {};
34,940,901✔
203

204
  while (!accepted) {
106,142,336✔
205
    // Sample a source site without considering constraints yet
206
    site = this->sample(seed);
36,260,534✔
207

208
    if (constraints_applied()) {
36,260,534✔
209
      accepted = true;
210
    } else {
211
      // Check whether sampled site satisfies constraints
212
      accepted = satisfies_spatial_constraints(site.r) &&
39,628,087✔
213
                 satisfies_energy_constraints(site.E) &&
2,673,732✔
214
                 satisfies_time_constraints(site.time);
682,739✔
215
      if (!accepted) {
1,319,633✔
216
        ++n_local_reject;
1,319,633✔
217

218
        // Check per-particle rejection limit
219
        if (n_local_reject >= MAX_SOURCE_REJECTIONS_PER_SAMPLE) {
1,319,633!
220
          fatal_error("Exceeded maximum number of source rejections per "
×
221
                      "sample. Please check your source definition.");
222
        }
223

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

234
  // Flush local rejection count, update accept counter, and check overall
235
  // rejection fraction
236
  if (n_local_reject > 0) {
34,940,901✔
237
    source_n_reject += n_local_reject;
19,089✔
238
  }
239
  ++source_n_accept;
34,940,901✔
240
  check_rejection_fraction(source_n_reject, source_n_accept);
34,940,901✔
241

242
  return site;
34,940,897✔
243
}
244

245
bool Source::satisfies_energy_constraints(double E) const
34,974,741✔
246
{
247
  return E > energy_bounds_.first && E < energy_bounds_.second;
34,974,741!
248
}
249

250
bool Source::satisfies_time_constraints(double time) const
682,739✔
251
{
252
  return time > time_bounds_.first && time < time_bounds_.second;
682,739✔
253
}
254

255
bool Source::satisfies_spatial_constraints(Position r) const
39,869,825✔
256
{
257
  GeometryState geom_state;
39,869,825✔
258
  geom_state.r() = r;
39,869,825✔
259
  geom_state.u() = {0.0, 0.0, 1.0};
39,869,825✔
260

261
  // Reject particle if it's not in the geometry at all
262
  bool found = exhaustive_find_cell(geom_state);
39,869,825✔
263
  if (!found)
39,869,825✔
264
    return false;
265

266
  // Check the geometry state against specified domains
267
  bool accepted = true;
39,379,485✔
268
  if (!domain_ids_.empty()) {
39,379,485✔
269
    if (domain_type_ == DomainType::MATERIAL) {
1,976,152!
270
      auto mat_index = geom_state.material();
×
271
      if (mat_index == MATERIAL_VOID) {
×
272
        accepted = false;
273
      } else {
274
        accepted = contains(domain_ids_, model::materials[mat_index]->id());
×
275
      }
276
    } else {
277
      for (int i = 0; i < geom_state.n_coord(); i++) {
3,801,740✔
278
        auto id =
1,976,152✔
279
          (domain_type_ == DomainType::CELL)
280
            ? model::cells[geom_state.coord(i).cell()].get()->id_
1,976,152!
281
            : model::universes[geom_state.coord(i).universe()].get()->id_;
×
282
        if ((accepted = contains(domain_ids_, id)))
3,952,304✔
283
          break;
284
      }
285
    }
286
  }
287

288
  // Check if spatial site is in fissionable material
289
  if (accepted && only_fissionable_) {
39,379,485✔
290
    // Determine material
291
    auto mat_index = geom_state.material();
1,076,309✔
292
    if (mat_index == MATERIAL_VOID) {
1,076,309!
293
      accepted = false;
294
    } else {
295
      accepted = model::materials[mat_index]->fissionable();
1,076,309✔
296
    }
297
  }
298

299
  return accepted;
300
}
39,869,825✔
301

302
//==============================================================================
303
// IndependentSource implementation
304
//==============================================================================
305

306
IndependentSource::IndependentSource(
2,136✔
307
  UPtrSpace space, UPtrAngle angle, UPtrDist energy, UPtrDist time)
2,136✔
308
  : space_ {std::move(space)}, angle_ {std::move(angle)},
2,136✔
309
    energy_ {std::move(energy)}, time_ {std::move(time)}
2,136✔
310
{}
2,136✔
311

312
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
45,742✔
313
{
314
  // Check for particle type
315
  if (check_for_node(node, "particle")) {
45,742✔
316
    auto temp_str = get_node_value(node, "particle", false, true);
44,917✔
317
    particle_ = ParticleType(temp_str);
44,917✔
318
    if (particle_ == ParticleType::photon() ||
44,917✔
319
        particle_ == ParticleType::electron() ||
44,917✔
320
        particle_ == ParticleType::positron()) {
44,743!
321
      settings::photon_transport = true;
174✔
322
    }
323
  }
44,917✔
324
  validate_particle_type(particle_, "IndependentSource");
45,742✔
325

326
  // Check for external source file
327
  if (check_for_node(node, "file")) {
45,742!
328

329
  } else {
330

331
    // Spatial distribution for external source
332
    if (check_for_node(node, "space")) {
45,742✔
333
      space_ = SpatialDistribution::create(node.child("space"));
7,546✔
334
    } else {
335
      // If no spatial distribution specified, make it a point source
336
      space_ = UPtrSpace {new SpatialPoint()};
38,196✔
337
    }
338

339
    // For backwards compatibility, check for only fissionable setting on box
340
    // source
341
    auto space_box = dynamic_cast<SpatialBox*>(space_.get());
45,741!
342
    if (space_box) {
45,741✔
343
      if (!only_fissionable_) {
4,063✔
344
        only_fissionable_ = space_box->only_fissionable();
2,633✔
345
      }
346
    }
347

348
    // Determine external source angular distribution
349
    if (check_for_node(node, "angle")) {
45,741✔
350
      angle_ = UnitSphereDistribution::create(node.child("angle"));
3,402✔
351
    } else {
352
      angle_ = UPtrAngle {new Isotropic()};
42,339✔
353
    }
354

355
    // Determine external source energy distribution
356
    if (check_for_node(node, "energy")) {
45,741✔
357
      pugi::xml_node node_dist = node.child("energy");
4,808✔
358
      energy_ = distribution_from_xml(node_dist);
4,808✔
359
    } else {
360
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
361
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
40,933✔
362
    }
363

364
    // Determine external source time distribution
365
    if (check_for_node(node, "time")) {
45,741✔
366
      pugi::xml_node node_dist = node.child("time");
41✔
367
      time_ = distribution_from_xml(node_dist);
41✔
368
    } else {
369
      // Default to a Constant time T=0
370
      double T[] {0.0};
45,700✔
371
      double p[] {1.0};
45,700✔
372
      time_ = UPtrDist {new Discrete {T, p, 1}};
45,700✔
373
    }
374
  }
375
}
45,741✔
376

377
SourceSite IndependentSource::sample(uint64_t* seed) const
36,542,861✔
378
{
379
  SourceSite site {};
36,542,861✔
380
  site.particle = particle_;
36,542,861✔
381
  double r_wgt = 1.0;
36,542,861✔
382
  double E_wgt = 1.0;
36,542,861✔
383

384
  // Repeat sampling source location until a good site has been accepted
385
  bool accepted = false;
36,542,861✔
386
  int64_t n_local_reject = 0;
36,542,861✔
387

388
  while (!accepted) {
74,421,693✔
389

390
    // Sample spatial distribution
391
    auto [r, r_wgt_temp] = space_->sample(seed);
37,878,832✔
392
    site.r = r;
37,878,832✔
393
    r_wgt = r_wgt_temp;
37,878,832✔
394

395
    // Check if sampled position satisfies spatial constraints
396
    accepted = satisfies_spatial_constraints(site.r);
37,878,832✔
397

398
    // Check for rejection
399
    if (!accepted) {
37,878,832✔
400
      ++n_local_reject;
1,335,971✔
401
      if (n_local_reject >= MAX_SOURCE_REJECTIONS_PER_SAMPLE) {
1,335,971!
402
        fatal_error("Exceeded maximum number of source rejections per "
×
403
                    "sample. Please check your source definition.");
404
      }
405
    }
406
  }
407

408
  // Sample angle
409
  auto [u, u_wgt] = angle_->sample(seed);
36,542,861✔
410
  site.u = u;
36,542,861✔
411

412
  site.wgt = r_wgt * u_wgt;
36,542,861✔
413

414
  // Sample energy and time for neutron and photon sources
415
  if (settings::solver_type != SolverType::RANDOM_RAY) {
36,542,861✔
416
    // Check for monoenergetic source above maximum particle energy
417
    auto p = particle_.transport_index();
34,269,541✔
418
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
34,269,541!
419
    if (energy_ptr) {
34,269,541✔
420
      auto energies =
18,244,881✔
421
        tensor::Tensor<double>(energy_ptr->x().data(), energy_ptr->x().size());
18,244,881✔
422
      if ((energies > data::energy_max[p]).any()) {
54,734,643!
423
        fatal_error("Source energy above range of energies of at least "
×
424
                    "one cross section table");
425
      }
426
    }
18,244,881✔
427

428
    while (true) {
34,269,541✔
429
      // Sample energy spectrum
430
      auto [E, E_wgt_temp] = energy_->sample(seed);
34,269,541✔
431
      site.E = E;
34,269,541✔
432
      E_wgt = E_wgt_temp;
34,269,541✔
433

434
      // Resample if energy falls above maximum particle energy
435
      if (site.E < data::energy_max[p] &&
68,539,082!
436
          (satisfies_energy_constraints(site.E)))
34,269,541✔
437
        break;
438

439
      ++n_local_reject;
×
440
      if (n_local_reject >= MAX_SOURCE_REJECTIONS_PER_SAMPLE) {
×
441
        fatal_error("Exceeded maximum number of source rejections per "
×
442
                    "sample. Please check your source definition.");
443
      }
444
    }
×
445

446
    // Sample particle creation time
447
    auto [time, time_wgt] = time_->sample(seed);
34,269,541✔
448
    site.time = time;
34,269,541✔
449

450
    site.wgt *= (E_wgt * time_wgt);
34,269,541✔
451
  }
452

453
  // Flush local rejection count into global counter
454
  if (n_local_reject > 0) {
36,542,861✔
455
    source_n_reject += n_local_reject;
350,035✔
456
  }
457

458
  return site;
36,542,861✔
459
}
460

461
//==============================================================================
462
// FileSource implementation
463
//==============================================================================
464

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

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

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

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

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

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

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

502
    // Close file
503
    file_close(file_id);
52✔
504
  }
52✔
505

506
  // Make sure particles in source file have valid types
507
  for (const auto& site : this->sites_) {
170,093✔
508
    validate_particle_type(site.particle, "FileSource");
340,022✔
509
  }
510
}
82✔
511

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

519
//==============================================================================
520
// CompiledSourceWrapper implementation
521
//==============================================================================
522

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

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

544
  // reset errors
545
  dlerror();
30✔
546

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

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

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

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

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

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

583
//==============================================================================
584
// MeshElementSpatial implementation
585
//==============================================================================
586

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

592
//==============================================================================
593
// MeshSource implementation
594
//==============================================================================
595

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

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

617
  // Set spatial distributions for each mesh element
618
  for (int elem_index = 0; elem_index < sources_.size(); ++elem_index) {
37,653✔
619
    sources_[elem_index]->set_space(
37,452✔
620
      std::make_unique<MeshElementSpatial>(mesh_idx, elem_index));
74,904✔
621
  }
622

623
  // Make sure sources use valid particle types
624
  for (const auto& src : sources_) {
37,653✔
625
    validate_particle_type(src->particle_type(), "MeshSource");
74,904✔
626
  }
627

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

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

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

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

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

653
void initialize_source()
4,028✔
654
{
655
  write_message("Initializing source particles...", 5);
4,028✔
656

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

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

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

679
SourceSite sample_external_source(uint64_t* seed)
33,457,078✔
680
{
681
  // Sample from among multiple source distributions
682
  int i = 0;
33,457,078✔
683
  int n_sources = model::external_sources.size();
33,457,078✔
684
  if (n_sources > 1) {
33,457,078✔
685
    if (settings::uniform_source_sampling) {
3,558,300✔
686
      i = prn(seed) * n_sources;
2,200✔
687
    } else {
688
      i = model::external_sources_probability.sample(seed);
3,556,100✔
689
    }
690
  }
691

692
  // Sample source site from i-th source distribution
693
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
33,457,078✔
694

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

704
  // If running in MG, convert site.E to group
705
  if (!settings::run_CE) {
33,457,074✔
706
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
1,742,730✔
707
      data::mg.rev_energy_bins_.end(), site.E);
708
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
1,742,730✔
709
  }
710

711
  if (!model::active_point_tallies.empty()) {
33,457,074!
NEW
712
    score_point_tally_source(site, i);
×
713
  }
714

715
  return site;
33,457,074✔
716
}
717

718
void free_memory_source()
8,460✔
719
{
720
  model::external_sources.clear();
8,460✔
721
  model::adjoint_sources.clear();
8,460✔
722
  reset_source_rejection_counters();
8,460✔
723
}
8,460✔
724

725
void reset_source_rejection_counters()
15,923✔
726
{
727
  source_n_accept = 0;
15,923✔
728
  source_n_reject = 0;
15,923✔
729
}
15,923✔
730

731
//==============================================================================
732
// C API
733
//==============================================================================
734

735
extern "C" int openmc_sample_external_source(
966✔
736
  size_t n, uint64_t* seed, void* sites)
737
{
738
  if (!sites || !seed) {
966!
739
    set_errmsg("Received null pointer.");
×
740
    return OPENMC_E_INVALID_ARGUMENT;
×
741
  }
742

743
  if (model::external_sources.empty()) {
966!
744
    set_errmsg("No external sources have been defined.");
×
745
    return OPENMC_E_OUT_OF_BOUNDS;
×
746
  }
747

748
  auto sites_array = static_cast<SourceSite*>(sites);
966✔
749

750
  // Derive independent per-particle seeds from the base seed so that
751
  // each iteration has its own RNG state for thread-safe parallel sampling.
752
  uint64_t base_seed = *seed;
966✔
753

754
#pragma omp parallel for schedule(static)
801✔
755
  for (size_t i = 0; i < n; ++i) {
1,071,485✔
756
    uint64_t particle_seed = init_seed(base_seed + i, STREAM_SOURCE);
1,071,320✔
757
    sites_array[i] = sample_external_source(&particle_seed);
1,071,320✔
758
  }
759
  return 0;
801✔
760
}
761

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