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

openmc-dev / openmc / 7071649772

02 Dec 2023 05:35PM UTC coverage: 84.541% (+0.02%) from 84.524%
7071649772

push

github

web-flow
Mesh Source Class (#2759)

Co-authored-by: Paul Romano <paul.k.romano@gmail.com>
Co-authored-by: Jonathan Shimwell <drshimwell@gmail.com>

220 of 231 new or added lines in 12 files covered. (95.24%)

53 existing lines in 2 files now uncovered.

47205 of 55837 relevant lines covered (84.54%)

34203579.09 hits per line

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

85.0
/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 <algorithm> // 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

49
//==============================================================================
50
// Source create implementation
51
//==============================================================================
52

53
unique_ptr<Source> Source::create(pugi::xml_node node)
8,169✔
54
{
55
  // if the source type is present, use it to determine the type
56
  // of object to create
57
  if (check_for_node(node, "type")) {
8,169✔
58
    std::string source_type = get_node_value(node, "type");
6,886✔
59
    if (source_type == "independent") {
6,886✔
60
      return make_unique<IndependentSource>(node);
6,570✔
61
    } else if (source_type == "file") {
316✔
62
      return make_unique<FileSource>(node);
40✔
63
    } else if (source_type == "compiled") {
276✔
64
      return make_unique<CompiledSourceWrapper>(node);
38✔
65
    } else if (source_type == "mesh") {
238✔
66
      return make_unique<MeshSource>(node);
238✔
67
    } else {
NEW
68
      fatal_error(fmt::format("Invalid source type '{}' found.", source_type));
×
69
    }
70
  } else {
6,873✔
71
    // support legacy source format
72
    if (check_for_node(node, "file")) {
1,283✔
73
      return make_unique<FileSource>(node);
38✔
74
    } else if (check_for_node(node, "library")) {
1,245✔
NEW
75
      return make_unique<CompiledSourceWrapper>(node);
×
76
    } else {
77
      return make_unique<IndependentSource>(node);
1,245✔
78
    }
79
  }
80
}
81

82
//==============================================================================
83
// IndependentSource implementation
84
//==============================================================================
85

86
IndependentSource::IndependentSource(
1,661✔
87
  UPtrSpace space, UPtrAngle angle, UPtrDist energy, UPtrDist time)
1,661✔
88
  : space_ {std::move(space)}, angle_ {std::move(angle)},
1,661✔
89
    energy_ {std::move(energy)}, time_ {std::move(time)}
3,322✔
90
{}
1,661✔
91

92
IndependentSource::IndependentSource(pugi::xml_node node)
7,815✔
93
{
94
  // Check for particle type
95
  if (check_for_node(node, "particle")) {
7,815✔
96
    auto temp_str = get_node_value(node, "particle", true, true);
6,570✔
97
    if (temp_str == "neutron") {
6,570✔
98
      particle_ = ParticleType::neutron;
6,457✔
99
    } else if (temp_str == "photon") {
113✔
100
      particle_ = ParticleType::photon;
113✔
101
      settings::photon_transport = true;
113✔
102
    } else {
103
      fatal_error(std::string("Unknown source particle type: ") + temp_str);
×
104
    }
105
  }
6,570✔
106

107
  // Check for source strength
108
  if (check_for_node(node, "strength")) {
7,815✔
109
    strength_ = std::stod(get_node_value(node, "strength"));
7,017✔
110
  }
111

112
  // Check for external source file
113
  if (check_for_node(node, "file")) {
7,815✔
114

115
  } else {
116

117
    // Spatial distribution for external source
118
    if (check_for_node(node, "space")) {
7,815✔
119
      space_ = SpatialDistribution::create(node.child("space"));
5,929✔
120
    } else {
121
      // If no spatial distribution specified, make it a point source
122
      space_ = UPtrSpace {new SpatialPoint()};
1,886✔
123
    }
124

125
    // Determine external source angular distribution
126
    if (check_for_node(node, "angle")) {
7,814✔
127
      angle_ = UnitSphereDistribution::create(node.child("angle"));
3,949✔
128
    } else {
129
      angle_ = UPtrAngle {new Isotropic()};
3,865✔
130
    }
131

132
    // Determine external source energy distribution
133
    if (check_for_node(node, "energy")) {
7,814✔
134
      pugi::xml_node node_dist = node.child("energy");
4,473✔
135
      energy_ = distribution_from_xml(node_dist);
4,473✔
136
    } else {
137
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
138
      energy_ = UPtrDist {new Watt(0.988e6, 2.249e-6)};
3,341✔
139
    }
140

141
    // Determine external source time distribution
142
    if (check_for_node(node, "time")) {
7,814✔
143
      pugi::xml_node node_dist = node.child("time");
52✔
144
      time_ = distribution_from_xml(node_dist);
52✔
145
    } else {
146
      // Default to a Constant time T=0
147
      double T[] {0.0};
7,762✔
148
      double p[] {1.0};
7,762✔
149
      time_ = UPtrDist {new Discrete {T, p, 1}};
7,762✔
150
    }
151

152
    // Check for domains to reject from
153
    if (check_for_node(node, "domain_type")) {
7,814✔
154
      std::string domain_type = get_node_value(node, "domain_type");
14✔
155
      if (domain_type == "cell") {
14✔
156
        domain_type_ = DomainType::CELL;
14✔
157
      } else if (domain_type == "material") {
×
158
        domain_type_ = DomainType::MATERIAL;
×
159
      } else if (domain_type == "universe") {
×
160
        domain_type_ = DomainType::UNIVERSE;
×
161
      } else {
162
        fatal_error(std::string(
×
163
          "Unrecognized domain type for source rejection: " + domain_type));
164
      }
165

166
      auto ids = get_node_array<int>(node, "domain_ids");
14✔
167
      domain_ids_.insert(ids.begin(), ids.end());
14✔
168
    }
14✔
169
  }
170
}
7,814✔
171

172
SourceSite IndependentSource::sample(uint64_t* seed) const
16,912,345✔
173
{
174
  SourceSite site;
16,912,345✔
175
  site.particle = particle_;
16,912,345✔
176

177
  // Repeat sampling source location until a good site has been found
178
  bool found = false;
16,912,345✔
179
  int n_reject = 0;
16,912,345✔
180
  static int n_accept = 0;
181

182
  while (!found) {
35,893,210✔
183
    // Set particle type
184
    Particle p;
18,980,865✔
185
    p.type() = particle_;
18,980,865✔
186
    p.u() = {0.0, 0.0, 1.0};
18,980,865✔
187

188
    // Sample spatial distribution
189
    p.r() = space_->sample(seed);
18,980,865✔
190

191
    // Now search to see if location exists in geometry
192
    found = exhaustive_find_cell(p);
18,980,865✔
193

194
    // Check if spatial site is in fissionable material
195
    if (found) {
18,980,865✔
196
      auto space_box = dynamic_cast<SpatialBox*>(space_.get());
18,937,157✔
197
      if (space_box) {
18,937,157✔
198
        if (space_box->only_fissionable()) {
4,358,006✔
199
          // Determine material
200
          auto mat_index = p.material();
1,188,094✔
201
          if (mat_index == MATERIAL_VOID) {
1,188,094✔
202
            found = false;
×
203
          } else {
204
            found = model::materials[mat_index]->fissionable_;
1,188,094✔
205
          }
206
        }
207
      }
208

209
      // Rejection based on cells/materials/universes
210
      if (!domain_ids_.empty()) {
18,937,157✔
211
        found = false;
1,715,518✔
212
        if (domain_type_ == DomainType::MATERIAL) {
1,715,518✔
213
          auto mat_index = p.material();
×
214
          if (mat_index != MATERIAL_VOID) {
×
215
            found = contains(domain_ids_, model::materials[mat_index]->id());
×
216
          }
217
        } else {
218
          for (int i = 0; i < p.n_coord(); i++) {
3,417,036✔
219
            auto id = (domain_type_ == DomainType::CELL)
1,715,518✔
220
                        ? model::cells[p.coord(i).cell]->id_
1,715,518✔
221
                        : model::universes[p.coord(i).universe]->id_;
×
222
            if ((found = contains(domain_ids_, id)))
1,715,518✔
223
              break;
14,000✔
224
          }
225
        }
226
      }
227
    }
228

229
    // Check for rejection
230
    if (!found) {
18,980,865✔
231
      ++n_reject;
2,068,520✔
232
      if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
2,068,520✔
233
          static_cast<double>(n_accept) / n_reject <= EXTSRC_REJECT_FRACTION) {
234
        fatal_error("More than 95% of external source sites sampled were "
×
235
                    "rejected. Please check your external source's spatial "
236
                    "definition.");
237
      }
238
    }
239

240
    site.r = p.r();
18,980,865✔
241
  }
18,980,865✔
242

243
  // Sample angle
244
  site.u = angle_->sample(seed);
16,912,345✔
245

246
  // Check for monoenergetic source above maximum particle energy
247
  auto p = static_cast<int>(particle_);
16,912,345✔
248
  auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
16,912,345✔
249
  if (energy_ptr) {
16,912,345✔
250
    auto energies = xt::adapt(energy_ptr->x());
6,378,180✔
251
    if (xt::any(energies > data::energy_max[p])) {
6,378,180✔
252
      fatal_error("Source energy above range of energies of at least "
×
253
                  "one cross section table");
254
    }
255
  }
6,378,180✔
256

257
  while (true) {
258
    // Sample energy spectrum
259
    site.E = energy_->sample(seed);
16,912,345✔
260

261
    // Resample if energy falls above maximum particle energy
262
    if (site.E < data::energy_max[p])
16,912,345✔
263
      break;
16,912,345✔
264

265
    n_reject++;
×
266
    if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
×
267
        static_cast<double>(n_accept) / n_reject <= EXTSRC_REJECT_FRACTION) {
268
      fatal_error("More than 95% of external source sites sampled were "
×
269
                  "rejected. Please check your external source energy spectrum "
270
                  "definition.");
271
    }
272
  }
