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

openmc-dev / openmc / 21489819490

29 Jan 2026 06:21PM UTC coverage: 80.077% (-1.9%) from 81.953%
21489819490

Pull #3757

github

web-flow
Merge d08626053 into f7a734189
Pull Request #3757: Testing point detectors

16004 of 22621 branches covered (70.75%)

Branch coverage included in aggregate %.

94 of 518 new or added lines in 26 files covered. (18.15%)

1021 existing lines in 52 files now uncovered.

53779 of 64524 relevant lines covered (83.35%)

8016833.26 hits per line

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

79.52
/src/surface.cpp
1
#include "openmc/surface.h"
2

3
#include <cmath>
4
#include <complex>
5
#include <initializer_list>
6
#include <set>
7
#include <utility>
8

9
#include <fmt/core.h>
10

11
#include "openmc/array.h"
12
#include "openmc/cell.h"
13
#include "openmc/container_util.h"
14
#include "openmc/error.h"
15
#include "openmc/external/quartic_solver.h"
16
#include "openmc/hdf5_interface.h"
17
#include "openmc/math_functions.h"
18
#include "openmc/random_lcg.h"
19
#include "openmc/settings.h"
20
#include "openmc/simulation.h"
21
#include "openmc/string_utils.h"
22
#include "openmc/xml_interface.h"
23

24
namespace openmc {
25

26
//==============================================================================
27
// Global variables
28
//==============================================================================
29

30
namespace model {
31
std::unordered_map<int, int> surface_map;
32
vector<unique_ptr<Surface>> surfaces;
33
} // namespace model
34

35
//==============================================================================
36
// Helper functions for reading the "coeffs" node of an XML surface element
37
//==============================================================================
38

39
void read_coeffs(
3,282✔
40
  pugi::xml_node surf_node, int surf_id, std::initializer_list<double*> coeffs)
41
{
42
  // Check the given number of coefficients.
43
  auto coeffs_file = get_node_array<double>(surf_node, "coeffs");
3,282✔
44
  if (coeffs_file.size() != coeffs.size()) {
3,282!
45
    fatal_error(
×
46
      fmt::format("Surface {} expects {} coefficient but was given {}", surf_id,
×
47
        coeffs.size(), coeffs_file.size()));
×
48
  }
49

50
  // Copy the coefficients
51
  int i = 0;
3,282✔
52
  for (auto c : coeffs) {
9,712✔
53
    *c = coeffs_file[i++];
6,430✔
54
  }
55
}
3,282✔
56

57
//==============================================================================
58
// Surface implementation
59
//==============================================================================
60

UNCOV
61
Surface::Surface() {} // empty constructor
×
62

63
Surface::Surface(pugi::xml_node surf_node)
3,282✔
64
{
65
  if (check_for_node(surf_node, "id")) {
3,282!
66
    id_ = std::stoi(get_node_value(surf_node, "id"));
3,282✔
67
    if (contains(settings::source_write_surf_id, id_) ||
6,488✔
68
        settings::source_write_surf_id.empty()) {
3,206✔
69
      surf_source_ = true;
3,181✔
70
    }
71
  } else {
72
    fatal_error("Must specify id of surface in geometry XML file.");
×
73
  }
74

75
  if (check_for_node(surf_node, "name")) {
3,282✔
76
    name_ = get_node_value(surf_node, "name", false);
720✔
77
  }
78

79
  if (check_for_node(surf_node, "boundary")) {
3,282✔
80
    std::string surf_bc = get_node_value(surf_node, "boundary", true, true);
1,955✔
81

82
    if (surf_bc == "transmission" || surf_bc == "transmit" || surf_bc.empty()) {
1,955!
83
      // Leave the bc_ a nullptr
84
    } else if (surf_bc == "vacuum") {
1,955✔
85
      bc_ = make_unique<VacuumBC>();
989✔
86
    } else if (surf_bc == "reflective" || surf_bc == "reflect" ||
1,014!
87
               surf_bc == "reflecting") {
48✔
88
      bc_ = make_unique<ReflectiveBC>();
918✔
89
    } else if (surf_bc == "white") {
48✔
90
      bc_ = make_unique<WhiteBC>();
6✔
91
    } else if (surf_bc == "periodic") {
42!
92
      // Periodic BCs are handled separately
93
    } else {
94
      fatal_error(fmt::format("Unknown boundary condition \"{}\" specified "
×
95
                              "on surface {}",
96
        surf_bc, id_));
×
97
    }
98

99
    if (check_for_node(surf_node, "albedo") && bc_) {
1,955!
100
      double surf_alb = std::stod(get_node_value(surf_node, "albedo"));
6✔
101

102
      if (surf_alb < 0.0)
6!
103
        fatal_error(fmt::format("Surface {} has an albedo of {}. "
×
104
                                "Albedo values must be positive.",
105
          id_, surf_alb));
×
106

107
      if (surf_alb > 1.0)
6!
108
        warning(fmt::format("Surface {} has an albedo of {}. "
×
109
                            "Albedos greater than 1 may cause "
110
                            "unphysical behaviour.",
111
          id_, surf_alb));
×
112

113
      bc_->set_albedo(surf_alb);
6✔
114
    }
115
  }
1,955✔
116
}
3,282✔
117

118
bool Surface::sense(Position r, Direction u) const
558,743,009✔
119
{
120
  // Evaluate the surface equation at the particle's coordinates to determine
121
  // which side the particle is on.
122
  const double f = evaluate(r);
558,743,009✔
123

124
  // Check which side of surface the point is on.
125
  if (std::abs(f) < FP_COINCIDENT) {
558,743,009✔
126
    // Particle may be coincident with this surface. To determine the sense, we
127
    // look at the direction of the particle relative to the surface normal (by
128
    // default in the positive direction) via their dot product.
129
    return u.dot(normal(r)) > 0.0;
967,497✔
130
  }
131
  return f > 0.0;
557,775,512✔
132
}
133

134
Direction Surface::reflect(Position r, Direction u, GeometryState* p) const
59,229,103✔
135
{
136
  // Determine projection of direction onto normal and squared magnitude of
137
  // normal.
138
  Direction n = normal(r);
59,229,103✔
139

140
  // Reflect direction according to normal.
141
  return u.reflect(n);
118,458,206✔
142
}
143

144
Direction Surface::diffuse_reflect(
91,559✔
145
  Position r, Direction u, uint64_t* seed) const
146
{
147
  // Diffuse reflect direction according to the normal.
148
  // cosine distribution
149

150
  Direction n = this->normal(r);
91,559✔
151
  n /= n.norm();
91,559✔
152
  const double projection = n.dot(u);
91,559✔
153

154
  // sample from inverse function, u=sqrt(rand) since p(u)=2u, so F(u)=u^2
155
  const double mu =
156
    (projection >= 0.0) ? -std::sqrt(prn(seed)) : std::sqrt(prn(seed));
91,559✔
157

158
  // sample azimuthal distribution uniformly
159
  u = rotate_angle(n, mu, nullptr, seed);
91,559✔
160

161
  // normalize the direction
162
  return u / u.norm();
183,118✔
163
}
164

165
void Surface::to_hdf5(hid_t group_id) const
3,068✔
166
{
167
  hid_t surf_group = create_group(group_id, fmt::format("surface {}", id_));
6,136✔
168

169
  if (geom_type() == GeometryType::DAG) {
3,068!
UNCOV
170
    write_string(surf_group, "geom_type", "dagmc", false);
×
171
  } else if (geom_type() == GeometryType::CSG) {
3,068!
172
    write_string(surf_group, "geom_type", "csg", false);
3,068✔
173

174
    if (bc_) {
3,068✔
175
      write_string(surf_group, "boundary_type", bc_->type(), false);
1,853✔
176
      bc_->to_hdf5(surf_group);
1,853✔
177

178
      // write periodic surface ID
179
      if (bc_->type() == "periodic") {
1,853✔
180
        auto pbc = dynamic_cast<PeriodicBC*>(bc_.get());
42!
181
        Surface& surf1 {*model::surfaces[pbc->i_surf()]};
42✔
182
        Surface& surf2 {*model::surfaces[pbc->j_surf()]};
42✔
183

184
        if (id_ == surf1.id_) {
42!
185
          write_dataset(surf_group, "periodic_surface_id", surf2.id_);
42✔
186
        } else {
187
          write_dataset(surf_group, "periodic_surface_id", surf1.id_);
×
188
        }
189
      }
190
    } else {
191
      write_string(surf_group, "boundary_type", "transmission", false);
1,215✔
192
    }
193
  }
194

195
  if (!name_.empty()) {
3,068✔
196
    write_string(surf_group, "name", name_, false);
694✔
197
  }
198

199
  to_hdf5_inner(surf_group);
3,068✔
200

201
  close_group(surf_group);
3,068✔
202
}
3,068✔
203

204
//==============================================================================
205
// Generic functions for x-, y-, and z-, planes.
206
//==============================================================================
207

208
// The template parameter indicates the axis normal to the plane.
209
template<int i>
210
double axis_aligned_plane_distance(
1,702,587,805✔
211
  Position r, Direction u, bool coincident, double offset)
212
{
213
  const double f = offset - r[i];
1,702,587,805✔
214
  if (coincident || std::abs(f) < FP_COINCIDENT || u[i] == 0.0)
1,702,587,805✔
215
    return INFTY;
60,820,171✔
216
  const double d = f / u[i];
1,641,767,634✔
217
  if (d < 0.0)
1,641,767,634✔
218
    return INFTY;
790,979,978✔
219
  return d;
850,787,656✔
220
}
221

222
//==============================================================================
223
// SurfaceXPlane implementation
224
//==============================================================================
225

226
SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) : Surface(surf_node)
873✔
227
{
228
  read_coeffs(surf_node, id_, {&x0_});
873✔
229
}
873✔
230

