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

openmc-dev / openmc / 16191134808

10 Jul 2025 09:17AM UTC coverage: 85.165% (-0.09%) from 85.251%
16191134808

Pull #3404

github

web-flow
Merge 81c2f26ff into d700d395d
Pull Request #3404: New Feature: electron/positron independent source.

18 of 24 new or added lines in 5 files covered. (75.0%)

82 existing lines in 15 files now uncovered.

52535 of 61686 relevant lines covered (85.17%)

36485395.19 hits per line

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

84.42
/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
//==============================================================================
41
// Global variables
42
//==============================================================================
43

44
namespace model {
45

46
vector<unique_ptr<Source>> external_sources;
47

48
DiscreteIndex external_sources_probability;
49

50
} // namespace model
51

52
//==============================================================================
53
// Source implementation
54
//==============================================================================
55

56
Source::Source(pugi::xml_node node)
44,471✔
57
{
58
  // Check for source strength
59
  if (check_for_node(node, "strength")) {
44,471✔
60
    strength_ = std::stod(get_node_value(node, "strength"));
43,767✔
61
    if (strength_ < 0.0) {
43,767✔
62
      fatal_error("Source strength is negative.");
×
63
    }
64
  }
65

66
  // Check for additional defined constraints
67
  read_constraints(node);
44,471✔
68
}
44,471✔
69

70
unique_ptr<Source> Source::create(pugi::xml_node node)
44,471✔
71
{
72
  // if the source type is present, use it to determine the type
73
  // of object to create
74
  if (check_for_node(node, "type")) {
44,471✔
75
    std::string source_type = get_node_value(node, "type");
43,539✔
76
    if (source_type == "independent") {
43,539✔
77
      return make_unique<IndependentSource>(node);
43,275✔
78
    } else if (source_type == "file") {
264✔
79
      return make_unique<FileSource>(node);
31✔
80
    } else if (source_type == "compiled") {
233✔
81
      return make_unique<CompiledSourceWrapper>(node);
32✔
82
    } else if (source_type == "mesh") {
201✔
83
      return make_unique<MeshSource>(node);
201✔
84
    } else {
85
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
86
    }
87
  } else {
43,529✔
88
    // support legacy source format
89
    if (check_for_node(node, "file")) {
932✔
90
      return make_unique<FileSource>(node);
32✔
91
    } else if (check_for_node(node, "library")) {
900✔
92
      return make_unique<CompiledSourceWrapper>(node);
×
93
    } else {
94
      return make_unique<IndependentSource>(node);
900✔
95
    }
96
  }
97
}
98

