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

openmc-dev / openmc / 18299973882

07 Oct 2025 02:14AM UTC coverage: 81.92% (-3.3%) from 85.194%
18299973882

push

github

web-flow
Switch to using coveralls github action for reporting (#3594)

16586 of 23090 branches covered (71.83%)

Branch coverage included in aggregate %.

53703 of 62712 relevant lines covered (85.63%)

43428488.21 hits per line

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

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

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

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

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

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

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

142
  if (check_for_node(node, "fissionable")) {
45,013✔
143
    only_fissionable_ = get_node_value_bool(node, "fissionable");
1,224✔
144
  }
145

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

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

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

184
  while (!accepted) {
64,995,199✔
185
    // Sample a source site without considering constraints yet
186
    site = this->sample(seed);
33,287,309✔
187

188
    if (constraints_applied()) {
33,287,306✔
189
      accepted = true;
31,030,530✔
190
    } else {
191
      // Check whether sampled site satisfies constraints
192
      accepted = satisfies_spatial_constraints(site.r) &&
2,256,776✔
193
                 satisfies_energy_constraints(site.E) &&
2,947,182✔
194
                 satisfies_time_constraints(site.time);
690,406✔
195
      if (!accepted) {
2,256,776✔
196
        // Increment number of rejections and check against minimum fraction
197
        ++n_reject;
1,579,416✔
198
        check_rejection_fraction(n_reject, n_accept);
1,579,416✔
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,579,416!
203
          accepted = true;
×
204
          site.wgt = 0.0;
×
205
        }
206
      }
207
    }
208
  }
209

210
  // Increment number of accepted samples
211
  ++n_accept;
31,707,890✔
212

213
  return site;
31,707,890✔
214
}
215

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

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

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

232
  // Reject particle if it's not in the geometry at all
233
  bool found = exhaustive_find_cell(geom_state);
36,320,842✔
234
  if (!found)
36,320,842✔
235
    return false;
385,813✔
236

237
  // Check the geometry state against specified domains
238
  bool accepted = true;
35,935,029✔
239
  if (!domain_ids_.empty()) {
35,935,029✔
240
    if (domain_type_ == DomainType::MATERIAL) {
2,056,836!
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++) {
4,068,252✔
249
        auto id =
250
          (domain_type_ == DomainType::CELL)
2,056,836✔
251
            ? model::cells[geom_state.coord(i).cell()].get()->id_
2,056,836!
252
            : model::universes[geom_state.coord(i).universe()].get()->id_;
×
253
        if ((accepted = contains(domain_ids_, id)))
2,056,836✔
254
          break;
45,420✔
255
      }
256
    }
257
  }
258

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

270
  return accepted;
35,935,029✔
271
}
36,320,842✔
272

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

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

283
IndependentSource::IndependentSource(pugi::xml_node node) : Source(node)
44,711✔
284
{
285
  // Check for particle type
286
  if (check_for_node(node, "particle")) {
44,711✔
287
    auto temp_str = get_node_value(node, "particle", true, true);
43,812✔
288
    if (temp_str == "neutron") {
43,812✔
289
      particle_ = ParticleType::neutron;
43,687✔
290
    } else if (temp_str == "photon") {
125!
291
      particle_ = ParticleType::photon;
125✔
292
      settings::photon_transport = true;
125✔
293
    } else {
294
      fatal_error(std::string("Unknown source particle type: ") + temp_str);
×
295
    }
296
  }
43,812✔
297

298
  // Check for external source file
299
  if (check_for_node(node, "file")) {
44,711!
300

301
  } else {
302

303
    // Spatial distribution for external source
304
    if (check_for_node(node, "space")) {
44,711✔
305
      space_ = SpatialDistribution::create(node.child("space"));
6,663✔
306
    } else {
307
      // If no spatial distribution specified, make it a point source
308
      space_ = UPtrSpace {new SpatialPoint()};
38,048✔
309
    }
310

311
    // For backwards compatibility, check for only fissionable setting on box
312
    // source
313
    auto space_box = dynamic_cast<SpatialBox*>(space_.get());
44,710!
314
    if (space_box) {
44,710✔
315
      if (!only_fissionable_) {
3,689✔
316
        only_fissionable_ = space_box->only_fissionable();
2,465✔
317
      }
318
    }
319

320
    // Determine external source angular distribution
321
    if (check_for_node(node, "angle")) {
44,710✔
322
      angle_ = UnitSphereDistribution::create(node.child("angle"));
3,171✔
323
    } else {
324
      angle_ = UPtrAngle {new Isotropic()};
41,539✔
325
    }
326

327
    // Determine external source energy distribution
328
    if (check_for_node(node, "energy")) {
44,710✔
329
      pugi::xml_node node_dist = node.child("energy");
4,394✔
330
      energy_ = distribution_from_xml(node_dist);
4,394✔
331
    } else {
332
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
333
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
40,316✔
334
    }
335

336
    // Determine external source time distribution
337
    if (check_for_node(node, "time")) {
44,710✔
338
      pugi::xml_node node_dist = node.child("time");
43✔
339
      time_ = distribution_from_xml(node_dist);
43✔
340
    } else {
341
      // Default to a Constant time T=0
342
      double T[] {0.0};
44,667✔
343
      double p[] {1.0};
44,667✔
344
      time_ = UPtrDist {new Discrete {T, p, 1}};
44,667✔
345
    }
346
  }
347
}
44,710✔
348