231
double SurfaceXPlane::evaluate(Position r) const
147,819,943✔
232
{
233
  return r.x - x0_;
147,819,943✔
234
}
235

236
double SurfaceXPlane::distance(Position r, Direction u, bool coincident) const
730,881,121✔
237
{
238
  return axis_aligned_plane_distance<0>(r, u, coincident, x0_);
730,881,121✔
239
}
240

241
Direction SurfaceXPlane::normal(Position r) const
25,823,718✔
242
{
243
  return {1., 0., 0.};
25,823,718✔
244
}
245

246
void SurfaceXPlane::to_hdf5_inner(hid_t group_id) const
742✔
247
{
248
  write_string(group_id, "type", "x-plane", false);
742✔
249
  array<double, 1> coeffs {{x0_}};
742✔
250
  write_dataset(group_id, "coefficients", coeffs);
742✔
251
}
742✔
252

253
BoundingBox SurfaceXPlane::bounding_box(bool pos_side) const
22✔
254
{
255
  if (pos_side) {
22✔
256
    return {{x0_, -INFTY, -INFTY}, {INFTY, INFTY, INFTY}};
11✔
257
  } else {
258
    return {{-INFTY, -INFTY, -INFTY}, {x0_, INFTY, INFTY}};
11✔
259
  }
260
}
261

262
//==============================================================================
263
// SurfaceYPlane implementation
264
//==============================================================================
265

266
SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) : Surface(surf_node)
710✔
267
{
268
  read_coeffs(surf_node, id_, {&y0_});
710✔
269
}
710✔
270

271
double SurfaceYPlane::evaluate(Position r) const
146,784,757✔
272
{
273
  return r.y - y0_;
146,784,757✔
274
}
275

276
double SurfaceYPlane::distance(Position r, Direction u, bool coincident) const
744,882,125✔
277
{
278
  return axis_aligned_plane_distance<1>(r, u, coincident, y0_);
744,882,125✔
279
}
280

281
Direction SurfaceYPlane::normal(Position r) const
27,660,676✔
282
{
283
  return {0., 1., 0.};
27,660,676✔
284
}
285

286
void SurfaceYPlane::to_hdf5_inner(hid_t group_id) const
676✔
287
{
288
  write_string(group_id, "type", "y-plane", false);
676✔
289
  array<double, 1> coeffs {{y0_}};
676✔
290
  write_dataset(group_id, "coefficients", coeffs);
676✔
291
}
676✔
292

293
BoundingBox SurfaceYPlane::bounding_box(bool pos_side) const
22✔
294
{
295
  if (pos_side) {
22✔
296
    return {{-INFTY, y0_, -INFTY}, {INFTY, INFTY, INFTY}};
11✔
297
  } else {
298
    return {{-INFTY, -INFTY, -INFTY}, {INFTY, y0_, INFTY}};
11✔
299
  }
300
}
301

302
//==============================================================================
303
// SurfaceZPlane implementation
304
//==============================================================================
305

306
SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) : Surface(surf_node)
537✔
307
{
308
  read_coeffs(surf_node, id_, {&z0_});
537✔
309
}
537✔
310

311
double SurfaceZPlane::evaluate(Position r) const
44,396,416✔
312
{
313
  return r.z - z0_;
44,396,416✔
314
}
315

316
double SurfaceZPlane::distance(Position r, Direction u, bool coincident) const
226,824,559✔
317
{
318
  return axis_aligned_plane_distance<2>(r, u, coincident, z0_);
226,824,559✔
319
}
320

321
Direction SurfaceZPlane::normal(Position r) const
4,938,568✔
322
{
323
  return {0., 0., 1.};
4,938,568✔
324
}
325

326
void SurfaceZPlane::to_hdf5_inner(hid_t group_id) const
533✔
327
{
328
  write_string(group_id, "type", "z-plane", false);
533✔
329
  array<double, 1> coeffs {{z0_}};
533✔
330
  write_dataset(group_id, "coefficients", coeffs);
533✔
331
}
533✔
332

333
BoundingBox SurfaceZPlane::bounding_box(bool pos_side) const
×
334
{
335
  if (pos_side) {
×
336
    return {{-INFTY, -INFTY, z0_}, {INFTY, INFTY, INFTY}};
×
337
  } else {
338
    return {{-INFTY, -INFTY, -INFTY}, {INFTY, INFTY, z0_}};
×
339
  }
340
}
341

342
//==============================================================================
343
// SurfacePlane implementation
344
//==============================================================================
345

346
SurfacePlane::SurfacePlane(pugi::xml_node surf_node) : Surface(surf_node)
124✔
347
{
348
  read_coeffs(surf_node, id_, {&A_, &B_, &C_, &D_});
124✔
349
}
124✔
350

351
double SurfacePlane::evaluate(Position r) const
20,085,874✔
352
{
353
  return A_ * r.x + B_ * r.y + C_ * r.z - D_;
20,085,874✔
354
}
355

356
double SurfacePlane::distance(Position r, Direction u, bool coincident) const
54,922,736✔
357
{
358
  const double f = A_ * r.x + B_ * r.y + C_ * r.z - D_;
54,922,736✔
359
  const double projection = A_ * u.x + B_ * u.y + C_ * u.z;
54,922,736✔
360
  if (coincident || std::abs(f) < FP_COINCIDENT || projection == 0.0) {
54,922,736!
361
    return INFTY;
3,544,058✔
362
  } else {
363
    const double d = -f / projection;
51,378,678✔
364
    if (d < 0.0)
51,378,678✔
365
      return INFTY;
23,934,402✔
366
    return d;
27,444,276✔
367
  }
368
}
369

370
Direction SurfacePlane::normal(Position r) const
527,048✔
371
{
372
  return {A_, B_, C_};
527,048✔
373
}
374

375
void SurfacePlane::to_hdf5_inner(hid_t group_id) const
120✔
376
{
377
  write_string(group_id, "type", "plane", false);
120✔
378
  array<double, 4> coeffs {{A_, B_, C_, D_}};
120✔
379
  write_dataset(group_id, "coefficients", coeffs);
120✔
380
}
120✔
381

382
//==============================================================================
383
// Generic functions for x-, y-, and z-, cylinders
384
//==============================================================================
385

386
// The template parameters indicate the axes perpendicular to the axis of the
387
// cylinder.  offset1 and offset2 should correspond with i1 and i2,
388
// respectively.
389
template<int i1, int i2>
390
double axis_aligned_cylinder_evaluate(
138,932,723✔
391
  Position r, double offset1, double offset2, double radius)
392
{
393
  const double r1 = r.get<i1>() - offset1;
138,932,723✔
394
  const double r2 = r.get<i2>() - offset2;
138,932,723✔
395
  return r1 * r1 + r2 * r2 - radius * radius;
138,932,723✔
396
}
397