99
void Source::read_constraints(pugi::xml_node node)
44,471✔
100
{
101
  // Check for constraints node. For backwards compatibility, if no constraints
102
  // node is given, still try searching for domain constraints from top-level
103
  // node.
104
  pugi::xml_node constraints_node = node.child("constraints");
44,471✔
105
  if (constraints_node) {
44,471✔
106
    node = constraints_node;
1,553✔
107
  }
108

109
  // Check for domains to reject from
110
  if (check_for_node(node, "domain_type")) {
44,471✔
111
    std::string domain_type = get_node_value(node, "domain_type");
421✔
112
    if (domain_type == "cell") {
421✔
113
      domain_type_ = DomainType::CELL;
69✔
114
    } else if (domain_type == "material") {
352✔
115
      domain_type_ = DomainType::MATERIAL;
16✔
116
    } else if (domain_type == "universe") {
336✔
117
      domain_type_ = DomainType::UNIVERSE;
336✔
118
    } else {
119
      fatal_error(
×
120
        std::string("Unrecognized domain type for constraint: " + domain_type));
×
121
    }
122

123
    auto ids = get_node_array<int>(node, "domain_ids");
421✔
124
    domain_ids_.insert(ids.begin(), ids.end());
421✔
125
  }
421✔
126

127
  if (check_for_node(node, "time_bounds")) {
44,471✔
128
    auto ids = get_node_array<double>(node, "time_bounds");
11✔
129
    if (ids.size() != 2) {
11✔
130
      fatal_error("Time bounds must be represented by two numbers.");
×
131
    }
132
    time_bounds_ = std::make_pair(ids[0], ids[1]);
11✔
133
  }
11✔
134
  if (check_for_node(node, "energy_bounds")) {
44,471✔
135
    auto ids = get_node_array<double>(node, "energy_bounds");
11✔
136
    if (ids.size() != 2) {
11✔
137
      fatal_error("Energy bounds must be represented by two numbers.");
×
138
    }
139
    energy_bounds_ = std::make_pair(ids[0], ids[1]);
11✔
140
  }
11✔
141

142
  if (check_for_node(node, "fissionable")) {
44,471✔
143
    only_fissionable_ = get_node_value_bool(node, "fissionable");
1,121✔
144
  }
145

146
  // Check for how to handle rejected particles
147
  if (check_for_node(node, "rejection_strategy")) {
44,471✔
148
    std::string rejection_strategy = get_node_value(node, "rejection_strategy");
×
149
    if (rejection_strategy == "kill") {
×
150
      rejection_strategy_ = RejectionStrategy::KILL;
×
151
    } else if (rejection_strategy == "resample") {
×
152
      rejection_strategy_ = RejectionStrategy::RESAMPLE;
×
153
    } else {
154
      fatal_error(std::string(
×
155
        "Unrecognized strategy source rejection: " + rejection_strategy));
156
    }
157
  }
158
}
44,471✔
159

160
void check_rejection_fraction(int64_t n_reject, int64_t n_accept)
2,462,826✔
161
{
162
  // Don't check unless we've hit a minimum number of total sites rejected
163
  if (n_reject < EXTSRC_REJECT_THRESHOLD)
2,462,826✔
164
    return;
749,544✔
165

166
  // Compute fraction of accepted sites and compare against minimum
167
  double fraction = static_cast<double>(n_accept) / n_reject;
1,713,282✔
168
  if (fraction <= settings::source_rejection_fraction) {
1,713,282✔
169
    fatal_error(fmt::format(
3✔
170
      "Too few source sites satisfied the constraints (minimum source "
171
      "rejection fraction = {}). Please check your source definition or "
172
      "set a lower value of Settings.source_rejection_fraction.",
173
      settings::source_rejection_fraction));
174
  }
175
}
176

177
SourceSite Source::sample_with_constraints(uint64_t* seed) const
28,073,266✔
178
{
179
  bool accepted = false;
28,073,266✔
180
  static int64_t n_reject = 0;
181
  static int64_t n_accept = 0;
182
  SourceSite site;
28,073,266✔
183

184
  while (!accepted) {
57,494,686✔
185
    // Sample a source site without considering constraints yet
186
    site = this->sample(seed);
29,421,423✔
187

188
    if (constraints_applied()) {
29,421,420✔
189
      accepted = true;
27,511,903✔
190
    } else {
191
      // Check whether sampled site satisfies constraints
192
      accepted = satisfies_spatial_constraints(site.r) &&
1,909,517✔
193
                 satisfies_energy_constraints(site.E) &&
2,481,692✔
194
                 satisfies_time_constraints(site.time);
572,175✔
195
      if (!accepted) {
1,909,517✔
196
        // Increment number of rejections and check against minimum fraction
197
        ++n_reject;
1,348,157✔
198
        check_rejection_fraction(n_reject, n_accept);
1,348,157✔
199

200
        // For the "kill" strategy, accept particle but set weight to 0 so that
201
        // it is terminated immediately
202
        if (rejection_strategy_ == RejectionStrategy::KILL) {
1,348,157✔
203
          accepted = true;
×
204
          site.wgt = 0.0;
×
205
        }
206
      }
207
    }
208
  }
209

210
  // Increment number of accepted samples
211
  ++n_accept;
28,073,263✔
212

213
  return site;
28,073,263✔
214
}
215