273

274
  // Sample particle creation time
275
  site.time = time_->sample(seed);
16,912,345✔
276

277
  // Increment number of accepted samples
278
  ++n_accept;
16,912,345✔
279

280
  return site;
16,912,345✔
281
}
282

283
//==============================================================================
284
// FileSource implementation
285
//==============================================================================
286
FileSource::FileSource(pugi::xml_node node)
78✔
287
{
288
  auto path = get_node_value(node, "file", false, true);
78✔
289
  if (ends_with(path, ".mcpl") || ends_with(path, ".mcpl.gz")) {
78✔
290
    sites_ = mcpl_source_sites(path);
19✔
291
  } else {
292
    this->load_sites_from_file(path);
59✔
293
  }
294
}
66✔
295

296
FileSource::FileSource(const std::string& path)
19✔
297
{
298
  load_sites_from_file(path);
19✔
299
}
19✔
300

301
void FileSource::load_sites_from_file(const std::string& path)
78✔
302
{
303
  // Check if source file exists
304
  if (!file_exists(path)) {
78✔
305
    fatal_error(fmt::format("Source file '{}' does not exist.", path));
×
306
  }
307

308
  // Read the source from a binary file instead of sampling from some
309
  // assumed source distribution
310
  write_message(6, "Reading source file from {}...", path);
78✔
311

312
  // Open the binary file
313
  hid_t file_id = file_open(path, 'r', true);
78✔
314

315
  // Check to make sure this is a source file
316
  std::string filetype;
78✔
317
  read_attribute(file_id, "filetype", filetype);
78✔
318
  if (filetype != "source" && filetype != "statepoint") {
78✔
319
    fatal_error("Specified starting source file not a source file type.");
×
320
  }
321

322
  // Read in the source particles
323
  read_source_bank(file_id, sites_, false);
78✔
324

325
  // Close file
326
  file_close(file_id);
66✔
327
}
66✔
328

