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

openmc-dev / openmc / 21686031975

04 Feb 2026 07:50PM UTC coverage: 81.024% (-0.7%) from 81.763%
21686031975

Pull #3755

github

web-flow
Merge 27d6053a4 into b41e22f68
Pull Request #3755: Warn users that tally heating score with photon bin but without electron and positron bins.

16378 of 22828 branches covered (71.75%)

Branch coverage included in aggregate %.

22 of 23 new or added lines in 1 file covered. (95.65%)

862 existing lines in 51 files now uncovered.

54491 of 64639 relevant lines covered (84.3%)

8259986.93 hits per line

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

78.65
/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)
19,109✔
43
{
44
  if (type.is_transportable())
19,109!
45
    return;
19,109✔
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)
1,005✔
71
{
72
  // Check for source strength
73
  if (check_for_node(node, "strength")) {
1,005✔
74
    strength_ = std::stod(get_node_value(node, "strength"));
919✔
75
    if (strength_ < 0.0) {
919!
76
      fatal_error("Source strength is negative.");
×
77
    }
78
  }
79

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

84
unique_ptr<Source> Source::create(pugi::xml_node node)
1,005✔
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")) {
1,005✔
89
    std::string source_type = get_node_value(node, "type");
898✔
90
    if (source_type == "independent") {
898✔
91
      return make_unique<IndependentSource>(node);
873✔
92
    } else if (source_type == "file") {
25✔
93
      return make_unique<FileSource>(node);
3✔
94
    } else if (source_type == "compiled") {
22✔
95
      return make_unique<CompiledSourceWrapper>(node);
4✔
96
    } else if (source_type == "mesh") {
18!
97
      return make_unique<MeshSource>(node);
18✔
98
    } else {
99
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
100
    }
101
  } else {
897✔
102
    // support legacy source format
103
    if (check_for_node(node, "file")) {
107✔
104
      return make_unique<FileSource>(node);
4✔
105
    } else if (check_for_node(node, "library")) {
103!
106
      return make_unique<CompiledSourceWrapper>(node);
×
107
    } else {
108
      return make_unique<IndependentSource>(node);
103✔
109
    }
110
  }
111
}
112

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

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

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

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

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

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

180
  // Compute fraction of accepted sites and compare against minimum
181
  double fraction = static_cast<double>(n_accept) / n_reject;
124,069✔
182
  if (fraction <= settings::source_rejection_fraction) {
124,069!
UNCOV
183
    fatal_error(fmt::format(
×
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
2,951,286✔
192
{
193
  bool accepted = false;
2,951,286✔
194
  static int64_t n_reject = 0;
195
  static int64_t n_accept = 0;
196
  SourceSite site;
2,951,286✔
197

198
  while (!accepted) {
6,025,454✔
199
    // Sample a source site without considering constraints yet
200
    site = this->sample(seed);
3,074,168✔
201

202
    if (constraints_applied()) {
3,074,168✔
203
      accepted = true;
2,890,256✔
204
    } else {
205
      // Check whether sampled site satisfies constraints
206
      accepted = satisfies_spatial_constraints(site.r) &&
183,912✔
207
                 satisfies_energy_constraints(site.E) &&
245,936✔
208
                 satisfies_time_constraints(site.time);
62,024✔
209
      if (!accepted) {
183,912✔
210
        // Increment number of rejections and check against minimum fraction
211
        ++n_reject;
122,882✔
212
        check_rejection_fraction(n_reject, n_accept);
122,882✔
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) {
122,882!
217
          accepted = true;
×
218
          site.wgt = 0.0;
×
219
        }
220
      }
221
    }
222
  }
223

224
  // Increment number of accepted samples
225
  ++n_accept;
2,951,286✔
226

227
  return site;
2,951,286✔
228
}
229

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

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

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

246
  // Reject particle if it's not in the geometry at all
247
  bool found = exhaustive_find_cell(geom_state);
3,328,455✔
248
  if (!found)
3,328,455✔
249
    return false;
44,547✔
250

251
  // Check the geometry state against specified domains
252
  bool accepted = true;
3,283,908✔
253
  if (!domain_ids_.empty()) {
3,283,908✔
254
    if (domain_type_ == DomainType::MATERIAL) {
137,622!
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++) {
262,244✔
263
        auto id =
264
          (domain_type_ == DomainType::CELL)
137,622✔
265
            ? model::cells[geom_state.coord(i).cell()].get()->id_
137,622!
266
            : model::universes[geom_state.coord(i).universe()].get()->id_;
×
267
        if ((accepted = contains(domain_ids_, id)))
137,622✔
268
          break;
13,000✔
269
      }
270
    }
271
  }
272

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

284
  return accepted;
3,283,908✔
285
}
3,328,455✔
286

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

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

