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

openmc-dev / openmc / 21492883686

29 Jan 2026 08:02PM UTC coverage: 81.749% (-0.2%) from 81.993%
21492883686

Pull #3756

github

web-flow
Merge 7d830ab98 into f7a734189
Pull Request #3756: Refactor ParticleType to use PDG Monte Carlo numbering scheme

17298 of 24251 branches covered (71.33%)

Branch coverage included in aggregate %.

346 of 501 new or added lines in 32 files covered. (69.06%)

453 existing lines in 6 files now uncovered.

55889 of 65276 relevant lines covered (85.62%)

44298457.78 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 "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,873✔
43
{
44
  if (type.is_transportable())
256,873!
45
    return;
256,873✔
46

NEW
47
  fatal_error(
×
NEW
48
    fmt::format("Unsupported source particle type '{}' (PDG {}) in {}.",
×
NEW
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,706✔
71
{
72
  // Check for source strength
73
  if (check_for_node(node, "strength")) {
45,706✔
74
    strength_ = std::stod(get_node_value(node, "strength"));
45,018✔
75
    if (strength_ < 0.0) {
45,018!
76
      fatal_error("Source strength is negative.");
×
77
    }
78
  }
79

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

84
unique_ptr<Source> Source::create(pugi::xml_node node)
45,706✔
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,706✔
89
    std::string source_type = get_node_value(node, "type");
44,805✔
90
    if (source_type == "independent") {
44,805✔
91
      return make_unique<IndependentSource>(node);
44,541✔
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✔
98
    } else {
99
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
100
    }
101
  } else {
44,795✔
102
    // support legacy source format
103
    if (check_for_node(node, "file")) {
901✔
104
      return make_unique<FileSource>(node);
32✔
105
    } else if (check_for_node(node, "library")) {
869!
106
      return make_unique<CompiledSourceWrapper>(node);
×
107
    } else {
108
      return make_unique<IndependentSource>(node);
869✔
109
    }
110
  }
111
}
112

113
void Source::read_constraints(pugi::xml_node node)
45,706✔
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");
45,706✔
119
  if (constraints_node) {
45,706✔
120
    node = constraints_node;
1,871✔
121
  }
122

123
  // Check for domains to reject from
124
  if (check_for_node(node, "domain_type")) {
45,706✔
125
    std::string domain_type = get_node_value(node, "domain_type");
475✔
126
    if (domain_type == "cell") {
475✔
127
      domain_type_ = DomainType::CELL;
91✔
128
    } else if (domain_type == "material") {
384✔
129
      domain_type_ = DomainType::MATERIAL;
16✔
130
    } else if (domain_type == "universe") {
368!
131
      domain_type_ = DomainType::UNIVERSE;
368✔
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");
475✔
138
    domain_ids_.insert(ids.begin(), ids.end());
475✔
139
  }
475✔
140

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

156
  if (check_for_node(node, "fissionable")) {
45,706✔
157
    only_fissionable_ = get_node_value_bool(node, "fissionable");
1,385✔
158
  }
159

160
  // Check for how to handle rejected particles
161
  if (check_for_node(node, "rejection_strategy")) {
45,706!
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
}
45,706✔
173

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

180
  // Compute fraction of accepted sites and compare against minimum
181
  double fraction = static_cast<double>(n_accept) / n_reject;
1,697,337✔
182
  if (fraction <= settings::source_rejection_fraction) {
1,697,337✔
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
33,244,340✔
192
{
193
  bool accepted = false;
33,244,340✔
194
  static int64_t n_reject = 0;
195
  static int64_t n_accept = 0;
196
  SourceSite site;
33,244,340✔
197

198
  while (!accepted) {
67,826,297✔
199
    // Sample a source site without considering constraints yet
200
    site = this->sample(seed);
34,581,960✔
201

202
    if (constraints_applied()) {
34,581,957✔
203
      accepted = true;
32,572,977✔
204
    } else {
205
      // Check whether sampled site satisfies constraints
206
      accepted = satisfies_spatial_constraints(site.r) &&
2,008,980✔
207
                 satisfies_energy_constraints(site.E) &&
2,691,433✔
208
                 satisfies_time_constraints(site.time);
682,453✔
209
      if (!accepted) {
2,008,980✔
210
        // Increment number of rejections and check against minimum fraction
211
        ++n_reject;
1,337,620✔
212
        check_rejection_fraction(n_reject, n_accept);
1,337,620✔
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,337,620!
217
          accepted = true;
×
218
          site.wgt = 0.0;
×
219
        }
220
      }
221
    }
222
  }
223

224
  // Increment number of accepted samples
225
  ++n_accept;
33,244,337✔
226

227
  return site;
33,244,337✔
228
}
229

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

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

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

246
  // Reject particle if it's not in the geometry at all
247
  bool found = exhaustive_find_cell(geom_state);
37,790,062✔
248
  if (!found)
37,790,062✔
249
    return false;
490,340✔
250

251
  // Check the geometry state against specified domains
252
  bool accepted = true;
37,299,722✔
253
  if (!domain_ids_.empty()) {
37,299,722✔
254
    if (domain_type_ == DomainType::MATERIAL) {
1,916,423!
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,683,426✔
263
        auto id =
264
          (domain_type_ == DomainType::CELL)
1,916,423✔
265
            ? model::cells[geom_state.coord(i).cell()].get()->id_
1,916,423!
266
            : model::universes[geom_state.coord(i).universe()].get()->id_;
×
267
        if ((accepted = contains(domain_ids_, id)))
1,916,423✔
268
          break;
149,420✔
269
      }
270
    }
271
  }
272

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

284
  return accepted;
37,299,722✔
285
}
37,790,062✔
286

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

291
IndependentSource::IndependentSource(
2,028✔
292
  UPtrSpace space, UPtrAngle angle, UPtrDist energy, UPtrDist time)
2,028✔
293
  : space_ {std::move(space)}, angle_ {std::move(angle)},
2,028✔
294
    energy_ {std::move(energy)}, time_ {std::move(time)}
4,056✔
295
{}
2,028✔
296

297
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
45,410✔
298
{
299
  // Check for particle type
300
  if (check_for_node(node, "particle")) {
45,410✔
301
    auto temp_str = get_node_value(node, "particle", false, true);
44,541✔
302
    particle_ = ParticleType(temp_str);
44,541✔
303
    if (particle_ == ParticleType::photon() ||
88,935✔
304
        particle_ == ParticleType::electron() ||
88,935!
305
        particle_ == ParticleType::positron()) {
44,378✔
306
      settings::photon_transport = true;
163✔
307
    }
308
  }
44,541✔
309
  validate_particle_type(particle_, "IndependentSource");
45,410✔
310

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

314
  } else {
315

316
    // Spatial distribution for external source
317
    if (check_for_node(node, "space")) {
45,410✔
318
      space_ = SpatialDistribution::create(node.child("space"));
7,279✔
319
    } else {
320
      // If no spatial distribution specified, make it a point source
321
      space_ = UPtrSpace {new SpatialPoint()};
38,131✔
322
    }
323

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

333
    // Determine external source angular distribution
334
    if (check_for_node(node, "angle")) {
45,409✔
335
      angle_ = UnitSphereDistribution::create(node.child("angle"));
3,356✔
336
    } else {
337
      angle_ = UPtrAngle {new Isotropic()};
42,053✔
338
    }
339

340
    // Determine external source energy distribution
341
    if (check_for_node(node, "energy")) {
45,409✔
342
      pugi::xml_node node_dist = node.child("energy");
4,674✔
343
      energy_ = distribution_from_xml(node_dist);
4,674✔
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,735✔
347
    }
348

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

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

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

374
  while (!accepted) {
70,308,379✔
375

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

381
    // Check if sampled position satisfies spatial constraints
382
    accepted = satisfies_spatial_constraints(site.r);
35,781,082✔
383

384
    // Check for rejection
385
    if (!accepted) {
35,781,082✔
386
      ++n_reject;
1,253,785✔
387
      check_rejection_fraction(n_reject, n_accept);
1,253,785✔
388
    }
389
  }
390

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

395
  site.wgt = r_wgt * u_wgt;
34,527,297✔
396

397
  // Sample energy and time for neutron and photon sources
398
  if (settings::solver_type != SolverType::RANDOM_RAY) {
34,527,297✔
399
    // Check for monoenergetic source above maximum particle energy
400
    auto p = particle_.transport_index();
32,572,977✔
401
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
32,572,977!
402
    if (energy_ptr) {
32,572,977✔
403
      auto energies = xt::adapt(energy_ptr->x());
18,114,049✔
404
      if (xt::any(energies > data::energy_max[p])) {
18,114,049!
405
        fatal_error("Source energy above range of energies of at least "
×
406
                    "one cross section table");
407
      }
408
    }
18,114,049✔
409

410
    while (true) {
411
      // Sample energy spectrum
412
      auto [E, E_wgt_temp] = energy_->sample(seed);
32,572,977✔
413
      site.E = E;
32,572,977✔
414
      E_wgt = E_wgt_temp;
32,572,977✔
415

416
      // Resample if energy falls above maximum particle energy
417
      if (site.E < data::energy_max[p] &&
65,145,954!
418
          (satisfies_energy_constraints(site.E)))
32,572,977!
419
        break;
32,572,977✔
420

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

425
    // Sample particle creation time
426
    auto [time, time_wgt] = time_->sample(seed);
32,572,977✔
427
    site.time = time;
32,572,977✔
428

429
    site.wgt *= (E_wgt * time_wgt);
32,572,977✔
430
  }
431

432
  // Increment number of accepted samples
433
  ++n_accept;
34,527,297✔
434

435
  return site;
69,054,594✔
436
}
437

438
//==============================================================================
439
// FileSource implementation
440
//==============================================================================
441

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

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

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

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

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

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

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

479
    // Close file
480
    file_close(file_id);
54✔
481
  }
54✔
482

483
  // Make sure particles in source file have valid types
484
  for (const auto& site : this->sites_) {
174,097✔
485
    validate_particle_type(site.particle, "FileSource");
174,011✔
486
  }
487
}
86✔
488

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

