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

openmc-dev / openmc / 20278909785

16 Dec 2025 06:41PM UTC coverage: 81.834% (-0.09%) from 81.92%
20278909785

Pull #3493

github

web-flow
Merge 9dc7c7a58 into bbfa18d72
Pull Request #3493: Implement vector fitting to replace external `vectfit` package

17020 of 23572 branches covered (72.2%)

Branch coverage included in aggregate %.

188 of 207 new or added lines in 3 files covered. (90.82%)

3101 existing lines in 56 files now uncovered.

54979 of 64410 relevant lines covered (85.36%)

41388074.54 hits per line

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

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

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

70
unique_ptr<Source> Source::create(pugi::xml_node node)
44,259✔
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,259✔
75
    std::string source_type = get_node_value(node, "type");
43,465✔
76
    if (source_type == "independent") {
43,465✔
77
      return make_unique<IndependentSource>(node);
43,206✔
78
    } else if (source_type == "file") {
259✔
79
      return make_unique<FileSource>(node);
28✔
80
    } else if (source_type == "compiled") {
231✔
81
      return make_unique<CompiledSourceWrapper>(node);
28✔
82
    } else if (source_type == "mesh") {
203!
83
      return make_unique<MeshSource>(node);
203✔
84
    } else {
85
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
86
    }
87
  } else {
43,456✔
88
    // support legacy source format
89
    if (check_for_node(node, "file")) {
794✔
90
      return make_unique<FileSource>(node);
28✔
91
    } else if (check_for_node(node, "library")) {
766!
92
      return make_unique<CompiledSourceWrapper>(node);
×
93
    } else {
94
      return make_unique<IndependentSource>(node);
766✔
95
    }
96
  }
97
}
98

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

109
  // Check for domains to reject from
110
  if (check_for_node(node, "domain_type")) {
44,259✔
111
    std::string domain_type = get_node_value(node, "domain_type");
405✔
112
    if (domain_type == "cell") {
405✔
113
      domain_type_ = DomainType::CELL;
83✔
114
    } else if (domain_type == "material") {
322✔
115
      domain_type_ = DomainType::MATERIAL;
14✔
116
    } else if (domain_type == "universe") {
308!
117
      domain_type_ = DomainType::UNIVERSE;
308✔
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");
405✔
124
    domain_ids_.insert(ids.begin(), ids.end());
405✔
125
  }
405✔
126

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

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

146
  // Check for how to handle rejected particles
147
  if (check_for_node(node, "rejection_strategy")) {
44,259!
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,259✔
159

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

166
  // Compute fraction of accepted sites and compare against minimum
167
  double fraction = static_cast<double>(n_accept) / n_reject;
1,560,557✔
168
  if (fraction <= settings::source_rejection_fraction) {
1,560,557✔
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,086,995✔
178
{
179
  bool accepted = false;
28,086,995✔
180
  static int64_t n_reject = 0;
181
  static int64_t n_accept = 0;
182
  SourceSite site;
28,086,995✔
183

184
  while (!accepted) {
57,372,674✔
185
    // Sample a source site without considering constraints yet
186
    site = this->sample(seed);
29,285,682✔
187

188
    if (constraints_applied()) {
29,285,679✔
189
      accepted = true;
27,376,662✔
190
    } else {
191
      // Check whether sampled site satisfies constraints
192
      accepted = satisfies_spatial_constraints(site.r) &&
1,909,017✔
193
                 satisfies_energy_constraints(site.E) &&
2,629,195✔
194
                 satisfies_time_constraints(site.time);
720,178✔
195
      if (!accepted) {
1,909,017✔
196
        // Increment number of rejections and check against minimum fraction
197
        ++n_reject;
1,198,687✔
198
        check_rejection_fraction(n_reject, n_accept);
1,198,687✔
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,198,687!
203
          accepted = true;
×
204
          site.wgt = 0.0;
×
205
        }
206
      }
207
    }
208
  }
209

210
  // Increment number of accepted samples
211
  ++n_accept;
28,086,992✔
212

213
  return site;
28,086,992✔
214
}
215

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

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

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

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

237
  // Check the geometry state against specified domains
238
  bool accepted = true;
31,745,698✔
239
  if (!domain_ids_.empty()) {
31,745,698✔
240
    if (domain_type_ == DomainType::MATERIAL) {
1,767,016!
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,397,612✔
249
        auto id =
250
          (domain_type_ == DomainType::CELL)
1,767,016✔
251
            ? model::cells[geom_state.coord(i).cell()].get()->id_
1,767,016!
252
            : model::universes[geom_state.coord(i).universe()].get()->id_;
×
253
        if ((accepted = contains(domain_ids_, id)))
1,767,016✔
254
          break;
136,420✔
255
      }
256
    }
257
  }
258

259
  // Check if spatial site is in fissionable material
260
  if (accepted && only_fissionable_) {
31,745,698✔
261
    // Determine material
262
    auto mat_index = geom_state.material();
968,071✔
263
    if (mat_index == MATERIAL_VOID) {
968,071!
264
      accepted = false;
×
265
    } else {
266
      accepted = model::materials[mat_index]->fissionable();
968,071✔
267
    }
268
  }
269

270
  return accepted;
31,745,698✔
271
}
32,114,211✔
272

273
//==============================================================================
274
// IndependentSource implementation
275
//==============================================================================
276

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

283
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
43,972✔
284
{
285
  // Check for particle type
286
  if (check_for_node(node, "particle")) {
43,972✔
287
    auto temp_str = get_node_value(node, "particle", true, true);
43,206✔
288
    if (temp_str == "neutron") {
43,206✔
289
      particle_ = ParticleType::neutron;
43,040✔
290
    } else if (temp_str == "photon") {
166✔
291
      particle_ = ParticleType::photon;
152✔
292
      settings::photon_transport = true;
152✔
293
    } else if (temp_str == "electron") {
14!
294
      particle_ = ParticleType::electron;
14✔
295
      settings::photon_transport = true;
14✔
UNCOV
296
    } else if (temp_str == "positron") {
×
UNCOV
297
      particle_ = ParticleType::positron;
×
UNCOV
298
      settings::photon_transport = true;
×
299
    } else {
UNCOV
300
      fatal_error(std::string("Unknown source particle type: ") + temp_str);
×
301
    }
302
  }
43,206✔
303

304
  // Check for external source file
305
  if (check_for_node(node, "file")) {
43,972!
306

307
  } else {
308

309
    // Spatial distribution for external source
310
    if (check_for_node(node, "space")) {
43,972✔
311
      space_ = SpatialDistribution::create(node.child("space"));
6,044✔
312
    } else {
313
      // If no spatial distribution specified, make it a point source
314
      space_ = UPtrSpace {new SpatialPoint()};
37,928✔
315
    }
316

317
    // For backwards compatibility, check for only fissionable setting on box
318
    // source
319
    auto space_box = dynamic_cast<SpatialBox*>(space_.get());
43,971!
320
    if (space_box) {
43,971✔
321
      if (!only_fissionable_) {
3,331✔
322
        only_fissionable_ = space_box->only_fissionable();
2,149✔
323
      }
324
    }
325

326
    // Determine external source angular distribution
327
    if (check_for_node(node, "angle")) {
43,971✔
328
      angle_ = UnitSphereDistribution::create(node.child("angle"));
2,870✔
329
    } else {
330
      angle_ = UPtrAngle {new Isotropic()};
41,101✔
331
    }
332

333
    // Determine external source energy distribution
334
    if (check_for_node(node, "energy")) {
43,971✔
335
      pugi::xml_node node_dist = node.child("energy");
4,014✔
336
      energy_ = distribution_from_xml(node_dist);
4,014✔
337
    } else {
338
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
339
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
39,957✔
340
    }
341

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

355
SourceSite IndependentSource::sample(uint64_t* seed) const
29,104,385✔
356
{
357
  SourceSite site;
29,104,385✔
358
  site.particle = particle_;
29,104,385✔
359

360
  // Repeat sampling source location until a good site has been accepted
361
  bool accepted = false;
29,104,385✔
362
  static int64_t n_reject = 0;
363
  static int64_t n_accept = 0;
364

365
  while (!accepted) {
59,309,576✔
366

367
    // Sample spatial distribution
368
    site.r = space_->sample(seed);
30,205,194✔
369

370
    // Check if sampled position satisfies spatial constraints
371
    accepted = satisfies_spatial_constraints(site.r);
30,205,194✔
372

373
    // Check for rejection
374
    if (!accepted) {
30,205,194✔
375
      ++n_reject;
1,100,812✔
376
      check_rejection_fraction(n_reject, n_accept);
1,100,812✔
377
    }
378
  }
379

380
  // Sample angle
381
  site.u = angle_->sample(seed);
29,104,382✔
382

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

396
    while (true) {
397
      // Sample energy spectrum
398
      site.E = energy_->sample(seed);
27,376,662✔
399

400
      // Resample if energy falls above maximum particle energy
401
      if (site.E < data::energy_max[p] &&
54,753,324!
402
          (satisfies_energy_constraints(site.E)))
27,376,662!
403
        break;
27,376,662✔
404

UNCOV
405
      n_reject++;
×
UNCOV
406
      check_rejection_fraction(n_reject, n_accept);
×
407
    }
408

409
    // Sample particle creation time
410
    site.time = time_->sample(seed);
27,376,662✔
411
  }
412

413
  // Increment number of accepted samples
414
  ++n_accept;
29,104,382✔
415

416
  return site;
29,104,382✔
417
}
418

419
//==============================================================================
420
// FileSource implementation
421
//==============================================================================
422

423
FileSource::FileSource(pugi::xml_node node) : Source(node)
56✔
424
{
425
  auto path = get_node_value(node, "file", false, true);
56✔
426
  load_sites_from_file(path);
56✔
427
}
48✔
428

429
FileSource::FileSource(const std::string& path)
28✔
430
{
431
  load_sites_from_file(path);
28✔
432
}
28✔
433

434
void FileSource::load_sites_from_file(const std::string& path)
84✔
435
{
436
  // If MCPL file, use the dedicated file reader
437
  if (ends_with(path, ".mcpl") || ends_with(path, ".mcpl.gz")) {
84!
438
    sites_ = mcpl_source_sites(path);
28✔
439
  } else {
440
    // Check if source file exists
441
    if (!file_exists(path)) {
56!
UNCOV
442
      fatal_error(fmt::format("Source file '{}' does not exist.", path));
×
443
    }
444

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

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

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

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

460
    // Close file
461
    file_close(file_id);
48✔
462
  }
48✔
463
}
76✔
464

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

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

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

487
void CompiledSourceWrapper::setup(
28✔
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);
28✔
493
  if (!shared_library_) {
28!
UNCOV
494
    fatal_error("Couldn't open source library " + path);
×
495
  }
496

497
  // reset errors
498
  dlerror();
28✔
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"));
28✔
503

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

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

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

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

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

536
//==============================================================================
537
// MeshElementSpatial implementation
538
//==============================================================================
539

540
Position MeshElementSpatial::sample(uint64_t* seed) const
1,462,443✔
541
{
542
  return model::meshes[mesh_index_]->sample_element(elem_index_, seed);
1,462,443✔
543
}
544

545
//==============================================================================
546
// MeshSource implementation
547
//==============================================================================
548

549
MeshSource::MeshSource(pugi::xml_node node) : Source(node)
203✔
550
{
551
  int32_t mesh_id = stoi(get_node_value(node, "mesh"));
203✔
552
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
203✔
553
  const auto& mesh = model::meshes[mesh_idx];
203✔
554

555
  std::vector<double> strengths;
203✔
556
  // read all source distributions and populate strengths vector for MeshSpatial
557
  // object
558
  for (auto source_node : node.children("source")) {
37,543✔
559
    auto src = Source::create(source_node);
37,340✔
560
    if (auto ptr = dynamic_cast<IndependentSource*>(src.get())) {
37,340!
561
      src.release();
37,340✔
562
      sources_.emplace_back(ptr);
37,340✔
563
    } else {
UNCOV
564
      fatal_error(
×
565
        "The source assigned to each element must be an IndependentSource.");
566
    }
567
    strengths.push_back(sources_.back()->strength());
37,340✔
568
  }
37,340✔
569

570
  // Set spatial distributions for each mesh element
571
  for (int elem_index = 0; elem_index < sources_.size(); ++elem_index) {
37,543✔
572
    sources_[elem_index]->set_space(
74,680✔
573
      std::make_unique<MeshElementSpatial>(mesh_idx, elem_index));
74,680✔
574
  }
575

576
  // the number of source distributions should either be one or equal to the
577
  // number of mesh elements
578
  if (sources_.size() > 1 && sources_.size() != mesh->n_bins()) {
203!
UNCOV
579
    fatal_error(fmt::format("Incorrect number of source distributions ({}) for "
×
580
                            "mesh source with {} elements.",
UNCOV
581
      sources_.size(), mesh->n_bins()));
×
582
  }
583

584
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
203✔
585
}
203✔
586

587
SourceSite MeshSource::sample(uint64_t* seed) const
1,449,168✔
588
{
589
  // Sample a mesh element based on the relative strengths
590
  int32_t element = space_->sample_element_index(seed);
1,449,168✔
591

592
  // Sample the distribution for the specific mesh element; note that the
593
  // spatial distribution has been set for each element using MeshElementSpatial
594
  return source(element)->sample_with_constraints(seed);
1,449,168✔
595
}
596

597
//==============================================================================
598
// Non-member functions
599
//==============================================================================
600

601
void initialize_source()
3,393✔
602
{
603
  write_message("Initializing source particles...", 5);
3,393✔
604

605
// Generation source sites from specified distribution in user input
606
#pragma omp parallel for
607
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
922,927✔
608
    // initialize random number seed
609
    int64_t id = simulation::total_gen * settings::n_particles +
1,843,304✔
610
                 simulation::work_index[mpi::rank] + i + 1;
921,652✔
611
    uint64_t seed = init_seed(id, STREAM_SOURCE);
921,652✔
612

613
    // sample external source distribution
614
    simulation::source_bank[i] = sample_external_source(&seed);
921,652✔
615
  }
616

617
  // Write out initial source
618
  if (settings::write_initial_source) {
3,393!
UNCOV
619
    write_message("Writing out initial source...", 5);
×
UNCOV
620
    std::string filename = settings::path_output + "initial_source.h5";
×
UNCOV
621
    hid_t file_id = file_open(filename, 'w', true);
×
UNCOV
622
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
×
UNCOV
623
    file_close(file_id);
×
UNCOV
624
  }
×
625
}
3,393✔
626

627
SourceSite sample_external_source(uint64_t* seed)
26,637,827✔
628
{
629
  // Sample from among multiple source distributions
630
  int i = 0;
26,637,827✔
631
  int n_sources = model::external_sources.size();
26,637,827✔
632
  if (n_sources > 1) {
26,637,827✔
633
    if (settings::uniform_source_sampling) {
1,835,000✔
634
      i = prn(seed) * n_sources;
2,000✔
635
    } else {
636
      i = model::external_sources_probability.sample(seed);
1,833,000✔
637
    }
638
  }
639

640
  // Sample source site from i-th source distribution
641
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
26,637,827✔
642

643
  // For uniform source sampling, multiply the weight by the ratio of the actual
644
  // probability of sampling source i to the biased probability of sampling
645
  // source i, which is (strength_i / total_strength) / (1 / n)
646
  if (n_sources > 1 && settings::uniform_source_sampling) {
26,637,824✔
647
    double total_strength = model::external_sources_probability.integral();
2,000✔
648
    site.wgt *=
2,000✔
649
      model::external_sources[i]->strength() * n_sources / total_strength;
2,000✔
650
  }
651

652
  // If running in MG, convert site.E to group
653
  if (!settings::run_CE) {
26,637,824✔
654
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
1,584,000✔
655
      data::mg.rev_energy_bins_.end(), site.E);
656
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
1,584,000✔
657
  }
658

659
  return site;
26,637,824✔
660
}
661

662
void free_memory_source()
6,899✔
663
{
664
  model::external_sources.clear();
6,899✔
665
}
6,899✔
666

667
//==============================================================================
668
// C API
669
//==============================================================================
670

671
extern "C" int openmc_sample_external_source(
763✔
672
  size_t n, uint64_t* seed, void* sites)
673
{
674
  if (!sites || !seed) {
763!
675
    set_errmsg("Received null pointer.");
×
UNCOV
676
    return OPENMC_E_INVALID_ARGUMENT;
×
677
  }
678

679
  if (model::external_sources.empty()) {
763!
UNCOV
680
    set_errmsg("No external sources have been defined.");
×
UNCOV
681
    return OPENMC_E_OUT_OF_BOUNDS;
×
682
  }
683

684
  auto sites_array = static_cast<SourceSite*>(sites);
763✔
685
  for (size_t i = 0; i < n; ++i) {
1,143,333✔
686
    sites_array[i] = sample_external_source(seed);
1,142,570✔
687
  }
688
  return 0;
763✔
689
}
690

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

© 2025 Coveralls, Inc