polyhedral-gravity 3.3.1rc2__tar.gz → 3.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/CMakeLists.txt +1 -0
  2. polyhedral_gravity-3.4/MANIFEST.in +4 -0
  3. {polyhedral_gravity-3.3.1rc2/polyhedral_gravity.egg-info → polyhedral_gravity-3.4}/PKG-INFO +13 -6
  4. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/README.md +12 -5
  5. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/gtest.cmake +1 -1
  6. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/pybind11.cmake +1 -1
  7. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/spdlog.cmake +1 -1
  8. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/xsimd.cmake +1 -1
  9. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/yaml.cmake +2 -2
  10. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4/polyhedral_gravity.egg-info}/PKG-INFO +13 -6
  11. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/polyhedral_gravity.egg-info/SOURCES.txt +2 -0
  12. polyhedral_gravity-3.4/python/polyhedral_gravity/__init__.py +2 -0
  13. polyhedral_gravity-3.4/python/polyhedral_gravity/torch.py +252 -0
  14. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/setup.py +10 -6
  15. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/CMakeLists.txt +2 -2
  16. polyhedral_gravity-3.4/src/polyhedralGravity/input/MeshReader.cpp +125 -0
  17. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/input/MeshReader.h +3 -1
  18. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/GravityModelDetail.cpp +5 -3
  19. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/Polyhedron.cpp +17 -0
  20. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/Polyhedron.h +9 -0
  21. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravityPython/CMakeLists.txt +2 -2
  22. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravityPython/PolyhedralGravityPython.cpp +1 -1
  23. polyhedral_gravity-3.3.1rc2/MANIFEST.in +0 -3
  24. polyhedral_gravity-3.3.1rc2/src/polyhedralGravity/input/MeshReader.cpp +0 -69
  25. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/LICENSE +0 -0
  26. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/FindSphinx.cmake +0 -0
  27. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/clang_format.cmake +0 -0
  28. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/cmake_format.cmake +0 -0
  29. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/git.cmake +0 -0
  30. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/tbb.cmake +0 -0
  31. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/tetgen.cmake +0 -0
  32. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/cmake/thrust.cmake +0 -0
  33. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/polyhedral_gravity.egg-info/dependency_links.txt +0 -0
  34. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/polyhedral_gravity.egg-info/not-zip-safe +0 -0
  35. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/polyhedral_gravity.egg-info/top_level.txt +0 -0
  36. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/setup.cfg +0 -0
  37. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/main.cpp +0 -0
  38. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/CMakeLists.txt +0 -0
  39. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/Info.h.in +0 -0
  40. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/input/ConfigSource.h +0 -0
  41. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/input/TetgenAdapter.cpp +0 -0
  42. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/input/TetgenAdapter.h +0 -0
  43. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/input/YAMLConfigReader.cpp +0 -0
  44. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/input/YAMLConfigReader.h +0 -0
  45. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/GravityEvaluable.cpp +0 -0
  46. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/GravityEvaluable.h +0 -0
  47. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/GravityModel.cpp +0 -0
  48. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/GravityModel.h +0 -0
  49. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/GravityModelData.h +0 -0
  50. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/GravityModelDetail.h +0 -0
  51. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/PolyhedronDefinitions.cpp +0 -0
  52. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/model/PolyhedronDefinitions.h +0 -0
  53. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/output/CSVWriter.cpp +0 -0
  54. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/output/CSVWriter.h +0 -0
  55. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/output/Logging.cpp +0 -0
  56. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/output/Logging.h +0 -0
  57. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/util/UtilityConstants.h +0 -0
  58. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/util/UtilityContainer.h +0 -0
  59. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/util/UtilityFloatArithmetic.cpp +0 -0
  60. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/util/UtilityFloatArithmetic.h +0 -0
  61. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/util/UtilityString.h +0 -0
  62. {polyhedral_gravity-3.3.1rc2 → polyhedral_gravity-3.4}/src/polyhedralGravity/util/UtilityThrust.h +0 -0
@@ -1,4 +1,5 @@
1
1
  cmake_minimum_required(VERSION 3.16)
2
+ cmake_policy(SET CMP0079 NEW)
2
3
  project(polyhedralGravity)
3
4
 
4
5
  set(CMAKE_CXX_STANDARD 17)
@@ -0,0 +1,4 @@
1
+ include CMakeLists.txt
2
+ recursive-include src *
3
+ recursive-include cmake *
4
+ recursive-include python *
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: polyhedral_gravity
3
- Version: 3.3.1rc2
3
+ Version: 3.4
4
4
  Summary: Package to compute full gravity tensor of a given constant density polyhedron for arbitrary points according to the geodetic convention
5
5
  Author: Jonas Schuhmacher
6
6
  Author-email: jonas.schuhmacher@tum.de
@@ -261,6 +261,13 @@ Similarly to Python, the C++ implementation also provides mesh checking capabili
261
261
  > [!TIP]
262
262
  > For reference, have a look at [the main method](./src/main.cpp) of the C++ executable.
263
263
 