398
// The first template parameter indicates which axis the cylinder is aligned to.
399
// The other two parameters indicate the other two axes.  offset1 and offset2
400
// should correspond with i2 and i3, respectively.
401
template<int i1, int i2, int i3>
402
double axis_aligned_cylinder_distance(Position r, Direction u, bool coincident,
163,993,791✔
403
  double offset1, double offset2, double radius)
404
{
405
  const double a = 1.0 - u.get<i1>() * u.get<i1>(); // u^2 + v^2
163,993,791✔
406
  if (a == 0.0)
163,993,791✔
407
    return INFTY;
73,636✔
408

409
  const double r2 = r.get<i2>() - offset1;
163,920,155✔
410
  const double r3 = r.get<i3>() - offset2;
163,920,155✔
411
  const double k = r2 * u.get<i2>() + r3 * u.get<i3>();
163,920,155✔
412
  const double c = r2 * r2 + r3 * r3 - radius * radius;
163,920,155✔
413
  const double quad = k * k - a * c;
163,920,155✔
414

415
  if (quad < 0.0) {
163,920,155✔
416
    // No intersection with cylinder.
417
    return INFTY;
27,195,792✔
418

419
  } else if (coincident || std::abs(c) < FP_COINCIDENT) {
136,724,363✔
420
    // Particle is on the cylinder, thus one distance is positive/negative
421
    // and the other is zero. The sign of k determines if we are facing in or
422
    // out.
423
    if (k >= 0.0) {
63,611,973✔
424
      return INFTY;
31,907,686✔
425
    } else {
426
      return (-k + sqrt(quad)) / a;
31,704,287✔
427
    }
428

429
  } else if (c < 0.0) {
73,112,390✔
430
    // Particle is inside the cylinder, thus one distance must be negative
431
    // and one must be positive. The positive distance will be the one with
432
    // negative sign on sqrt(quad).
433
    return (-k + sqrt(quad)) / a;
28,787,032✔
434

435
  } else {
436
    // Particle is outside the cylinder, thus both distances are either
437
    // positive or negative. If positive, the smaller distance is the one
438
    // with positive sign on sqrt(quad).
439
    const double d = (-k - sqrt(quad)) / a;
44,325,358✔
440
    if (d < 0.0)
44,325,358✔
441
      return INFTY;
6,027,930✔
442
    return d;
38,297,428✔
443
  }
444
}
445

446
// The first template parameter indicates which axis the cylinder is aligned to.
447
// The other two parameters indicate the other two axes.  offset1 and offset2
448
// should correspond with i2 and i3, respectively.
449
template<int i1, int i2, int i3>
450
Direction axis_aligned_cylinder_normal(
141,742✔
451
  Position r, double offset1, double offset2)
452
{
453
  Direction u;
141,742✔
454
  u.get<i2>() = 2.0 * (r.get<i2>() - offset1);
141,742✔
455
  u.get<i3>() = 2.0 * (r.get<i3>() - offset2);
141,742✔
456
  u.get<i1>() = 0.0;
141,742✔
457
  return u;
141,742✔
458
}
459

460
//==============================================================================
461
// SurfaceXCylinder implementation
462
//==============================================================================
463

464
SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node)
3✔
465
  : Surface(surf_node)
3✔
466
{
467
  read_coeffs(surf_node, id_, {&y0_, &z0_, &radius_});
3✔
468
}
3✔
469

470
double SurfaceXCylinder::evaluate(Position r) const
138,737✔
471
{
472
  return axis_aligned_cylinder_evaluate<1, 2>(r, y0_, z0_, radius_);
138,737✔
473
}
474

475
double SurfaceXCylinder::distance(
158,812✔
476
  Position r, Direction u, bool coincident) const
477
{
478
  return axis_aligned_cylinder_distance<0, 1, 2>(
158,812✔
479
    r, u, coincident, y0_, z0_, radius_);
158,812✔
480
}
481

482
Direction SurfaceXCylinder::normal(Position r) const
×
483
{
484
  return axis_aligned_cylinder_normal<0, 1, 2>(r, y0_, z0_);
×
485
}
486

487
void SurfaceXCylinder::to_hdf5_inner(hid_t group_id) const
3✔
488
{
489
  write_string(group_id, "type", "x-cylinder", false);
3✔
490
  array<double, 3> coeffs {{y0_, z0_, radius_}};
3✔
491
  write_dataset(group_id, "coefficients", coeffs);
3✔
492
}
3✔
493

494
BoundingBox SurfaceXCylinder::bounding_box(bool pos_side) const
×
495
{
496
  if (!pos_side) {
×
497
    return {{-INFTY, y0_ - radius_, z0_ - radius_},
×
498
      {INFTY, y0_ + radius_, z0_ + radius_}};
×
499
  } else {
500
    return {};
×
501
  }
502
}
503
//==============================================================================
504
// SurfaceYCylinder implementation
505
//==============================================================================
506

507
SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node)
1✔
508
  : Surface(surf_node)
1✔
509
{
510
  read_coeffs(surf_node, id_, {&x0_, &z0_, &radius_});
1✔
511
}
1✔
512

513
double SurfaceYCylinder::evaluate(Position r) const
15,544✔
514
{
515
  return axis_aligned_cylinder_evaluate<0, 2>(r, x0_, z0_, radius_);
15,544✔
516
}
517

518
double SurfaceYCylinder::distance(
59,979✔
519
  Position r, Direction u, bool coincident) const
520
{
521
  return axis_aligned_cylinder_distance<1, 0, 2>(
59,979✔
522
    r, u, coincident, x0_, z0_, radius_);
59,979✔
523
}
524

525
Direction SurfaceYCylinder::normal(Position r) const
×
526
{
527
  return axis_aligned_cylinder_normal<1, 0, 2>(r, x0_, z0_);
×
528
}
529

530
void SurfaceYCylinder::to_hdf5_inner(hid_t group_id) const
1✔
531
{
532
  write_string(group_id, "type", "y-cylinder", false);
1✔
533
  array<double, 3> coeffs {{x0_, z0_, radius_}};
1✔
534
  write_dataset(group_id, "coefficients", coeffs);
1✔
535
}
1✔
536

537
BoundingBox SurfaceYCylinder::bounding_box(bool pos_side) const
×
538
{
539
  if (!pos_side) {
×
540
    return {{x0_ - radius_, -INFTY, z0_ - radius_},
×
541
      {x0_ + radius_, INFTY, z0_ + radius_}};
×
542
  } else {
543
    return {};
×
544
  }
545
}
546

547
//==============================================================================
548
// SurfaceZCylinder implementation
549
//==============================================================================
550

551
SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node)
376✔
552
  : Surface(surf_node)
376✔
553
{
554
  read_coeffs(surf_node, id_, {&x0_, &y0_, &radius_});
376✔
555
}
376✔
556

557
double SurfaceZCylinder::evaluate(Position r) const
138,778,442✔
558
{
559
  return axis_aligned_cylinder_evaluate<0, 1>(r, x0_, y0_, radius_);
138,778,442✔
560
}
561

562
double SurfaceZCylinder::distance(
163,775,000✔
563
  Position r, Direction u, bool coincident) const
564
{
565
  return axis_aligned_cylinder_distance<2, 0, 1>(
163,775,000✔
566
    r, u, coincident, x0_, y0_, radius_);
163,775,000✔
567
}
568

569
Direction SurfaceZCylinder::normal(Position r) const
141,742✔
570
{
571
  return axis_aligned_cylinder_normal<2, 0, 1>(r, x0_, y0_);
141,742✔
572
}
573

574
void SurfaceZCylinder::to_hdf5_inner(hid_t group_id) const
351✔
575
{
576
  write_string(group_id, "type", "z-cylinder", false);
351✔
577
  array<double, 3> coeffs {{x0_, y0_, radius_}};
351✔
578
  write_dataset(group_id, "coefficients", coeffs);
351✔
579
}
351✔
580

581
BoundingBox SurfaceZCylinder::bounding_box(bool pos_side) const
4✔
582
{
583
  if (!pos_side) {
4✔
584
    return {{x0_ - radius_, y0_ - radius_, -INFTY},
2✔
585
      {x0_ + radius_, y0_ + radius_, INFTY}};
2✔
586
  } else {
587
    return {};
2✔
588
  }
589
}
590

591
//==============================================================================
592
// SurfaceSphere implementation
593
//==============================================================================
594

595
SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) : Surface(surf_node)
638✔
596
{
597
  read_coeffs(surf_node, id_, {&x0_, &y0_, &z0_, &radius_});
638✔
598
}
638✔
599

