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

openmc-dev / openmc / 15568622188

10 Jun 2025 07:34PM UTC coverage: 85.155% (-0.003%) from 85.158%
15568622188

Pull #3404

github

web-flow
Merge 0cbc32e92 into f796fa04e
Pull Request #3404: New Feature: electron/positron independent source.

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

7 existing lines in 1 file now uncovered.

52371 of 61501 relevant lines covered (85.15%)

36523045.37 hits per line

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

84.23
/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,427✔
57
{
58
  // Check for source strength
59
  if (check_for_node(node, "strength")) {
44,427✔
60
    strength_ = std::stod(get_node_value(node, "strength"));
43,723✔
61
    if (strength_ < 0.0) {
43,723✔
62
      fatal_error("Source strength is negative.");
×
63
    }
64
  }
65

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

70
unique_ptr<Source> Source::create(pugi::xml_node node)
44,427✔
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,427✔
75
    std::string source_type = get_node_value(node, "type");
43,510✔
76
    if (source_type == "independent") {
43,510✔
77
      return make_unique<IndependentSource>(node);
43,235✔
78
    } else if (source_type == "file") {
275✔
79
      return make_unique<FileSource>(node);
42✔
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,500✔
88
    // support legacy source format
89
    if (check_for_node(node, "file")) {
917✔
90
      return make_unique<FileSource>(node);
32✔
91
    } else if (check_for_node(node, "library")) {
885✔
92
      return make_unique<CompiledSourceWrapper>(node);
×
93
    } else {
94
      return make_unique<IndependentSource>(node);
885✔
95
    }
96
  }
97
}
98

99
void Source::read_constraints(pugi::xml_node node)
44,427✔
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,427✔
105
  if (constraints_node) {
44,427✔
106
    node = constraints_node;
1,525✔
107
  }
108

109
  // Check for domains to reject from