329
SourceSite FileSource::sample(uint64_t* seed) const
168,560✔
330
{
331
  size_t i_site = sites_.size() * prn(seed);
168,560✔
332
  return sites_[i_site];
168,560✔
333
}
334

335
//==============================================================================
336
// CompiledSourceWrapper implementation
337
//==============================================================================
338
CompiledSourceWrapper::CompiledSourceWrapper(pugi::xml_node node)
38✔
339
{
340
  // Get shared library path and parameters
341
  auto path = get_node_value(node, "library", false, true);
38✔
342
  std::string parameters;
38✔
343
  if (check_for_node(node, "parameters")) {
38✔
344
    parameters = get_node_value(node, "parameters", false, true);
19✔
345
  }
346
  setup(path, parameters);
38✔
347
}
38✔
348

349
void CompiledSourceWrapper::setup(
38✔
350
  const std::string& path, const std::string& parameters)
351
{
352
#ifdef HAS_DYNAMIC_LINKING
353
  // Open the library
354
  shared_library_ = dlopen(path.c_str(), RTLD_LAZY);
38✔
355
  if (!shared_library_) {
38✔
356
    fatal_error("Couldn't open source library " + path);
×
357
  }
358

359
  // reset errors
360
  dlerror();
38✔
361

362
  // get the function to create the custom source from the library
363
  auto create_compiled_source = reinterpret_cast<create_compiled_source_t*>(
364
    dlsym(shared_library_, "openmc_create_source"));
38✔
365

366
  // check for any dlsym errors
367
  auto dlsym_error = dlerror();
38✔
368
  if (dlsym_error) {
38✔
369
    std::string error_msg = fmt::format(
370
      "Couldn't open the openmc_create_source symbol: {}", dlsym_error);
×
371
    dlclose(shared_library_);
×
372
    fatal_error(error_msg);
×
373
  }
×
374

375
  // create a pointer to an instance of the custom source
376
  compiled_source_ = create_compiled_source(parameters);
38✔
377

378
#else
379
  fatal_error("Custom source libraries have not yet been implemented for "
380
              "non-POSIX systems");
381
#endif
382
}
38✔
383