600
double SurfaceSphere::evaluate(Position r) const
60,416,764✔
601
{
602
  const double x = r.x - x0_;
60,416,764✔
603
  const double y = r.y - y0_;
60,416,764✔
604
  const double z = r.z - z0_;
60,416,764✔
605
  return x * x + y * y + z * z - radius_ * radius_;
60,416,764✔
606
}
607

608
double SurfaceSphere::distance(Position r, Direction u, bool coincident) const
67,606,098✔
609
{
610
  const double x = r.x - x0_;
67,606,098✔
611
  const double y = r.y - y0_;
67,606,098✔
612
  const double z = r.z - z0_;
67,606,098✔
613
  const double k = x * u.x + y * u.y + z * u.z;
67,606,098✔
614
  const double c = x * x + y * y + z * z - radius_ * radius_;
67,606,098✔
615
  const double quad = k * k - c;
67,606,098✔
616

617
  if (quad < 0.0) {
67,606,098✔
618
    // No intersection with sphere.
619
    return INFTY;
14,976,547✔
620

621
  } else if (coincident || std::abs(c) < FP_COINCIDENT) {
52,629,551!
622
    // Particle is on the sphere, thus one distance is positive/negative and
623
    // the other is zero. The sign of k determines if we are facing in or out.
624
    if (k >= 0.0) {
9,452,950✔
625
      return INFTY;
4,034,352✔
626
    } else {
627
      return -k + sqrt(quad);
5,418,598✔
628
    }
629

630
  } else if (c < 0.0) {
43,176,601✔
631
    // Particle is inside the sphere, thus one distance must be negative and
632
    // one must be positive. The positive distance will be the one with
633
    // negative sign on sqrt(quad)
634
    return -k + sqrt(quad);
38,048,173✔
635

636
  } else {
637
    // Particle is outside the sphere, thus both distances are either positive
638
    // or negative. If positive, the smaller distance is the one with positive
639
    // sign on sqrt(quad).
640
    const double d = -k - sqrt(quad);
5,128,428✔
641
    if (d < 0.0)
5,128,428✔
642
      return INFTY;
989,671✔
643
    return d;
4,138,757✔
644
  }
645
}
646

647
Direction SurfaceSphere::normal(Position r) const
1,951,676✔
648
{
649
  return {2.0 * (r.x - x0_), 2.0 * (r.y - y0_), 2.0 * (r.z - z0_)};
1,951,676✔
650
}
651

652
void SurfaceSphere::to_hdf5_inner(hid_t group_id) const
622✔
653
{
654
  write_string(group_id, "type", "sphere", false);
622✔
655
  array<double, 4> coeffs {{x0_, y0_, z0_, radius_}};
622✔
656
  write_dataset(group_id, "coefficients", coeffs);
622✔
657
}
622✔
658

659
BoundingBox SurfaceSphere::bounding_box(bool pos_side) const
×
660
{
661
  if (!pos_side) {
×
662
    return {{x0_ - radius_, y0_ - radius_, z0_ - radius_},
×
663
      {x0_ + radius_, y0_ + radius_, z0_ + radius_}};
×
664
  } else {
665
    return {};
×
666
  }
667
}
668

669
//==============================================================================
670
// Generic functions for x-, y-, and z-, cones
671
//==============================================================================
672

673
// The first template parameter indicates which axis the cone is aligned to.
674
// The other two parameters indicate the other two axes.  offset1, offset2,
675
// and offset3 should correspond with i1, i2, and i3, respectively.
676
template<int i1, int i2, int i3>
677
double axis_aligned_cone_evaluate(
29,623✔
678
  Position r, double offset1, double offset2, double offset3, double radius_sq)
679
{
680
  const double r1 = r.get<i1>() - offset1;
29,623✔
681
  const double r2 = r.get<i2>() - offset2;
29,623✔
682
  const double r3 = r.get<i3>() - offset3;
29,623✔
683
  return r2 * r2 + r3 * r3 - radius_sq * r1 * r1;
29,623✔
684
}
685

686
// The first template parameter indicates which axis the cone is aligned to.
687
// The other two parameters indicate the other two axes.  offset1, offset2,
688
// and offset3 should correspond with i1, i2, and i3, respectively.
689
template<int i1, int i2, int i3>
690
double axis_aligned_cone_distance(Position r, Direction u, bool coincident,
88,911✔
691
  double offset1, double offset2, double offset3, double radius_sq)
692
{
693
  const double r1 = r.get<i1>() - offset1;
88,911✔
694
  const double r2 = r.get<i2>() - offset2;
88,911✔
695
  const double r3 = r.get<i3>() - offset3;
88,911✔
696
  const double a = u.get<i2>() * u.get<i2>() + u.get<i3>() * u.get<i3>() -
88,911✔
697
                   radius_sq * u.get<i1>() * u.get<i1>();
88,911✔
698
  const double k =
88,911✔
699
    r2 * u.get<i2>() + r3 * u.get<i3>() - radius_sq * r1 * u.get<i1>();
88,911✔
700
  const double c = r2 * r2 + r3 * r3 - radius_sq * r1 * r1;
88,911✔
701
  double quad = k * k - a * c;
88,911✔
702

703
  double d;
704

705
  if (quad < 0.0) {
88,911!
706
    // No intersection with cone.
707
    return INFTY;
×
708

709
  } else if (coincident || std::abs(c) < FP_COINCIDENT) {
88,911!
710
    // Particle is on the cone, thus one distance is positive/negative
711
    // and the other is zero. The sign of k determines if we are facing in or
712
    // out.
713
    if (k >= 0.0) {
5,410!
714
      d = (-k - sqrt(quad)) / a;
×
715
    } else {
716
      d = (-k + sqrt(quad)) / a;
5,410✔
717
    }
718

719
  } else {
720
    // Calculate both solutions to the quadratic.
721
    quad = sqrt(quad);
83,501✔
722
    d = (-k - quad) / a;
83,501✔
723
    const double b = (-k + quad) / a;
83,501✔
724

725
    // Determine the smallest positive solution.
726
    if (d < 0.0) {
83,501✔
727
      if (b > 0.0)
70,913✔
728
        d = b;
60,464✔
729
    } else {
730
      if (b > 0.0) {
12,588!
731
        if (b < d)
12,588!
732
          d = b;
12,588✔
733
      }
734
    }
735
  }
736

737
  // If the distance was negative, set boundary distance to infinity.
738
  if (d <= 0.0)
88,911✔
739
    return INFTY;
12,402✔
740
  return d;
76,509✔
741
}
742

743
// The first template parameter indicates which axis the cone is aligned to.
744
// The other two parameters indicate the other two axes.  offset1, offset2,
745
// and offset3 should correspond with i1, i2, and i3, respectively.
746
template<int i1, int i2, int i3>
747
Direction axis_aligned_cone_normal(
5,410✔
748
  Position r, double offset1, double offset2, double offset3, double radius_sq)
749
{
750
  Direction u;
5,410✔
751
  u.get<i1>() = -2.0 * radius_sq * (r.get<i1>() - offset1);
5,410✔
752
  u.get<i2>() = 2.0 * (r.get<i2>() - offset2);
5,410✔
753
  u.get<i3>() = 2.0 * (r.get<i3>() - offset3);
5,410✔
754
  return u;
5,410✔
755
}
756

757
//==============================================================================
758
// SurfaceXCone implementation
759
//==============================================================================
760

761
SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) : Surface(surf_node)
×
762
{
763
  read_coeffs(surf_node, id_, {&x0_, &y0_, &z0_, &radius_sq_});
×
764
}
×
765

766
double SurfaceXCone::evaluate(Position r) const
×
767
{
768
  return axis_aligned_cone_evaluate<0, 1, 2>(r, x0_, y0_, z0_, radius_sq_);
×
769
}
770

771
double SurfaceXCone::distance(Position r, Direction u, bool coincident) const
×
772
{
773
  return axis_aligned_cone_distance<0, 1, 2>(
×
774
    r, u, coincident, x0_, y0_, z0_, radius_sq_);
×
775
}
776

777
Direction SurfaceXCone::normal(Position r) const
×
778
{
779
  return axis_aligned_cone_normal<0, 1, 2>(r, x0_, y0_, z0_, radius_sq_);
×
780
}
781