496
//==============================================================================
497
// CompiledSourceWrapper implementation
498
//==============================================================================
499

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

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

521
  // reset errors
522
  dlerror();
32✔
523

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

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

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

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

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

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

560
//==============================================================================
561
// MeshElementSpatial implementation
562
//==============================================================================
563

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

569
//==============================================================================
570
// MeshSource implementation
571
//==============================================================================
572

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

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

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

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

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

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

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

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

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

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

634
// Generation source sites from specified distribution in user input
635
#pragma omp parallel for
636
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
1,199,018✔
637
    // initialize random number seed
638
    int64_t id = simulation::total_gen * settings::n_particles +
2,394,530✔
639
                 simulation::work_index[mpi::rank] + i + 1;
1,197,265✔
640
    uint64_t seed = init_seed(id, STREAM_SOURCE);
1,197,265✔
641

642
    // sample external source distribution
643
    simulation::source_bank[i] = sample_external_source(&seed);
1,197,265✔
644
  }
645

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

656
SourceSite sample_external_source(uint64_t* seed)
31,742,152✔
657
{
658
  // Sample from among multiple source distributions
659
  int i = 0;
31,742,152✔
660
  int n_sources = model::external_sources.size();
31,742,152✔
661
  if (n_sources > 1) {
31,742,152✔
662
    if (settings::uniform_source_sampling) {
2,458,300✔
663
      i = prn(seed) * n_sources;
2,200✔
664
    } else {
665
      i = model::external_sources_probability.sample(seed);
2,456,100✔
666
    }
667
  }
668

669
  // Sample source site from i-th source distribution
670
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
31,742,152✔
671

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

681
  // If running in MG, convert site.E to group
682
  if (!settings::run_CE) {
31,742,149✔
683
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
1,742,400✔
684
      data::mg.rev_energy_bins_.end(), site.E);
685
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
1,742,400✔
686
  }
687

688
  return site;
31,742,149✔
689
}
690

691
void free_memory_source()
8,164✔
692
{
693
  model::external_sources.clear();
8,164✔
694
}
8,164✔
695

696
//==============================================================================
697
// C API
698
//==============================================================================
699

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

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

713
  auto sites_array = static_cast<SourceSite*>(sites);
955✔
714
  for (size_t i = 0; i < n; ++i) {
2,957,779✔
715
    sites_array[i] = sample_external_source(seed);
2,956,824✔
716
  }
717
  return 0;
955✔
718
}
719

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