216
bool Source::satisfies_energy_constraints(double E) const
28,105,820✔
217
{
218
  return E > energy_bounds_.first && E < energy_bounds_.second;
28,105,820✔
219
}
220

221
bool Source::satisfies_time_constraints(double time) const
572,175✔
222
{
223
  return time > time_bounds_.first && time < time_bounds_.second;
572,175✔
224
}
225

226
bool Source::satisfies_spatial_constraints(Position r) const
32,381,889✔
227
{
228
  GeometryState geom_state;
32,381,889✔
229
  geom_state.r() = r;
32,381,889✔
230
  geom_state.u() = {0.0, 0.0, 1.0};
32,381,889✔
231

232
  // Reject particle if it's not in the geometry at all
233
  bool found = exhaustive_find_cell(geom_state);
32,381,889✔
234
  if (!found)
32,381,889✔
235
    return false;
375,441✔
236

237
  // Check the geometry state against specified domains
238
  bool accepted = true;
32,006,448✔
239
  if (!domain_ids_.empty()) {
32,006,448✔
240
    if (domain_type_ == DomainType::MATERIAL) {
1,823,276✔
241
      auto mat_index = geom_state.material();
×
242
      if (mat_index == MATERIAL_VOID) {
×
243
        accepted = false;
×
244
      } else {
245
        accepted = contains(domain_ids_, model::materials[mat_index]->id());
×
246
      }
247
    } else {
248
      for (int i = 0; i < geom_state.n_coord(); i++) {
3,607,132✔
249
        auto id = (domain_type_ == DomainType::CELL)
1,823,276✔
250
                    ? model::cells[geom_state.coord(i).cell]->id_
1,823,276✔
251
                    : model::universes[geom_state.coord(i).universe]->id_;
×
252
        if ((accepted = contains(domain_ids_, id)))
1,823,276✔
253
          break;
39,420✔
254
      }
255
    }
256
  }
257

258
  // Check if spatial site is in fissionable material
259
  if (accepted && only_fissionable_) {
32,006,448✔
260
    // Determine material
261
    auto mat_index = geom_state.material();
1,008,252✔
262
    if (mat_index == MATERIAL_VOID) {
1,008,252✔
263
      accepted = false;
×
264
    } else {
265
      accepted = model::materials[mat_index]->fissionable();
1,008,252✔
266
    }
267
  }
268

269
  return accepted;
32,006,448✔
270
}
32,381,889✔
271

272
//==============================================================================
273
// IndependentSource implementation
274
//==============================================================================
275

276
IndependentSource::IndependentSource(
1,686✔
277
  UPtrSpace space, UPtrAngle angle, UPtrDist energy, UPtrDist time)
1,686✔
278
  : space_ {std::move(space)}, angle_ {std::move(angle)},
1,686✔
279
    energy_ {std::move(energy)}, time_ {std::move(time)}
3,372✔
280
{}
1,686✔
281

