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

openmc-dev / openmc / 21822677700

09 Feb 2026 11:09AM UTC coverage: 81.694% (-0.1%) from 81.817%
21822677700

Pull #3785

github

web-flow
Merge 83143abcc into d0346e94a
Pull Request #3785: Coincident source

17361 of 24416 branches covered (71.11%)

Branch coverage included in aggregate %.

137 of 197 new or added lines in 5 files covered. (69.54%)

8 existing lines in 1 file now uncovered.

56180 of 65604 relevant lines covered (85.64%)

45050359.49 hits per line

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

64.81
/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 "xtensor/xadapt.hpp"
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
namespace {
41

42
void validate_particle_type(ParticleType type, const std::string& context)
256,884✔
43
{
44
  if (type.is_transportable())
256,884!
45
    return;
256,884✔
46

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

52
} // namespace
53

54
//==============================================================================
55
// Global variables
56
//==============================================================================
57

58
namespace model {
59

60
vector<unique_ptr<Source>> external_sources;
61

62
DiscreteIndex external_sources_probability;
63

64
} // namespace model
65

66
//==============================================================================
67
// Source implementation
68
//==============================================================================
69

70
Source::Source(pugi::xml_node node)
45,717✔
71
{
72
  // Check for source strength
73
  if (check_for_node(node, "strength")) {
45,717✔
74
    strength_ = std::stod(get_node_value(node, "strength"));
45,029✔
75
    if (strength_ < 0.0) {
45,029!
76
      fatal_error("Source strength is negative.");
×
77
    }
78
  }
79

80
  // Check for additional defined constraints
81
  read_constraints(node);
45,717✔
82
}
45,717✔
83

84
unique_ptr<Source> Source::create(pugi::xml_node node)
45,717✔
85
{
86
  // if the source type is present, use it to determine the type
87
  // of object to create
88
  if (check_for_node(node, "type")) {
45,717✔
89
    std::string source_type = get_node_value(node, "type");
44,816✔
90
    if (source_type == "independent") {
44,816✔
91
      return make_unique<IndependentSource>(node);
44,552✔
92
    } else if (source_type == "file") {
264✔
93
      return make_unique<FileSource>(node);
31✔
94
    } else if (source_type == "compiled") {
233✔
95
      return make_unique<CompiledSourceWrapper>(node);
32✔
96
    } else if (source_type == "mesh") {
201!
97
      return make_unique<MeshSource>(node);
201✔
NEW
98
    } else if (source_type == "correlated") {
×
NEW
99
      return make_unique<CorrelatedSource>(node);
×
100
    } else {
101
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
102
    }
103
  } else {
44,806✔
104
    // support legacy source format
105
    if (check_for_node(node, "file")) {
901✔
106
      return make_unique<FileSource>(node);
32✔
107
    } else if (check_for_node(node, "library")) {
869!
108
      return make_unique<CompiledSourceWrapper>(node);
×
109
    } else {
110
      return make_unique<IndependentSource>(node);
869✔
111
    }
112
  }
113
}
114

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

125
  // Check for domains to reject from
126
  if (check_for_node(node, "domain_type")) {
45,717✔
127
    std::string domain_type = get_node_value(node, "domain_type");
475✔
128
    if (domain_type == "cell") {
475✔
129
      domain_type_ = DomainType::CELL;
91✔
130
    } else if (domain_type == "material") {
384✔
131
      domain_type_ = DomainType::MATERIAL;
16✔
132
    } else if (domain_type == "universe") {
368!
133
      domain_type_ = DomainType::UNIVERSE;
368✔
134
    } else {
135
      fatal_error(
×
136
        std::string("Unrecognized domain type for constraint: " + domain_type));
×
137
    }
138

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

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

158
  if (check_for_node(node, "fissionable")) {
45,717✔
159
    only_fissionable_ = get_node_value_bool(node, "fissionable");
1,385✔
160
  }
161

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

176
void check_rejection_fraction(int64_t n_reject, int64_t n_accept)
2,575,642✔
177
{
178
  // Don't check unless we've hit a minimum number of total sites rejected
179
  if (n_reject < EXTSRC_REJECT_THRESHOLD)
2,575,642✔
180
    return;
894,082✔
181

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

193
SourceSite Source::sample_with_constraints(uint64_t* seed) const
1,483,405✔
194
{
195
  bool accepted = false;
1,483,405✔
196
  static int64_t n_reject = 0;
197
  static int64_t n_accept = 0;
198
  SourceSite site;
1,483,405✔
199

200
  while (!accepted) {
2,966,810✔
201
    // Sample a source site without considering constraints yet
202
    site = this->sample(seed);
1,483,405✔
203

204
    if (constraints_applied()) {
1,483,405!
205
      accepted = true;
1,483,405✔
206
    } else {
207
      // Check whether sampled site satisfies constraints
UNCOV
208
      accepted = satisfies_spatial_constraints(site.r) &&
×
UNCOV
209
                 satisfies_energy_constraints(site.E) &&
×
UNCOV
210
                 satisfies_time_constraints(site.time);
×
UNCOV
211
      if (!accepted) {
×
212
        // Increment number of rejections and check against minimum fraction
UNCOV
213
        ++n_reject;
×
UNCOV
214
        check_rejection_fraction(n_reject, n_accept);
×
215

216
        // For the "kill" strategy, accept particle but set weight to 0 so that
217
        // it is terminated immediately
UNCOV
218
        if (rejection_strategy_ == RejectionStrategy::KILL) {
×
219
          accepted = true;
×
220
          site.wgt = 0.0;
×
221
        }
222
      }
223
    }
224
  }
225

226
  // Increment number of accepted samples
227
  ++n_accept;
1,483,405✔
228

229
  return site;
1,483,405✔
230
}
231

232
vector<SourceSite> Source::sample_sites_with_constraints(uint64_t* seed) const
31,742,252✔
233
{
234
  bool accepted = false;
31,742,252✔
235
  static int64_t n_reject = 0;
236
  static int64_t n_accept = 0;
237
  vector<SourceSite> sites;
31,742,252✔
238

239
  while (!accepted) {
64,803,511✔
240
    // Sample all sites from the source
241
    sites = this->sample_sites(seed);
33,061,262✔
242

243
    if (constraints_applied()) {
33,061,259✔
244
      accepted = true;
31,070,889✔
245
    } else {
246
      // Check whether all sampled sites satisfy constraints
247
      accepted = true;
1,990,370✔
248
      for (const auto& site : sites) {
2,661,730✔
249
        if (!satisfies_spatial_constraints(site.r) ||
1,990,370✔
250
            !satisfies_energy_constraints(site.E) ||
2,672,942✔
251
            !satisfies_time_constraints(site.time)) {
682,572✔
252
          accepted = false;
1,319,010✔
253
          break;
1,319,010✔
254
        }
255
      }
256

257
      if (!accepted) {
1,990,370✔
258
        ++n_reject;
1,319,010✔
259
        check_rejection_fraction(n_reject, n_accept);
1,319,010✔
260

261
        if (rejection_strategy_ == RejectionStrategy::KILL) {
1,319,010!
NEW
262
          accepted = true;
×
NEW
263
          for (auto& site : sites) {
×
NEW
264
            site.wgt = 0.0;
×
265
          }
266
        }
267
      }
268
    }
269
  }
270

271
  ++n_accept;
31,742,249✔
272
  return sites;
31,742,249✔
NEW
273
}
×
274

275
bool Source::satisfies_energy_constraints(double E) const
33,259,289✔
276
{
277
  return E > energy_bounds_.first && E < energy_bounds_.second;
33,259,289!
278
}
279

280
bool Source::satisfies_time_constraints(double time) const
682,572✔
281
{
282
  return time > time_bounds_.first && time < time_bounds_.second;
682,572✔
283
}
284

285
bool Source::satisfies_spatial_constraints(Position r) const
37,865,616✔
286
{
287
  GeometryState geom_state;
37,865,616✔
288
  geom_state.r() = r;
37,865,616✔
289
  geom_state.u() = {0.0, 0.0, 1.0};
37,865,616✔
290

291
  // Reject particle if it's not in the geometry at all
292
  bool found = exhaustive_find_cell(geom_state);
37,865,616✔
293
  if (!found)
37,865,616✔
294
    return false;
490,340✔
295

296
  // Check the geometry state against specified domains
297
  bool accepted = true;
37,375,276✔
298
  if (!domain_ids_.empty()) {
37,375,276✔
299
    if (domain_type_ == DomainType::MATERIAL) {
1,900,487!
300
      auto mat_index = geom_state.material();
×
301
      if (mat_index == MATERIAL_VOID) {
×
302
        accepted = false;
×
303
      } else {
304
        accepted = contains(domain_ids_, model::materials[mat_index]->id());
×
305
      }
306
    } else {
307
      for (int i = 0; i < geom_state.n_coord(); i++) {
3,651,554✔
308
        auto id =
309
          (domain_type_ == DomainType::CELL)
1,900,487✔
310
            ? model::cells[geom_state.coord(i).cell()].get()->id_
1,900,487!
311
            : model::universes[geom_state.coord(i).universe()].get()->id_;
×
312
        if ((accepted = contains(domain_ids_, id)))
1,900,487✔
313
          break;
149,420✔
314
      }
315
    }
316
  }
317

318
  // Check if spatial site is in fissionable material
319
  if (accepted && only_fissionable_) {
37,375,276✔
320
    // Determine material
321
    auto mat_index = geom_state.material();
1,068,763✔
322
    if (mat_index == MATERIAL_VOID) {
1,068,763!
323
      accepted = false;
×
324
    } else {
325
      accepted = model::materials[mat_index]->fissionable();
1,068,763✔
326
    }
327
  }
328

329
  return accepted;
37,375,276✔
330
}
37,865,616✔
331

332
//==============================================================================
333
// IndependentSource implementation
334
//==============================================================================
335

336
IndependentSource::IndependentSource(
2,051✔
337
  UPtrSpace space, UPtrAngle angle, UPtrDist energy, UPtrDist time)
2,051✔
338
  : space_ {std::move(space)}, angle_ {std::move(angle)},
2,051✔
339
    energy_ {std::move(energy)}, time_ {std::move(time)}
4,102✔
340
{}
2,051✔
341

342
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
45,421✔
343
{
344
  // Check for particle type
345
  if (check_for_node(node, "particle")) {
45,421✔
346
    auto temp_str = get_node_value(node, "particle", false, true);
44,552✔
347
    particle_ = ParticleType(temp_str);
44,552✔
348
    if (particle_ == ParticleType::photon() ||
88,957✔
349
        particle_ == ParticleType::electron() ||
88,957!
350
        particle_ == ParticleType::positron()) {
44,389✔
351
      settings::photon_transport = true;
163✔
352
    }
353
  }
44,552✔
354
  validate_particle_type(particle_, "IndependentSource");
45,421✔
355

356
  // Check for external source file
357
  if (check_for_node(node, "file")) {
45,421!
358

359
  } else {
360

361
    // Spatial distribution for external source
362
    if (check_for_node(node, "space")) {
45,421✔
363
      space_ = SpatialDistribution::create(node.child("space"));
7,290✔
364
    } else {
365
      // If no spatial distribution specified, make it a point source
366
      space_ = UPtrSpace {new SpatialPoint()};
38,131✔
367
    }
368

369
    // For backwards compatibility, check for only fissionable setting on box
370
    // source
371
    auto space_box = dynamic_cast<SpatialBox*>(space_.get());
45,420!
372
    if (space_box) {
45,420✔
373
      if (!only_fissionable_) {
3,978✔
374
        only_fissionable_ = space_box->only_fissionable();
2,593✔
375
      }
376
    }
377

378
    // Determine external source angular distribution
379
    if (check_for_node(node, "angle")) {
45,420✔
380
      angle_ = UnitSphereDistribution::create(node.child("angle"));
3,356✔
381
    } else {
382
      angle_ = UPtrAngle {new Isotropic()};
42,064✔
383
    }
384

385
    // Determine external source energy distribution
386
    if (check_for_node(node, "energy")) {
45,420✔
387
      pugi::xml_node node_dist = node.child("energy");
4,674✔
388
      energy_ = distribution_from_xml(node_dist);
4,674✔
389
    } else {
390
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
391
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
40,746✔
392
    }
393

394
    // Determine external source time distribution
395
    if (check_for_node(node, "time")) {
45,420✔
396
      pugi::xml_node node_dist = node.child("time");
43✔
397
      time_ = distribution_from_xml(node_dist);
43✔
398
    } else {
399
      // Default to a Constant time T=0
400
      double T[] {0.0};
45,377✔
401
      double p[] {1.0};
45,377✔
402
      time_ = UPtrDist {new Discrete {T, p, 1}};
45,377✔
403
    }
404
  }
405
}
45,420✔
406

407
SourceSite IndependentSource::sample(uint64_t* seed) const
34,618,617✔
408
{
409
  SourceSite site;
34,618,617✔
410
  site.particle = particle_;
34,618,617✔
411
  double r_wgt = 1.0;
34,618,617✔
412
  double E_wgt = 1.0;
34,618,617✔
413

414
  // Repeat sampling source location until a good site has been accepted
415
  bool accepted = false;
34,618,617✔
416
  static int64_t n_reject = 0;
417
  static int64_t n_accept = 0;
418

419
  while (!accepted) {
70,493,860✔
420

421
    // Sample spatial distribution
422
    auto [r, r_wgt_temp] = space_->sample(seed);
35,875,246✔
423
    site.r = r;
35,875,246✔
424
    r_wgt = r_wgt_temp;
35,875,246✔
425

426
    // Check if sampled position satisfies spatial constraints
427
    accepted = satisfies_spatial_constraints(site.r);
35,875,246✔
428

429
    // Check for rejection
430
    if (!accepted) {
35,875,246✔
431
      ++n_reject;
1,256,632✔
432
      check_rejection_fraction(n_reject, n_accept);
1,256,632✔
433
    }
434
  }
435

436
  // Sample angle
437
  auto [u, u_wgt] = angle_->sample(seed);
34,618,614✔
438
  site.u = u;
34,618,614✔
439

440
  site.wgt = r_wgt * u_wgt;
34,618,614✔
441

442
  // Sample energy and time for neutron and photon sources
443
  if (settings::solver_type != SolverType::RANDOM_RAY) {
34,618,614✔
444
    // Check for monoenergetic source above maximum particle energy
445
    auto p = particle_.transport_index();
32,554,294✔
446
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
32,554,294!
447
    if (energy_ptr) {
32,554,294✔
448
      auto energies = xt::adapt(energy_ptr->x());
18,114,049✔
449
      if (xt::any(energies > data::energy_max[p])) {
18,114,049!
450
        fatal_error("Source energy above range of energies of at least "
×
451
                    "one cross section table");
452
      }
453
    }
18,114,049✔
454

455
    while (true) {
456
      // Sample energy spectrum
457
      auto [E, E_wgt_temp] = energy_->sample(seed);
32,554,294✔
458
      site.E = E;
32,554,294✔
459
      E_wgt = E_wgt_temp;
32,554,294✔
460

461
      // Resample if energy falls above maximum particle energy
462
      if (site.E < data::energy_max[p] &&
65,108,588!
463
          (satisfies_energy_constraints(site.E)))
32,554,294!
464
        break;
32,554,294✔
465

466
      n_reject++;
×
467
      check_rejection_fraction(n_reject, n_accept);
×
468
    }
×
469

470
    // Sample particle creation time
471
    auto [time, time_wgt] = time_->sample(seed);
32,554,294✔
472
    site.time = time;
32,554,294✔
473

474
    site.wgt *= (E_wgt * time_wgt);
32,554,294✔
475
  }
476

477
  // Increment number of accepted samples
478
  ++n_accept;
34,618,614✔
479

480
  return site;
69,237,228✔
481
}
482

483
//==============================================================================
484
// FileSource implementation
485
//==============================================================================
486

487
FileSource::FileSource(pugi::xml_node node) : Source(node)
63✔
488
{
489
  auto path = get_node_value(node, "file", false, true);
63✔
490
  load_sites_from_file(path);
63✔
491
}
54✔
492

493
FileSource::FileSource(const std::string& path)
32✔
494
{
495
  load_sites_from_file(path);
32✔
496
}
32✔
497

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

509
    write_message(6, "Reading source file from {}...", path);
63✔
510

511
    // Open the binary file
512
    hid_t file_id = file_open(path, 'r', true);
63✔
513

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

521
    // Read in the source particles
522
    read_source_bank(file_id, sites_, false);
63✔
523

524
    // Close file
525
    file_close(file_id);
54✔
526
  }
54✔
527

528
  // Make sure particles in source file have valid types
529
  for (const auto& site : this->sites_) {
174,097✔
530
    validate_particle_type(site.particle, "FileSource");
174,011✔
531
  }
532
}
86✔
533

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

541
//==============================================================================
542
// CompiledSourceWrapper implementation
543
//==============================================================================
544

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

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

566
  // reset errors
567
  dlerror();
32✔
568

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

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

582
  // create a pointer to an instance of the custom source
583
  compiled_source_ = create_compiled_source(parameters);
32✔
584

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

591
CompiledSourceWrapper::~CompiledSourceWrapper()
64✔
592
{
593
  // Make sure custom source is cleared before closing shared library
594
  if (compiled_source_.get())
32!
595
    compiled_source_.reset();
32✔
596

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

605
//==============================================================================
606
// MeshElementSpatial implementation
607
//==============================================================================
608

609
std::pair<Position, double> MeshElementSpatial::sample(uint64_t* seed) const
1,498,474✔
610
{
611
  return {model::meshes[mesh_index_]->sample_element(elem_index_, seed), 1.0};
1,498,474✔
612
}
613

614
//==============================================================================
615
// MeshSource implementation
616
//==============================================================================
617

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

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

639
  // Set spatial distributions for each mesh element
640
  for (int elem_index = 0; elem_index < sources_.size(); ++elem_index) {
37,653✔
641
    sources_[elem_index]->set_space(
74,904✔
642
      std::make_unique<MeshElementSpatial>(mesh_idx, elem_index));
74,904✔
643
  }
644

645
  // Make sure sources use valid particle types
646
  for (const auto& src : sources_) {
37,653✔
647
    validate_particle_type(src->particle_type(), "MeshSource");
37,452✔
648
  }
649

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

658
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
201✔
659
}
201✔
660

661
SourceSite MeshSource::sample(uint64_t* seed) const
1,483,405✔
662
{
663
  // Sample a mesh element based on the relative strengths
664
  int32_t element = space_->sample_element_index(seed);
1,483,405✔
665

666
  // Sample the distribution for the specific mesh element; note that the
667
  // spatial distribution has been set for each element using MeshElementSpatial
668
  return source(element)->sample_with_constraints(seed);
1,483,405✔
669
}
670

671
//==============================================================================
672
// CorrelatedSource implementation
673
//==============================================================================
674

NEW
675
CorrelatedSource::CorrelatedSource(pugi::xml_node node) : Source(node)
×
676
{
677
  // Correlated sources are only valid for fixed-source simulations
NEW
678
  if (settings::run_mode == RunMode::EIGENVALUE) {
×
NEW
679
    fatal_error("Correlated sources cannot be used in eigenvalue mode.");
×
680
  }
681

682
  // Read shared spatial distribution
NEW
683
  if (check_for_node(node, "space")) {
×
NEW
684
    space_ = SpatialDistribution::create(node.child("space"));
×
685
  } else {
NEW
686
    space_ = UPtrSpace {new SpatialPoint()};
×
687
  }
688

689
  // Read shared time distribution
NEW
690
  if (check_for_node(node, "time")) {
×
NEW
691
    pugi::xml_node node_dist = node.child("time");
×
NEW
692
    time_ = distribution_from_xml(node_dist);
×
693
  } else {
NEW
694
    double T[] {0.0};
×
NEW
695
    double p[] {1.0};
×
NEW
696
    time_ = UPtrDist {new Discrete {T, p, 1}};
×
697
  }
698

699
  // Read child <source> elements as sub-sources
NEW
700
  for (auto source_node : node.children("source")) {
×
701
    // Read emission probability (default 1.0)
NEW
702
    double prob = 1.0;
×
NEW
703
    if (source_node.attribute("probability")) {
×
NEW
704
      prob = std::stod(source_node.attribute("probability").value());
×
NEW
705
      if (prob <= 0.0 || prob > 1.0) {
×
NEW
706
        fatal_error("Sub-source probability must be in (0, 1].");
×
707
      }
708
    }
709

NEW
710
    auto src = Source::create(source_node);
×
NEW
711
    if (auto ptr = dynamic_cast<IndependentSource*>(src.get())) {
×
NEW
712
      src.release();
×
NEW
713
      sources_.emplace_back(ptr);
×
714
    } else {
NEW
715
      fatal_error(
×
716
        "Sub-sources of a correlated source must be IndependentSource.");
717
    }
NEW
718
    probabilities_.push_back(prob);
×
NEW
719
  }
×
720

721
  // Validate at least 2 sub-sources
NEW
722
  if (sources_.size() < 2) {
×
NEW
723
    fatal_error("A correlated source must have at least 2 sub-sources.");
×
724
  }
NEW
725
}
×
726

NEW
727
SourceSite CorrelatedSource::sample(uint64_t* seed) const
×
728
{
NEW
729
  auto sites = sample_sites(seed);
×
NEW
730
  return sites[0];
×
NEW
731
}
×
732

NEW
733
vector<SourceSite> CorrelatedSource::sample_sites(uint64_t* seed) const
×
734
{
735
  // Sample shared position once
NEW
736
  auto [r, r_wgt] = space_->sample(seed);
×
737

738
  // Sample shared time once
NEW
739
  auto [time, time_wgt] = time_->sample(seed);
×
740

741
  // Build a site for each sub-source, applying emission probabilities
NEW
742
  vector<SourceSite> sites;
×
NEW
743
  sites.reserve(sources_.size());
×
744

NEW
745
  for (size_t i = 0; i < sources_.size(); ++i) {
×
746
    // Roll against emission probability for this sub-source
NEW
747
    if (prn(seed) >= probabilities_[i])
×
NEW
748
      continue;
×
749

750
    // Sample from the sub-source to get particle type, energy, angle
NEW
751
    SourceSite site = sources_[i]->sample(seed);
×
752

753
    // Override position and time with shared values
NEW
754
    site.r = r;
×
NEW
755
    site.time = time;
×
756

757
    // Apply shared spatial and time weights
NEW
758
    site.wgt *= (r_wgt * time_wgt);
×
759

NEW
760
    sites.push_back(site);
×
761
  }
762

763
  // If all rolls failed, push first sub-source with zero weight so the
764
  // history can still initialize
NEW
765
  if (sites.empty()) {
×
NEW
766
    SourceSite site = sources_[0]->sample(seed);
×
NEW
767
    site.r = r;
×
NEW
768
    site.time = time;
×
NEW
769
    site.wgt = 0.0;
×
NEW
770
    sites.push_back(site);
×
771
  }
772

NEW
773
  return sites;
×
NEW
774
}
×
775

776
//==============================================================================
777
// Non-member functions
778
//==============================================================================
779

780
void initialize_source()
3,943✔
781
{
782
  write_message("Initializing source particles...", 5);
3,943✔
783

784
// Generation source sites from specified distribution in user input
785
#pragma omp parallel for
786
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
1,199,018✔
787
    // initialize random number seed
788
    int64_t id = simulation::total_gen * settings::n_particles +
2,394,530✔
789
                 simulation::work_index[mpi::rank] + i + 1;
1,197,265✔
790
    uint64_t seed = init_seed(id, STREAM_SOURCE);
1,197,265✔
791

792
    // sample external source distribution (store only primary site)
793
    auto sites = sample_external_source(&seed);
1,197,265✔
794
    simulation::source_bank[i] = sites[0];
1,197,265✔
795
  }
1,197,265✔
796

797
  // Write out initial source
798
  if (settings::write_initial_source) {
3,943!
799
    write_message("Writing out initial source...", 5);
×
800
    std::string filename = settings::path_output + "initial_source.h5";
×
801
    hid_t file_id = file_open(filename, 'w', true);
×
802
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
×
803
    file_close(file_id);
×
804
  }
×
805
}
3,943✔
806