349
SourceSite IndependentSource::sample(uint64_t* seed) const
32,886,953✔
350
{
351
  SourceSite site;
32,886,953✔
352
  site.particle = particle_;
32,886,953✔
353

354
  // Repeat sampling source location until a good site has been accepted
355
  bool accepted = false;
32,886,953✔
356
  static int64_t n_reject = 0;
357
  static int64_t n_accept = 0;
358

359
  while (!accepted) {
66,951,016✔
360

361
    // Sample spatial distribution
362
    site.r = space_->sample(seed);
34,064,066✔
363

364
    // Check if sampled position satisfies spatial constraints
365
    accepted = satisfies_spatial_constraints(site.r);
34,064,066✔
366

367
    // Check for rejection
368
    if (!accepted) {
34,064,066✔
369
      ++n_reject;
1,177,116✔
370
      check_rejection_fraction(n_reject, n_accept);
1,177,116✔
371
    }
372
  }
373

374
  // Sample angle
375
  site.u = angle_->sample(seed);
32,886,950✔
376

377
  // Sample energy and time for neutron and photon sources
378
  if (settings::solver_type != SolverType::RANDOM_RAY) {
32,886,950✔
379
    // Check for monoenergetic source above maximum particle energy
380
    auto p = static_cast<int>(particle_);
31,030,530✔
381
    auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
31,030,530!
382
    if (energy_ptr) {
31,030,530✔
383
      auto energies = xt::adapt(energy_ptr->x());
19,615,687✔
384
      if (xt::any(energies > data::energy_max[p])) {
19,615,687!
385
        fatal_error("Source energy above range of energies of at least "
×
386
                    "one cross section table");
387
      }
388
    }
19,615,687✔
389

390
    while (true) {
391
      // Sample energy spectrum
392
      site.E = energy_->sample(seed);
31,030,530✔
393

394
      // Resample if energy falls above maximum particle energy
395
      if (site.E < data::energy_max[p] &&
62,061,060!
396
          (satisfies_energy_constraints(site.E)))
31,030,530!
397
        break;
31,030,530✔
398

399
      n_reject++;
×
400
      check_rejection_fraction(n_reject, n_accept);
×
401
    }
402

403
    // Sample particle creation time
404
    site.time = time_->sample(seed);
31,030,530✔
405
  }
406

407
  // Increment number of accepted samples
408
  ++n_accept;
32,886,950✔
409

410
  return site;
32,886,950✔
411
}
412

413
//==============================================================================
414
// FileSource implementation
415
//==============================================================================
416

417
FileSource::FileSource(pugi::xml_node node) : Source(node)
65✔
418
{
419
  auto path = get_node_value(node, "file", false, true);
65✔
420
  load_sites_from_file(path);
65✔
421
}
56✔
422

423
FileSource::FileSource(const std::string& path)
32✔
424
{
425
  load_sites_from_file(path);
32✔
426
}
32✔
427