282
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
44,175✔
283
{
284
  // Check for particle type
285
  if (check_for_node(node, "particle")) {
44,175✔
286
    auto temp_str = get_node_value(node, "particle", true, true);
43,275✔
287
    if (temp_str == "neutron") {
43,275✔
288
      particle_ = ParticleType::neutron;
43,134✔
289
    } else if (temp_str == "photon") {
141✔
290
      particle_ = ParticleType::photon;
125✔
291
      settings::photon_transport = true;
125✔
292
    } else if (temp_str == "electron") {
16✔
293
      particle_ = ParticleType::electron;
16✔
294
      settings::photon_transport = true;
16✔
295
      if (settings::electron_treatment == ElectronTreatment::LED)
16✔
NEW
296
        settings::electron_treatment = ElectronTreatment::TTB;
×
NEW
297
    } else if (temp_str == "positron") {
×
NEW
298
      particle_ = ParticleType::positron;
×
NEW
299
      settings::photon_transport = true;
×
NEW
300
      if (settings::electron_treatment == ElectronTreatment::LED)
×
NEW
301
        settings::electron_treatment = ElectronTreatment::TTB;
×
302
    } else {
303
      fatal_error(std::string("Unknown source particle type: ") + temp_str);
×
304
    }
305
  }
43,275✔
306

307
  // Check for external source file
308
  if (check_for_node(node, "file")) {
44,175✔
309

310
  } else {
311

312
    // Spatial distribution for external source
313
    if (check_for_node(node, "space")) {
44,175✔
314
      space_ = SpatialDistribution::create(node.child("space"));
6,157✔
315
    } else {
316
      // If no spatial distribution specified, make it a point source
317
      space_ = UPtrSpace {new SpatialPoint()};
38,018✔
318
    }
319

320
    // For backwards compatibility, check for only fissionable setting on box
321
    // source
322
    auto space_box = dynamic_cast<SpatialBox*>(space_.get());
44,174✔
323
    if (space_box) {
44,174✔
324
      if (!only_fissionable_) {
3,365✔
325
        only_fissionable_ = space_box->only_fissionable();
2,244✔
326
      }
327
    }
328

329
    // Determine external source angular distribution
330
    if (check_for_node(node, "angle")) {
44,174✔
331
      angle_ = UnitSphereDistribution::create(node.child("angle"));
3,179✔
332
    } else {
333
      angle_ = UPtrAngle {new Isotropic()};
40,995✔
334
    }
335

336
    // Determine external source energy distribution
337
    if (check_for_node(node, "energy")) {
44,174✔
338
      pugi::xml_node node_dist = node.child("energy");
4,208✔
339
      energy_ = distribution_from_xml(node_dist);
4,208✔
340
    } else {
341
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
342
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
39,966✔
343
    }
344

345
    // Determine external source time distribution
346
    if (check_for_node(node, "time")) {
44,174✔
347
      pugi::xml_node node_dist = node.child("time");
43✔
348
      time_ = distribution_from_xml(node_dist);
43✔
349
    } else {
350
      // Default to a Constant time T=0
351
      double T[] {0.0};
44,131✔
352
      double p[] {1.0};
44,131✔
353
      time_ = UPtrDist {new Discrete {T, p, 1}};
44,131✔
354
    }
355
  }
356
}
44,174✔
357

358
SourceSite IndependentSource::sample(uint64_t* seed) const
29,357,706✔
359
{
360
  SourceSite site;
29,357,706✔
361
  site.particle = particle_;
29,357,706✔
362

363
  // Repeat sampling source location until a good site has been accepted
364
  bool accepted = false;
29,357,706✔
365
  static int64_t n_reject = 0;
366
  static int64_t n_accept = 0;
367

368
  while (!accepted) {
59,830,075✔
369

370
    // Sample spatial distribution
371
    site.r = space_->sample(seed);
30,472,372✔
372

373
    // Check if sampled position satisfies spatial constraints
374
    accepted = satisfies_spatial_constraints(site.r);
30,472,372✔
375

376
    // Check for rejection
377
    if (!accepted) {
30,472,372✔
378
      ++n_reject;
1,114,669✔
379
      check_rejection_fraction(n_reject, n_accept);
1,114,669✔
380
    }
381
  }
382

383
  // Sample angle
384
  site.u = angle_->sample(seed);
29,357,703✔
385

386
  // Sample energy and time for neutron and photon sources
387
  if (settings::solver_type != SolverType::RANDOM_RAY) {
29,357,703✔
388
    // Check for monoenergetic source above maximum particle energy
389
    auto p = static_cast<int>(particle_);
27,511,903✔
390
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
27,511,903✔
391
    if (energy_ptr) {
27,511,903✔
392
      auto energies = xt::adapt(energy_ptr->x());
16,880,827✔
393
      if (xt::any(energies > data::energy_max[p])) {
16,880,827✔
394
        fatal_error("Source energy above range of energies of at least "
×
395
                    "one cross section table");
396
      }
397
    }
16,880,827✔
398

399
    while (true) {
400
      // Sample energy spectrum
401
      site.E = energy_->sample(seed);
27,511,903✔
402

403
      // Resample if energy falls above maximum particle energy
404
      if (site.E < data::energy_max[p] &&
55,023,806✔
405
          (satisfies_energy_constraints(site.E)))
27,511,903✔
406
        break;
27,511,903✔
407

408
      n_reject++;
×
409
      check_rejection_fraction(n_reject, n_accept);
×
410
    }
411

412
    // Sample particle creation time
413
    site.time = time_->sample(seed);
27,511,903✔
414
  }
415

416
  // Increment number of accepted samples
417
  ++n_accept;
29,357,703✔
418

419
  return site;
29,357,703✔
420
}
421