807
vector<SourceSite> sample_external_source(uint64_t* seed)
31,742,252✔
808
{
809
  // Sample from among multiple source distributions
810
  int i = 0;
31,742,252✔
811
  int n_sources = model::external_sources.size();
31,742,252✔
812
  if (n_sources > 1) {
31,742,252✔
813
    if (settings::uniform_source_sampling) {
2,458,300✔
814
      i = prn(seed) * n_sources;
2,200✔
815
    } else {
816
      i = model::external_sources_probability.sample(seed);
2,456,100✔
817
    }
818
  }
819

820
  // Sample source sites from i-th source distribution
821
  vector<SourceSite> sites {
822
    model::external_sources[i]->sample_sites_with_constraints(seed)};
31,742,252✔
823

824
  // For uniform source sampling, multiply the weight by the ratio of the actual
825
  // probability of sampling source i to the biased probability of sampling
826
  // source i, which is (strength_i / total_strength) / (1 / n)
827
  if (n_sources > 1 && settings::uniform_source_sampling) {
31,742,249✔
828
    double total_strength = model::external_sources_probability.integral();
2,200✔
829
    double wgt_factor =
830
      model::external_sources[i]->strength() * n_sources / total_strength;
2,200✔
831
    for (auto& site : sites) {
4,400✔
832
      site.wgt *= wgt_factor;
2,200✔
833
    }
834
  }
835

836
  // If running in MG, convert site.E to group
837
  if (!settings::run_CE) {
31,742,249✔
838
    for (auto& site : sites) {
3,484,800✔
839
      site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
1,742,400✔
840
        data::mg.rev_energy_bins_.end(), site.E);
1,742,400✔
841
      site.E = data::mg.num_energy_groups_ - site.E - 1.;
1,742,400✔
842
    }
843
  }
844

845
  return sites;
31,742,249✔
UNCOV
846
}
×
847

848
void free_memory_source()
8,208✔
849
{
850
  model::external_sources.clear();
8,208✔
851
}
8,208✔
852

853
//==============================================================================
854
// C API
855
//==============================================================================
856

857
extern "C" int openmc_sample_external_source(
955✔
858
  size_t n, uint64_t* seed, void* sites)
859
{
860
  if (!sites || !seed) {
955!
861
    set_errmsg("Received null pointer.");
×
862
    return OPENMC_E_INVALID_ARGUMENT;
×
863
  }
864

865
  if (model::external_sources.empty()) {
955!
866
    set_errmsg("No external sources have been defined.");
×
867
    return OPENMC_E_OUT_OF_BOUNDS;
×
868
  }
869

870
  auto sites_array = static_cast<SourceSite*>(sites);
955✔
871
  for (size_t i = 0; i < n; ++i) {
2,957,779✔
872
    auto sampled = sample_external_source(seed);
2,956,824✔
873
    sites_array[i] = sampled[0];
2,956,824✔
874
  }
2,956,824✔
875
  return 0;
955✔
876
}
877

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