384
CompiledSourceWrapper::~CompiledSourceWrapper()
76✔
385
{
386
  // Make sure custom source is cleared before closing shared library
387
  if (compiled_source_.get())
38✔
388
    compiled_source_.reset();
38✔
389

390
#ifdef HAS_DYNAMIC_LINKING
391
  dlclose(shared_library_);
38✔
392
#else
393
  fatal_error("Custom source libraries have not yet been implemented for "
394
              "non-POSIX systems");
395
#endif
396
}
76✔
397

38✔
398
//==============================================================================
399
// MeshSource implementation
400
//==============================================================================
401

402
MeshSource::MeshSource(pugi::xml_node node)
403
{
404
  int32_t mesh_id = stoi(get_node_value(node, "mesh"));
405
  int32_t mesh_idx = model::mesh_map.at(mesh_id);
406
  const auto& mesh = model::meshes[mesh_idx];
407

408
  std::vector<double> strengths;
409
  // read all source distributions and populate strengths vector for MeshSpatial
38✔
410
  // object
38✔
411
  for (auto source_node : node.children("source")) {
412
    sources_.emplace_back(Source::create(source_node));
413
    strengths.push_back(sources_.back()->strength());
38✔
414
  }
38✔
415

416
  // the number of source distributions should either be one or equal to the
417
  // number of mesh elements
38✔
418
  if (sources_.size() > 1 && sources_.size() != mesh->n_bins()) {
419
    fatal_error(fmt::format("Incorrect number of source distributions ({}) for "
420
                            "mesh source with {} elements.",
421
      sources_.size(), mesh->n_bins()));
422
  }
38✔
423

424
  space_ = std::make_unique<MeshSpatial>(mesh_idx, strengths);
425
}
426