422
//==============================================================================
423
// FileSource implementation
424
//==============================================================================
425

426
FileSource::FileSource(pugi::xml_node node) : Source(node)
63✔
427
{
428
  auto path = get_node_value(node, "file", false, true);
63✔
429
  if (ends_with(path, ".mcpl") || ends_with(path, ".mcpl.gz")) {
63✔
430
    sites_ = mcpl_source_sites(path);
16✔
431
  } else {
432
    this->load_sites_from_file(path);
47✔
433
  }
434
}
54✔
435

436
FileSource::FileSource(const std::string& path)
16✔
437
{
438
  load_sites_from_file(path);
16✔
439
}
16✔
440

441
void FileSource::load_sites_from_file(const std::string& path)
63✔
442
{
443
  // Check if source file exists
444
  if (!file_exists(path)) {
63✔
445
    fatal_error(fmt::format("Source file '{}' does not exist.", path));
×
446
  }
447

448
  // Read the source from a binary file instead of sampling from some
449
  // assumed source distribution
450
  write_message(6, "Reading source file from {}...", path);
63✔
451

452
  // Open the binary file
453
  hid_t file_id = file_open(path, 'r', true);
63✔
454

455
  // Check to make sure this is a source file
456
  std::string filetype;
63✔
457
  read_attribute(file_id, "filetype", filetype);
63✔
458
  if (filetype != "source" && filetype != "statepoint") {
63✔
459
    fatal_error("Specified starting source file not a source file type.");
×
460
  }
461

462
  // Read in the source particles
463
  read_source_bank(file_id, sites_, false);
63✔
464

465
  // Close file
466
  file_close(file_id);
54✔
467
}
54✔
468

469
SourceSite FileSource::sample(uint64_t* seed) const
175,887✔
470
{
471
  // Sample a particle randomly from list
472
  size_t i_site = sites_.size() * prn(seed);
175,887✔
473
  return sites_[i_site];
175,887✔
474
}
475

476
//==============================================================================
477
// CompiledSourceWrapper implementation
478
//==============================================================================
479

480
CompiledSourceWrapper::CompiledSourceWrapper(pugi::xml_node node) : Source(node)
32✔
481
{
482
  // Get shared library path and parameters
483
  auto path = get_node_value(node, "library", false, true);
32✔
484
  std::string parameters;
32✔
485
  if (check_for_node(node, "parameters")) {
32✔
486
    parameters = get_node_value(node, "parameters", false, true);
16✔
487
  }
488
  setup(path, parameters);
32✔
489
}
32✔
490

491
void CompiledSourceWrapper::setup(
32✔
492
  const std::string& path, const std::string& parameters)
