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

openmc-dev / openmc / 20824991646

08 Jan 2026 05:03PM UTC coverage: 82.033% (-0.2%) from 82.195%
20824991646

Pull #3460

github

web-flow
Merge 05289af22 into dfc80c706
Pull Request #3460: Source biasing capabilities

17178 of 23851 branches covered (72.02%)

Branch coverage included in aggregate %.

536 of 720 new or added lines in 12 files covered. (74.44%)

117 existing lines in 5 files now uncovered.

55664 of 64945 relevant lines covered (85.71%)

43069601.84 hits per line

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

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

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

70
unique_ptr<Source> Source::create(pugi::xml_node node)
45,507 ✔
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")) {
45,507 ✔
75
    std::string source_type = get_node_value(node, "type");
44,606 ✔
76
    if (source_type == "independent") {
44,606 ✔
77
      return make_unique<IndependentSource>(node);
44,320 ✔
78
    } else if (source_type == "file") {
286 ✔
79
      return make_unique<FileSource>(node);
31 ✔
80
    } else if (source_type == "compiled") {
255 ✔
81
      return make_unique<CompiledSourceWrapper>(node);
32 ✔
82
    } else if (source_type == "mesh") {
223 !
83
      return make_unique<MeshSource>(node);
223 ✔
84
    } else {
85
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
86
    }
87
  } else {
44,596 ✔
88
    // support legacy source format
89
    if (check_for_node(node, "file")) {
901 ✔
90
      return make_unique<FileSource>(node);
32 ✔
91
    } else if (check_for_node(node, "library")) {
869 !
92
      return make_unique<CompiledSourceWrapper>(node);
×
93
    } else {
94
      return make_unique<IndependentSource>(node);
869 ✔
95
    }
96
  }
97
}
98

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

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

127
  if (check_for_node(node, "time_bounds")) {
45,507 ✔
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")) {
45,507 ✔
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")) {
45,507 ✔
143
    only_fissionable_ = get_node_value_bool(node, "fissionable");
1,326 ✔
144
  }
145

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

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

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

184
  while (!accepted) {
66,870,591 ✔
185
    // Sample a source site without considering constraints yet
186
    site = this->sample(seed);
34,091,823 ✔
187

188
    if (constraints_applied()) {
34,091,820 ✔
189
      accepted = true;
31,997,408 ✔
190
    } else {
191
      // Check whether sampled site satisfies constraints
192
      accepted = satisfies_spatial_constraints(site.r) &&
2,094,412 ✔
193
                 satisfies_energy_constraints(site.E) &&
2,886,910 ✔
194
                 satisfies_time_constraints(site.time);
792,498 ✔
195
      if (!accepted) {
2,094,412 ✔
196
        // Increment number of rejections and check against minimum fraction
197
        ++n_reject;
1,313,052 ✔
198
        check_rejection_fraction(n_reject, n_accept);
1,313,052 ✔
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,313,052 !
203
          accepted = true;
×
204
          site.wgt = 0.0;
×
205
        }
206
      }
207
    }
208
  }
209

210
  // Increment number of accepted samples
211
  ++n_accept;
32,778,768 ✔
212

213
  return site;
32,778,768 ✔
214
}
215

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

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

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

232
  // Reject particle if it's not in the geometry at all
233
  bool found = exhaustive_find_cell(geom_state);
37,244,524 ✔
234
  if (!found)
37,244,524 ✔
235
    return false;
490,340 ✔
236

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

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

270
  return accepted;
36,754,184 ✔
271
}
37,244,524 ✔
272

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

277
IndependentSource::IndependentSource(
2,007 ✔
278
  UPtrSpace space, UPtrAngle angle, UPtrDist energy, UPtrDist time)
2,007 ✔
279
  : space_ {std::move(space)}, angle_ {std::move(angle)},
2,007 ✔
280
    energy_ {std::move(energy)}, time_ {std::move(time)}
4,014 ✔
281
{}
2,007 ✔
282

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

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

307
  } else {
308

309
    // Spatial distribution for external source
310
    if (check_for_node(node, "space")) {
45,189 ✔
311
      space_ = SpatialDistribution::create(node.child("space"));
7,052 ✔
312
    } else {
313
      // If no spatial distribution specified, make it a point source
314
      space_ = UPtrSpace {new SpatialPoint()};
38,137 ✔
315
    }
316

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

326
    // Determine external source angular distribution
327
    if (check_for_node(node, "angle")) {
45,188 ✔
328
      angle_ = UnitSphereDistribution::create(node.child("angle"));
3,356 ✔
329
    } else {
330
      angle_ = UPtrAngle {new Isotropic()};
41,832 ✔
331
    }
332

333
    // Determine external source energy distribution
334
    if (check_for_node(node, "energy")) {
45,188 ✔
335
      pugi::xml_node node_dist = node.child("energy");
4,614 ✔
336
      energy_ = distribution_from_xml(node_dist);
4,614 ✔
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)};
40,574 ✔
340
    }