782
void SurfaceXCone::to_hdf5_inner(hid_t group_id) const
×
783
{
784
  write_string(group_id, "type", "x-cone", false);
×
785
  array<double, 4> coeffs {{x0_, y0_, z0_, radius_sq_}};
×
786
  write_dataset(group_id, "coefficients", coeffs);
×
787
}
×
788

789
//==============================================================================
790
// SurfaceYCone implementation
791
//==============================================================================
792

793
SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) : Surface(surf_node)
×
794
{
795
  read_coeffs(surf_node, id_, {&x0_, &y0_, &z0_, &radius_sq_});
×
796
}
×
797

798
double SurfaceYCone::evaluate(Position r) const
×
799
{
800
  return axis_aligned_cone_evaluate<1, 0, 2>(r, y0_, x0_, z0_, radius_sq_);
×
801
}
802

803
double SurfaceYCone::distance(Position r, Direction u, bool coincident) const
×
804
{
805
  return axis_aligned_cone_distance<1, 0, 2>(
×
806
    r, u, coincident, y0_, x0_, z0_, radius_sq_);
×
807
}
808

809
Direction SurfaceYCone::normal(Position r) const
×
810
{
811
  return axis_aligned_cone_normal<1, 0, 2>(r, y0_, x0_, z0_, radius_sq_);
×
812
}
813

814
void SurfaceYCone::to_hdf5_inner(hid_t group_id) const
×
815
{
816
  write_string(group_id, "type", "y-cone", false);
×
817
  array<double, 4> coeffs {{x0_, y0_, z0_, radius_sq_}};
×
818
  write_dataset(group_id, "coefficients", coeffs);
×
819
}
×
820

821
//==============================================================================
822
// SurfaceZCone implementation
823
//==============================================================================
824

825
SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) : Surface(surf_node)
1✔
826
{
827
  read_coeffs(surf_node, id_, {&x0_, &y0_, &z0_, &radius_sq_});
1✔
828
}
1✔
829

830
double SurfaceZCone::evaluate(Position r) const
29,623✔
831
{
832
  return axis_aligned_cone_evaluate<2, 0, 1>(r, z0_, x0_, y0_, radius_sq_);
29,623✔
833
}
834

835
double SurfaceZCone::distance(Position r, Direction u, bool coincident) const
88,911✔
836
{
837
  return axis_aligned_cone_distance<2, 0, 1>(
88,911✔
838
    r, u, coincident, z0_, x0_, y0_, radius_sq_);
88,911✔
839
}
840

841
Direction SurfaceZCone::normal(Position r) const
5,410✔
842
{
843
  return axis_aligned_cone_normal<2, 0, 1>(r, z0_, x0_, y0_, radius_sq_);
5,410✔
844
}
845

846
void SurfaceZCone::to_hdf5_inner(hid_t group_id) const
1✔
847
{
848
  write_string(group_id, "type", "z-cone", false);
1✔
849
  array<double, 4> coeffs {{x0_, y0_, z0_, radius_sq_}};
1✔
850
  write_dataset(group_id, "coefficients", coeffs);
1✔
851
}
1✔
852

853
//==============================================================================
854
// SurfaceQuadric implementation
855
//==============================================================================
856

857
SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) : Surface(surf_node)
1✔
858
{
859
  read_coeffs(
×
860
    surf_node, id_, {&A_, &B_, &C_, &D_, &E_, &F_, &G_, &H_, &J_, &K_});
1✔
861
}
1✔
862

863
double SurfaceQuadric::evaluate(Position r) const
13,938✔
864
{
865
  const double x = r.x;
13,938✔
866
  const double y = r.y;
13,938✔
867
  const double z = r.z;
13,938✔
868
  return x * (A_ * x + D_ * y + G_) + y * (B_ * y + E_ * z + H_) +
13,938✔
869
         z * (C_ * z + F_ * x + J_) + K_;
13,938✔
870
}
871

872
double SurfaceQuadric::distance(
28,789✔
873
  Position r, Direction ang, bool coincident) const
874
{
875
  const double& x = r.x;
28,789✔
876
  const double& y = r.y;
28,789✔
877
  const double& z = r.z;
28,789✔
878
  const double& u = ang.x;
28,789✔
879
  const double& v = ang.y;
28,789✔
880
  const double& w = ang.z;
28,789✔
881

882
  const double a =
28,789✔
883
    A_ * u * u + B_ * v * v + C_ * w * w + D_ * u * v + E_ * v * w + F_ * u * w;
28,789✔
884
  const double k = A_ * u * x + B_ * v * y + C_ * w * z +
28,789✔
885
                   0.5 * (D_ * (u * y + v * x) + E_ * (v * z + w * y) +
28,789✔
886
                           F_ * (w * x + u * z) + G_ * u + H_ * v + J_ * w);
28,789✔
887
  const double c = A_ * x * x + B_ * y * y + C_ * z * z + D_ * x * y +
28,789✔
888
                   E_ * y * z + F_ * x * z + G_ * x + H_ * y + J_ * z + K_;
28,789✔
889
  double quad = k * k - a * c;
28,789✔
890

891
  double d;
892

893
  if (quad < 0.0) {
28,789!
894
    // No intersection with surface.
895
    return INFTY;
×
896

897
  } else if (coincident || std::abs(c) < FP_COINCIDENT) {
28,789!
898
    // Particle is on the surface, thus one distance is positive/negative and
899
    // the other is zero. The sign of k determines which distance is zero and
900
    // which is not. Additionally, if a is zero, it means the particle is on
901
    // a plane-like surface.
902
    if (a == 0.0) {
3,278!
903
      d = INFTY; // see the below explanation
×
904
    } else if (k >= 0.0) {
3,278!
905
      d = (-k - sqrt(quad)) / a;
×
906
    } else {
907
      d = (-k + sqrt(quad)) / a;
3,278✔
908
    }
909

910
  } else if (a == 0.0) {
25,511!
911
    // Given the orientation of the particle, the quadric looks like a plane in
912
    // this case, and thus we have only one solution despite potentially having
913
    // quad > 0.0. While the term under the square root may be real, in one
914
    // case of the +/- of the quadratic formula, 0/0 results, and in another, a
915
    // finite value over 0 results. Applying L'Hopital's to the 0/0 case gives
916
    // the below. Alternatively this can be found by simply putting a=0 in the
917
    // equation ax^2 + bx + c = 0.
918
    d = -0.5 * c / k;
×
919
  } else {
920
    // Calculate both solutions to the quadratic.
921
    quad = sqrt(quad);
25,511✔
922
    d = (-k - quad) / a;
25,511✔
923
    double b = (-k + quad) / a;
25,511✔
924

925
    // Determine the smallest positive solution.
926
    if (d < 0.0) {
25,511!
927
      if (b > 0.0)
25,511!
928
        d = b;
25,511✔
929
    } else {
930
      if (b > 0.0) {
×
931
        if (b < d)
×
932
          d = b;
×
933
      }
934
    }
935
  }
936

937
  // If the distance was negative, set boundary distance to infinity.
938
  if (d <= 0.0)
28,789!
939
    return INFTY;
×
940
  return d;
28,789✔
941
}
942

943
Direction SurfaceQuadric::normal(Position r) const
3,278✔
944
{
945
  const double& x = r.x;
3,278✔
946
  const double& y = r.y;
3,278✔
947
  const double& z = r.z;
3,278✔
948
  return {2.0 * A_ * x + D_ * y + F_ * z + G_,
3,278✔
949
    2.0 * B_ * y + D_ * x + E_ * z + H_, 2.0 * C_ * z + E_ * y + F_ * x + J_};
3,278✔
950
}
951

952
void SurfaceQuadric::to_hdf5_inner(hid_t group_id) const
1✔
953
{
954
  write_string(group_id, "type", "quadric", false);
1✔
955
  array<double, 10> coeffs {{A_, B_, C_, D_, E_, F_, G_, H_, J_, K_}};
1✔
956
  write_dataset(group_id, "coefficients", coeffs);
1✔
957
}
1✔
958

959
//==============================================================================
960
// Torus helper functions
961
//==============================================================================
962

963
double torus_distance(double x1, double x2, double x3, double u1, double u2,
2,412,233✔
964
  double u3, double A, double B, double C, bool coincident)