110
  if (check_for_node(node, "domain_type")) {
44,427✔
111
    std::string domain_type = get_node_value(node, "domain_type");
393✔
112
    if (domain_type == "cell") {
393✔
113
      domain_type_ = DomainType::CELL;
41✔
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");
393✔
124
    domain_ids_.insert(ids.begin(), ids.end());
393✔
125
  }
393✔
126

127
  if (check_for_node(node, "time_bounds")) {
44,427✔
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,427✔
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,427✔
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,427✔
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,427✔
159

160
SourceSite Source::sample_with_constraints(uint64_t* seed) const
26,692,956✔
161
{
162
  bool accepted = false;
26,692,956✔
163
  static int n_reject = 0;
164
  static int n_accept = 0;
165
  SourceSite site;
26,692,956✔
166

167
  while (!accepted) {
53,418,127✔
168
    // Sample a source site without considering constraints yet
169
    site = this->sample(seed);
26,725,174✔
170

171
    if (constraints_applied()) {
26,725,171✔
172
      accepted = true;
26,329,513✔
173
    } else {
174
      // Check whether sampled site satisfies constraints
175
      accepted = satisfies_spatial_constraints(site.r) &&
395,658✔
176
                 satisfies_energy_constraints(site.E) &&
769,968✔
177
                 satisfies_time_constraints(site.time);
374,310✔
178
      if (!accepted) {
395,658✔
179
        ++n_reject;
32,218✔
180
        if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
32,218✔
181
            static_cast<double>(n_accept) / n_reject <=
182
              EXTSRC_REJECT_FRACTION) {
183
          fatal_error("More than 95% of external source sites sampled were "
×
184
                      "rejected. Please check your source definition.");
185
        }
186

187
        // For the "kill" strategy, accept particle but set weight to 0 so that
188
        // it is terminated immediately
189
        if (rejection_strategy_ == RejectionStrategy::KILL) {
32,218✔
190
          accepted = true;
×
191
          site.wgt = 0.0;
×
192
        }
193
      }
194
    }
195
  }
196

197
  // Increment number of accepted samples
198
  ++n_accept;
26,692,953✔
199

200
  return site;
26,692,953✔
201
}
202

203
bool Source::satisfies_energy_constraints(double E) const
26,725,171✔
204
{
205
  return E > energy_bounds_.first && E < energy_bounds_.second;
26,725,171✔
206
}
207

208
bool Source::satisfies_time_constraints(double time) const
561,450✔
209
{
210
  return time > time_bounds_.first && time < time_bounds_.second;
561,450✔
211
}
212

213
bool Source::satisfies_spatial_constraints(Position r) const
30,589,714✔
214
{
215
  GeometryState geom_state;
30,589,714✔
216
  geom_state.r() = r;
30,589,714✔
217
  geom_state.u() = {0.0, 0.0, 1.0};
30,589,714✔
218

219
  // Reject particle if it's not in the geometry at all
220
  bool found = exhaustive_find_cell(geom_state);
30,589,714✔
221
  if (!found)
30,589,714✔
222
    return false;
375,441✔
223

224
  // Check the geometry state against specified domains
225
  bool accepted = true;
30,214,273✔
226
  if (!domain_ids_.empty()) {
30,214,273✔
227
    if (domain_type_ == DomainType::MATERIAL) {
1,397,806✔
228
      auto mat_index = geom_state.material();
×
229
      if (mat_index != MATERIAL_VOID) {
×
230
        accepted = contains(domain_ids_, model::materials[mat_index]->id());
×
231
      }
232
    } else {
233
      for (int i = 0; i < geom_state.n_coord(); i++) {
2,773,612✔
234
        auto id = (domain_type_ == DomainType::CELL)
1,397,806✔
235
                    ? model::cells[geom_state.coord(i).cell]->id_
1,397,806✔
236
                    : model::universes[geom_state.coord(i).universe]->id_;
×
237
        if ((accepted = contains(domain_ids_, id)))
1,397,806✔
238
          break;
22,000✔
239
      }
240
    }
241
  }
242

243
  // Check if spatial site is in fissionable material
244
  if (accepted && only_fissionable_) {
30,214,273✔
245
    // Determine material
246
    auto mat_index = geom_state.material();
1,003,176✔
247
    if (mat_index == MATERIAL_VOID) {
1,003,176✔
248
      accepted = false;
×
249
    } else {
250
      accepted = model::materials[mat_index]->fissionable();
1,003,176✔
251
    }
252
  }
253

254
  return accepted;
30,214,273✔
255
}
30,589,714✔
256

257
//==============================================================================
258
// IndependentSource implementation
259
//==============================================================================
260

261
IndependentSource::IndependentSource(
1,621✔
262
  UPtrSpace space, UPtrAngle angle, UPtrDist energy, UPtrDist time)
1,621✔
263
  : space_ {std::move(space)}, angle_ {std::move(angle)},
1,621✔
264
    energy_ {std::move(energy)}, time_ {std::move(time)}
3,242✔
265
{}
1,621✔
266

267
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
44,120✔
268
{
269
  // Check for particle type
270
  if (check_for_node(node, "particle")) {
44,120✔
271
    auto temp_str = get_node_value(node, "particle", true, true);
43,235✔
272
    if (temp_str == "neutron") {
43,235✔
273
      particle_ = ParticleType::neutron;
43,094✔
274
    } else if (temp_str == "photon") {
141✔
275
      particle_ = ParticleType::photon;
125✔
276
      settings::photon_transport = true;
125✔
277
    } else if (temp_str == "electron") {
16✔
278
      particle_ = ParticleType::electron;
16✔
279
      settings::photon_transport = true;
16✔
280
      if (settings::electron_treatment == ElectronTreatment::LED)
16✔
NEW
UNCOV
281
        settings::electron_treatment = ElectronTreatment::TTB;
×
NEW
UNCOV
282
    } else if (temp_str == "positron") {
×
NEW
UNCOV
283
      particle_ = ParticleType::positron;
×
NEW
UNCOV
284
      settings::photon_transport = true;
×
NEW
UNCOV
285
      if (settings::electron_treatment == ElectronTreatment::LED)
×
NEW
UNCOV
286
        settings::electron_treatment = ElectronTreatment::TTB;
×
287
    } else {
UNCOV
288
      fatal_error(std::string("Unknown source particle type: ") + temp_str);
×
289
    }
290
  }
43,235✔
291

292
  // Check for external source file
293
  if (check_for_node(node, "file")) {
44,120✔
294

295
  } else {
296

297
    // Spatial distribution for external source
298
    if (check_for_node(node, "space")) {
44,120✔
299
      space_ = SpatialDistribution::create(node.child("space"));
6,135✔
300
    } else {
301
      // If no spatial distribution specified, make it a point source
302
      space_ = UPtrSpace {new SpatialPoint()};
37,985✔
303
    }
304

305
    // For backwards compatibility, check for only fissionable setting on box
306
    // source
307
    auto space_box = dynamic_cast<SpatialBox*>(space_.get());
44,119✔
308
    if (space_box) {
44,119✔
309
      if (!only_fissionable_) {
3,340✔
310
        only_fissionable_ = space_box->only_fissionable();
2,219✔
311
      }
312
    }
313

314
    // Determine external source angular distribution
315
    if (check_for_node(node, "angle")) {
44,119✔
316
      angle_ = UnitSphereDistribution::create(node.child("angle"));
3,168✔
317
    } else {
318
      angle_ = UPtrAngle {new Isotropic()};
40,951✔
319
    }
320

321
    // Determine external source energy distribution
322
    if (check_for_node(node, "energy")) {
44,119✔
323
      pugi::xml_node node_dist = node.child("energy");
4,208✔
324
      energy_ = distribution_from_xml(node_dist);
4,208✔
325
    } else {
326
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
327
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
39,911✔
328
    }
329

330
    // Determine external source time distribution
331
    if (check_for_node(node, "time")) {
44,119✔
332
      pugi::xml_node node_dist = node.child("time");
43✔
333
      time_ = distribution_from_xml(node_dist);
43✔
334
    } else {
335
      // Default to a Constant time T=0
336
      double T[] {0.0};
44,076✔
337
      double p[] {1.0};
44,076✔
338
      time_ = UPtrDist {new Discrete {T, p, 1}};
44,076✔
339
    }
340
  }
341
}
44,119✔
342

343
SourceSite IndependentSource::sample(uint64_t* seed) const
27,988,176✔
344
{
345
  SourceSite site;
27,988,176✔
346
  site.particle = particle_;
27,988,176✔
347

348
  // Repeat sampling source location until a good site has been accepted
349
  bool accepted = false;
27,988,176✔
350
  static int n_reject = 0;
351
  static int n_accept = 0;
352

353
  while (!accepted) {
56,680,358✔
354

355
    // Sample spatial distribution
356
    site.r = space_->sample(seed);
28,692,185✔
357

358
    // Check if sampled position satisfies spatial constraints
359
    accepted = satisfies_spatial_constraints(site.r);
28,692,185✔
360

361
    // Check for rejection
362
    if (!accepted) {
28,692,185✔
363
      ++n_reject;
704,012✔
364
      if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
704,012✔
365
          static_cast<double>(n_accept) / n_reject <= EXTSRC_REJECT_FRACTION) {
127,902✔
366
        fatal_error("More than 95% of external source sites sampled were "
3✔
367
                    "rejected. Please check your external source's spatial "
368
                    "definition.");
369
      }
370
    }
371
  }
372

373
  // Sample angle
374
  site.u = angle_->sample(seed);
27,988,173✔
375

376
  // Sample energy and time for neutron and photon sources
377
  if (settings::solver_type != SolverType::RANDOM_RAY) {
27,988,173✔
378
    // Check for monoenergetic source above maximum particle energy
379
    auto p = static_cast<int>(particle_);
26,142,373✔
380
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
26,142,373✔
381
    if (energy_ptr) {
26,142,373✔
382
      auto energies = xt::adapt(energy_ptr->x());
16,880,827✔
383
      if (xt::any(energies > data::energy_max[p])) {
16,880,827✔
384
        fatal_error("Source energy above range of energies of at least "
×
385
                    "one cross section table");
386
      }
387
    }
16,880,827✔
388

389
    while (true) {
390
      // Sample energy spectrum
391
      site.E = energy_->sample(seed);
26,142,373✔
392

393
      // Resample if energy falls above maximum particle energy
394
      if (site.E < data::energy_max[p] and
52,284,746✔
395
          (satisfies_energy_constraints(site.E)))
26,142,373✔
396
        break;
26,142,373✔
397

398
      n_reject++;
×
399
      if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
×
400
          static_cast<double>(n_accept) / n_reject <= EXTSRC_REJECT_FRACTION) {
401
        fatal_error(
×
402
          "More than 95% of external source sites sampled were "
403
          "rejected. Please check your external source energy spectrum "
404
          "definition.");
405
      }
406
    }
407

408
    // Sample particle creation time
409
    site.time = time_->sample(seed);
26,142,373✔
410
  }