341

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

355
SourceSite IndependentSource::sample(uint64_t* seed) const
33,897,831 ✔
356
{
357
  SourceSite site;
33,897,831 ✔
358
  site.particle = particle_;
33,897,831 ✔
359
  double r_wgt = 1.0, E_wgt = 1.0;
33,897,831 ✔
360

361
  // Repeat sampling source location until a good site has been accepted
362
  bool accepted = false;
33,897,831 ✔
363
  static int64_t n_reject = 0;
364
  static int64_t n_accept = 0;
365

366
  while (!accepted) {
69,047,940 ✔
367

368
    // Sample spatial distribution
369
    auto [r, r_wgt_temp] = space_->sample(seed);
35,150,112 ✔
370
    site.r = r;
35,150,112 ✔
371
    r_wgt = r_wgt_temp;
35,150,112 ✔
372

373
    // Check if sampled position satisfies spatial constraints
374
    accepted = satisfies_spatial_constraints(site.r);
35,150,112 ✔
375

376
    // Check for rejection
377
    if (!accepted) {
35,150,112 ✔
378
      ++n_reject;
1,252,284 ✔
379
      check_rejection_fraction(n_reject, n_accept);
1,252,284 ✔
380
    }
381
  }
382

383
  // Sample angle
384
  auto [u, u_wgt] = angle_->sample(seed);
33,897,828 ✔
385
  site.u = u;
33,897,828 ✔
386

387
  site.wgt = r_wgt * u_wgt;
33,897,828 ✔
388

389
  // Sample energy and time for neutron and photon sources
390
  if (settings::solver_type != SolverType::RANDOM_RAY) {
33,897,828 ✔
391
    // Check for monoenergetic source above maximum particle energy
392
    auto p = static_cast<int>(particle_);
31,997,408 ✔
393
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
31,997,408 !
394
    if (energy_ptr) {
31,997,408 ✔
395
      auto energies = xt::adapt(energy_ptr->x());
18,109,363 ✔
396
      if (xt::any(energies > data::energy_max[p])) {
18,109,363 !
397
        fatal_error("Source energy above range of energies of at least "
×
398
                    "one cross section table");
399
      }
400
    }
18,109,363 ✔
401

402
    while (true) {
403
      // Sample energy spectrum
404
      auto [E, E_wgt_temp] = energy_->sample(seed);
31,997,408 ✔
405
      site.E = E;
31,997,408 ✔
406
      E_wgt = E_wgt_temp;
31,997,408 ✔
407

408
      // Resample if energy falls above maximum particle energy
409
      if (site.E < data::energy_max[p] &&
63,994,816 !
410
          (satisfies_energy_constraints(site.E)))
31,997,408 !
411
        break;
31,997,408 ✔
412

413
      n_reject++;
×
414
      check_rejection_fraction(n_reject, n_accept);
×
UNCOV
415
    }
×
416

417
    // Sample particle creation time
418
    auto [time, time_wgt] = time_->sample(seed);
31,997,408 ✔
419
    site.time = time;
31,997,408 ✔
420

421
    site.wgt *= (E_wgt * time_wgt);
31,997,408 ✔
422
  }
423

424
  // Increment number of accepted samples
425
  ++n_accept;
33,897,828 ✔
426

427
  return site;
67,795,656 ✔
428
}
429

430
//==============================================================================
431
// FileSource implementation
432
//==============================================================================
433

434
FileSource::FileSource(pugi::xml_node node) : Source(node)
63 ✔
435
{
436
  auto path = get_node_value(node, "file", false, true);
63 ✔
437
  load_sites_from_file(path);
63 ✔
438
}
54 ✔
439

440
FileSource::FileSource(const std::string& path)
32 ✔
441
{
442
  load_sites_from_file(path);
32 ✔
443
}
32 ✔
444

445
void FileSource::load_sites_from_file(const std::string& path)
95 ✔
446
{
447
  // If MCPL file, use the dedicated file reader
448
  if (ends_with(path, ".mcpl") || ends_with(path, ".mcpl.gz")) {
95 !
449
    sites_ = mcpl_source_sites(path);
32 ✔
450
  } else {
451
    // Check if source file exists
452
    if (!file_exists(path)) {
63 !
453
      fatal_error(fmt::format("Source file '{}' does not exist.", path));
×
454
    }
455

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

458
    // Open the binary file
459
    hid_t file_id = file_open(path, 'r', true);
63 ✔
460

461
    // Check to make sure this is a source file
462
    std::string filetype;
63 ✔
463
    read_attribute(file_id, "filetype", filetype);
63 ✔
464
    if (filetype != "source" && filetype != "statepoint") {
63 !
465
      fatal_error("Specified starting source file not a source file type.");
×
466
    }
467

468
    // Read in the source particles
469
    read_source_bank(file_id, sites_, false);
63 ✔
470

471
    // Close file
472
    file_close(file_id);
54 ✔
473
  }
54 ✔
474
}
86 ✔
475

