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

openmc-dev / openmc / 23312026612

19 Mar 2026 07:02PM UTC coverage: 81.446% (-0.001%) from 81.447%
23312026612

Pull #3717

github

web-flow
Merge 8f08c1f06 into 3ce6cbfdd
Pull Request #3717: Local adjoint source for Random Ray

17710 of 25540 branches covered (69.34%)

Branch coverage included in aggregate %.

367 of 401 new or added lines in 9 files covered. (91.52%)

2 existing lines in 2 files now uncovered.

58356 of 67854 relevant lines covered (86.0%)

44913680.6 hits per line

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

80.86
/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,850✔
46
{
47
  if (type.is_transportable())
78,850!
48
    return;
78,850✔
49

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

55
} // namespace
56

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

61
namespace model {
62

63
vector<unique_ptr<Source>> external_sources;
64

65
vector<unique_ptr<Source>> adjoint_sources;
66

67
DiscreteIndex external_sources_probability;
68

69
} // namespace model
70

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

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

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

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

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

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

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

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

161
  if (check_for_node(node, "fissionable")) {
4,314✔
162
    only_fissionable_ = get_node_value_bool(node, "fissionable");
617✔
163
  }
164

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

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

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

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

202
  while (!accepted) {
46,583,296✔
203
    // Sample a source site without considering constraints yet
204
    site = this->sample(seed);
15,933,722✔
205

206
    if (constraints_applied()) {
15,933,722✔
207
      accepted = true;
208
    } else {
209
      // Check whether sampled site satisfies constraints
210
      accepted = satisfies_spatial_constraints(site.r) &&
17,472,824✔
211
                 satisfies_energy_constraints(site.E) &&
1,224,114✔
212
                 satisfies_time_constraints(site.time);
310,029✔
213
      if (!accepted) {
608,935✔
214
        ++n_local_reject;
608,935✔
215

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

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

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

240
  return site;
15,324,783✔
241
}
242

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

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

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

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

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

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

297
  return accepted;
298
}
17,649,348✔
299

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

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

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

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

327
  } else {
328

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

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

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

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

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

375
SourceSite IndependentSource::sample(uint64_t* seed) const
16,052,637✔
376
{
377
  SourceSite site {};
16,052,637✔
378
  site.particle = particle_;
16,052,637✔
379
  double r_wgt = 1.0;
16,052,637✔
380
  double E_wgt = 1.0;
16,052,637✔
381

382
  // Repeat sampling source location until a good site has been accepted
383
  bool accepted = false;
16,052,637✔
384
  int64_t n_local_reject = 0;
16,052,637✔
385

386
  while (!accepted) {
32,787,900✔
387

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

393
    // Check if sampled position satisfies spatial constraints
394
    accepted = satisfies_spatial_constraints(site.r);
16,735,263✔
395

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

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

410
  site.wgt = r_wgt * u_wgt;
16,052,637✔
411

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

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

432
      // Resample if energy falls above maximum particle energy
433
      if (site.E < data::energy_max[p] &&
30,039,274!
434
          (satisfies_energy_constraints(site.E)))
15,019,637✔
435
        break;
436

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

444
    // Sample particle creation time
445
    auto [time, time_wgt] = time_->sample(seed);
15,019,637✔
446
    site.time = time;
15,019,637✔
447

448
    site.wgt *= (E_wgt * time_wgt);
15,019,637✔
449
  }
450

451
  // Flush local rejection count into global counter
452
  if (n_local_reject > 0) {
16,052,637✔
453
    source_n_reject += n_local_reject;
160,311✔
454
  }
455

456
  return site;
16,052,637✔
457
}
458

459
//==============================================================================
460
// FileSource implementation
461
//==============================================================================
462

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

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

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

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

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

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

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

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

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

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

517
//==============================================================================
518
// CompiledSourceWrapper implementation
519
//==============================================================================
520

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

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

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

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

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

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

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

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

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

581
//==============================================================================
582
// MeshElementSpatial implementation
583
//==============================================================================
584

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

590
//==============================================================================
591
// MeshSource implementation
592
//==============================================================================
593

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

709
  return site;
14,640,565✔
710
}
711

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

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

724
//==============================================================================
725
// C API
726
//==============================================================================
727

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

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

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

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

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

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