965
{
966
  // Coefficients for equation: (c2 t^2 + c1 t + c0)^2 = c2' t^2 + c1' t + c0'
967
  double D = (C * C) / (B * B);
2,412,233✔
968
  double c2 = u1 * u1 + u2 * u2 + D * u3 * u3;
2,412,233✔
969
  double c1 = 2 * (u1 * x1 + u2 * x2 + D * u3 * x3);
2,412,233✔
970
  double c0 = x1 * x1 + x2 * x2 + D * x3 * x3 + A * A - C * C;
2,412,233✔
971
  double four_A2 = 4 * A * A;
2,412,233✔
972
  double c2p = four_A2 * (u1 * u1 + u2 * u2);
2,412,233✔
973
  double c1p = 2 * four_A2 * (u1 * x1 + u2 * x2);
2,412,233✔
974
  double c0p = four_A2 * (x1 * x1 + x2 * x2);
2,412,233✔
975

976
  // Coefficient for equation: a t^4 + b t^3 + c t^2 + d t + e = 0. If the point
977
  // is coincident, the 'e' coefficient should be zero. Explicitly setting it to
978
  // zero helps avoid numerical issues below with root finding.
979
  double coeff[5];
980
  coeff[0] = coincident ? 0.0 : c0 * c0 - c0p;
2,412,233✔
981
  coeff[1] = 2 * c0 * c1 - c1p;
2,412,233✔
982
  coeff[2] = c1 * c1 + 2 * c0 * c2 - c2p;
2,412,233✔
983
  coeff[3] = 2 * c1 * c2;
2,412,233✔
984
  coeff[4] = c2 * c2;
2,412,233✔
985

986
  std::complex<double> roots[4];
2,412,233✔
987
  oqs::quartic_solver(coeff, roots);
2,412,233✔
988

989
  // Find smallest positive, real root. In the case where the particle is
990
  // coincident with the surface, we are sure to have one root very close to
991
  // zero but possibly small and positive. A tolerance is set to discard that
992
  // zero.
993
  double distance = INFTY;
2,412,233✔
994
  double cutoff = coincident ? TORUS_TOL : 0.0;
2,412,233✔
995
  for (int i = 0; i < 4; ++i) {
12,061,165✔
996
    if (roots[i].imag() == 0) {
9,648,932✔
997
      double root = roots[i].real();
2,358,548✔
998
      if (root > cutoff && root < distance) {
2,358,548✔
999
        // Avoid roots corresponding to internal surfaces
1000
        double s1 = x1 + u1 * root;
946,545✔
1001
        double s2 = x2 + u2 * root;
946,545✔
1002
        double s3 = x3 + u3 * root;
946,545✔
1003
        double check = D * s3 * s3 + s1 * s1 + s2 * s2 + A * A - C * C;
946,545✔
1004
        if (check >= 0) {
946,545!
1005
          distance = root;
946,545✔
1006
        }
1007
      }
1008
    }
1009
  }
1010
  return distance;
2,412,233✔
1011
}
1012

1013
//==============================================================================
1014
// SurfaceXTorus implementation
1015
//==============================================================================
1016

1017
SurfaceXTorus::SurfaceXTorus(pugi::xml_node surf_node) : Surface(surf_node)
5✔
1018
{
1019
  read_coeffs(surf_node, id_, {&x0_, &y0_, &z0_, &A_, &B_, &C_});
5✔
1020
}
5✔
1021

1022
void SurfaceXTorus::to_hdf5_inner(hid_t group_id) const
5✔
1023
{
1024
  write_string(group_id, "type", "x-torus", false);
5✔
1025
  std::array<double, 6> coeffs {{x0_, y0_, z0_, A_, B_, C_}};
5✔
1026
  write_dataset(group_id, "coefficients", coeffs);
5✔
1027
}
5✔
1028

1029
double SurfaceXTorus::evaluate(Position r) const
73,749✔
1030
{
1031
  double x = r.x - x0_;
73,749✔
1032
  double y = r.y - y0_;
73,749✔
1033
  double z = r.z - z0_;
73,749✔
1034
  return (x * x) / (B_ * B_) +
147,498✔
1035
         std::pow(std::sqrt(y * y + z * z) - A_, 2) / (C_ * C_) - 1.;
73,749✔
1036
}
1037

1038
double SurfaceXTorus::distance(Position r, Direction u, bool coincident) const
758,965✔
1039
{
1040
  double x = r.x - x0_;
758,965✔
1041
  double y = r.y - y0_;
758,965✔
1042
  double z = r.z - z0_;
758,965✔
1043
  return torus_distance(y, z, x, u.y, u.z, u.x, A_, B_, C_, coincident);
758,965✔
1044
}
1045

1046
Direction SurfaceXTorus::normal(Position r) const
×
1047
{
1048
  // reduce the expansion of the full form for torus
1049
  double x = r.x - x0_;
×
1050
  double y = r.y - y0_;
×
1051
  double z = r.z - z0_;
×
1052

1053
  // f(x,y,z) = x^2/B^2 + (sqrt(y^2 + z^2) - A)^2/C^2 - 1
1054
  // ∂f/∂x = 2x/B^2
1055
  // ∂f/∂y = 2y(g - A)/(g*C^2) where g = sqrt(y^2 + z^2)
1056
  // ∂f/∂z = 2z(g - A)/(g*C^2)
1057
  // Multiplying by g*C^2*B^2 / 2 gives:
1058
  double g = std::sqrt(y * y + z * z);
×
1059
  double nx = C_ * C_ * g * x;
×
1060
  double ny = y * (g - A_) * B_ * B_;
×
1061
  double nz = z * (g - A_) * B_ * B_;
×
1062
  Direction n(nx, ny, nz);
×
1063
  return n / n.norm();
×
1064
}
1065

1066
//==============================================================================
1067
// SurfaceYTorus implementation
1068
//==============================================================================
1069

1070
SurfaceYTorus::SurfaceYTorus(pugi::xml_node surf_node) : Surface(surf_node)
5✔
1071
{
1072
  read_coeffs(surf_node, id_, {&x0_, &y0_, &z0_, &A_, &B_, &C_});
5✔
1073
}
5✔
1074

1075
void SurfaceYTorus::to_hdf5_inner(hid_t group_id) const
5✔
1076
{
1077
  write_string(group_id, "type", "y-torus", false);
5✔
1078
  std::array<double, 6> coeffs {{x0_, y0_, z0_, A_, B_, C_}};
5✔
1079
  write_dataset(group_id, "coefficients", coeffs);
5✔
1080
}
5✔
1081

1082
double SurfaceYTorus::evaluate(Position r) const
69,815✔
1083
{
1084
  double x = r.x - x0_;
69,815✔
1085
  double y = r.y - y0_;
69,815✔
1086
  double z = r.z - z0_;
69,815✔
1087
  return (y * y) / (B_ * B_) +
139,630✔
1088
         std::pow(std::sqrt(x * x + z * z) - A_, 2) / (C_ * C_) - 1.;
69,815✔
1089
}
1090

1091
double SurfaceYTorus::distance(Position r, Direction u, bool coincident) const
764,900✔
1092
{
1093
  double x = r.x - x0_;
764,900✔
1094
  double y = r.y - y0_;
764,900✔
1095
  double z = r.z - z0_;
764,900✔
1096
  return torus_distance(x, z, y, u.x, u.z, u.y, A_, B_, C_, coincident);
764,900✔
1097
}
1098

1099
Direction SurfaceYTorus::normal(Position r) const
×
1100
{
1101
  // reduce the expansion of the full form for torus
1102
  double x = r.x - x0_;
×
1103
  double y = r.y - y0_;
×
1104
  double z = r.z - z0_;
×
1105

1106
  // f(x,y,z) = y^2/B^2 + (sqrt(x^2 + z^2) - A)^2/C^2 - 1
1107
  // ∂f/∂x = 2x(g - A)/(g*C^2) where g = sqrt(x^2 + z^2)
1108
  // ∂f/∂y = 2y/B^2
1109
  // ∂f/∂z = 2z(g - A)/(g*C^2)
1110
  // Multiplying by g*C^2*B^2 / 2 gives:
1111
  double g = std::sqrt(x * x + z * z);
×
1112
  double nx = x * (g - A_) * B_ * B_;
×
1113
  double ny = C_ * C_ * g * y;
×
1114
  double nz = z * (g - A_) * B_ * B_;
×
1115
  Direction n(nx, ny, nz);
×
1116
  return n / n.norm();
×
1117
}
1118