411

412
  // Increment number of accepted samples
413
  ++n_accept;
27,988,173✔
414

415
  return site;
27,988,173✔
416
}
417

418
//==============================================================================
419
// FileSource implementation
420
//==============================================================================
421

422
FileSource::FileSource(pugi::xml_node node) : Source(node)
74✔
423
{
424
  auto path = get_node_value(node, "file", false, true);
74✔
425
  if (ends_with(path, ".mcpl") || ends_with(path, ".mcpl.gz")) {
74✔
426
    sites_ = mcpl_source_sites(path);
16✔
427
  } else {
428
    this->load_sites_from_file(path);
58✔
429
  }
430
}
65✔
431

432
FileSource::FileSource(const std::string& path)
16✔
433
{
434
  load_sites_from_file(path);
16✔
435
}
16✔
436

437
void FileSource::load_sites_from_file(const std::string& path)
74✔
438
{
439
  // Check if source file exists
440
  if (!file_exists(path)) {
74✔
441
    fatal_error(fmt::format("Source file '{}' does not exist.", path));
×
442
  }
443

444
  // Read the source from a binary file instead of sampling from some
445
  // assumed source distribution
446
  write_message(6, "Reading source file from {}...", path);
74✔
447

448
  // Open the binary file
449
  hid_t file_id = file_open(path, 'r', true);
74✔
450

451
  // Check to make sure this is a source file
452
  std::string filetype;
74✔
453
  read_attribute(file_id, "filetype", filetype);
74✔
454
  if (filetype != "source" && filetype != "statepoint") {
74✔
455
    fatal_error("Specified starting source file not a source file type.");
×
456
  }
457

458
  // Read in the source particles
459
  read_source_bank(file_id, sites_, false);
74✔
460

461
  // Close file
462
  file_close(file_id);
65✔
463
}
65✔
464

