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

openmc-dev / openmc / 21991279157

13 Feb 2026 02:53PM UTC coverage: 81.82% (-0.06%) from 81.875%
21991279157

Pull #3805

github

web-flow
Merge 0a7a80411 into bcb939520
Pull Request #3805: Remove xtensor and xtl Dependencies

17242 of 24268 branches covered (71.05%)

Branch coverage included in aggregate %.

977 of 1013 new or added lines in 39 files covered. (96.45%)

404 existing lines in 8 files now uncovered.

57420 of 66983 relevant lines covered (85.72%)

45458907.73 hits per line

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

79.01
/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
namespace {
41

42
void validate_particle_type(ParticleType type, const std::string& context)
238,054✔
43
{
44
  if (type.is_transportable())
238,054!
45
    return;
238,054✔
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)
44,991✔
71
{
72
  // Check for source strength
73
  if (check_for_node(node, "strength")) {
44,991✔
74
    strength_ = std::stod(get_node_value(node, "strength"));
44,389✔
75
    if (strength_ < 0.0) {
44,389!
76
      fatal_error("Source strength is negative.");
×
77
    }
78
  }
79

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

84
unique_ptr<Source> Source::create(pugi::xml_node node)
44,991✔
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")) {
44,991✔
89
    std::string source_type = get_node_value(node, "type");
44,197✔
90
    if (source_type == "independent") {
44,197✔
91
      return make_unique<IndependentSource>(node);
43,958✔
92
    } else if (source_type == "file") {
239✔
93
      return make_unique<FileSource>(node);
28✔
94
    } else if (source_type == "compiled") {
211✔
95
      return make_unique<CompiledSourceWrapper>(node);
28✔
96
    } else if (source_type == "mesh") {
183!
97
      return make_unique<MeshSource>(node);
183✔
98
    } else {
99
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
100
    }
101
  } else {
44,188✔
102
    // support legacy source format
103
    if (check_for_node(node, "file")) {
794✔
104
      return make_unique<FileSource>(node);
28✔
105
    } else if (check_for_node(node, "library")) {
766!
106
      return make_unique<CompiledSourceWrapper>(node);
×
107
    } else {
108
      return make_unique<IndependentSource>(node);
766✔
109
    }
110
  }
111
}
112

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

123
  // Check for domains to reject from
124
  if (check_for_node(node, "domain_type")) {
44,991✔
125
    std::string domain_type = get_node_value(node, "domain_type");
419✔
126
    if (domain_type == "cell") {
419✔
127
      domain_type_ = DomainType::CELL;
83✔
128
    } else if (domain_type == "material") {
336✔
129
      domain_type_ = DomainType::MATERIAL;
14✔
130
    } else if (domain_type == "universe") {
322!
131
      domain_type_ = DomainType::UNIVERSE;
322✔
132
    } else {
133
      fatal_error(
×
134
        std::string("Unrecognized domain type for constraint: " + domain_type));
×
135
    }
136

137
    auto ids = get_node_array<int>(node, "domain_ids");
419✔
138
    domain_ids_.insert(ids.begin(), ids.end());
419✔
139
  }
419✔
140

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

156
  if (check_for_node(node, "fissionable")) {
44,991✔
157
    only_fissionable_ = get_node_value_bool(node, "fissionable");
1,296✔
158
  }
159

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