428
void FileSource::load_sites_from_file(const std::string& path)
97✔
429
{
430
  // If MCPL file, use the dedicated file reader
431
  if (ends_with(path, ".mcpl") || ends_with(path, ".mcpl.gz")) {
97!
432
    sites_ = mcpl_source_sites(path);
32✔
433
  } else {
434
    // Check if source file exists
435
    if (!file_exists(path)) {
65!
436
      fatal_error(fmt::format("Source file '{}' does not exist.", path));
×
437
    }
438

439
    write_message(6, "Reading source file from {}...", path);
65✔
440

441
    // Open the binary file
442
    hid_t file_id = file_open(path, 'r', true);
65✔
443

444
    // Check to make sure this is a source file
445
    std::string filetype;
65✔
446
    read_attribute(file_id, "filetype", filetype);
65✔
447
    if (filetype != "source" && filetype != "statepoint") {
65!
448
      fatal_error("Specified starting source file not a source file type.");
×
449
    }
450

451
    // Read in the source particles
452
    read_source_bank(file_id, sites_, false);
65✔
453

454
    // Close file
455
    file_close(file_id);
56✔
456
  }
56✔
457
}
88✔
458

459
SourceSite FileSource::sample(uint64_t* seed) const
294,167✔
460
{
461
  // Sample a particle randomly from list
462
  size_t i_site = sites_.size() * prn(seed);
294,167✔
463
  return sites_[i_site];
294,167✔
464
}
465

466
//==============================================================================
467
// CompiledSourceWrapper implementation
468
//==============================================================================
469

470
CompiledSourceWrapper::CompiledSourceWrapper(pugi::xml_node node) : Source(node)
32✔
471
{
472
  // Get shared library path and parameters
473
  auto path = get_node_value(node, "library", false, true);
32✔
474
  std::string parameters;
32✔
475
  if (check_for_node(node, "parameters")) {
32✔
476
    parameters = get_node_value(node, "parameters", false, true);
16✔
477
  }
478
  setup(path, parameters);
32✔
479
}
32✔
480

481
void CompiledSourceWrapper::setup(
32✔
482
  const std::string& path, const std::string& parameters)
483
{
484
#ifdef HAS_DYNAMIC_LINKING
485
  // Open the library
486
  shared_library_ = dlopen(path.c_str(), RTLD_LAZY);
32✔
487
  if (!shared_library_) {
32!
488
    fatal_error("Couldn't open source library " + path);
×
489
  }
490

491
  // reset errors
492
  dlerror();
32✔
493

494
  // get the function to create the custom source from the library
495
  auto create_compiled_source = reinterpret_cast<create_compiled_source_t*>(
496
    dlsym(shared_library_, "openmc_create_source"));
32✔
497

498
  // check for any dlsym errors
499
  auto dlsym_error = dlerror();
32✔
500
  if (dlsym_error) {
32!
501
    std::string error_msg = fmt::format(
502
      "Couldn't open the openmc_create_source symbol: {}", dlsym_error);
×
503
    dlclose(shared_library_);
×
504
    fatal_error(error_msg);
×
505
  }
×
506

507
  // create a pointer to an instance of the custom source
508
  compiled_source_ = create_compiled_source(parameters);
32✔
509

510
#else
511
  fatal_error("Custom source libraries have not yet been implemented for "
512
              "non-POSIX systems");
513
#endif
514
}
32✔
515

516
CompiledSourceWrapper::~CompiledSourceWrapper()
64✔
517
{
518
  // Make sure custom source is cleared before closing shared library
519
  if (compiled_source_.get())
32!
520
    compiled_source_.reset();
32✔
521

522
#ifdef HAS_DYNAMIC_LINKING
523
  dlclose(shared_library_);
32✔
524
#else
525
  fatal_error("Custom source libraries have not yet been implemented for "
526
              "non-POSIX systems");
527
#endif
528
}
64✔
529

530
//==============================================================================
531
// MeshElementSpatial implementation
532
//==============================================================================
533

534
Position MeshElementSpatial::sample(uint64_t* seed) const
1,756,544✔
535
{
536
  return model::meshes[mesh_index_]->sample_element(elem_index_, seed);
1,756,544✔
537
}
538