465
SourceSite FileSource::sample(uint64_t* seed) const
175,658✔
466
{
467
  // Sample a particle randomly from list
468
  size_t i_site = sites_.size() * prn(seed);
175,658✔
469
  return sites_[i_site];
175,658✔
470
}
471

472
//==============================================================================
473
// CompiledSourceWrapper implementation
474
//==============================================================================
475

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

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

497
  // reset errors
498
  dlerror();
32✔
499

500
  // get the function to create the custom source from the library
501
  auto create_compiled_source = reinterpret_cast<create_compiled_source_t*>(
502
    dlsym(shared_library_, "openmc_create_source"));
32✔
503

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

513
  // create a pointer to an instance of the custom source
514
  compiled_source_ = create_compiled_source(parameters);
32✔
515

516
#else
517
  fatal_error("Custom source libraries have not yet been implemented for "
518
              "non-POSIX systems");
519
#endif
520
}
32✔
521

522
CompiledSourceWrapper::~CompiledSourceWrapper()
64✔
523
{
524
  // Make sure custom source is cleared before closing shared library
525
  if (compiled_source_.get())
32✔
526
    compiled_source_.reset();
32✔
527

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

32✔
536
//==============================================================================
537
// MeshSource implementation
538
//==============================================================================
539

540
MeshSource::MeshSource(pugi::xml_node node) : Source(node)
541
{
542
  int32_t mesh_id = stoi(get_node_value(node, "mesh"));
543
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
544
  const auto& mesh = model::meshes[mesh_idx];
545

546
  std::vector<double> strengths;
547
  // read all source distributions and populate strengths vector for MeshSpatial
32✔
548
  // object
32✔
549
  for (auto source_node : node.children("source")) {
550
    sources_.emplace_back(Source::create(source_node));
551
    strengths.push_back(sources_.back()->strength());
32✔
552
  }
32✔
553

554
  // the number of source distributions should either be one or equal to the
555
  // number of mesh elements
32✔
556
  if (sources_.size() > 1 && sources_.size() != mesh->n_bins()) {
557
    fatal_error(fmt::format("Incorrect number of source distributions ({}) for "
558
                            "mesh source with {} elements.",
559
      sources_.size(), mesh->n_bins()));
560
  }
32✔
561

562
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
563
}
564

565
SourceSite MeshSource::sample(uint64_t* seed) const
566
{
201✔
567
  // Sample the CDF defined in initialization above
568
  int32_t element = space_->sample_element_index(seed);
201✔
569

201✔
570
  // Sample position and apply rejection on spatial domains
201✔
571
  Position r;
572
  do {
201✔
573
    r = space_->mesh()->sample_element(element, seed);
574
  } while (!this->satisfies_spatial_constraints(r));
575

37,642✔
576
  SourceSite site;
37,441✔
577
  while (true) {
37,441✔
578
    // Sample source for the chosen element and replace the position
579
    site = source(element)->sample_with_constraints(seed);
580
    site.r = r;
581

582
    // Apply other rejections
201✔
583
    if (satisfies_energy_constraints(site.E) &&
×
584
        satisfies_time_constraints(site.time)) {
585
      break;
×
586
    }
587
  }
588

201✔
589
  return site;
201✔
590
}
591

187,140✔
592
//==============================================================================
593
// Non-member functions
594
//==============================================================================
187,140✔
595

596
void initialize_source()
597
{
187,140✔
598
  write_message("Initializing source particles...", 5);
599

1,501,871✔
600
// Generation source sites from specified distribution in user input
1,501,871✔
601
#pragma omp parallel for
602
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
187,140✔
603
    // initialize random number seed
604
    int64_t id = simulation::total_gen * settings::n_particles +
605
                 simulation::work_index[mpi::rank] + i + 1;
187,140✔
606
    uint64_t seed = init_seed(id, STREAM_SOURCE);
187,140✔
607

608
    // sample external source distribution
609
    simulation::source_bank[i] = sample_external_source(&seed);
374,280✔
610
  }
187,140✔
611

187,140✔
612
  // Write out initial source
613
  if (settings::write_initial_source) {
614
    write_message("Writing out initial source...", 5);
615
    std::string filename = settings::path_output + "initial_source.h5";
374,280✔
616
    hid_t file_id = file_open(filename, 'w', true);
617
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
618
    file_close(file_id);
619
  }
620
}
621