493
{
494
#ifdef HAS_DYNAMIC_LINKING
495
  // Open the library
496
  shared_library_ = dlopen(path.c_str(), RTLD_LAZY);
32✔
497
  if (!shared_library_) {
32✔
498
    fatal_error("Couldn't open source library " + path);
×
499
  }
500

501
  // reset errors
502
  dlerror();
32✔
503

504
  // get the function to create the custom source from the library
505
  auto create_compiled_source = reinterpret_cast<create_compiled_source_t*>(
506
    dlsym(shared_library_, "openmc_create_source"));
32✔
507

508
  // check for any dlsym errors
509
  auto dlsym_error = dlerror();
32✔
510
  if (dlsym_error) {
32✔
511
    std::string error_msg = fmt::format(
512
      "Couldn't open the openmc_create_source symbol: {}", dlsym_error);
×
513
    dlclose(shared_library_);
×
514
    fatal_error(error_msg);
×
515
  }
×
516

517
  // create a pointer to an instance of the custom source
518
  compiled_source_ = create_compiled_source(parameters);
32✔
519

520
#else
521
  fatal_error("Custom source libraries have not yet been implemented for "
522
              "non-POSIX systems");
523
#endif
524
}
32✔
525

526
CompiledSourceWrapper::~CompiledSourceWrapper()
64✔
527
{
528
  // Make sure custom source is cleared before closing shared library
529
  if (compiled_source_.get())
32✔
530
    compiled_source_.reset();
32✔
531

532
#ifdef HAS_DYNAMIC_LINKING
533
  dlclose(shared_library_);
32✔
534
#else
535
  fatal_error("Custom source libraries have not yet been implemented for "
536
              "non-POSIX systems");
537
#endif
538
}
64✔
539

32✔
540
//==============================================================================
541
// MeshElementSpatial implementation
542
//==============================================================================
543

544
Position MeshElementSpatial::sample(uint64_t* seed) const
545
{
546
  return model::meshes[mesh_index_]->sample_element(elem_index_, seed);
547
}
548

549
//==============================================================================
550
// MeshSource implementation
551
//==============================================================================
32✔
552

32✔
553
MeshSource::MeshSource(pugi::xml_node node) : Source(node)
554
{
555
  int32_t mesh_id = stoi(get_node_value(node, "mesh"));
32✔
556
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
32✔
557
  const auto& mesh = model::meshes[mesh_idx];
558

559
  std::vector<double> strengths;
32✔
560
  // read all source distributions and populate strengths vector for MeshSpatial
561
  // object
562
  for (auto source_node : node.children("source")) {
563
    auto src = Source::create(source_node);
564
    if (auto ptr = dynamic_cast<IndependentSource*>(src.get())) {
32✔
565
      src.release();
566
      sources_.emplace_back(ptr);
567
    } else {
568
      fatal_error(
569
        "The source assigned to each element must be an IndependentSource.");
570
    }
1,530,727✔
571
    strengths.push_back(sources_.back()->strength());
572
  }
1,530,727✔
573

574
  // Set spatial distributions for each mesh element
575
  for (int elem_index = 0; elem_index < sources_.size(); ++elem_index) {
576
    sources_[elem_index]->set_space(
577
      std::make_unique<MeshElementSpatial>(mesh_idx, elem_index));
578
  }
579

201✔
580
  // the number of source distributions should either be one or equal to the
581
  // number of mesh elements
201✔
582
  if (sources_.size() > 1 && sources_.size() != mesh->n_bins()) {
201✔
583
    fatal_error(fmt::format("Incorrect number of source distributions ({}) for "
201✔
584
                            "mesh source with {} elements.",
585
      sources_.size(), mesh->n_bins()));
201✔
586
  }
587

588
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
37,653✔
589
}
37,452✔
590

37,452✔
591
SourceSite MeshSource::sample(uint64_t* seed) const
37,452✔
592
{
37,452✔
593
  // Sample a mesh element based on the relative strengths
594
  int32_t element = space_->sample_element_index(seed);
×
595

596
  // Sample the distribution for the specific mesh element; note that the
597
  // spatial distribution has been set for each element using MeshElementSpatial
37,452✔
598
  return source(element)->sample_with_constraints(seed);
37,452✔
599
}
600