1119
//==============================================================================
1120
// SurfaceZTorus implementation
1121
//==============================================================================
1122

1123
SurfaceZTorus::SurfaceZTorus(pugi::xml_node surf_node) : Surface(surf_node)
8✔
1124
{
1125
  read_coeffs(surf_node, id_, {&x0_, &y0_, &z0_, &A_, &B_, &C_});
8✔
1126
}
8✔
1127

1128
void SurfaceZTorus::to_hdf5_inner(hid_t group_id) const
8✔
1129
{
1130
  write_string(group_id, "type", "z-torus", false);
8✔
1131
  std::array<double, 6> coeffs {{x0_, y0_, z0_, A_, B_, C_}};
8✔
1132
  write_dataset(group_id, "coefficients", coeffs);
8✔
1133
}
8✔
1134

1135
double SurfaceZTorus::evaluate(Position r) const
119,491✔
1136
{
1137
  double x = r.x - x0_;
119,491✔
1138
  double y = r.y - y0_;
119,491✔
1139
  double z = r.z - z0_;
119,491✔
1140
  return (z * z) / (B_ * B_) +
238,982✔
1141
         std::pow(std::sqrt(x * x + y * y) - A_, 2) / (C_ * C_) - 1.;
119,491✔
1142
}
1143

1144
double SurfaceZTorus::distance(Position r, Direction u, bool coincident) const
888,368✔
1145
{
1146
  double x = r.x - x0_;
888,368✔
1147
  double y = r.y - y0_;
888,368✔
1148
  double z = r.z - z0_;
888,368✔
1149
  return torus_distance(x, y, z, u.x, u.y, u.z, A_, B_, C_, coincident);
888,368✔
1150
}
1151

1152
Direction SurfaceZTorus::normal(Position r) const
×
1153
{
1154
  // reduce the expansion of the full form for torus
1155
  double x = r.x - x0_;
×
1156
  double y = r.y - y0_;
×
1157
  double z = r.z - z0_;
×
1158

1159
  // f(x,y,z) = z^2/B^2 + (sqrt(x^2 + y^2) - A)^2/C^2 - 1
1160
  // ∂f/∂x = 2x(g - A)/(g*C^2) where g = sqrt(x^2 + y^2)
1161
  // ∂f/∂y = 2y(g - A)/(g*C^2)
1162
  // ∂f/∂z = 2z/B^2
1163
  // Multiplying by g*C^2*B^2 / 2 gives:
1164
  double g = std::sqrt(x * x + y * y);
×
1165
  double nx = x * (g - A_) * B_ * B_;
×
1166
  double ny = y * (g - A_) * B_ * B_;
×
1167
  double nz = C_ * C_ * g * z;
×
1168
  Position n(nx, ny, nz);
×
1169
  return n / n.norm();
×
1170
}
1171

1172
//==============================================================================
1173

1174
void read_surfaces(pugi::xml_node node,
627✔
1175
  std::set<std::pair<int, int>>& periodic_pairs,
1176
  std::unordered_map<int, double>& albedo_map,
1177
  std::unordered_map<int, int>& periodic_sense_map)
1178
{
1179
  simulation::nonvacuum_boundary_present = false;
627✔
1180
  // Count the number of surfaces
1181
  int n_surfaces = 0;
627✔
1182
  for (pugi::xml_node surf_node : node.children("surface")) {
3,828✔
1183
    n_surfaces++;
3,201✔
1184
  }
1185

1186
  // Loop over XML surface elements and populate the array.  Keep track of
1187
  // periodic surfaces and their albedos.
1188
  model::surfaces.reserve(n_surfaces);
627✔
1189
  {
1190
    pugi::xml_node surf_node;
627✔
1191
    int i_surf;
1192
    for (surf_node = node.child("surface"), i_surf = 0; surf_node;
3,828✔
1193
         surf_node = surf_node.next_sibling("surface"), i_surf++) {
3,201✔
1194
      std::string surf_type = get_node_value(surf_node, "type", true, true);
3,201✔
1195

1196
      // Allocate and initialize the new surface
1197

1198
      if (surf_type == "x-plane") {
3,201✔
1199
        model::surfaces.push_back(make_unique<SurfaceXPlane>(surf_node));
792✔
1200

1201
      } else if (surf_type == "y-plane") {
2,409✔
1202
        model::surfaces.push_back(make_unique<SurfaceYPlane>(surf_node));
710✔
1203

1204
      } else if (surf_type == "z-plane") {
1,699✔
1205
        model::surfaces.push_back(make_unique<SurfaceZPlane>(surf_node));
537✔
1206

1207
      } else if (surf_type == "plane") {
1,162✔
1208
        model::surfaces.push_back(make_unique<SurfacePlane>(surf_node));
124✔
1209

1210
      } else if (surf_type == "x-cylinder") {
1,038✔
1211
        model::surfaces.push_back(make_unique<SurfaceXCylinder>(surf_node));
3✔
1212

1213
      } else if (surf_type == "y-cylinder") {
1,035✔
1214
        model::surfaces.push_back(make_unique<SurfaceYCylinder>(surf_node));
1✔
1215

1216
      } else if (surf_type == "z-cylinder") {
1,034✔
1217
        model::surfaces.push_back(make_unique<SurfaceZCylinder>(surf_node));
376✔
1218

1219
      } else if (surf_type == "sphere") {
658✔
1220
        model::surfaces.push_back(make_unique<SurfaceSphere>(surf_node));
638✔
1221

1222
      } else if (surf_type == "x-cone") {
20!
1223
        model::surfaces.push_back(make_unique<SurfaceXCone>(surf_node));
×
1224

1225
      } else if (surf_type == "y-cone") {
20!
1226
        model::surfaces.push_back(make_unique<SurfaceYCone>(surf_node));
×
1227

1228
      } else if (surf_type == "z-cone") {
20✔
1229
        model::surfaces.push_back(make_unique<SurfaceZCone>(surf_node));
1✔
1230

1231
      } else if (surf_type == "quadric") {
19✔
1232
        model::surfaces.push_back(make_unique<SurfaceQuadric>(surf_node));
1✔
1233

1234
      } else if (surf_type == "x-torus") {
18✔
1235
        model::surfaces.push_back(std::make_unique<SurfaceXTorus>(surf_node));
5✔
1236

1237
      } else if (surf_type == "y-torus") {
13✔
1238
        model::surfaces.push_back(std::make_unique<SurfaceYTorus>(surf_node));
5✔
1239

1240
      } else if (surf_type == "z-torus") {
8!
1241
        model::surfaces.push_back(std::make_unique<SurfaceZTorus>(surf_node));
8✔
1242

1243
      } else {
1244
        fatal_error(fmt::format("Invalid surface type, \"{}\"", surf_type));
×
1245
      }
1246

1247
      // Check for a periodic surface
1248
      if (check_for_node(surf_node, "boundary")) {
3,201✔
1249
        std::string surf_bc = get_node_value(surf_node, "boundary", true, true);
1,955✔
1250
        if (surf_bc != "vacuum")
1,955✔
1251
          simulation::nonvacuum_boundary_present = true;
966✔
1252
        if (surf_bc == "periodic") {
1,955✔
1253
          periodic_sense_map[model::surfaces.back()->id_] = 0;
42✔
1254
          // Check for surface albedo. Skip sanity check as it is already done
1255
          // in the Surface class's constructor.
1256
          if (check_for_node(surf_node, "albedo")) {
42!
1257
            albedo_map[model::surfaces.back()->id_] =
×
1258
              std::stod(get_node_value(surf_node, "albedo"));
×
1259
          }
1260
          if (check_for_node(surf_node, "periodic_surface_id")) {
42✔
1261
            int i_periodic =
1262
              std::stoi(get_node_value(surf_node, "periodic_surface_id"));
28✔
1263
            int lo_id = std::min(model::surfaces.back()->id_, i_periodic);
28✔
1264
            int hi_id = std::max(model::surfaces.back()->id_, i_periodic);
28✔
1265
            periodic_pairs.insert({lo_id, hi_id});
28✔
1266
          } else {
1267
            periodic_pairs.insert({model::surfaces.back()->id_, -1});
14✔
1268
          }
1269
        }
1270
      }
1,955✔
1271
    }
3,201✔
1272
  }
1273

1274
  // Fill the surface map
1275
  for (int i_surf = 0; i_surf < model::surfaces.size(); i_surf++) {
3,828✔
1276
    int id = model::surfaces[i_surf]->id_;
3,201✔
1277
    auto in_map = model::surface_map.find(id);
3,201✔
1278
    if (in_map == model::surface_map.end()) {
3,201!
1279
      model::surface_map[id] = i_surf;
3,201✔
1280
    } else {
1281
      fatal_error(
×
1282
        fmt::format("Two or more surfaces use the same unique ID: {}", id));
×
1283
    }
1284
  }
1285
}
627✔
1286