622
SourceSite sample_external_source(uint64_t* seed)
3,411✔
623
{
624
  // Sample from among multiple source distributions
3,411✔
625
  int i = 0;
626
  int n_sources = model::external_sources.size();
627
  if (n_sources > 1) {
628
    if (settings::uniform_source_sampling) {
1,047,964✔
629
      i = prn(seed) * n_sources;
630
    } else {
2,092,900✔
631
      i = model::external_sources_probability.sample(seed);
1,046,450✔
632
    }
1,046,450✔
633
  }
634

635
  // Sample source site from i-th source distribution
1,046,450✔
636
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
637

638
  // For uniform source sampling, multiply the weight by the ratio of the actual
639
  // probability of sampling source i to the biased probability of sampling
3,411✔
640
  // source i, which is (strength_i / total_strength) / (1 / n)
×
641
  if (n_sources > 1 && settings::uniform_source_sampling) {
×
642
    double total_strength = model::external_sources_probability.integral();
×
643
    site.wgt *=
×
644
      model::external_sources[i]->strength() * n_sources / total_strength;
×
645
  }
646

3,411✔
647
  // If running in MG, convert site.E to group
648
  if (!settings::run_CE) {
26,505,816✔
649
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
650
      data::mg.rev_energy_bins_.end(), site.E);
651
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
26,505,816✔
652
  }
26,505,816✔
653

26,505,816✔
654
  return site;
146,300✔
655
}
2,200✔
656

657
void free_memory_source()
144,100✔
658
{
659
  model::external_sources.clear();
660
}
661

662
//==============================================================================
26,505,816✔
663
// C API
664
//==============================================================================
665

666
extern "C" int openmc_sample_external_source(
667
  size_t n, uint64_t* seed, void* sites)
26,505,813✔
668
{
2,200✔
669
  if (!sites || !seed) {
2,200✔
670
    set_errmsg("Received null pointer.");
2,200✔
671
    return OPENMC_E_INVALID_ARGUMENT;
672
  }
673

674
  if (model::external_sources.empty()) {
26,505,813✔
675
    set_errmsg("No external sources have been defined.");
1,742,400✔
676
    return OPENMC_E_OUT_OF_BOUNDS;
677
  }
1,742,400✔
678

679
  auto sites_array = static_cast<SourceSite*>(sites);
680
  for (size_t i = 0; i < n; ++i) {
26,505,813✔
681
    sites_array[i] = sample_external_source(seed);
682
  }
683
  return 0;
6,784✔
684
}
685

6,784✔
686
} // namespace openmc
6,784✔
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