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

openmc-dev / openmc / 20925680857

12 Jan 2026 03:51PM UTC coverage: 82.058% (-0.1%) from 82.198%
20925680857

push

github

web-flow
Source biasing capabilities (#3460)

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

17208 of 23885 branches covered (72.05%)

Branch coverage included in aggregate %.

479 of 626 new or added lines in 12 files covered. (76.52%)

8 existing lines in 3 files now uncovered.

55640 of 64891 relevant lines covered (85.74%)

43208543.16 hits per line

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

62.02
/src/distribution_spatial.cpp
1
#include "openmc/distribution_spatial.h"
2

3
#include "openmc/error.h"
4
#include "openmc/mesh.h"
5
#include "openmc/random_lcg.h"
6
#include "openmc/search.h"
7
#include "openmc/xml_interface.h"
8

9
namespace openmc {
10

11
//==============================================================================
12
// SpatialDistribution implementation
13
//==============================================================================
14

15
unique_ptr<SpatialDistribution> SpatialDistribution::create(pugi::xml_node node)
7,052✔
16
{
17
  // Check for type of spatial distribution and read
18
  std::string type;
7,052✔
19
  if (check_for_node(node, "type"))
7,052!
20
    type = get_node_value(node, "type", true, true);
7,052✔
21
  if (type == "cartesian") {
7,052✔
22
    return UPtrSpace {new CartesianIndependent(node)};
16✔
23
  } else if (type == "cylindrical") {
7,036✔
24
    return UPtrSpace {new CylindricalIndependent(node)};
48✔
25
  } else if (type == "spherical") {
6,988✔
26
    return UPtrSpace {new SphericalIndependent(node)};
63✔
27
  } else if (type == "mesh") {
6,925✔
28
    return UPtrSpace {new MeshSpatial(node)};
40✔
29
  } else if (type == "cloud") {
6,885✔
30
    return UPtrSpace {new PointCloud(node)};
11✔
31
  } else if (type == "box") {
6,874✔
32
    return UPtrSpace {new SpatialBox(node)};
3,784✔
33
  } else if (type == "fission") {
3,090✔
34
    return UPtrSpace {new SpatialBox(node, true)};
22✔
35
  } else if (type == "point") {
3,068!
36
    return UPtrSpace {new SpatialPoint(node)};
3,068✔
37
  } else {
38
    fatal_error(fmt::format(
×
39
      "Invalid spatial distribution for external source: {}", type));
40
  }
41
}
7,051✔
42

43
//==============================================================================
44
// CartesianIndependent implementation
45
//==============================================================================
46

47
CartesianIndependent::CartesianIndependent(pugi::xml_node node)
16✔
48
{
49
  // Read distribution for x coordinate
50
  if (check_for_node(node, "x")) {
16!
51
    pugi::xml_node node_dist = node.child("x");
16✔
52
    x_ = distribution_from_xml(node_dist);
16✔
53
  } else {
54
    // If no distribution was specified, default to a single point at x=0
55
    double x[] {0.0};
×
56
    double p[] {1.0};
×
57
    x_ = UPtrDist {new Discrete {x, p, 1}};
×
58
  }
59

60
  // Read distribution for y coordinate
61
  if (check_for_node(node, "y")) {
16!
62
    pugi::xml_node node_dist = node.child("y");
16✔
63
    y_ = distribution_from_xml(node_dist);
16✔
64
  } else {
65
    // If no distribution was specified, default to a single point at y=0
66
    double x[] {0.0};
×
67
    double p[] {1.0};
×
68
    y_ = UPtrDist {new Discrete {x, p, 1}};
×
69
  }
70

71
  // Read distribution for z coordinate
72
  if (check_for_node(node, "z")) {
16!
73
    pugi::xml_node node_dist = node.child("z");
16✔
74
    z_ = distribution_from_xml(node_dist);
16✔
75
  } else {
76
    // If no distribution was specified, default to a single point at z=0
77
    double x[] {0.0};
×
78
    double p[] {1.0};
×
79
    z_ = UPtrDist {new Discrete {x, p, 1}};
×
80
  }
81
}
16✔
82

83
std::pair<Position, double> CartesianIndependent::sample(uint64_t* seed) const
3,190✔
84
{
85
  auto [x_val, x_wgt] = x_->sample(seed);
3,190✔
86
  auto [y_val, y_wgt] = y_->sample(seed);
3,190✔
87
  auto [z_val, z_wgt] = z_->sample(seed);
3,190✔
88
  Position xi {x_val, y_val, z_val};
3,190✔
89
  return {xi, x_wgt * y_wgt * z_wgt};
3,190✔
90
}
91

92
//==============================================================================
93
// CylindricalIndependent implementation
94
//==============================================================================
95

96
CylindricalIndependent::CylindricalIndependent(pugi::xml_node node)
48✔
97
{
98
  // Read distribution for r-coordinate
99
  if (check_for_node(node, "r")) {
48!
100
    pugi::xml_node node_dist = node.child("r");
48✔
101
    r_ = distribution_from_xml(node_dist);
48✔
102
  } else {
103
    // If no distribution was specified, default to a single point at r=0
104
    double x[] {0.0};
×
105
    double p[] {1.0};
×
106
    r_ = make_unique<Discrete>(x, p, 1);
×
107
  }
108

109
  // Read distribution for phi-coordinate
110
  if (check_for_node(node, "phi")) {
48!
111
    pugi::xml_node node_dist = node.child("phi");
48✔
112
    phi_ = distribution_from_xml(node_dist);
48✔
113
  } else {
114
    // If no distribution was specified, default to a single point at phi=0
115
    double x[] {0.0};
×
116
    double p[] {1.0};
×
117
    phi_ = make_unique<Discrete>(x, p, 1);
×
118
  }
119

120
  // Read distribution for z-coordinate
121
  if (check_for_node(node, "z")) {
48!
122
    pugi::xml_node node_dist = node.child("z");
48✔
123
    z_ = distribution_from_xml(node_dist);
48✔
124
  } else {
125
    // If no distribution was specified, default to a single point at z=0
126
    double x[] {0.0};
×
127
    double p[] {1.0};
×
128
    z_ = make_unique<Discrete>(x, p, 1);
×
129
  }
130

131
  // Read cylinder center coordinates
132
  if (check_for_node(node, "origin")) {
48!
133
    auto origin = get_node_array<double>(node, "origin");
48✔
134
    if (origin.size() == 3) {
48!
135
      origin_ = origin;
48✔
136
    } else {
137
      fatal_error(
×
138
        "Origin for cylindrical source distribution must be length 3");
139
    }
140
  } else {
48✔
141
    // If no coordinates were specified, default to (0, 0, 0)
142
    origin_ = {0.0, 0.0, 0.0};
×
143
  }
144
}
48✔
145

146
std::pair<Position, double> CylindricalIndependent::sample(uint64_t* seed) const
3,542✔
147
{
148
  auto [r, r_wgt] = r_->sample(seed);
3,542✔
149
  auto [phi, phi_wgt] = phi_->sample(seed);
3,542✔
150
  auto [z, z_wgt] = z_->sample(seed);
3,542✔
151
  double x = r * cos(phi) + origin_.x;
3,542✔
152
  double y = r * sin(phi) + origin_.y;
3,542✔
153
  z += origin_.z;
3,542✔
154
  Position xi {x, y, z};
3,542✔
155
  return {xi, r_wgt * phi_wgt * z_wgt};
3,542✔
156
}
157

158
//==============================================================================
159
// SphericalIndependent implementation
160
//==============================================================================
161

162
SphericalIndependent::SphericalIndependent(pugi::xml_node node)
63✔
163
{
164
  // Read distribution for r-coordinate
165
  if (check_for_node(node, "r")) {
63!
166
    pugi::xml_node node_dist = node.child("r");
63✔
167
    r_ = distribution_from_xml(node_dist);
63✔
168
  } else {
169
    // If no distribution was specified, default to a single point at r=0
170
    double x[] {0.0};
×
171
    double p[] {1.0};
×
172
    r_ = make_unique<Discrete>(x, p, 1);
×
173
  }
174

175
  // Read distribution for cos_theta-coordinate
176
  if (check_for_node(node, "cos_theta")) {
63!
177
    pugi::xml_node node_dist = node.child("cos_theta");
63✔
178
    cos_theta_ = distribution_from_xml(node_dist);
63✔
179
  } else {
180
    // If no distribution was specified, default to a single point at
181
    // cos_theta=0
182
    double x[] {0.0};
×
183
    double p[] {1.0};
×
184
    cos_theta_ = make_unique<Discrete>(x, p, 1);
×
185
  }
186

187
  // Read distribution for phi-coordinate
188
  if (check_for_node(node, "phi")) {
63!
189
    pugi::xml_node node_dist = node.child("phi");
63✔
190
    phi_ = distribution_from_xml(node_dist);
63✔
191
  } else {
192
    // If no distribution was specified, default to a single point at phi=0
193
    double x[] {0.0};
×
194
    double p[] {1.0};
×
195
    phi_ = make_unique<Discrete>(x, p, 1);
×
196
  }
197

198
  // Read sphere center coordinates
199
  if (check_for_node(node, "origin")) {
63!
200
    auto origin = get_node_array<double>(node, "origin");
63✔
201
    if (origin.size() == 3) {
63!
202
      origin_ = origin;
63✔
203
    } else {
204
      fatal_error("Origin for spherical source distribution must be length 3");
×
205
    }
206
  } else {
63✔
207
    // If no coordinates were specified, default to (0, 0, 0)
208
    origin_ = {0.0, 0.0, 0.0};
×
209
  }
210
}
63✔
211

212
std::pair<Position, double> SphericalIndependent::sample(uint64_t* seed) const
182,288✔
213
{
214
  auto [r, r_wgt] = r_->sample(seed);
182,288✔
215
  auto [cos_theta, cos_theta_wgt] = cos_theta_->sample(seed);
182,288✔
216
  auto [phi, phi_wgt] = phi_->sample(seed);
182,288✔
217
  // sin(theta) by sin**2 + cos**2 = 1
218
  double x = r * std::sqrt(1 - cos_theta * cos_theta) * cos(phi) + origin_.x;
182,288✔
219
  double y = r * std::sqrt(1 - cos_theta * cos_theta) * sin(phi) + origin_.y;
182,288✔
220
  double z = r * cos_theta + origin_.z;
182,288✔
221
  Position xi {x, y, z};
182,288✔
222
  return {xi, r_wgt * cos_theta_wgt * phi_wgt};
182,288✔
223
}
224

225
//==============================================================================
226
// MeshSpatial implementation
227
//==============================================================================
228

229
MeshSpatial::MeshSpatial(pugi::xml_node node)
40✔
230
{
231

232
  if (get_node_value(node, "type", true, true) != "mesh") {
40!
233
    fatal_error(fmt::format(
×
234
      "Incorrect spatial type '{}' for a MeshSpatial distribution"));
235
  }
236

237
  // No in-tet distributions implemented, could include distributions for the
238
  // barycentric coords Read in unstructured mesh from mesh_id value
239
  int32_t mesh_id = std::stoi(get_node_value(node, "mesh_id"));
40✔
240
  // Get pointer to spatial distribution
241
  mesh_idx_ = model::mesh_map.at(mesh_id);
40✔
242

243
  const auto mesh_ptr = model::meshes.at(mesh_idx_).get();
40✔
244

245
  check_element_types();
40✔
246

247
  size_t n_bins = this->n_sources();
40✔
248
  std::vector<double> strengths(n_bins, 1.0);
40✔
249

250
  // Create cdfs for sampling for an element over a mesh
251
  // Volume scheme is weighted by the volume of each tet
252
  // File scheme is weighted by an array given in the xml file
253
  if (check_for_node(node, "strengths")) {
40✔
254
    strengths = get_node_array<double>(node, "strengths");
37✔
255
    if (strengths.size() != n_bins) {
37✔
256
      fatal_error(
1✔
257
        fmt::format("Number of entries in the source strengths array {} does "
1!
258
                    "not match the number of entities in mesh {} ({}).",
259
          strengths.size(), mesh_id, n_bins));
1✔
260
    }
261
  }
262

263
  if (get_node_value_bool(node, "volume_normalized")) {
39✔
264
    for (int i = 0; i < n_bins; i++) {
37,356✔
265
      strengths[i] *= this->mesh()->volume(i);
37,320✔
266
    }
267
  }
268

269
  elem_idx_dist_.assign(strengths);
39✔
270

271
  if (check_for_node(node, "bias")) {
39!
NEW
272
    pugi::xml_node bias_node = node.child("bias");
×
273

NEW
274
    if (check_for_node(bias_node, "strengths")) {
×
NEW
275
      std::vector<double> bias_strengths(n_bins, 1.0);
×
NEW
276
      bias_strengths = get_node_array<double>(node, "strengths");
×
277

NEW
278
      if (bias_strengths.size() != n_bins) {
×
NEW
279
        fatal_error(
×
NEW
280
          fmt::format("Number of entries in the bias strengths array {} does "
×
281
                      "not match the number of entities in mesh {} ({}).",
NEW
282
            bias_strengths.size(), mesh_id, n_bins));
×
283
      }
284

NEW
285
      if (get_node_value_bool(node, "volume_normalized")) {
×
NEW
286
        for (int i = 0; i < n_bins; i++) {
×
NEW
287
          bias_strengths[i] *= this->mesh()->volume(i);
×
288
        }
289
      }
290

291
      // Compute importance weights
NEW
292
      weight_ = compute_importance_weights(strengths, bias_strengths);
×
293

294
      // Re-initialize DiscreteIndex with bias strengths for sampling
NEW
295
      elem_idx_dist_.assign(bias_strengths);
×
NEW
296
    } else {
×
NEW
297
      fatal_error(fmt::format(
×
298
        "Bias node for mesh {} found without strengths array.", mesh_id));
299
    }
300
  }
301
}
39✔
302

303
MeshSpatial::MeshSpatial(int32_t mesh_idx, span<const double> strengths)
223✔
304
  : mesh_idx_(mesh_idx)
223✔
305
{
306
  check_element_types();
223✔
307
  elem_idx_dist_.assign(strengths);
223✔
308
}
223✔
309

310
void MeshSpatial::check_element_types() const
263✔
311
{
312
  const auto umesh_ptr = dynamic_cast<const UnstructuredMesh*>(this->mesh());
263!
313
  if (umesh_ptr) {
263✔
314
    // ensure that the unstructured mesh contains only linear tets
315
    for (int bin = 0; bin < umesh_ptr->n_bins(); bin++) {
120,010✔
316
      if (umesh_ptr->element_type(bin) != ElementType::LINEAR_TET) {
120,000!
317
        fatal_error(
×
318
          "Mesh specified for source must contain only linear tetrahedra.");
319
      }
320
    }
321
  }
322
}
263✔
323

324
int32_t MeshSpatial::sample_element_index(uint64_t* seed) const
2,213,285✔
325
{
326
  return elem_idx_dist_.sample(seed);
2,213,285✔
327
}
328

329
std::pair<int32_t, Position> MeshSpatial::sample_mesh(uint64_t* seed) const
601,530✔
330
{
331
  // Sample the CDF defined in initialization above
332
  int32_t elem_idx = this->sample_element_index(seed);
601,530✔
333
  return {elem_idx, mesh()->sample_element(elem_idx, seed)};
601,530✔
334
}
335

336
std::pair<Position, double> MeshSpatial::sample(uint64_t* seed) const
601,530✔
337
{
338
  auto [elem_idx, u] = this->sample_mesh(seed);
601,530✔
339
  double wgt = weight_.empty() ? 1.0 : weight_[elem_idx];
601,530!
340
  return {u, wgt};
1,203,060✔
341
}
342

343
//==============================================================================
344
// PointCloud implementation
345
//==============================================================================
346

347
PointCloud::PointCloud(pugi::xml_node node)
11✔
348
{
349
  if (check_for_node(node, "coords")) {
11!
350
    point_cloud_ = get_node_position_array(node, "coords");
11✔
351
  } else {
352
    fatal_error("No coordinates were provided for the PointCloud "
×
353
                "spatial distribution");
354
  }
355

356
  std::vector<double> strengths;
11✔
357

358
  if (check_for_node(node, "strengths"))
11!
359
    strengths = get_node_array<double>(node, "strengths");
11✔
360
  else
361
    strengths.resize(point_cloud_.size(), 1.0);
×
362

363
  if (strengths.size() != point_cloud_.size()) {
11!
364
    fatal_error(
×
365
      fmt::format("Number of entries for the strengths array {} does "
×
366
                  "not match the number of spatial points provided {}.",
367
        strengths.size(), point_cloud_.size()));
×
368
  }
369

370
  point_idx_dist_.assign(strengths);
11✔
371

372
  if (check_for_node(node, "bias")) {
11!
NEW
373
    pugi::xml_node bias_node = node.child("bias");
×
374

NEW
375
    if (check_for_node(bias_node, "strengths")) {
×
NEW
376
      std::vector<double> bias_strengths(point_cloud_.size(), 1.0);
×
NEW
377
      bias_strengths = get_node_array<double>(node, "strengths");
×
378

NEW
379
      if (bias_strengths.size() != point_cloud_.size()) {
×
NEW
380
        fatal_error(
×
NEW
381
          fmt::format("Number of entries in the bias strengths array {} does "
×
382
                      "not match the number of spatial points provided {}.",
NEW
383
            bias_strengths.size(), point_cloud_.size()));
×
384
      }
385

386
      // Compute importance weights
NEW
387
      weight_ = compute_importance_weights(strengths, bias_strengths);
×
388

389
      // Re-initialize DiscreteIndex with bias strengths for sampling
NEW
390
      point_idx_dist_.assign(bias_strengths);
×
NEW
391
    } else {
×
NEW
392
      fatal_error(
×
NEW
393
        fmt::format("Bias node for PointCloud found without strengths array."));
×
394
    }
395
  }
396
}
11✔
397

398
PointCloud::PointCloud(
×
399
  std::vector<Position> point_cloud, span<const double> strengths)
×
400
{
401
  point_cloud_.assign(point_cloud.begin(), point_cloud.end());
×
402
  point_idx_dist_.assign(strengths);
×
403
}
×
404

405
std::pair<Position, double> PointCloud::sample(uint64_t* seed) const
550,000✔
406
{
407
  int32_t index = point_idx_dist_.sample(seed);
550,000✔
408
  double wgt = weight_.empty() ? 1.0 : weight_[index];
550,000!
409
  return {point_cloud_[index], wgt};
1,100,000✔
410
}
411

412
//==============================================================================
413
// SpatialBox implementation
414
//==============================================================================
415

416
SpatialBox::SpatialBox(pugi::xml_node node, bool fission)
3,806✔
417
  : only_fissionable_ {fission}
3,806✔
418
{
419
  // Read lower-right/upper-left coordinates
420
  auto params = get_node_array<double>(node, "parameters");
3,806✔
421
  if (params.size() != 6)
3,806!
422
    openmc::fatal_error("Box/fission spatial source must have six "
×
423
                        "parameters specified.");
424

425
  lower_left_ = Position {params[0], params[1], params[2]};
3,806✔
426
  upper_right_ = Position {params[3], params[4], params[5]};
3,806✔
427
}
3,806✔
428

429
std::pair<Position, double> SpatialBox::sample(uint64_t* seed) const
6,150,695✔
430
{
431
  Position xi {prn(seed), prn(seed), prn(seed)};
6,150,695✔
432
  return {lower_left_ + xi * (upper_right_ - lower_left_), 1.0};
6,150,695✔
433
}
434

435
//==============================================================================
436
// SpatialPoint implementation
437
//==============================================================================
438

439
SpatialPoint::SpatialPoint(pugi::xml_node node)
3,068✔
440
{
441
  // Read location of point source
442
  auto params = get_node_array<double>(node, "parameters");
3,068✔
443
  if (params.size() != 3)
3,068!
444
    openmc::fatal_error("Point spatial source must have three "
×
445
                        "parameters specified.");
446

447
  // Set position
448
  r_ = Position {params.data()};
3,068✔
449
}
3,068✔
450

451
std::pair<Position, double> SpatialPoint::sample(uint64_t* seed) const
26,058,334✔
452
{
453
  return {r_, 1.0};
26,058,334✔
454
}
455

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

© 2026 Coveralls, Inc