1287
void prepare_boundary_conditions(std::set<std::pair<int, int>>& periodic_pairs,
627✔
1288
  std::unordered_map<int, double>& albedo_map,
1289
  std::unordered_map<int, int>& periodic_sense_map)
1290
{
1291
  // Fill the senses map for periodic surfaces
1292
  auto n_periodic = periodic_sense_map.size();
627✔
1293
  for (const auto& cell : model::cells) {
648✔
1294
    if (n_periodic == 0)
637✔
1295
      break; // Early exit once all periodic surfaces found
616✔
1296

1297
    for (auto s : cell->surfaces()) {
107✔
1298
      auto surf_idx = std::abs(s) - 1;
86✔
1299
      auto id = model::surfaces[surf_idx]->id_;
86✔
1300

1301
      if (periodic_sense_map.count(id)) {
86✔
1302
        periodic_sense_map[id] = std::copysign(1, s);
42✔
1303
        --n_periodic;
42✔
1304
      }
1305
    }
21✔
1306
  }
1307

1308
  // Resolve unpaired periodic surfaces.  A lambda function is used with
1309
  // std::find_if to identify the unpaired surfaces.
1310
  auto is_unresolved_pair = [](const std::pair<int, int> p) {
28✔
1311
    return p.second == -1;
28✔
1312
  };
1313
  auto first_unresolved = std::find_if(
627✔
1314
    periodic_pairs.begin(), periodic_pairs.end(), is_unresolved_pair);
1315
  if (first_unresolved != periodic_pairs.end()) {
627✔
1316
    // Found one unpaired surface; search for a second one
1317
    auto next_elem = first_unresolved;
7✔
1318
    next_elem++;
7✔
1319
    auto second_unresolved =
1320
      std::find_if(next_elem, periodic_pairs.end(), is_unresolved_pair);
7✔
1321
    if (second_unresolved == periodic_pairs.end()) {
7!
1322
      fatal_error("Found only one periodic surface without a specified partner."
×
1323
                  " Please specify the partner for each periodic surface.");
1324
    }
1325

1326
    // Make sure there isn't a third unpaired surface
1327
    next_elem = second_unresolved;
7✔
1328
    next_elem++;
7✔
1329
    auto third_unresolved =
1330
      std::find_if(next_elem, periodic_pairs.end(), is_unresolved_pair);
7✔
1331
    if (third_unresolved != periodic_pairs.end()) {
7!
1332
      fatal_error(
×
1333
        "Found at least three periodic surfaces without a specified "
1334
        "partner. Please specify the partner for each periodic surface.");
1335
    }
1336

1337
    // Add the completed pair and remove the old, unpaired entries
1338
    int lo_id = std::min(first_unresolved->first, second_unresolved->first);
7✔
1339
    int hi_id = std::max(first_unresolved->first, second_unresolved->first);
7✔
1340
    periodic_pairs.insert({lo_id, hi_id});
7✔
1341
    periodic_pairs.erase(first_unresolved);
7✔
1342
    periodic_pairs.erase(second_unresolved);
7✔
1343
  }
1344

1345
  // Assign the periodic boundary conditions with albedos
1346
  for (auto periodic_pair : periodic_pairs) {
648✔
1347
    int i_surf = model::surface_map[periodic_pair.first];
21✔
1348
    int j_surf = model::surface_map[periodic_pair.second];
21✔
1349
    Surface& surf1 {*model::surfaces[i_surf]};
21✔
1350
    Surface& surf2 {*model::surfaces[j_surf]};
21✔
1351

1352
    // Compute the dot product of the surface normals
1353
    Direction norm1 = surf1.normal({0, 0, 0});
21✔
1354
    Direction norm2 = surf2.normal({0, 0, 0});
21✔
1355
    norm1 /= norm1.norm();
21✔
1356
    norm2 /= norm2.norm();
21✔
1357
    double dot_prod = norm1.dot(norm2);
21✔
1358

1359
    // If the dot product is 1 (to within floating point precision) then the
1360
    // planes are parallel which indicates a translational periodic boundary
1361
    // condition.  Otherwise, it is a rotational periodic BC.
1362
    if (std::abs(1.0 - dot_prod) < FP_PRECISION) {
21✔
1363
      surf1.bc_ = make_unique<TranslationalPeriodicBC>(i_surf, j_surf);
9✔
1364
      surf2.bc_ = make_unique<TranslationalPeriodicBC>(j_surf, i_surf);
9✔
1365
    } else {
1366
      // check that both normals have at least one 0 component
1367
      if (std::abs(norm1.x) > FP_PRECISION &&
23✔
1368
          std::abs(norm1.y) > FP_PRECISION &&
23!
1369
          std::abs(norm1.z) > FP_PRECISION) {
9✔
1370
        fatal_error(fmt::format(
×
1371
          "The normal ({}) of the periodic surface ({}) does not contain any "
1372
          "component with a zero value. A RotationalPeriodicBC requires one "
1373
          "component which is zero for both plane normals.",
1374
          norm1, i_surf));
1375
      }
1376
      if (std::abs(norm2.x) > FP_PRECISION &&
22✔
1377
          std::abs(norm2.y) > FP_PRECISION &&
22!
1378
          std::abs(norm2.z) > FP_PRECISION) {
9✔
1379
        fatal_error(fmt::format(
×
1380
          "The normal ({}) of the periodic surface ({}) does not contain any "
1381
          "component with a zero value. A RotationalPeriodicBC requires one "
1382
          "component which is zero for both plane normals.",
1383
          norm2, j_surf));
1384
      }
1385
      // find common zero component, which indicates the periodic axis
1386
      RotationalPeriodicBC::PeriodicAxis axis;
1387
      if (std::abs(norm1.x) <= FP_PRECISION &&
13!
1388
          std::abs(norm2.x) <= FP_PRECISION) {
1✔
1389
        axis = RotationalPeriodicBC::PeriodicAxis::x;
1✔
1390
      } else if (std::abs(norm1.y) <= FP_PRECISION &&
13✔
1391
                 std::abs(norm2.y) <= FP_PRECISION) {
2✔
1392
        axis = RotationalPeriodicBC::PeriodicAxis::y;
1✔
1393
      } else if (std::abs(norm1.z) <= FP_PRECISION &&
20!
1394
                 std::abs(norm2.z) <= FP_PRECISION) {
10✔
1395
        axis = RotationalPeriodicBC::PeriodicAxis::z;
10✔
1396
      } else {
1397
        fatal_error(fmt::format(
×
1398
          "There is no component which is 0.0 in both normal vectors. This "
1399
          "indicates that the two planes are not periodic about the X, Y, or Z "
1400
          "axis, which is not supported."));
1401
      }
1402
      auto i_sign = periodic_sense_map[periodic_pair.first];
12✔
1403
      auto j_sign = periodic_sense_map[periodic_pair.second];
12✔
1404
      surf1.bc_ = make_unique<RotationalPeriodicBC>(
12✔
1405
        i_sign * (i_surf + 1), j_sign * (j_surf + 1), axis);
12✔
1406
      surf2.bc_ = make_unique<RotationalPeriodicBC>(
12✔
1407
        j_sign * (j_surf + 1), i_sign * (i_surf + 1), axis);
24✔
1408
    }
1409

1410
    // If albedo data is present in albedo map, set the boundary albedo.
1411
    if (albedo_map.count(surf1.id_)) {
21!
1412
      surf1.bc_->set_albedo(albedo_map[surf1.id_]);
×
1413
    }
1414
    if (albedo_map.count(surf2.id_)) {
21!
1415
      surf2.bc_->set_albedo(albedo_map[surf2.id_]);
×
1416
    }
1417
  }
1418
}
627✔
1419

1420
void free_memory_surfaces()
635✔
1421
{
1422
  model::surfaces.clear();
635✔
1423
  model::surface_map.clear();
635✔
1424
}
635✔
1425

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