601
//==============================================================================
37,653✔
602
// Non-member functions
74,904✔
603
//==============================================================================
74,904✔
604

605
void initialize_source()
606
{
607
  write_message("Initializing source particles...", 5);
608

201✔
609
// Generation source sites from specified distribution in user input
×
610
#pragma omp parallel for
611
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
×
612
    // initialize random number seed
613
    int64_t id = simulation::total_gen * settings::n_particles +
614
                 simulation::work_index[mpi::rank] + i + 1;
201✔
615
    uint64_t seed = init_seed(id, STREAM_SOURCE);
201✔
616

617
    // sample external source distribution
1,513,630✔
618
    simulation::source_bank[i] = sample_external_source(&seed);
619
  }
620

1,513,630✔
621
  // Write out initial source
622
  if (settings::write_initial_source) {
623
    write_message("Writing out initial source...", 5);
624
    std::string filename = settings::path_output + "initial_source.h5";
1,513,630✔
625
    hid_t file_id = file_open(filename, 'w', true);
626
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
627
    file_close(file_id);
628
  }
629
}
630

631
SourceSite sample_external_source(uint64_t* seed)
3,455✔
632
{
633
  // Sample from among multiple source distributions
3,455✔
634
  int i = 0;
635
  int n_sources = model::external_sources.size();
636
  if (n_sources > 1) {
637
    if (settings::uniform_source_sampling) {
1,057,974✔
638
      i = prn(seed) * n_sources;
639
    } else {
2,112,900✔
640
      i = model::external_sources_probability.sample(seed);
1,056,450✔
641
    }
1,056,450✔
642
  }
643

644
  // Sample source site from i-th source distribution
1,056,450✔
645
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
646

647
  // For uniform source sampling, multiply the weight by the ratio of the actual
648
  // probability of sampling source i to the biased probability of sampling
3,455✔
649
  // source i, which is (strength_i / total_strength) / (1 / n)
×
650
  if (n_sources > 1 && settings::uniform_source_sampling) {
×
651
    double total_strength = model::external_sources_probability.integral();
×
652
    site.wgt *=
×
653
      model::external_sources[i]->strength() * n_sources / total_strength;
×
654
  }
655

3,455✔
656
  // If running in MG, convert site.E to group
657
  if (!settings::run_CE) {
26,559,636✔
658
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
659
      data::mg.rev_energy_bins_.end(), site.E);
660
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
26,559,636✔
661
  }
26,559,636✔
662

26,559,636✔
663
  return site;
146,300✔
664
}
2,200✔
665

666
void free_memory_source()
144,100✔
667
{
668
  model::external_sources.clear();
669
}
670

671
//==============================================================================
26,559,636✔
672
// C API
673
//==============================================================================
674

675
extern "C" int openmc_sample_external_source(
676
  size_t n, uint64_t* seed, void* sites)
26,559,633✔
677
{
2,200✔
678
  if (!sites || !seed) {
2,200✔
679
    set_errmsg("Received null pointer.");
2,200✔
680
    return OPENMC_E_INVALID_ARGUMENT;
681
  }
682

683
  if (model::external_sources.empty()) {
26,559,633✔
684
    set_errmsg("No external sources have been defined.");
1,742,400✔
685
    return OPENMC_E_OUT_OF_BOUNDS;
686
  }
1,742,400✔
687

688
  auto sites_array = static_cast<SourceSite*>(sites);
689
  for (size_t i = 0; i < n; ++i) {
26,559,633✔
690
    sites_array[i] = sample_external_source(seed);
691
  }
692
  return 0;
6,882✔
693
}
694

6,882✔
695
} // namespace openmc
6,882✔
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