297
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
976✔
298
{
299
  // Check for particle type
300
  if (check_for_node(node, "particle")) {
976✔
301
    auto temp_str = get_node_value(node, "particle", false, true);
873✔
302
    particle_ = ParticleType(temp_str);
873✔
303
    if (particle_ == ParticleType::photon() ||
1,731✔
304
        particle_ == ParticleType::electron() ||
1,731!
305
        particle_ == ParticleType::positron()) {
856✔
306
      settings::photon_transport = true;
17✔
307
    }
308
  }
873✔
309
  validate_particle_type(particle_, "IndependentSource");
976✔
310

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

314
  } else {
315

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

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

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

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

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

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

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

374
  while (!accepted) {
6,212,399✔
375

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

381
    // Check if sampled position satisfies spatial constraints
382
    accepted = satisfies_spatial_constraints(site.r);
3,144,543✔
383

384
    // Check for rejection
385
    if (!accepted) {
3,144,543✔
386
      ++n_reject;
76,687✔
387
      check_rejection_fraction(n_reject, n_accept);
76,687✔
388
    }
389
  }
390

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

395
  site.wgt = r_wgt * u_wgt;
3,067,856✔
396

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

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

416
      // Resample if energy falls above maximum particle energy
417
      if (site.E < data::energy_max[p] &&
5,780,512!
418
          (satisfies_energy_constraints(site.E)))
2,890,256!
419
        break;
2,890,256✔
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);
2,890,256✔
427
    site.time = time;
2,890,256✔
428

429
    site.wgt *= (E_wgt * time_wgt);
2,890,256✔
430
  }
431

432
  // Increment number of accepted samples
433
  ++n_accept;
3,067,856✔
434

435
  return site;
6,135,712✔
436
}
437

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

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

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

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

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

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

469
    // Check to make sure this is a source file
470
    std::string filetype;
7✔
471
    read_attribute(file_id, "filetype", filetype);
7✔
472
    if (filetype != "source" && filetype != "statepoint") {
7!
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);
7✔
478

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

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

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

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

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

511
void CompiledSourceWrapper::setup(
4✔
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);
4✔
517
  if (!shared_library_) {
4!
518
    fatal_error("Couldn't open source library " + path);
×
519
  }
520

521
  // reset errors
522
  dlerror();
4✔
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"));
4✔
527

528
  // check for any dlsym errors
529
  auto dlsym_error = dlerror();
4✔
530
  if (dlsym_error) {
4!
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);
4✔
539

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

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

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

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

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

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

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

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

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

600
  // Make sure sources use valid particle types
601
  for (const auto& src : sources_) {
150✔
602
    validate_particle_type(src->particle_type(), "MeshSource");
132✔
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()) {
18!
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);
18✔
614
}
18✔
615

616
SourceSite MeshSource::sample(uint64_t* seed) const
137,861✔
617
{
618
  // Sample a mesh element based on the relative strengths
619
  int32_t element = space_->sample_element_index(seed);
137,861✔
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);
137,861✔
624
}
625

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

630
void initialize_source()
434✔
631
{
632
  write_message("Initializing source particles...", 5);
434✔
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) {
239,647✔
637
    // initialize random number seed
638
    int64_t id = simulation::total_gen * settings::n_particles +
478,426✔
639
                 simulation::work_index[mpi::rank] + i + 1;
239,213✔
640
    uint64_t seed = init_seed(id, STREAM_SOURCE);
239,213✔
641

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

646
  // Write out initial source
647
  if (settings::write_initial_source) {
434!
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
}
434✔
655

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

669
  // Sample source site from i-th source distribution
670
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
2,813,425✔
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) {
2,813,425✔
676
    double total_strength = model::external_sources_probability.integral();
200✔
677
    site.wgt *=
200✔
678
      model::external_sources[i]->strength() * n_sources / total_strength;
200✔
679
  }
680

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

688
  return site;
2,813,425✔
689
}
690

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

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

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

708
  if (model::external_sources.empty()) {
32!
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);
32✔
714
  for (size_t i = 0; i < n; ++i) {
214,286✔
715
    sites_array[i] = sample_external_source(seed);
214,254✔
716
  }
717
  return 0;
32✔
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