264
+ > [!NOTE]
265
+ > An optional, differentiable `polyhedral_gravity.torch` submodule is also available,
266
+ > useful if you need autograd gradients (e.g. for shape/density optimization) or want
267
+ > to run on a CUDA GPU — see the
268
+ > [PyTorch interface documentation](https://esa.github.io/polyhedral-gravity-model/api/python.html#pytorch-interface-differentiable)
269
+ > for details and examples.
270
+
264
271
  ## Installation
265
272
 
266
273
  ### With conda
@@ -291,13 +298,13 @@ you have a C++17 capable compiler and CMake installed.
291
298
  The project uses the following dependencies,
292
299
  all of them are **automatically** set up via CMake:
293
300
 
294
- - GoogleTest (1.15.2 or compatible), only required for testing
295
- - spdlog (1.13.0 or compatible), required for logging
301
+ - GoogleTest (1.18.0 or compatible), only required for testing
302
+ - spdlog (1.17.0 or compatible), required for logging
296
303
  - tetgen (1.6 or compatible), required for I/O
297
- - yaml-cpp (0.8.0 or compatible), required for I/O
304
+ - yaml-cpp (0.9.0 or compatible), required for I/O
298
305
  - thrust (2.1.0 or compatible), required for parallelization and utility
299
- - xsimd (11.1.0 or compatible), required for vectorization of the `atan(..)`
300
- - pybind11 (2.12.0 or compatible), required for the Python interface, but not the C++ standalone
306
+ - xsimd (14.3.0 or compatible), required for vectorization of the `atan(..)`
307
+ - pybind11 (3.1.0 or compatible), required for the Python interface, but not the C++ standalone
301
308
 
302
309
  The module will be built using a C++17 capable compiler,
303
310
  CMake. Just execute the following command in
@@ -232,6 +232,13 @@ Similarly to Python, the C++ implementation also provides mesh checking capabili
232
232
  > [!TIP]
233
233
  > For reference, have a look at [the main method](./src/main.cpp) of the C++ executable.
234
234
 
235
+ > [!NOTE]
236
+ > An optional, differentiable `polyhedral_gravity.torch` submodule is also available,
237
+ > useful if you need autograd gradients (e.g. for shape/density optimization) or want
238
+ > to run on a CUDA GPU — see the
239
+ > [PyTorch interface documentation](https://esa.github.io/polyhedral-gravity-model/api/python.html#pytorch-interface-differentiable)
240
+ > for details and examples.
241
+
235
242
  ## Installation
236
243
 
237
244
  ### With conda
@@ -262,13 +269,13 @@ you have a C++17 capable compiler and CMake installed.
262
269
  The project uses the following dependencies,
263
270
  all of them are **automatically** set up via CMake:
264
271
 
265
- - GoogleTest (1.15.2 or compatible), only required for testing
266
- - spdlog (1.13.0 or compatible), required for logging
272
+ - GoogleTest (1.18.0 or compatible), only required for testing
273
+ - spdlog (1.17.0 or compatible), required for logging
267
274
  - tetgen (1.6 or compatible), required for I/O
268
- - yaml-cpp (0.8.0 or compatible), required for I/O
275
+ - yaml-cpp (0.9.0 or compatible), required for I/O
269
276
  - thrust (2.1.0 or compatible), required for parallelization and utility
270
- - xsimd (11.1.0 or compatible), required for vectorization of the `atan(..)`
271
- - pybind11 (2.12.0 or compatible), required for the Python interface, but not the C++ standalone
277
+ - xsimd (14.3.0 or compatible), required for vectorization of the `atan(..)`
278
+ - pybind11 (3.1.0 or compatible), required for the Python interface, but not the C++ standalone
272
279
 
273
280
  The module will be built using a C++17 capable compiler,
274
281
  CMake. Just execute the following command in
@@ -1,7 +1,7 @@
1
1
  include(FetchContent)
2
2
 
3
3
  message(STATUS "Setting up Google Test")
4
- set(GOOGLE_TEST_VERSION 1.15.2)
4
+ set(GOOGLE_TEST_VERSION 1.18.0)
5
5
 
6
6
  find_package(GTest ${GOOGLE_TEST_VERSION} QUIET)
7
7
 
@@ -1,7 +1,7 @@
1
1
  include(FetchContent)
2
2
 
3
3
  message(STATUS "Setting up Pybind11 Library")
4
- set(PYBIND11_VERSION 3.0.1)
4
+ set(PYBIND11_VERSION 3.1.0)
5
5
  set(PYBIND11_FINDPYTHON ON)
6
6
 
7
7
  find_package(pybind11 ${PYBIND11_VERSION} QUIET)
@@ -1,7 +1,7 @@
1
1
  include(FetchContent)
2
2
 
3
3
  message(STATUS "Setting up spdlog")
4
- set(SPDLOG_VERSION 1.14.1)
4
+ set(SPDLOG_VERSION 1.17.0)
5
5
 
6
6
  # Known Issue:
7
7
  # If you install spdlog@1.14.1 via homebrew on ARM macOS, CMake will find spdlog
@@ -1,7 +1,7 @@
1
1
  include(FetchContent)
2
2
 
3
3
  message(STATUS "Setting up xsimd Library")
4
- set(XSIMD_VERSION 11.1.0)
4
+ set(XSIMD_VERSION 14.3.0)
5
5
 
6
6
  find_package(xsimd ${XSIMD_VERSION} QUIET)
7
7
 
@@ -1,7 +1,7 @@
1
1
  include(FetchContent)
2
2
 
3
3
  message(STATUS "Setting up yaml-cpp")
4
- set(YAML_CPP_VERSION 0.8.0)
4
+ set(YAML_CPP_VERSION 0.9.0)
5
5
 
6
6
  find_package(yaml-cpp ${YAML_CPP_VERSION} QUIET)
7
7
 
@@ -11,7 +11,7 @@ else()
11
11
  message(STATUS "Using yaml-cpp from GitHub Release ${YAML_CPP_VERSION}")
12
12
  FetchContent_Declare(yaml-cpp
13
13
  GIT_REPOSITORY https://github.com/jbeder/yaml-cpp.git
14
- GIT_TAG ${YAML_CPP_VERSION}
14
+ GIT_TAG yaml-cpp-${YAML_CPP_VERSION}
15
15
  )
16
16
  # Disable everything we don't need
17
17
  set(YAML_CPP_BUILD_TESTS OFF CACHE INTERNAL "")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: polyhedral_gravity
3
- Version: 3.3.1rc2
3
+ Version: 3.4
4
4
  Summary: Package to compute full gravity tensor of a given constant density polyhedron for arbitrary points according to the geodetic convention
5
5
  Author: Jonas Schuhmacher
6
6
  Author-email: jonas.schuhmacher@tum.de
@@ -261,6 +261,13 @@ Similarly to Python, the C++ implementation also provides mesh checking capabili
261
261
  > [!TIP]
262
262
  > For reference, have a look at [the main method](./src/main.cpp) of the C++ executable.
263
263
 
264
+ > [!NOTE]
265
+ > An optional, differentiable `polyhedral_gravity.torch` submodule is also available,
266
+ > useful if you need autograd gradients (e.g. for shape/density optimization) or want
267
+ > to run on a CUDA GPU — see the
268
+ > [PyTorch interface documentation](https://esa.github.io/polyhedral-gravity-model/api/python.html#pytorch-interface-differentiable)
269
+ > for details and examples.
270
+
264
271
  ## Installation
265
272
 
266
273
  ### With conda
@@ -291,13 +298,13 @@ you have a C++17 capable compiler and CMake installed.
291
298
  The project uses the following dependencies,
292
299
  all of them are **automatically** set up via CMake:
293
300
 
294
- - GoogleTest (1.15.2 or compatible), only required for testing
295
- - spdlog (1.13.0 or compatible), required for logging
301
+ - GoogleTest (1.18.0 or compatible), only required for testing
302
+ - spdlog (1.17.0 or compatible), required for logging
296
303
  - tetgen (1.6 or compatible), required for I/O
297
- - yaml-cpp (0.8.0 or compatible), required for I/O
304
+ - yaml-cpp (0.9.0 or compatible), required for I/O
298
305
  - thrust (2.1.0 or compatible), required for parallelization and utility
299
- - xsimd (11.1.0 or compatible), required for vectorization of the `atan(..)`
300
- - pybind11 (2.12.0 or compatible), required for the Python interface, but not the C++ standalone
306
+ - xsimd (14.3.0 or compatible), required for vectorization of the `atan(..)`
307
+ - pybind11 (3.1.0 or compatible), required for the Python interface, but not the C++ standalone
301
308
 
302
309
  The module will be built using a C++17 capable compiler,
303
310
  CMake. Just execute the following command in
@@ -20,6 +20,8 @@ polyhedral_gravity.egg-info/SOURCES.txt
20
20
  polyhedral_gravity.egg-info/dependency_links.txt
21
21
  polyhedral_gravity.egg-info/not-zip-safe
22
22
  polyhedral_gravity.egg-info/top_level.txt
23
+ python/polyhedral_gravity/__init__.py
24
+ python/polyhedral_gravity/torch.py
23
25
  src/CMakeLists.txt
24
26
  src/main.cpp
25
27
  src/polyhedralGravity/CMakeLists.txt
@@ -0,0 +1,2 @@
1
+ from ._core import *
2
+ from ._core import __version__, __parallelization__, __commit__, __logging__
@@ -0,0 +1,252 @@
1
+ """
2
+ Differentiable polyhedral gravity model - PyTorch interface.
3
+
4
+ Implements the Tsoulis (2012) line-integral formula in pure PyTorch, making
5
+ the gravitational potential and acceleration differentiable with respect to
6
+ vertex positions and density. Supports CPU and CUDA execution.
7
+ """
8
+
9
+ try:
10
+ import torch
11
+ from torch import Tensor
12
+ except ImportError as _err:
13
+ raise ImportError(
14
+ "polyhedral_gravity.torch requires PyTorch. Install it with: pip install torch"
15
+ ) from _err
16
+
17
+ import math
18
+
19
+ G_SI: float = 6.67430e-11 # m^3 kg^-1 s^-2
20
+
21
+
22
+ def evaluate(
23
+ vertices: Tensor,
24
+ faces: Tensor,
25
+ density: float,
26
+ computation_points: Tensor,
27
+ gravitational_constant: float = G_SI,
28
+ ) -> tuple[Tensor, Tensor, Tensor]:
29
+ """
30
+ Gravitational potential, acceleration, and gradient tensor for a polyhedron,
31
+ differentiable w.r.t. vertex positions and density.
32
+
33
+ Args:
34
+ vertices: (N, 3) vertex positions [m].
35
+ faces: (F, 3) triangle vertex indices, integer dtype.
36
+ density: Constant density [kg/m^3].
37
+ computation_points: (Q, 3) evaluation positions [m].
38
+ gravitational_constant: Gravitational constant, defaults to 6.67430e-11.
39
+
40
+ Returns:
41
+ potential: (Q,) gravitational potential [m^2/s^2].
42
+ acceleration: (Q, 3) gravitational acceleration [m/s^2].
43
+ tensor: (Q, 6) gravity gradient tensor [1/s^2],
44
+ components ordered as [Vxx, Vyy, Vzz, Vxy, Vxz, Vyz].
45
+ """
46
+
47
+ eps = 1e-30
48
+
49
+ # face vertex coords: (F, 3, 3)
50
+ face_vertices = vertices[faces] # [f, vertex_idx, xyz]
51
+
52
+ # shift so each query point is at the origin: (Q, F, 3, 3)
53
+ face_vertices_rel = face_vertices[None] - computation_points[:, None, None, :]
54
+
55
+ v0 = face_vertices_rel[:, :, 0] # (Q, F, 3)
56
+ v1 = face_vertices_rel[:, :, 1]
57
+ v2 = face_vertices_rel[:, :, 2]
58
+
59
+ # ------------------------------------------------------------------ #
60
+ # Edge vectors G_pq and outward unit normal (face_normal)
61
+ # ------------------------------------------------------------------ #
62
+ edge0 = v1 - v0 # (Q, F, 3)
63
+ edge1 = v2 - v1
64
+ edge2 = v0 - v2
65
+
66
+ edges = torch.stack([edge0, edge1, edge2], dim=2) # (Q, F, 3, 3) [q,f,seg,xyz]
67
+ segment_start_points = torch.stack(
68
+ [v0, v1, v2], dim=2
69
+ ) # (Q, F, 3, 3) segment start vertices
70
+
71
+ cross_01 = torch.linalg.cross(edge0, edge1) # (Q, F, 3)
72
+ face_normal = cross_01 / cross_01.norm(dim=-1, keepdim=True).clamp(min=eps)
73
+
74
+ # ------------------------------------------------------------------ #
75
+ # Segment unit normals n_pq = (G_pq x face_normal) / |...|
76
+ # ------------------------------------------------------------------ #
77
+ face_normal_expanded = face_normal[:, :, None].expand_as(edges) # (Q, F, 3, 3)
78
+ n_pq = torch.linalg.cross(edges, face_normal_expanded)
79
+ n_pq = n_pq / n_pq.norm(dim=-1, keepdim=True).clamp(min=eps)
80
+
81
+ # ------------------------------------------------------------------ #
82
+ # Signed plane distance, plane normal orientation, projection P'
83
+ # ------------------------------------------------------------------ #
84
+ hp_signed = (face_normal * v0).sum(dim=-1) # (Q, F) = N_p . v0
85
+ h_p = hp_signed.abs()
86
+ sigma_p = hp_signed.sign() # sigma_p
87
+
88
+ plane_projection = (
89
+ hp_signed[..., None] * face_normal
90
+ ) # (Q, F, 3) P' = hp_signed * face_normal
91
+
92
+ # ------------------------------------------------------------------ #
93
+ # Segment normal orientations sigma_pq and edge distances h_pq
94
+ #
95
+ # h_pq_signed = -(n_pq . (P' - v_start)) is the signed distance from
96
+ # P' to the edge line within the face plane. Deriving both sigma_pq
97
+ # and h_pq from this single expression keeps d(n_pq)/d(v) in the
98
+ # gradient graph; the equivalent norm-based formula (||P''-P'||) shares
99
+ # the same value but its graph misses that contribution.
100
+ # ------------------------------------------------------------------ #
101
+ plane_projection_expanded = plane_projection[:, :, None].expand_as(
102
+ segment_start_points
103
+ ) # (Q, F, 3, 3)
104
+ h_pq_raw = -(n_pq * (plane_projection_expanded - segment_start_points)).sum(
105
+ dim=-1
106
+ ) # (Q, F, 3)
107
+
108
+ # Threshold relative to edge length: floating-point noise in
109
+ # normalised-vector arithmetic can produce |h_pq_raw| / edge_scale ~ 1e-16
110
+ # for algebraically-zero distances. Zeroing these before .sign() prevents
111
+ # misclassifying the singularity case (all_inside vs on_edge/on_vertex),
112
+ # which would corrupt singularity_scalar by 2-4x.
113
+ edge_length = edges.norm(dim=-1) # (Q, F, 3)
114
+ edge_scale = edge_length.amax(dim=-1, keepdim=True) # (Q, F, 1)
115
+ h_pq_signed = torch.where(
116
+ h_pq_raw.abs() < 1e-10 * edge_scale,
117
+ torch.zeros_like(h_pq_raw),
118
+ h_pq_raw,
119
+ )
120
+ sigma_pq = h_pq_signed.sign() # (Q, F, 3)
121
+ h_pq = h_pq_signed.abs() # (Q, F, 3)
122
+
123
+ # ------------------------------------------------------------------ #
124
+ # Projection parameter t along each edge (needed for s1, s2)
125
+ # ------------------------------------------------------------------ #
126
+ edge_length_sq = (edges * edges).sum(dim=-1).clamp(min=eps) # (Q, F, 3)
127
+ t_pq = ((plane_projection_expanded - segment_start_points) * edges).sum(
128
+ dim=-1
129
+ ) / edge_length_sq # (Q, F, 3)
130
+
131
+ # ------------------------------------------------------------------ #
132
+ # Distances from P (origin) to segment endpoints
133
+ # ------------------------------------------------------------------ #
134
+ segment_end_points = torch.roll(
135
+ segment_start_points, -1, dims=2
136
+ ) # v_end = v_{(q+1)%3}
137
+ l1 = segment_start_points.norm(dim=-1) # (Q, F, 3) |v_start|
138
+ l2 = segment_end_points.norm(dim=-1) # (Q, F, 3) |v_end|
139
+
140
+ # signed 1-D distances along the edge: s1 = -t*|G|, s2 = (1-t)*|G|
141
+ s1 = -t_pq * edge_length
142
+ s2 = (1.0 - t_pq) * edge_length
143
+
144
+ # ------------------------------------------------------------------ #
145
+ # Transcendental expressions LN_pq and AN_pq (Tsoulis Eqs 14-15)
146
+ # ------------------------------------------------------------------ #
147
+ ln_num = (s2 + l2).clamp(min=eps)
148
+ ln_den = (s1 + l1).clamp(min=eps)
149
+ log_term = torch.log(ln_num / ln_den)
150
+
151
+ h_p_e = h_p[:, :, None].expand_as(h_pq) # (Q, F, 3)
152
+ degenerate = (h_p_e < 1e-15) | (h_pq < 1e-15)
153
+ arctan_term = torch.atan(h_p_e * s2 / (h_pq * l2).clamp(min=eps)) - torch.atan(
154
+ h_p_e * s1 / (h_pq * l1).clamp(min=eps)
155
+ )
156
+ arctan_term = torch.where(degenerate, torch.zeros_like(arctan_term), arctan_term)
157
+
158
+ # ------------------------------------------------------------------ #
159
+ # Per-face sums S1, S2, singularity correction (Tsoulis Eqs 11-12)
160
+ # ------------------------------------------------------------------ #
161
+ sum1 = (h_pq_signed * log_term).sum(dim=-1) # (Q, F)
162
+ sum2 = (sigma_pq * arctan_term).sum(dim=-1) # (Q, F)
163
+ sum1_tensor = (n_pq * log_term[..., None]).sum(
164
+ dim=-2
165
+ ) # (Q, F, 3) for gradient tensor
166
+
167
+ # Singularity correction - three cases detected from the sigma_pq pattern:
168
+ # all +1 -> P' strictly inside face -> -2*pi*h_p
169
+ # two +1, one 0 -> P' on a face edge -> -pi*h_p
170
+ # one +1, two 0 -> P' at a face vertex -> -theta_v*h_p
171
+ n_pos = (sigma_pq > 0).sum(dim=-1) # (Q, F)
172
+ n_zero = (sigma_pq == 0).sum(dim=-1) # (Q, F)
173
+
174
+ all_inside = n_pos == 3
175
+ on_edge = (n_pos == 2) & (n_zero == 1)
176
+ on_vertex = (n_pos == 1) & (n_zero == 2)
177
+
178
+ edge_unit_vector = edges / edge_length[..., None].clamp(min=eps) # (Q, F, 3, 3)
179
+ cos_t0 = -(edge_unit_vector[..., 0, :] * edge_unit_vector[..., 2, :]).sum(
180
+ dim=-1
181
+ ) # (Q, F)
182
+ cos_t1 = -(edge_unit_vector[..., 1, :] * edge_unit_vector[..., 0, :]).sum(dim=-1)
183
+ cos_t2 = -(edge_unit_vector[..., 2, :] * edge_unit_vector[..., 1, :]).sum(dim=-1)
184
+ theta_0 = torch.acos(cos_t0.clamp(-1.0, 1.0))
185
+ theta_1 = torch.acos(cos_t1.clamp(-1.0, 1.0))
186
+ theta_2 = torch.acos(cos_t2.clamp(-1.0, 1.0))
187
+ theta_v = (
188
+ theta_2 * (sigma_pq[..., 0] > 0).to(h_p.dtype)
189
+ + theta_0 * (sigma_pq[..., 1] > 0).to(h_p.dtype)
190
+ + theta_1 * (sigma_pq[..., 2] > 0).to(h_p.dtype)
191
+ ) # (Q, F)
192
+
193
+ singularity_scalar = torch.where(
194
+ all_inside,
195
+ -2.0 * math.pi * h_p,
196
+ torch.where(
197
+ on_edge,
198
+ -math.pi * h_p,
199
+ torch.where(on_vertex, -theta_v * h_p, torch.zeros_like(h_p)),
200
+ ),
201
+ )
202
+
203
+ singularity_vector = torch.where(
204
+ all_inside[..., None],
205
+ -2.0 * math.pi * sigma_p[..., None] * face_normal,
206
+ torch.where(
207
+ on_edge[..., None],
208
+ -math.pi * sigma_p[..., None] * face_normal,
209
+ torch.where(
210
+ on_vertex[..., None],
211
+ -theta_v[..., None] * sigma_p[..., None] * face_normal,
212
+ torch.zeros_like(face_normal),
213
+ ),
214
+ ),
215
+ ) # (Q, F, 3)
216
+
217
+ face_sum = sum1 + h_p * sum2 + singularity_scalar # (Q, F) per-face scalar sum
218
+
219
+ # ------------------------------------------------------------------ #
220
+ # Sum over faces -> potential and acceleration
221
+ # ------------------------------------------------------------------ #
222
+ potential_terms = sigma_p * h_p * face_sum # (Q, F)
223
+ g_contributions = face_normal * face_sum[..., None] # (Q, F, 3)
224
+
225
+ potential = (gravitational_constant * density / 2.0) * potential_terms.sum(dim=-1)
226
+ acceleration = -gravitational_constant * density * g_contributions.sum(dim=-2)
227
+
228
+ # ------------------------------------------------------------------ #
229
+ # Gradient tensor (Tsoulis Eq. 13)
230
+ # ------------------------------------------------------------------ #
231
+ tensor_subterm = (
232
+ sum1_tensor + face_normal * (sigma_p * sum2)[..., None] + singularity_vector
233
+ ) # (Q, F, 3)
234
+
235
+ # diagonal components: Vxx, Vyy, Vzz -> face_normal[i] * tensor_subterm[i]
236
+ diag = face_normal * tensor_subterm # (Q, F, 3)
237
+ # off-diagonal: Vxy=N[0]*sub[1], Vxz=N[0]*sub[2], Vyz=N[1]*sub[2]
238
+ offdiag_normal = torch.stack(
239
+ [face_normal[..., 0], face_normal[..., 0], face_normal[..., 1]], dim=-1
240
+ )
241
+ offdiag_subterm = torch.stack(
242
+ [tensor_subterm[..., 1], tensor_subterm[..., 2], tensor_subterm[..., 2]], dim=-1
243
+ )
244
+ offdiag = offdiag_normal * offdiag_subterm # (Q, F, 3)
245
+
246
+ tensor = (
247
+ gravitational_constant
248
+ * density
249
+ * torch.cat([diag, offdiag], dim=-1).sum(dim=-2)
250
+ ) # (Q, 6)
251
+
252
+ return potential, acceleration, tensor
@@ -111,12 +111,12 @@ class CMakeBuild(build_ext):
111
111
  if not extdir.endswith(os.path.sep):
112
112
  extdir += os.path.sep
113
113
 
114
- # Set Python_EXECUTABLE instead if you use PYBIND11_FINDPYTHON
115
- # EXAMPLE_VERSION_INFO shows you how to pass a value into the C++ code
116
- # from Python.
114
+ # We use PYBIND11_FINDPYTHON, i.e. CMake's FindPython, which only respects Python_EXECUTABLE.
115
+ # Without it, FindPython searches on its own and does not find free-threaded interpreters
116
+ # (e.g. python3.14t), picking up any other Python on the system instead (wrong ABI/extension suffix).
117
117
  cmake_args = [
118
118
  f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}",
119
- f"-DPYTHON_EXECUTABLE={sys.executable}",
119
+ f"-DPython_EXECUTABLE={sys.executable}",
120
120
  ]
121
121
  build_args = []
122
122
 
@@ -157,7 +157,9 @@ class CMakeBuild(build_ext):
157
157
  # MSVC special cases
158
158
  if self.compiler.compiler_type == "msvc":
159
159
  # Single config generators are handled "normally"
160
- single_config = any(x in cmake_generator for x in {"NMake", "Ninja"})
160
+ single_config = cmake_generator is not None and any(
161
+ x in cmake_generator for x in {"NMake", "Ninja"}
162
+ )
161
163
  # Multi-config generators have a different way to specify configs
162
164
  if not single_config:
163
165
  cmake_args += [
@@ -217,7 +219,9 @@ setup(
217
219
  "according to the geodetic convention",
218
220
  long_description=open("README.md").read().replace(picture_in_readme, ''),
219
221
  long_description_content_type="text/markdown",
220
- ext_modules=[CMakeExtension("polyhedral_gravity")],
222
+ ext_modules=[CMakeExtension("polyhedral_gravity._core")],
223
+ packages=["polyhedral_gravity"],
224
+ package_dir={"polyhedral_gravity": "python/polyhedral_gravity"},
221
225
  cmdclass={"build_ext": CMakeBuild},
222
226
  license="GPLv3",
223
227
  license_file="LICENSE",
@@ -54,11 +54,11 @@ if(BUILD_POLYHEDRAL_GRAVITY_PYTHON_INTERFACE)
54
54
 
55
55
  add_subdirectory(polyhedralGravityPython)
56
56
 
57
- target_include_directories(polyhedral_gravity PUBLIC
57
+ target_include_directories(_core PUBLIC
58
58
  "${CMAKE_CURRENT_SOURCE_DIR}"
59
59
  )
60
60
 
61
- target_link_libraries(polyhedral_gravity PUBLIC
61
+ target_link_libraries(_core PUBLIC
62
62
  spdlog::spdlog
63
63
  tetgen_lib
64
64
  xsimd
@@ -0,0 +1,125 @@
1
+ #include "MeshReader.h"
2
+
3
+ #include "TetgenAdapter.h"
4
+ #include "polyhedralGravity/util/UtilityString.h"
5
+
6
+ namespace polyhedralGravity {
7
+
8
+ namespace {
9
+ std::string malformedLineMessage(const std::string &filename, size_t lineNumber, const std::string &line,
10
+ const std::string &reason) {
11
+ std::stringstream sstream{};
12
+ sstream << "Malformed line " << lineNumber << " in file '" << filename << "': \"" << line << "\". " << reason;
13
+ return sstream.str();
14
+ }
15
+
16
+ /**
17
+ * Parses a single vertex index of a face definition. Accepts the plain index as well as the
18
+ * v/vt/vn notation of the OBJ format, of which only the vertex part is relevant here.
19
+ */
20
+ size_t parseObjVertexIndex(const std::string &token, const std::string &filename, size_t lineNumber,
21
+ const std::string &line) {
22
+ const std::string vertexPart = token.substr(0, token.find('/'));
23
+ size_t charactersParsed = 0;
24
+ long long index = 0;
25
+ try {
26
+ index = std::stoll(vertexPart, &charactersParsed);
27
+ } catch (const std::logic_error &) {
28
+ throw std::runtime_error(malformedLineMessage(filename, lineNumber, line,
29
+ "The vertex index '" + token + "' is not an integer."));
30
+ }
31
+ if (charactersParsed != vertexPart.size()) {
32
+ throw std::runtime_error(malformedLineMessage(filename, lineNumber, line,
33
+ "The vertex index '" + token + "' is not an integer."));
34
+ }
35
+ // Relative (negative) indices of the OBJ format are unsupported and must not wrap around when cast
36
+ if (index < 0) {
37
+ throw std::runtime_error(malformedLineMessage(filename, lineNumber, line,
38
+ "The vertex index '" + token + "' is negative. Relative vertex "
39
+ "indices are not supported."));
40
+ }
41
+ return static_cast<size_t>(index);
42
+ }
43
+ }
44
+
45
+ PolyhedralSource MeshReader::getPolyhedralSource(const std::vector<std::string> &fileNames) {
46
+ // Input Sanity Check if the files exists
47
+ for (const auto &fileName: fileNames) {
48
+ if (!std::filesystem::exists(fileName)) {
49
+ throw std::runtime_error("File '" + fileName + "' does not exist.");
50
+ }
51
+ }
52
+ switch (fileNames.size()) {
53
+ case 0:
54
+ throw std::runtime_error("No mesh file given");
55
+ case 1:
56
+ if (util::ends_with(fileNames[0], ".obj", ".tab")) {
57
+ return readObj(fileNames[0]);
58
+ } else {
59
+ // The TetGen Adapter complains if the suffix is unknown
60
+ // No need to check for suffices here, as this happens later anyway
61
+ return readTetgenFormat(fileNames);
62
+ }
63
+ case 2:
64
+ // The TetGen Adapter complains if the suffix is unknown
65
+ // No need to check for suffices here, as this happens later anyway
66
+ return readTetgenFormat(fileNames);
67
+ default:
68
+ throw std::invalid_argument("More than two mesh files given. There is no known mesh-format consisting of three files. "
69
+ "The polyhedron will be over-specified!");
70
+ }
71
+ }
72
+
73
+ PolyhedralSource MeshReader::readTetgenFormat(const std::vector<std::string> &fileNames) {
74
+ return TetgenAdapter{fileNames}.getPolyhedralSource();
75
+ }
76
+
77
+ PolyhedralSource MeshReader::readObj(const std::string &filename) {
78
+ std::vector<Array3> vertices{};
79
+ std::vector<IndexArray3> faces{};
80
+ POLYHEDRAL_GRAVITY_LOG_DEBUG("Reading the file {}", filename);
81
+ std::ifstream file(filename);
82
+ if (!file) {
83
+ throw std::runtime_error("Could not open file " + filename + " for reading.");
84
+ }
85
+ std::string line;
86
+ size_t lineNumber = 0;
87
+ while (std::getline(file, line)) {
88
+ ++lineNumber;
89
+ std::stringstream ss(line);
90
+ std::string keyword;
91
+ // Skips empty lines, whitespace-only lines and comments
92
+ if (!(ss >> keyword) || keyword[0] == '#') {
93
+ continue;
94
+ }
95
+
96
+ if (keyword == "v") {
97
+ Array3 vertex{};
98
+ if (!(ss >> vertex[0] >> vertex[1] >> vertex[2])) {
99
+ throw std::runtime_error(malformedLineMessage(filename, lineNumber, line,
100
+ "A vertex (v) requires three numeric coordinates."));
101
+ }
102
+ vertices.push_back(vertex);
103
+ } else if (keyword == "f") {
104
+ IndexArray3 face{};
105
+ std::string token;
106
+ for (size_t i = 0; i < 3; ++i) {
107
+ if (!(ss >> token)) {
108
+ throw std::runtime_error(malformedLineMessage(filename, lineNumber, line,
109
+ "A face (f) requires three vertex indices since only triangular meshes are supported."));
110
+ }
111
+ face[i] = parseObjVertexIndex(token, filename, lineNumber, line);
112
+ }
113
+ // A fourth index would silently be dropped and yield a different mesh than the file describes
114
+ if (ss >> token) {
115
+ throw std::runtime_error(malformedLineMessage(filename, lineNumber, line,
116
+ "A face (f) references more than three vertices, but only triangular meshes are supported."));
117
+ }
118
+ faces.push_back(face);
119
+ }
120
+ // Every other keyword (vn, vt, vp, g, o, s, usemtl, ...) carries no information for the gravity model
121
+ }
122
+ file.close();
123
+ return {vertices, faces};
124
+ }
125
+ }
@@ -31,12 +31,14 @@ namespace polyhedralGravity {
31
31
 
32
32
  /**
33
33
  * Reads elements from a .obj file (Wavefront OBJ file format)
34
- * This method only supports vertex (v) and faces (f) as input.
34
+ * This method only supports vertex (v) and faces (f) as input. Every other keyword is ignored.
35
+ * Faces must be triangular and must reference their vertices by a non-negative index.
35
36
  *
36
37
  * This is also the file format of polyhedrons in some datasets, e.g.,in
37
38
  * https://pds.nasa.gov/ds-view/pds/viewDataset.jsp?dsid=EAR-A-5-DDR-RADARSHAPE-MODELS-V2.0
38
39
  * However, the suffix for these files is .tab
39
40
  * @param filename of the input source without suffix
41
+ * @throws std::runtime_error if the file cannot be opened or contains a malformed vertex or face
40
42
  * @see Refer to https://de.wikipedia.org/wiki/Wavefront_OBJ for further help with the format
41
43
  */
42
44
  PolyhedralSource readObj(const std::string &filename);
@@ -337,7 +337,9 @@ namespace polyhedralGravity::GravityModel::detail {
337
337
 
338
338
  const double segmentVectorNorm = euclideanNorm(segmentVector);
339
339
  return projectionPointVertexNorms[(j + 1) % 3] < segmentVectorNorm &&
340
- projectionPointVertexNorms[j] < segmentVectorNorm;
340
+ projectionPointVertexNorms[j] < segmentVectorNorm &&
341
+ projectionPointVertexNorms[(j + 1) % 3] >= EPSILON_ZERO_OFFSET &&
342
+ projectionPointVertexNorms[j] >= EPSILON_ZERO_OFFSET;
341
343
  })) {
342
344
  using namespace util;
343
345
  return std::make_pair(-1.0 * util::PI * planeDistance, //sing alpha = -pi*h_p
@@ -369,8 +371,8 @@ namespace polyhedralGravity::GravityModel::detail {
369
371
  })) {
370
372
  using namespace util;
371
373
  //Two segment vectors G_1 and G_2 of this plane
372
- const Array3 &g1 = r1Norm == 0.0 ? segmentVectorsForPlane[j] : segmentVectorsForPlane[(j - 1 + 3) % 3];
373
- const Array3 &g2 = r1Norm == 0.0 ? segmentVectorsForPlane[(j + 1) % 3] : segmentVectorsForPlane[j];
374
+ const Array3 &g1 = r1Norm < EPSILON_ZERO_OFFSET ? segmentVectorsForPlane[j] : segmentVectorsForPlane[(j - 1 + 3) % 3];
375
+ const Array3 &g2 = r1Norm < EPSILON_ZERO_OFFSET ? segmentVectorsForPlane[(j + 1) % 3] : segmentVectorsForPlane[j];
374
376
  // theta = arcos((G_2 * -G_1) / (|G_2| * |G_1|))
375
377
  const double gdot = dot(g1 * -1.0, g2);
376
378
  const double theta = gdot == 0.0 ? util::PI_2 : std::acos(gdot / (euclideanNorm(g1) * euclideanNorm(g2)));
@@ -19,6 +19,8 @@ namespace polyhedralGravity {
19
19
  POLYHEDRAL_GRAVITY_LOG_DEBUG("The indexing of the polyhedron's vertices seems to start at 1 instead of 0. The faces array is modfied accordingly!");
20
20
  std::transform(_faces.begin(), _faces.end(), _faces.begin(), [&](const std::array<size_t, 3> &face) {return face - 1;});
21
21
  }
22
+ // Must happen before any face index is resolved to a vertex (including the integrity measures below)
23
+ this->checkVertexIndicesInRange();
22
24
  this->runIntegrityMeasures(integrity);
23
25
  }
24
26
 
@@ -170,6 +172,21 @@ namespace polyhedralGravity {
170
172
  }
171
173
  }
172
174
 
175
+ void Polyhedron::checkVertexIndicesInRange() const {
176
+ const size_t numberOfVertices = _vertices.size();
177
+ for (size_t faceIndex = 0; faceIndex < _faces.size(); ++faceIndex) {
178
+ for (const size_t vertexIndex: _faces[faceIndex]) {
179
+ if (vertexIndex >= numberOfVertices) {
180
+ std::stringstream sstream{};
181
+ sstream << "The face with index " << faceIndex << " references the vertex index " << vertexIndex
182
+ << ", but the mesh only contains " << numberOfVertices << " vertices. "
183
+ << "The mesh is malformed and cannot be used to construct a polyhedron!";
184
+ throw std::invalid_argument(sstream.str());
185
+ }
186
+ }
187
+ }
188
+ }
189
+
173
190
  void Polyhedron::runIntegrityMeasures(const PolyhedronIntegrity &integrity) {
174
191
  using util::operator<<;
175
192
  switch (integrity) {
@@ -298,6 +298,15 @@ namespace polyhedralGravity {
298
298
  [[nodiscard]] std::pair<NormalOrientation, std::set<size_t>> checkPlaneUnitNormalOrientation() const;
299
299
 
300
300
  private:
301
+ /**
302
+ * Checks that every face references only existing vertices, i.e. that every vertex index is
303
+ * smaller than the number of vertices. This check is mandatory and always executed at construction time
304
+ * since resolving an out-of-range index would otherwise cause an out-of-bounds read.
305
+ *
306
+ * @throws std::invalid_argument if a face references a non-existing vertex
307
+ */
308
+ void checkVertexIndicesInRange() const;
309
+
301
310
  /**
302
311
  * Checks the integrity of the polyhedron depending on the integrity flag.
303
312
  *
@@ -7,14 +7,14 @@ file(GLOB_RECURSE PYTHON_INTERFACE_SRC
7
7
  )
8
8
  list(FILTER PYTHON_INTERFACE_SRC EXCLUDE REGEX ".*YAML.*")
9
9
 
10
- pybind11_add_module(polyhedral_gravity ${PYTHON_INTERFACE_SRC} PolyhedralGravityPython.cpp)
10
+ pybind11_add_module(_core ${PYTHON_INTERFACE_SRC} PolyhedralGravityPython.cpp)
11
11
 
12
12
  # Checks if MinGW is used, in this case, the .dll of the the standard library need to be linked statically to the
13
13
  # Python interface since otherwise they won't be found
14
14
  # https://github.com/pybind/pybind11/issues/2010 and https://cython.readthedocs.io/en/latest/src/tutorial/appendix.html
15
15
  if(WIN32 AND ${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU")
16
16
  message(STATUS "Compiler is GNU, Platform is Windows, Linking libaries statically to the Python interface")
17
- target_link_libraries(polyhedral_gravity PUBLIC
17
+ target_link_libraries(_core PUBLIC
18
18
  -static-libgcc
19
19
  -static-libstdc++
20
20
  -W
@@ -15,7 +15,7 @@
15
15
 
16
16
  namespace py = pybind11;
17
17
 
18
- PYBIND11_MODULE(polyhedral_gravity, m, py::mod_gil_not_used()) {
18
+ PYBIND11_MODULE(_core, m, py::mod_gil_not_used()) {
19
19
  using namespace polyhedralGravity;
20
20
  m.doc() = R"mydelimiter(
21
21
  The evaluation of the polyhedral gravity model requires the following parameters:
@@ -1,3 +0,0 @@
1
- include CMakeLists.txt
2
- recursive-include src *
3
- recursive-include cmake *
@@ -1,69 +0,0 @@
1
- #include "MeshReader.h"
2
-
3
- #include "TetgenAdapter.h"
4
- #include "polyhedralGravity/util/UtilityString.h"
5
-
6
- namespace polyhedralGravity {
7
-
8
- PolyhedralSource MeshReader::getPolyhedralSource(const std::vector<std::string> &fileNames) {
9
- // Input Sanity Check if the files exists
10
- for (const auto &fileName: fileNames) {
11
- if (!std::filesystem::exists(fileName)) {
12
- throw std::runtime_error("File '" + fileName + "' does not exist.");
13
- }
14
- }
15
- switch (fileNames.size()) {
16
- case 0:
17
- throw std::runtime_error("No mesh file given");
18
- case 1:
19
- if (util::ends_with(fileNames[0], ".obj", ".tab")) {
20
- return readObj(fileNames[0]);
21
- } else {
22
- // The TetGen Adapter complains if the suffix is unknown
23
- // No need to check for suffices here, as this happens later anyway
24
- return readTetgenFormat(fileNames);
25
- }
26
- case 2:
27
- // The TetGen Adapter complains if the suffix is unknown
28
- // No need to check for suffices here, as this happens later anyway
29
- return readTetgenFormat(fileNames);
30
- default:
31
- throw std::invalid_argument("More than two mesh files given. There is no known mesh-format consisting of three files. "
32
- "The polyhedron will be over-specified!");
33
- }
34
- }
35
-
36
- PolyhedralSource MeshReader::readTetgenFormat(const std::vector<std::string> &fileNames) {
37
- return TetgenAdapter{fileNames}.getPolyhedralSource();
38
- }
39
-
40
- PolyhedralSource MeshReader::readObj(const std::string &filename) {
41
- std::vector<Array3> vertices{};
42
- std::vector<IndexArray3> faces{};
43
- POLYHEDRAL_GRAVITY_LOG_DEBUG("Reading the file {}", filename);
44
- std::ifstream file(filename);
45
- if (!file) {
46
- throw std::runtime_error("Could not open file " + filename + " for reading.");
47
- }
48
- std::string line;
49
- char prefix;
50
- std::array<double, 3> vertex{};
51
- std::array<size_t, 3> face{};
52
- while (std::getline(file, line)) {
53
- std::stringstream ss(line);
54
- if (line.empty() || line[0] == '#') {
55
- continue;
56
- }
57
-
58
- if (line[0] == 'v') {
59
- ss >> prefix >> vertex[0] >> vertex[1] >> vertex[2];
60
- vertices.push_back(vertex);
61
- } else if (line[0] == 'f') {
62
- ss >> prefix >> face[0] >> face[1] >> face[2];
63
- faces.push_back(face);
64
- }
65
- }
66
- file.close();
67
- return {vertices, faces};
68
- }
69
- }