427
SourceSite MeshSource::sample(uint64_t* seed) const
428
{
238✔
429
  // sample location and element from mesh
430
  auto mesh_location = space_->sample_mesh(seed);
238✔
431

238✔
432
  // Sample source for the chosen element
238✔
433
  int32_t element = mesh_location.first;
434
  SourceSite site = source(element)->sample(seed);
238✔
435

436
  // Replace spatial position with the one already sampled
437
  site.r = mesh_location.second;
2,044✔
438

1,806✔
439
  return site;
1,806✔
440
}
441

442
//==============================================================================
443
// Non-member functions
444
//==============================================================================
238✔
UNCOV
445

×
446
void initialize_source()
UNCOV
447
{
×
448
  write_message("Initializing source particles...", 5);
449

450
// Generation source sites from specified distribution in user input
238✔
451
#pragma omp parallel for
238✔
452
  for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
453
    // initialize random number seed
224,140✔
454
    int64_t id = simulation::total_gen * settings::n_particles +
455
                 simulation::work_index[mpi::rank] + i + 1;
456
    uint64_t seed = init_seed(id, STREAM_SOURCE);
224,140✔
457

458
    // sample external source distribution
459
    simulation::source_bank[i] = sample_external_source(&seed);
224,140✔
460
  }
224,140✔
461

462
  // Write out initial source
463
  if (settings::write_initial_source) {
224,140✔
464
    write_message("Writing out initial source...", 5);
465
    std::string filename = settings::path_output + "initial_source.h5";
448,280✔
466
    hid_t file_id = file_open(filename, 'w', true);
467
    write_source_bank(file_id, simulation::source_bank, simulation::work_index);
468
    file_close(file_id);
469
  }
470
}
471

472
SourceSite sample_external_source(uint64_t* seed)
3,864✔
473
{
474
  // Determine total source strength
3,864✔
475
  double total_strength = 0.0;
476
  for (auto& s : model::external_sources)
477
    total_strength += s->strength();
478

1,687,969✔
479
  // Sample from among multiple source distributions
480
  int i = 0;
3,371,800✔
481
  if (model::external_sources.size() > 1) {
1,685,900✔
482
    double xi = prn(seed) * total_strength;
1,685,900✔
483
    double c = 0.0;
484
    for (; i < model::external_sources.size(); ++i) {
485
      c += model::external_sources[i]->strength();
1,685,900✔
486
      if (xi < c)
487
        break;
488
    }
489
  }
3,864✔
490

×
491
  // Sample source site from i-th source distribution
×
492
  SourceSite site {model::external_sources[i]->sample(seed)};
×
493

×
494
  // If running in MG, convert site.E to group
×
495
  if (!settings::run_CE) {
496
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
3,864✔
497
      data::mg.rev_energy_bins_.end(), site.E);
498
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
17,360,905✔
499
  }
500

501
  return site;
17,360,905✔
502
}
40,251,810✔
503

22,890,905✔
504
void free_memory_source()
505
{
506
  model::external_sources.clear();
17,360,905✔
507
}
17,360,905✔
508

182,000✔
509
//==============================================================================
182,000✔
510
// C API
2,922,528✔
511
//==============================================================================
2,922,528✔
512

2,922,528✔
513
extern "C" int openmc_sample_external_source(
182,000✔
514
  size_t n, uint64_t* seed, void* sites)
515
{
516
  if (!sites || !seed) {
517
    set_errmsg("Received null pointer.");
518
    return OPENMC_E_INVALID_ARGUMENT;
17,360,905✔
519
  }
520

521
  if (model::external_sources.empty()) {
17,360,905✔
522
    set_errmsg("No external sources have been defined.");
817,600✔
523
    return OPENMC_E_OUT_OF_BOUNDS;
524
  }
817,600✔
525

526
  auto sites_array = static_cast<SourceSite*>(sites);
527
  for (size_t i = 0; i < n; ++i) {
17,360,905✔
528
    sites_array[i] = sample_external_source(seed);
529
  }
530
  return 0;
6,408✔
531
}
532

6,408✔
533
} // namespace openmc
6,408✔
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