539
//==============================================================================
540
// MeshSource implementation
541
//==============================================================================
542

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

549
  std::vector<double> strengths;
205✔
550
  // read all source distributions and populate strengths vector for MeshSpatial
551
  // object
552
  for (auto source_node : node.children("source")) {
37,665✔
553
    auto src = Source::create(source_node);
37,460✔
554
    if (auto ptr = dynamic_cast<IndependentSource*>(src.get())) {
37,460!
555
      src.release();
37,460✔
556
      sources_.emplace_back(ptr);
37,460✔
557
    } else {
558
      fatal_error(
×
559
        "The source assigned to each element must be an IndependentSource.");
560
    }
561
    strengths.push_back(sources_.back()->strength());
37,460✔
562
  }
37,460✔
563

564
  // Set spatial distributions for each mesh element
565
  for (int elem_index = 0; elem_index < sources_.size(); ++elem_index) {
37,665✔
566
    sources_[elem_index]->set_space(
74,920✔
567
      std::make_unique<MeshElementSpatial>(mesh_idx, elem_index));
74,920✔
568
  }
569

570
  // the number of source distributions should either be one or equal to the
571
  // number of mesh elements
572
  if (sources_.size() > 1 && sources_.size() != mesh->n_bins()) {
205!
573
    fatal_error(fmt::format("Incorrect number of source distributions ({}) for "
×
574
                            "mesh source with {} elements.",
575
      sources_.size(), mesh->n_bins()));
×
576
  }
577

578
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
205✔
579
}
205✔
580

581
SourceSite MeshSource::sample(uint64_t* seed) const
1,742,609✔
582
{
583
  // Sample a mesh element based on the relative strengths
584
  int32_t element = space_->sample_element_index(seed);
1,742,609✔
585

586
  // Sample the distribution for the specific mesh element; note that the
587
  // spatial distribution has been set for each element using MeshElementSpatial
588
  return source(element)->sample_with_constraints(seed);
1,742,609✔
589
}
590

591
//==============================================================================
592
// Non-member functions
593
//==============================================================================
594

595
void initialize_source()
3,679✔
596
{
597
  write_message("Initializing source particles...", 5);
3,679✔
598

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

607
    // sample external source distribution
608
    simulation::source_bank[i] = sample_external_source(&seed);
1,122,050✔
609
  }
610

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

621
SourceSite sample_external_source(uint64_t* seed)
29,965,284✔
622
{
623
  // Sample from among multiple source distributions
624
  int i = 0;
29,965,284✔
625
  int n_sources = model::external_sources.size();
29,965,284✔
626
  if (n_sources > 1) {
29,965,284✔
627
    if (settings::uniform_source_sampling) {
146,500✔
628
      i = prn(seed) * n_sources;
2,400✔
629
    } else {
630
      i = model::external_sources_probability.sample(seed);
144,100✔
631
    }
632
  }
633

634
  // Sample source site from i-th source distribution
635
  SourceSite site {model::external_sources[i]->sample_with_constraints(seed)};
29,965,284✔
636

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

646
  // If running in MG, convert site.E to group
647
  if (!settings::run_CE) {
29,965,281✔
648
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
1,742,400✔
649
      data::mg.rev_energy_bins_.end(), site.E);
650
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
1,742,400✔
651
  }
652

653
  return site;
29,965,281✔
654
}
655

656
void free_memory_source()
8,084✔
657
{
658
  model::external_sources.clear();
8,084✔
659
}
8,084✔
660

661
//==============================================================================
662
// C API
663
//==============================================================================
664

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

673
  if (model::external_sources.empty()) {
817!
674
    set_errmsg("No external sources have been defined.");
×
675
    return OPENMC_E_OUT_OF_BOUNDS;
×
676
  }
677

678
  auto sites_array = static_cast<SourceSite*>(sites);
817✔
679
  for (size_t i = 0; i < n; ++i) {
1,306,389✔
680
    sites_array[i] = sample_external_source(seed);
1,305,572✔
681
  }
682
  return 0;
817✔
683
}
684

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