476
SourceSite FileSource::sample(uint64_t* seed) const
286,793 ✔
477
{
478
  // Sample a particle randomly from list
479
  size_t i_site = sites_.size() * prn(seed);
286,793 ✔
480
  return sites_[i_site];
286,793 ✔
481
}
482

483
//==============================================================================
484
// CompiledSourceWrapper implementation
485
//==============================================================================
486

487
CompiledSourceWrapper::CompiledSourceWrapper(pugi::xml_node node) : Source(node)
32 ✔
488
{
489
  // Get shared library path and parameters
490
  auto path = get_node_value(node, "library", false, true);
32 ✔
491
  std::string parameters;
32 ✔
492
  if (check_for_node(node, "parameters")) {
32 ✔
493
    parameters = get_node_value(node, "parameters", false, true);
16 ✔
494
  }
495
  setup(path, parameters);
32 ✔
496
}
32 ✔
497

498
void CompiledSourceWrapper::setup(
32 ✔
499
  const std::string& path, const std::string& parameters)
500
{
501
#ifdef HAS_DYNAMIC_LINKING
502
  // Open the library
503
  shared_library_ = dlopen(path.c_str(), RTLD_LAZY);
32 ✔
504
  if (!shared_library_) {
32 !
505
    fatal_error("Couldn't open source library " + path);
×
506
  }
507

508
  // reset errors
509
  dlerror();
32 ✔
510

511
  // get the function to create the custom source from the library
512
  auto create_compiled_source = reinterpret_cast<create_compiled_source_t*>(
513
    dlsym(shared_library_, "openmc_create_source"));
32 ✔
514

515
  // check for any dlsym errors
516
  auto dlsym_error = dlerror();
32 ✔
517
  if (dlsym_error) {
32 !
518
    std::string error_msg = fmt::format(
519
      "Couldn't open the openmc_create_source symbol: {}", dlsym_error);
×
520
    dlclose(shared_library_);
×
521
    fatal_error(error_msg);
×
522
  }
×
523

524
  // create a pointer to an instance of the custom source
525
  compiled_source_ = create_compiled_source(parameters);
32 ✔
526

527
#else
528
  fatal_error("Custom source libraries have not yet been implemented for "
529
              "non-POSIX systems");
530
#endif
531
}
32 ✔
532