174
void check_rejection_fraction(int64_t n_reject, int64_t n_accept)
2,376,613✔
175
{
176
  // Don't check unless we've hit a minimum number of total sites rejected
177
  if (n_reject < EXTSRC_REJECT_THRESHOLD)
2,376,613✔
178
    return;
823,348✔
179

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

191
SourceSite Source::sample_with_constraints(uint64_t* seed) const
31,306,829✔
192
{
193
  bool accepted = false;
31,306,829✔
194
  static int64_t n_reject = 0;
195
  static int64_t n_accept = 0;
196
  SourceSite site;
31,306,829✔
197

198
  while (!accepted) {
63,804,240✔
199
    // Sample a source site without considering constraints yet
200
    site = this->sample(seed);
32,497,414✔
201

202
    if (constraints_applied()) {
32,497,411✔
203
      accepted = true;
30,696,496✔
204
    } else {
205
      // Check whether sampled site satisfies constraints
206
      accepted = satisfies_spatial_constraints(site.r) &&
1,800,915✔
207
                 satisfies_energy_constraints(site.E) &&
2,421,448✔
208
                 satisfies_time_constraints(site.time);
620,533✔
209
      if (!accepted) {
1,800,915✔
210
        // Increment number of rejections and check against minimum fraction
211
        ++n_reject;
1,190,585✔
212
        check_rejection_fraction(n_reject, n_accept);
1,190,585✔
213

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

224
  // Increment number of accepted samples
225
  ++n_accept;
31,306,826✔
226

227
  return site;
31,306,826✔
228
}
229

230
bool Source::satisfies_energy_constraints(double E) const
31,337,339✔
231
{
232
  return E > energy_bounds_.first && E < energy_bounds_.second;
31,337,339!
233
}
234

235
bool Source::satisfies_time_constraints(double time) const
620,533✔
236
{
237
  return time > time_bounds_.first && time < time_bounds_.second;
620,533✔
238
}
239

240
bool Source::satisfies_spatial_constraints(Position r) const
35,600,159✔
241
{
242
  GeometryState geom_state;
35,600,159✔
243
  geom_state.r() = r;
35,600,159✔
244
  geom_state.u() = {0.0, 0.0, 1.0};
35,600,159✔
245

246
  // Reject particle if it's not in the geometry at all
247
  bool found = exhaustive_find_cell(geom_state);
35,600,159✔
248
  if (!found)
35,600,159✔
249
    return false;
445,793✔
250

251
  // Check the geometry state against specified domains
252
  bool accepted = true;
35,154,366✔
253
  if (!domain_ids_.empty()) {
35,154,366✔
254
    if (domain_type_ == DomainType::MATERIAL) {
1,758,746!
255
      auto mat_index = geom_state.material();
×
256
      if (mat_index == MATERIAL_VOID) {
×
257
        accepted = false;
×
258
      } else {
259
        accepted = contains(domain_ids_, model::materials[mat_index]->id());
×
260
      }
261
    } else {
262
      for (int i = 0; i < geom_state.n_coord(); i++) {
3,381,072✔
263
        auto id =
264
          (domain_type_ == DomainType::CELL)
1,758,746✔
265
            ? model::cells[geom_state.coord(i).cell()].get()->id_
1,758,746!
266
            : model::universes[geom_state.coord(i).universe()].get()->id_;
×
267
        if ((accepted = contains(domain_ids_, id)))
1,758,746✔
268
          break;
136,420✔
269
      }
270
    }
271
  }
272

273
  // Check if spatial site is in fissionable material
274
  if (accepted && only_fissionable_) {
35,154,366✔
275
    // Determine material
276
    auto mat_index = geom_state.material();
978,211✔
277
    if (mat_index == MATERIAL_VOID) {
978,211!
278
      accepted = false;
×
279
    } else {
280
      accepted = model::materials[mat_index]->fissionable();
978,211✔
281
    }
282
  }
283

284
  return accepted;
35,154,366✔
285
}
35,600,159✔
286

287
//==============================================================================
288
// IndependentSource implementation
289
//==============================================================================
290

291
IndependentSource::IndependentSource(
1,848✔
292
  UPtrSpace space, UPtrAngle angle, UPtrDist energy, UPtrDist time)
1,848✔
293
  : space_ {std::move(space)}, angle_ {std::move(angle)},
1,848✔
294
    energy_ {std::move(energy)}, time_ {std::move(time)}
3,696✔
295
{}
1,848✔
296

297
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
44,724✔
298
{
299
  // Check for particle type
300
  if (check_for_node(node, "particle")) {
44,724✔
301
    auto temp_str = get_node_value(node, "particle", false, true);
43,958✔
302
    particle_ = ParticleType(temp_str);
43,958✔
303
    if (particle_ == ParticleType::photon() ||
87,784✔
304
        particle_ == ParticleType::electron() ||
87,784!
305
        particle_ == ParticleType::positron()) {
43,812✔
306
      settings::photon_transport = true;
146✔
307
    }
308
  }
43,958✔
309
  validate_particle_type(particle_, "IndependentSource");
44,724✔
310

311
  // Check for external source file
312
  if (check_for_node(node, "file")) {
44,724!
313

314
  } else {
315

316
    // Spatial distribution for external source
317
    if (check_for_node(node, "space")) {
44,724✔
318
      space_ = SpatialDistribution::create(node.child("space"));
6,802✔
319
    } else {
320
      // If no spatial distribution specified, make it a point source
321
      space_ = UPtrSpace {new SpatialPoint()};
37,922✔
322
    }
323

324
    // For backwards compatibility, check for only fissionable setting on box
325
    // source
326
    auto space_box = dynamic_cast<SpatialBox*>(space_.get());
44,723!
327
    if (space_box) {
44,723✔
328
      if (!only_fissionable_) {
3,683✔
329
        only_fissionable_ = space_box->only_fissionable();
2,387✔
330
      }
331
    }
332

333
    // Determine external source angular distribution
334
    if (check_for_node(node, "angle")) {
44,723✔
335
      angle_ = UnitSphereDistribution::create(node.child("angle"));
3,044✔
336
    } else {
337
      angle_ = UPtrAngle {new Isotropic()};
41,679✔
338
    }
339

340
    // Determine external source energy distribution
341
    if (check_for_node(node, "energy")) {
44,723✔
342
      pugi::xml_node node_dist = node.child("energy");
4,310✔
343
      energy_ = distribution_from_xml(node_dist);
4,310✔
344
    } else {
345
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
346
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
40,413✔
347
    }
348

349
    // Determine external source time distribution
350
    if (check_for_node(node, "time")) {
44,723✔
351
      pugi::xml_node node_dist = node.child("time");
38✔
352
      time_ = distribution_from_xml(node_dist);
38✔
353
    } else {
354
      // Default to a Constant time T=0
355
      double T[] {0.0};
44,685✔
356
      double p[] {1.0};
44,685✔
357
      time_ = UPtrDist {new Discrete {T, p, 1}};
44,685✔
358
    }
359
  }
360
}
44,723✔
361

362
SourceSite IndependentSource::sample(uint64_t* seed) const
32,613,219✔
363
{
364
  SourceSite site;
32,613,219✔
365
  site.particle = particle_;
32,613,219✔
366
  double r_wgt = 1.0;
32,613,219✔
367
  double E_wgt = 1.0;
32,613,219✔
368

369
  // Repeat sampling source location until a good site has been accepted
370
  bool accepted = false;
32,613,219✔
371
  static int64_t n_reject = 0;
372
  static int64_t n_accept = 0;
373

374
  while (!accepted) {
66,412,460✔
375

376
    // Sample spatial distribution
377
    auto [r, r_wgt_temp] = space_->sample(seed);
33,799,244✔
378
    site.r = r;
33,799,244✔
379
    r_wgt = r_wgt_temp;
33,799,244✔
380

381
    // Check if sampled position satisfies spatial constraints
382
    accepted = satisfies_spatial_constraints(site.r);
33,799,244✔
383

384
    // Check for rejection
385
    if (!accepted) {
33,799,244✔
386
      ++n_reject;
1,186,028✔
387
      check_rejection_fraction(n_reject, n_accept);
1,186,028✔
388
    }
389
  }
390

391
  // Sample angle
392
  auto [u, u_wgt] = angle_->sample(seed);
32,613,216✔
393
  site.u = u;
32,613,216✔
394

395
  site.wgt = r_wgt * u_wgt;
32,613,216✔
396

397
  // Sample energy and time for neutron and photon sources
398
  if (settings::solver_type != SolverType::RANDOM_RAY) {
32,613,216✔
399
    // Check for monoenergetic source above maximum particle energy
400
    auto p = particle_.transport_index();
30,696,496✔
401
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
30,696,496!
402
    if (energy_ptr) {
30,696,496✔
403
      auto energies =
404
        tensor::Tensor<double>(energy_ptr->x().data(), energy_ptr->x().size());
16,583,190✔
405
      if ((energies > data::energy_max[p]).any()) {
16,583,190!
UNCOV
406
        fatal_error("Source energy above range of energies of at least "
×
407
                    "one cross section table");
408
      }
409
    }
16,583,190✔
410

411
    while (true) {
412
      // Sample energy spectrum
413
      auto [E, E_wgt_temp] = energy_->sample(seed);
30,696,496✔
414
      site.E = E;
30,696,496✔
415
      E_wgt = E_wgt_temp;
30,696,496✔
416

417
      // Resample if energy falls above maximum particle energy
418
      if (site.E < data::energy_max[p] &&
61,392,992!
419
          (satisfies_energy_constraints(site.E)))
30,696,496!
420
        break;
30,696,496✔
421

422
      n_reject++;
×
423
      check_rejection_fraction(n_reject, n_accept);
×
424
    }
×
425

426
    // Sample particle creation time
427
    auto [time, time_wgt] = time_->sample(seed);
30,696,496✔
428
    site.time = time;
30,696,496✔
429

430
    site.wgt *= (E_wgt * time_wgt);
30,696,496✔
431
  }
432

433
  // Increment number of accepted samples
434
  ++n_accept;
32,613,216✔
435

436
  return site;
65,226,432✔
437
}
438

439
//==============================================================================
440
// FileSource implementation
441
//==============================================================================
442

443
FileSource::FileSource(pugi::xml_node node) : Source(node)
56✔
444
{
445
  auto path = get_node_value(node, "file", false, true);
56✔
446
  load_sites_from_file(path);
56✔
447
}
48✔
448

449
FileSource::FileSource(const std::string& path)
28✔
450
{
451
  load_sites_from_file(path);
28✔
452
}
28✔
453

454
void FileSource::load_sites_from_file(const std::string& path)
84✔
455
{
456
  // If MCPL file, use the dedicated file reader
457
  if (ends_with(path, ".mcpl") || ends_with(path, ".mcpl.gz")) {
84!
458
    sites_ = mcpl_source_sites(path);
28✔
459
  } else {
460
    // Check if source file exists
461
    if (!file_exists(path)) {
56!
462
      fatal_error(fmt::format("Source file '{}' does not exist.", path));
×
463
    }
464

465
    write_message(6, "Reading source file from {}...", path);
56✔
466

467
    // Open the binary file
468
    hid_t file_id = file_open(path, 'r', true);
56✔
469

470
    // Check to make sure this is a source file
471
    std::string filetype;
56✔
472
    read_attribute(file_id, "filetype", filetype);
56✔
473
    if (filetype != "source" && filetype != "statepoint") {
56!
474
      fatal_error("Specified starting source file not a source file type.");
×
475
    }
476

477
    // Read in the source particles
478
    read_source_bank(file_id, sites_, false);
56✔
479

480
    // Close file
481
    file_close(file_id);
48✔
482
  }
48✔
483

484
  // Make sure particles in source file have valid types
485
  for (const auto& site : this->sites_) {
156,086✔
486
    validate_particle_type(site.particle, "FileSource");
156,010✔
487
  }
488
}
76✔
489

490
SourceSite FileSource::sample(uint64_t* seed) const
260,813✔
491
{
492
  // Sample a particle randomly from list
493
  size_t i_site = sites_.size() * prn(seed);
260,813✔
494
  return sites_[i_site];
260,813✔
495
}
496

497
//==============================================================================
498
// CompiledSourceWrapper implementation
499
//==============================================================================
500

501
CompiledSourceWrapper::CompiledSourceWrapper(pugi::xml_node node) : Source(node)
28✔
502
{
503
  // Get shared library path and parameters
504
  auto path = get_node_value(node, "library", false, true);
28✔
505
  std::string parameters;
28✔
506
  if (check_for_node(node, "parameters")) {
28✔
507
    parameters = get_node_value(node, "parameters", false, true);
14✔
508
  }
509
  setup(path, parameters);
28✔
510
}
28✔
511

512
void CompiledSourceWrapper::setup(
28✔
513
  const std::string& path, const std::string& parameters)
514
{
515
#ifdef HAS_DYNAMIC_LINKING
516
  // Open the library
517
  shared_library_ = dlopen(path.c_str(), RTLD_LAZY);
28✔
518
  if (!shared_library_) {
28!
519
    fatal_error("Couldn't open source library " + path);
×
520
  }
521

522
  // reset errors
523
  dlerror();
28✔
524

525
  // get the function to create the custom source from the library
526
  auto create_compiled_source = reinterpret_cast<create_compiled_source_t*>(
527
    dlsym(shared_library_, "openmc_create_source"));
28✔
528

529
  // check for any dlsym errors
530
  auto dlsym_error = dlerror();
28✔
531
  if (dlsym_error) {
28!
532
    std::string error_msg = fmt::format(
533
      "Couldn't open the openmc_create_source symbol: {}", dlsym_error);
×
534
    dlclose(shared_library_);
×
535
    fatal_error(error_msg);
×
536
  }
×
537

538
  // create a pointer to an instance of the custom source
539
  compiled_source_ = create_compiled_source(parameters);
28✔
540

541
#else
542
  fatal_error("Custom source libraries have not yet been implemented for "
543
              "non-POSIX systems");
544
#endif
545
}
28✔
546

547
CompiledSourceWrapper::~CompiledSourceWrapper()
56✔
548
{
549
  // Make sure custom source is cleared before closing shared library
550
  if (compiled_source_.get())
28!
551
    compiled_source_.reset();
28✔
552

553
#ifdef HAS_DYNAMIC_LINKING
554
  dlclose(shared_library_);
28✔
555
#else
556
  fatal_error("Custom source libraries have not yet been implemented for "
557
              "non-POSIX systems");
558
#endif
559
}
56✔
560

561
//==============================================================================
562
// MeshElementSpatial implementation
563
//==============================================================================
564

565
std::pair<Position, double> MeshElementSpatial::sample(uint64_t* seed) const
1,353,310✔
566
{
567
  return {model::meshes[mesh_index_]->sample_element(elem_index_, seed), 1.0};
1,353,310✔
568
}
569

570
//==============================================================================
571
// MeshSource implementation
572
//==============================================================================
573

574
MeshSource::MeshSource(pugi::xml_node node) : Source(node)
183✔
575
{
576
  int32_t mesh_id = stoi(get_node_value(node, "mesh"));
183✔
577
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
183✔
578
  const auto& mesh = model::meshes[mesh_idx];
183✔
579

580
  std::vector<double> strengths;
183✔
581
  // read all source distributions and populate strengths vector for MeshSpatial
582
  // object
583
  for (auto source_node : node.children("source")) {
37,503✔
584
    auto src = Source::create(source_node);
37,320✔
585
    if (auto ptr = dynamic_cast<IndependentSource*>(src.get())) {
37,320!
586
      src.release();
37,320✔
587
      sources_.emplace_back(ptr);
37,320✔
588
    } else {
589
      fatal_error(
×
590
        "The source assigned to each element must be an IndependentSource.");
591
    }
592
    strengths.push_back(sources_.back()->strength());
37,320✔
593
  }
37,320✔
594

595
  // Set spatial distributions for each mesh element
596
  for (int elem_index = 0; elem_index < sources_.size(); ++elem_index) {
37,503✔
597
    sources_[elem_index]->set_space(
74,640✔
598
      std::make_unique<MeshElementSpatial>(mesh_idx, elem_index));
74,640✔
599
  }
600

601
  // Make sure sources use valid particle types
602
  for (const auto& src : sources_) {
37,503✔
603
    validate_particle_type(src->particle_type(), "MeshSource");
37,320✔
604
  }
605

606
  // the number of source distributions should either be one or equal to the
607
  // number of mesh elements
608
  if (sources_.size() > 1 && sources_.size() != mesh->n_bins()) {
183!
609
    fatal_error(fmt::format("Incorrect number of source distributions ({}) for "
×
610
                            "mesh source with {} elements.",
611
      sources_.size(), mesh->n_bins()));
×
612
  }
613

614
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
183✔
615
}
183✔
616

617
SourceSite MeshSource::sample(uint64_t* seed) const
1,340,102✔
618
{
619
  // Sample a mesh element based on the relative strengths
620
  int32_t element = space_->sample_element_index(seed);
1,340,102✔
621

622
  // Sample the distribution for the specific mesh element; note that the
623
  // spatial distribution has been set for each element using MeshElementSpatial
624
  return source(element)->sample_with_constraints(seed);
1,340,102✔
625
}
626

627
//==============================================================================
628
// Non-member functions
629
//==============================================================================
630

631
void initialize_source()
3,528✔
632
{
633
  write_message("Initializing source particles...", 5);
3,528✔
634

635
// Generation source sites from specified distribution in user input
636
#pragma omp parallel for
637
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
960,179✔
638
    // initialize random number seed
639
    int64_t id = simulation::total_gen * settings::n_particles +
1,917,704✔
640
                 simulation::work_index[mpi::rank] + i + 1;
958,852✔
641
    uint64_t seed = init_seed(id, STREAM_SOURCE);
958,852✔
642

643
    // sample external source distribution
644
    simulation::source_bank[i] = sample_external_source(&seed);
958,852✔
645
  }
646

647
  // Write out initial source
648
  if (settings::write_initial_source) {
3,528!
649
    write_message("Writing out initial source...", 5);
×
650
    std::string filename = settings::path_output + "initial_source.h5";
×
651
    hid_t file_id = file_open(filename, 'w', true);
×
652
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
×
653
    file_close(file_id);
×
654
  }
×
655
}
3,528✔
656

657
SourceSite sample_external_source(uint64_t* seed)
29,966,727✔
658
{
659
  // Sample from among multiple source distributions
660
  int i = 0;
29,966,727✔
661
  int n_sources = model::external_sources.size();
29,966,727✔
662
  if (n_sources > 1) {
29,966,727✔
663
    if (settings::uniform_source_sampling) {
3,235,000✔
664
      i = prn(seed) * n_sources;
2,000✔
665
    } else {
666
      i = model::external_sources_probability.sample(seed);
3,233,000✔
667
    }
668
  }
669

670
  // Sample source site from i-th source distribution
671
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
29,966,727✔
672

673
  // For uniform source sampling, multiply the weight by the ratio of the actual
674
  // probability of sampling source i to the biased probability of sampling
675
  // source i, which is (strength_i / total_strength) / (1 / n)
676
  if (n_sources > 1 && settings::uniform_source_sampling) {
29,966,724✔
677
    double total_strength = model::external_sources_probability.integral();
2,000✔
678
    site.wgt *=
2,000✔
679
      model::external_sources[i]->strength() * n_sources / total_strength;
2,000✔
680
  }
681

682
  // If running in MG, convert site.E to group
683
  if (!settings::run_CE) {
29,966,724✔
684
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
1,584,000✔
685
      data::mg.rev_energy_bins_.end(), site.E);
686
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
1,584,000✔
687
  }
688

689
  return site;
29,966,724✔
690
}
691

692
void free_memory_source()
7,507✔
693
{
694
  model::external_sources.clear();
7,507✔
695
}
7,507✔
696

697
//==============================================================================
698
// C API
699
//==============================================================================
700

701
extern "C" int openmc_sample_external_source(
923✔
702
  size_t n, uint64_t* seed, void* sites)
703
{
704
  if (!sites || !seed) {
923!
705
    set_errmsg("Received null pointer.");
×
706
    return OPENMC_E_INVALID_ARGUMENT;
×
707
  }
708

709
  if (model::external_sources.empty()) {
923!
710
    set_errmsg("No external sources have been defined.");
×
711
    return OPENMC_E_OUT_OF_BOUNDS;
×
712
  }
713

714
  auto sites_array = static_cast<SourceSite*>(sites);
923✔
715
  for (size_t i = 0; i < n; ++i) {
2,743,493✔
716
    sites_array[i] = sample_external_source(seed);
2,742,570✔
717
  }
718
  return 0;
923✔
719
}
720

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