533
CompiledSourceWrapper::~CompiledSourceWrapper()
64 ✔
534
{
535
  // Make sure custom source is cleared before closing shared library
536
  if (compiled_source_.get())
32 !
537
    compiled_source_.reset();
32 ✔
538

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

547
//==============================================================================
548
// MeshElementSpatial implementation
549
//==============================================================================
550

551
std::pair<Position, double> MeshElementSpatial::sample(uint64_t* seed) const
1,600,263 ✔
552
{
553
  return {model::meshes[mesh_index_]->sample_element(elem_index_, seed), 1.0};
1,600,263 ✔
554
}
555

556
//==============================================================================
557
// MeshSource implementation
558
//==============================================================================
559

560
MeshSource::MeshSource(pugi::xml_node node) : Source(node)
223 ✔
561
{
562
  int32_t mesh_id = stoi(get_node_value(node, "mesh"));
223 ✔
563
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
223 ✔
564
  const auto& mesh = model::meshes[mesh_idx];
223 ✔
565

566
  std::vector<double> strengths;
223 ✔
567
  // read all source distributions and populate strengths vector for MeshSpatial
568
  // object
569
  for (auto source_node : node.children("source")) {
37,697 ✔
570
    auto src = Source::create(source_node);
37,474 ✔
571
    if (auto ptr = dynamic_cast<IndependentSource*>(src.get())) {
37,474 !
572
      src.release();
37,474 ✔
573
      sources_.emplace_back(ptr);
37,474 ✔
574
    } else {
575
      fatal_error(
×
576
        "The source assigned to each element must be an IndependentSource.");
577
    }
578
    strengths.push_back(sources_.back()->strength());
37,474 ✔
579
  }
37,474 ✔
580

581
  // Set spatial distributions for each mesh element
582
  for (int elem_index = 0; elem_index < sources_.size(); ++elem_index) {
37,697 ✔
583
    sources_[elem_index]->set_space(
74,948 ✔
584
      std::make_unique<MeshElementSpatial>(mesh_idx, elem_index));
74,948 ✔
585
  }
586

587
  // the number of source distributions should either be one or equal to the
588
  // number of mesh elements
589
  if (sources_.size() > 1 && sources_.size() != mesh->n_bins()) {
223 !
590
    fatal_error(fmt::format("Incorrect number of source distributions ({}) for "
×
591
                            "mesh source with {} elements.",
592
      sources_.size(), mesh->n_bins()));
×
593
  }
594

595
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
223 ✔
596
}
223 ✔
597

598
SourceSite MeshSource::sample(uint64_t* seed) const
1,587,619 ✔
599
{
600
  // Sample a mesh element based on the relative strengths
601
  int32_t element = space_->sample_element_index(seed);
1,587,619 ✔
602

603
  // Sample the distribution for the specific mesh element; note that the
604
  // spatial distribution has been set for each element using MeshElementSpatial
605
  return source(element)->sample_with_constraints(seed);
1,587,619 ✔
606
}
607

608
//==============================================================================
609
// Non-member functions
610
//==============================================================================
611

612
void initialize_source()
3,932 ✔
613
{
614
  write_message("Initializing source particles...", 5);
3,932 ✔
615

616
// Generation source sites from specified distribution in user input
617
#pragma omp parallel for
618
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
1,198,513 ✔
619
    // initialize random number seed
620
    int64_t id = simulation::total_gen * settings::n_particles +
2,393,530 ✔
621
                 simulation::work_index[mpi::rank] + i + 1;
1,196,765 ✔
622
    uint64_t seed = init_seed(id, STREAM_SOURCE);
1,196,765 ✔
623

624
    // sample external source distribution
625
    simulation::source_bank[i] = sample_external_source(&seed);
1,196,765 ✔
626
  }
627

628
  // Write out initial source
629
  if (settings::write_initial_source) {
3,932 !
630
    write_message("Writing out initial source...", 5);
×
631
    std::string filename = settings::path_output + "initial_source.h5";
×
632
    hid_t file_id = file_open(filename, 'w', true);
×
633
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
×
634
    file_close(file_id);
×
635
  }
×
636
}
3,932 ✔
637

638
SourceSite sample_external_source(uint64_t* seed)
31,191,152 ✔
639
{
640
  // Sample from among multiple source distributions
641
  int i = 0;
31,191,152 ✔
642
  int n_sources = model::external_sources.size();
31,191,152 ✔
643
  if (n_sources > 1) {
31,191,152 ✔
644
    if (settings::uniform_source_sampling) {
2,018,300 ✔
645
      i = prn(seed) * n_sources;
2,200 ✔
646
    } else {
647
      i = model::external_sources_probability.sample(seed);
2,016,100 ✔
648
    }
649
  }
650

651
  // Sample source site from i-th source distribution
652
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
31,191,152 ✔
653

654
  // For uniform source sampling, multiply the weight by the ratio of the actual
655
  // probability of sampling source i to the biased probability of sampling
656
  // source i, which is (strength_i / total_strength) / (1 / n)
657
  if (n_sources > 1 && settings::uniform_source_sampling) {
31,191,149 ✔
658
    double total_strength = model::external_sources_probability.integral();
2,200 ✔
659
    site.wgt *=
2,200 ✔
660
      model::external_sources[i]->strength() * n_sources / total_strength;
2,200 ✔
661
  }
662

663
  // If running in MG, convert site.E to group
664
  if (!settings::run_CE) {
31,191,149 ✔
665
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
1,742,400 ✔
666
      data::mg.rev_energy_bins_.end(), site.E);
667
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
1,742,400 ✔
668
  }
669

670
  return site;
31,191,149 ✔
671
}
672

673
void free_memory_source()
8,018 ✔
674
{
675
  model::external_sources.clear();
8,018 ✔
676
}
8,018 ✔
677

678
//==============================================================================
679
// C API
680
//==============================================================================
681

682
extern "C" int openmc_sample_external_source(
955 ✔
683
  size_t n, uint64_t* seed, void* sites)
684
{
685
  if (!sites || !seed) {
955 !
686
    set_errmsg("Received null pointer.");
×
687
    return OPENMC_E_INVALID_ARGUMENT;
×
688
  }
689

690
  if (model::external_sources.empty()) {
955 !
691
    set_errmsg("No external sources have been defined.");
×
692
    return OPENMC_E_OUT_OF_BOUNDS;
×
693
  }
694

695
  auto sites_array = static_cast<SourceSite*>(sites);
955 ✔
696
  for (size_t i = 0; i < n; ++i) {
2,957,779 ✔
697
    sites_array[i] = sample_external_source(seed);
2,956,824 ✔
698
  }
699
  return 0;
955 ✔
700
}
701

702
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc