diff --git a/geoana/em/static/__init__.py b/geoana/em/static/__init__.py index 9212bc48..562a6691 100644 --- a/geoana/em/static/__init__.py +++ b/geoana/em/static/__init__.py @@ -24,6 +24,8 @@ PointCurrentHalfSpace DipoleHalfSpace MagneticPrism + MagneticPolyhedron + MagneticTetrahedron """ from geoana.em.static.sphere import ( @@ -44,7 +46,11 @@ DipoleHalfSpace ) -from geoana.em.static.freespace import MagneticPrism +from geoana.em.static.freespace import ( + MagneticPrism, + MagneticPolyhedron, + MagneticTetrahedron, +) LineCurrentFreeSpace = LineCurrentWholeSpace diff --git a/geoana/em/static/freespace.py b/geoana/em/static/freespace.py index 810efead..95445f51 100644 --- a/geoana/em/static/freespace.py +++ b/geoana/em/static/freespace.py @@ -3,7 +3,7 @@ from ..base import BaseLineCurrent from geoana.utils import check_xyz_dim -from geoana.shapes import BasePrism +from geoana.shapes import BasePrism, BasePolyhedron, BaseTetrahedron from geoana.kernels import ( prism_fz, prism_fzz, @@ -17,6 +17,8 @@ __all__ = [ "MagneticPrism", + "MagneticPolyhedron", + "MagneticTetrahedron", ] class MagneticPrism(BasePrism): @@ -147,11 +149,17 @@ def magnetic_flux_density(self, xyz): """ xyz = check_xyz_dim(xyz) H = self.magnetic_field(xyz) - is_inside = ( - np.all(xyz >= self.min_location, axis=-1) - & np.all(xyz <= self.max_location, axis=-1) + # Fraction of a small sphere about each point that lies inside the prism: + # 1 inside, 1/2 on a face, 1/4 on an edge, 1/8 at a corner. On the + # surface this makes the normal component of B exact (it is continuous) + # and the tangential component the mean of its limits from either side, + # consistent with H there. + lo, hi = self.min_location, self.max_location + per_axis = np.where( + (xyz > lo) & (xyz < hi), 1.0, np.where((xyz == lo) | (xyz == hi), 0.5, 0.0) ) - H[is_inside] = H[is_inside] + self.magnetization + inside = np.prod(per_axis, axis=-1) + H += inside[..., None] * self.magnetization return mu_0 * H @@ -198,3 +206,135 @@ def magnetic_field_gradient(self, xyz): H_grad = - 1.0/(4 * np.pi) * np.stack((first, second, third), axis=-1) return H_grad + + +class _PolyhedronMagnetics: + """Magnetostatic solutions shared by the uniformly magnetized polyhedral shapes. + + By Poisson's relation, the field of a uniformly magnetized body is the + Hessian of the Newtonian integral contracted with the magnetization, + :math:`\\mathbf{H} = \\frac{1}{4\\pi}(\\nabla\\nabla V)\\cdot\\mathbf{M}`, + with :math:`V` evaluated in closed form by + :class:`geoana.shapes.BasePolyhedron`. + """ + + @property + def magnetization(self): + return self._magnetization + + @magnetization.setter + def magnetization(self, vec): + try: + vec = np.asarray(vec, dtype=float) + except: + raise TypeError(f"magnetization must be array_like of float, got {type(vec)}") + vec = np.squeeze(vec) + if vec.shape != (3,): + raise ValueError( + f"magnetization must be array_like with shape (3,), got {vec.shape}" + ) + self._magnetization = vec + + @property + def moment(self): + return self.volume * self.magnetization + + def scalar_potential(self, xyz): + """ + Magnetic scalar potential due to the body. Defined such that + :math:`H = \\nabla \\phi`. + + Parameters + ---------- + xyz : (..., 3) numpy.ndarray + Observation locations in units m. + + Returns + ------- + (...) numpy.ndarray + Magnetic scalar potential at location xyz in units :math:`A`. + """ + xyz = check_xyz_dim(xyz) + return 1.0 / (4 * np.pi) * self._newtonian_integrals(xyz, 1) @ self.magnetization + + def magnetic_field(self, xyz): + """ + Magnetic field due to the body. + + Parameters + ---------- + xyz : (..., 3) numpy.ndarray + Observation locations in units m. + + Returns + ------- + (..., 3) numpy.ndarray + Magnetic field at location xyz in units :math:`\\frac{A}{m}`. + """ + xyz = check_xyz_dim(xyz) + return 1.0 / (4 * np.pi) * self._newtonian_integrals(xyz, 2) @ self.magnetization + + def magnetic_flux_density(self, xyz): + """ + Magnetic flux density due to the body. + + Parameters + ---------- + xyz : (..., 3) numpy.ndarray + Observation locations in units m. + + Returns + ------- + (..., 3) numpy.ndarray + Magnetic flux density at location xyz in units :math:`T`. + """ + xyz = check_xyz_dim(xyz) + H = self.magnetic_field(xyz) + # Weighted by the fraction of a small sphere about each point inside the + # body (1/2 on a face), as for MagneticPrism. + H += self._inside_fraction(xyz)[..., None] * self.magnetization + return mu_0 * H + + +class MagneticPolyhedron(_PolyhedronMagnetics, BasePolyhedron): + """Class for magnetic field solutions for a polyhedron. + + The ``MagneticPolyhedron`` class is used to analytically compute the + magnetic potentials and fields of a closed polyhedron with triangular faces + and constant magnetization. See :class:`geoana.shapes.BasePolyhedron` for + the requirements on ``faces``. + + Parameters + ---------- + vertices : (n_vertices, 3) array_like of float + Vertex locations. + faces : (n_faces, 3) array_like of int + Vertex indices of each triangular face of a closed, consistently + oriented surface. + magnetization : (3,) array_like, optional + Magnetization of the body (:math:`\\frac{A}{m}`). + """ + + def __init__(self, vertices, faces, magnetization=None): + if magnetization is None: + magnetization = np.r_[0.0, 0.0, 1.0] + self.magnetization = magnetization + super().__init__(vertices=vertices, faces=faces) + + +class MagneticTetrahedron(_PolyhedronMagnetics, BaseTetrahedron): + """Class for magnetic field solutions for a tetrahedron. + + Parameters + ---------- + vertices : (4, 3) array_like of float + The four vertex locations, in any order. + magnetization : (3,) array_like, optional + Magnetization of the tetrahedron (:math:`\\frac{A}{m}`). + """ + + def __init__(self, vertices, magnetization=None): + if magnetization is None: + magnetization = np.r_[0.0, 0.0, 1.0] + self.magnetization = magnetization + super().__init__(vertices=vertices) diff --git a/geoana/gravity.py b/geoana/gravity.py index 5441f5b9..bed664e7 100644 --- a/geoana/gravity.py +++ b/geoana/gravity.py @@ -15,18 +15,22 @@ PointMass Sphere Prism + Polyhedron + Tetrahedron """ import numpy as np from scipy.constants import G from geoana.utils import check_xyz_dim -from geoana.shapes import BasePrism +from geoana.shapes import BasePrism, BasePolyhedron, BaseTetrahedron from geoana.kernels import prism_f, prism_fz, prism_fzx, prism_fzy, prism_fzz __all__ = [ "PointMass", "Sphere", "Prism", + "Polyhedron", + "Tetrahedron", ] class PointMass: @@ -692,3 +696,131 @@ def gravitational_gradient(self, xyz): third = np.stack([gxz, gyz, gzz], axis=-1) return - G * self.rho * np.stack([first, second, third], axis=-1) + + +class _PolyhedronGravity: + """Gravitational solutions shared by the polyhedral shapes.""" + + @property + def rho(self): + """ The density of the body. + + Returns + ------- + density : float + In :math:`\\frac{kg}{m^3}`. + """ + return self._rho + + @rho.setter + def rho(self, value): + try: + value = float(value) + except: + raise TypeError(f"rho must be a number, got {type(value)}") + self._rho = value + + @property + def mass(self): + """ The mass of the body + + Returns + ------- + mass : float + In :math:`kg`. + """ + return self.volume * self.rho + + def gravitational_potential(self, xyz): + """ + Gravitational potential due to the body. + + Parameters + ---------- + xyz : (..., 3) numpy.ndarray + Observation locations in units m. + + Returns + ------- + (..., ) numpy.ndarray + Gravitational potential at location xyz in units :math:`\\frac{m^2}{s^2}`. + """ + xyz = check_xyz_dim(xyz) + return G * self.rho * self._newtonian_integrals(xyz, 0) + + def gravitational_field(self, xyz): + """ + Gravitational field due to the body. + + Parameters + ---------- + xyz : (..., 3) numpy.ndarray + Observation locations in units m. + + Returns + ------- + (..., 3) numpy.ndarray + Gravitational field at location xyz in units :math:`\\frac{m}{s^2}`. + """ + xyz = check_xyz_dim(xyz) + return G * self.rho * self._newtonian_integrals(xyz, 1) + + def gravitational_gradient(self, xyz): + """ + Gravitational gradient due to the body. + + Parameters + ---------- + xyz : (..., 3) numpy.ndarray + Observation locations in units m. + + Returns + ------- + (..., 3, 3) numpy.ndarray + Gravitational gradient at location xyz in units :math:`\\frac{1}{s^2}`. + """ + xyz = check_xyz_dim(xyz) + return G * self.rho * self._newtonian_integrals(xyz, 2) + + +class Polyhedron(_PolyhedronGravity, BasePolyhedron): + """Class for gravitational solutions for a polyhedron. + + The ``Polyhedron`` class is used to analytically compute the gravitational + potentials, fields, and gradients of a closed polyhedron with triangular + faces and constant density. See :class:`geoana.shapes.BasePolyhedron` for the + closed-form expressions and the requirements on ``faces``. + + Parameters + ---------- + vertices : (n_vertices, 3) array_like of float + Vertex locations. + faces : (n_faces, 3) array_like of int + Vertex indices of each triangular face of a closed, consistently + oriented surface. + rho : float, optional + Density of the body (:math:`\\frac{kg}{m^3}`). + """ + + def __init__(self, vertices, faces, rho=1.0): + self.rho = rho + super().__init__(vertices=vertices, faces=faces) + + +class Tetrahedron(_PolyhedronGravity, BaseTetrahedron): + """Class for gravitational solutions for a tetrahedron. + + The ``Tetrahedron`` class is used to analytically compute the gravitational + potentials, fields, and gradients of a tetrahedron with constant density. + + Parameters + ---------- + vertices : (4, 3) array_like of float + The four vertex locations, in any order. + rho : float, optional + Density of the tetrahedron (:math:`\\frac{kg}{m^3}`). + """ + + def __init__(self, vertices, rho=1.0): + self.rho = rho + super().__init__(vertices=vertices) diff --git a/geoana/kernels/__init__.py b/geoana/kernels/__init__.py index b94aef5a..888ed6a8 100644 --- a/geoana/kernels/__init__.py +++ b/geoana/kernels/__init__.py @@ -29,6 +29,21 @@ prism_fxxz prism_fxyz +Polyhedron Integral Kernels +=========================== +Pointwise terms of the closed-form 1/r volume integrals of polyhedra +(Werner and Scheeres, 1996), and those integrals over tetrahedra, which +broadcast over tetrahedra and observation points alike. + +.. autosummary:: + :toctree: generated/ + + polyhedron_edge_log + triangle_solid_angle + face_edge_solid_angle + tetrahedron_integrals + tetrahedron_inside_fraction + Layered Electromagnetic Reflection Kernels ========================================== .. autosummary:: @@ -50,3 +65,10 @@ prism_fxxz, prism_fxyz, ) +from geoana.kernels.potential_field_polyhedron import ( + polyhedron_edge_log, + triangle_solid_angle, + face_edge_solid_angle, + tetrahedron_integrals, + tetrahedron_inside_fraction, +) diff --git a/geoana/kernels/_extensions/__init__.py b/geoana/kernels/_extensions/__init__.py index 0b1da38d..f69be0aa 100644 --- a/geoana/kernels/_extensions/__init__.py +++ b/geoana/kernels/_extensions/__init__.py @@ -50,5 +50,28 @@ def f(x, y, z): for func in funcs: _numba_register_prism_func(func) + from .potential_field_polyhedron import ( + polyhedron_edge_log, + triangle_solid_angle, + face_edge_solid_angle, + ) + + def _numba_register_polyhedron_func(func, n_args): + module = 'geoana.kernels._extensions.potential_field_polyhedron' + func_address = get_cython_function_address(module, func.__name__) + func_type = ctypes.CFUNCTYPE(ctypes.c_double, *([ctypes.c_double] * n_args)) + c_func = func_type(func_address) + + @overload(func) + def numba_func(*args): + if len(args) == n_args and all(isinstance(a, types.Float) for a in args): + def f(*args): + return c_func(*args) + return f + + _numba_register_polyhedron_func(polyhedron_edge_log, 6) + _numba_register_polyhedron_func(triangle_solid_angle, 9) + _numba_register_polyhedron_func(face_edge_solid_angle, 10) + except ImportError as err: pass \ No newline at end of file diff --git a/geoana/kernels/_extensions/meson.build b/geoana/kernels/_extensions/meson.build index d50189cf..a41536ac 100644 --- a/geoana/kernels/_extensions/meson.build +++ b/geoana/kernels/_extensions/meson.build @@ -67,6 +67,22 @@ py.extension_module( dependencies : [py_dep, np_dep], ) +# The polyhedron kernels rely on swapping an edge's end points exactly negating +# a cross product, so that faces sharing an edge cancel; fused multiply-adds +# would break that. +polyhedron_c_args = cython_c_args + cc.get_supported_arguments('-ffp-contract=off') + +py.extension_module( + 'potential_field_polyhedron', + 'potential_field_polyhedron.pyx', + cython_args: cython_args, + c_args: polyhedron_c_args, + install: true, + subdir: module_path, + limited_api: limited_api, + dependencies : [py_dep, np_dep], +) + py.extension_module( 'rTE', ['rTE.pyx', '_rTE.cpp'], diff --git a/geoana/kernels/_extensions/potential_field_polyhedron.pyx b/geoana/kernels/_extensions/potential_field_polyhedron.pyx new file mode 100644 index 00000000..71b405ed --- /dev/null +++ b/geoana/kernels/_extensions/potential_field_polyhedron.pyx @@ -0,0 +1,178 @@ +# cython: freethreading_compatible = True +# cython: language_level=3 +# cython: embedsignature=True +cimport cython + +from libc.math cimport sqrt, log, atan2, INFINITY + +@cython.cdivision +@cython.ufunc +cdef api double polyhedron_edge_log( + double x1, double y1, double z1, + double x2, double y2, double z2, +) nogil: + """Evaluates the line integral of 1/r along a straight edge. + + This is the edge term of the closed-form volume integrals of polyhedra + (Werner and Scheeres, 1996): ln((r1 + r2 + l) / (r1 + r2 - l)), for the + edge whose end points are at (x1, y1, z1) and (x2, y2, z2) relative to the + observation point. + + Parameters + ---------- + x1, y1, z1, x2, y2, z2 : (...) numpy.ndarray + Locations of the edge's two end points relative to the observation + point. + + Returns + ------- + (...) numpy.ndarray + Infinite where the observation point lies on the edge. + + Notes + ----- + r1 + r2 - l cancels catastrophically near the edge and near its end + points, so it is instead evaluated as 2 (r1 r2 + r1 . r2) / (r1 + r2 + l) + when r1 . r2 >= 0, and as 2 |r1 x r2|^2 / ((r1 r2 - r1 . r2)(r1 + r2 + l)) + otherwise, which are exact algebraically and free of cancellation. + """ + cdef: + double n1 = sqrt(x1 * x1 + y1 * y1 + z1 * z1) + double n2 = sqrt(x2 * x2 + y2 * y2 + z2 * z2) + double dx = x2 - x1, dy = y2 - y1, dz = z2 - z1 + double length = sqrt(dx * dx + dy * dy + dz * dz) + double dot = x1 * x2 + y1 * y2 + z1 * z2 + double s = n1 + n2 + double cx, cy, cz, num, den, diff + if n1 == 0.0 or n2 == 0.0: + # At an end point. + return INFINITY + # Choose the numerator and denominator, then divide once: compilers may + # evaluate both branches, and the untaken one can be 0 / 0. + if dot >= 0.0: + num = n1 * n2 + dot + den = 1.0 + else: + cx = y1 * z2 - z1 * y2 + cy = z1 * x2 - x1 * z2 + cz = x1 * y2 - y1 * x2 + num = cx * cx + cy * cy + cz * cz + den = n1 * n2 - dot + diff = 2.0 * num / (den * (s + length)) + if diff > 0.0: + return log((s + length) / diff) + return INFINITY + +@cython.cdivision +@cython.ufunc +cdef api double triangle_solid_angle( + double x1, double y1, double z1, + double x2, double y2, double z2, + double x3, double y3, double z3, +) nogil: + """Evaluates the signed solid angle subtended by a triangle. + + Uses the formula of van Oosterom and Strackee (1983) for the triangle whose + vertices are given relative to the observation point. The sign is positive + when the vertices appear counterclockwise from the observation point. + + Parameters + ---------- + x1, y1, z1, x2, y2, z2, x3, y3, z3 : (...) numpy.ndarray + Vertex locations relative to the observation point. + + Returns + ------- + (...) numpy.ndarray + Solid angle in steradians, in [-2 pi, 2 pi]. Zero when the observation + point is in the triangle's plane, including on the triangle itself, + where zero is the mean of the limits from either side. + """ + cdef: + double n1 = sqrt(x1 * x1 + y1 * y1 + z1 * z1) + double n2 = sqrt(x2 * x2 + y2 * y2 + z2 * z2) + double n3 = sqrt(x3 * x3 + y3 * y3 + z3 * z3) + double num, den + num = ( + x1 * (y2 * z3 - z2 * y3) + + y1 * (z2 * x3 - x2 * z3) + + z1 * (x2 * y3 - y2 * x3) + ) + den = ( + n1 * n2 * n3 + + n1 * (x2 * x3 + y2 * y3 + z2 * z3) + + n2 * (x3 * x1 + y3 * y1 + z3 * z1) + + n3 * (x1 * x2 + y1 * y2 + z1 * z2) + ) + if num == 0.0: + return 0.0 + return 2.0 * atan2(num, den) + +@cython.cdivision +@cython.ufunc +cdef api double face_edge_solid_angle( + double x1, double y1, double z1, + double x2, double y2, double z2, + double nx, double ny, double nz, + double h, +) nogil: + """Evaluates the signed solid angle subtended by one edge of a planar face. + + This is the solid angle of the triangle formed by the edge and the foot of + the perpendicular from the observation point to the face's plane. Summed + over the directed boundary edges of a planar polygon, it gives the solid + angle the polygon subtends, without the polygon's internal diagonals, and + two faces that share an edge in opposite directions have exactly opposite + terms for it. + + Parameters + ---------- + x1, y1, z1, x2, y2, z2 : (...) numpy.ndarray + Locations of the edge's start and end points relative to the + observation point. + nx, ny, nz : (...) numpy.ndarray + Unit normal of the face; the edge runs counterclockwise about it. + h : (...) numpy.ndarray + Distance from the observation point to the face's plane along the + normal, i.e. n . r for any point r on the face relative to the + observation point. + + Returns + ------- + (...) numpy.ndarray + Solid angle in steradians, in [-pi, pi]. Zero when h is zero, so the + polygon's solid angle is zero on the polygon itself, the mean of its + limits from either side. + + Notes + ----- + With c = n . (r1 x r2), the solid angle is + 2 atan2(sign(h) c, r1 r2 + r1 . r2 + |h| (r1 + r2)) (van Oosterom and + Strackee, 1983, with one vertex at the foot of the perpendicular). Near the + edge r1 r2 + r1 . r2 cancels, so there it is evaluated as + |r1 x r2|^2 / (r1 r2 - r1 . r2). + """ + cdef: + double n1 = sqrt(x1 * x1 + y1 * y1 + z1 * z1) + double n2 = sqrt(x2 * x2 + y2 * y2 + z2 * z2) + double dot = x1 * x2 + y1 * y2 + z1 * z2 + double cx = y1 * z2 - z1 * y2 + double cy = z1 * x2 - x1 * z2 + double cz = x1 * y2 - y1 * x2 + double c = nx * cx + ny * cy + nz * cz + double num, den + if h == 0.0 or n1 == 0.0 or n2 == 0.0: + # In the plane, or at an end point (where c is zero). + return 0.0 + # Choose the numerator and denominator, then divide once: compilers may + # evaluate both branches, and the untaken one can be 0 / 0. + if dot >= 0.0: + num = n1 * n2 + dot + den = 1.0 + else: + num = cx * cx + cy * cy + cz * cz + den = n1 * n2 - dot + den = num / den + if h > 0.0: + return 2.0 * atan2(c, den + h * (n1 + n2)) + return 2.0 * atan2(-c, den - h * (n1 + n2)) diff --git a/geoana/kernels/_extensions/potential_field_prism.pyx b/geoana/kernels/_extensions/potential_field_prism.pyx index ff6a4ddd..8f3369d0 100644 --- a/geoana/kernels/_extensions/potential_field_prism.pyx +++ b/geoana/kernels/_extensions/potential_field_prism.pyx @@ -5,6 +5,14 @@ cimport cython from libc.math cimport sqrt, log, atan + +cdef inline double _plus_r(double a, double b, double c, double r) nogil: + """a + r, with r = sqrt(a**2 + b**2 + c**2), without cancellation for a < 0.""" + if a < 0.0: + return (b * b + c * c) / (r - a) + return a + r + + @cython.cdivision @cython.ufunc cdef api double prism_f(double x, double y, double z) nogil: @@ -27,17 +35,17 @@ cdef api double prism_f(double x, double y, double z) nogil: r = sqrt(x * x + y * y + z * z) if x != 0.0 and y != 0.0: - temp = z + r + temp = _plus_r(z, x, y, r) if temp > 0.0: v -= x * y * log(temp) v += 0.5 * x * x * atan( y * z / (x * r)) if y != 0.0 and z != 0.0: - temp = x + r + temp = _plus_r(x, y, z, r) if temp > 0.0: v -= y * z * log(temp) v += 0.5 * y * y * atan(z * x / (y * r)) if z != 0.0 and x != 0.0: - temp = y + r + temp = _plus_r(y, x, z, r) if temp > 0.0: v -= z * x * log(temp) v += 0.5 * z * z * atan(x * y / (z * r)) @@ -69,11 +77,11 @@ cdef api double prism_fz(double x, double y, double z) nogil: r = sqrt(x * x + y * y + z * z) if x != 0.0: - temp = y + r + temp = _plus_r(y, x, z, r) if temp > 0.0: v += x * log(temp) if y != 0.0: - temp = x + r + temp = _plus_r(x, y, z, r) if temp > 0.0: v += y * log(temp) if z != 0.0: @@ -133,15 +141,20 @@ cdef api double prism_fzx(double x, double y, double z) nogil: """ cdef: double v = 0.0 - double r + double r, temp r = sqrt(x * x + y * y + z * z) + if y < 0.0: + # y + r cancels near the negative y axis; there it equals + # (x**2 + z**2) / (r - y). On the axis the kernel diverges as + # -2 ln(d) with the distance d to it; keep the finite part. + temp = x * x + z * z + if temp == 0.0: + return log(-2 * y) + return log((r - y) / temp) v = y + r if v == 0.0: - if y < 0: - v = log(-2 * y) - else: - v = -log(v) - return v + return 0.0 + return -log(v) @cython.ufunc @@ -168,13 +181,18 @@ cdef api double prism_fzy(double x, double y, double z) nogil: double v = 0.0 double r, temp r = sqrt(x * x + y * y + z * z) + if x < 0.0: + # x + r cancels near the negative x axis; there it equals + # (y**2 + z**2) / (r - x). On the axis the kernel diverges as + # -2 ln(d) with the distance d to it; keep the finite part. + temp = y * y + z * z + if temp == 0.0: + return log(-2 * x) + return log((r - x) / temp) v = x + r if v == 0.0: - if x < 0: - v = log(-2 * x) - else: - v = -log(v) - return v + return 0.0 + return -log(v) @cython.ufunc diff --git a/geoana/kernels/meson.build b/geoana/kernels/meson.build index a0ba5bf8..8acc8b82 100644 --- a/geoana/kernels/meson.build +++ b/geoana/kernels/meson.build @@ -2,6 +2,7 @@ python_sources = [ '__init__.py', 'potential_field_prism.py', + 'potential_field_polyhedron.py', 'tranverse_electric_reflections.py', ] diff --git a/geoana/kernels/potential_field_polyhedron.py b/geoana/kernels/potential_field_polyhedron.py new file mode 100644 index 00000000..272c1d17 --- /dev/null +++ b/geoana/kernels/potential_field_polyhedron.py @@ -0,0 +1,392 @@ +import numpy as np + +__all__ = [ + "polyhedron_edge_log", + "triangle_solid_angle", + "face_edge_solid_angle", + "tetrahedron_integrals", + "tetrahedron_inside_fraction", +] + + +def _polyhedron_edge_log(x1, y1, z1, x2, y2, z2): + """ + Evaluates the line integral of 1/r along a straight edge. + + This is the edge term of the closed-form volume integrals of polyhedra + (Werner and Scheeres, 1996): + :math:`L = \\ln\\frac{r_1 + r_2 + \\ell}{r_1 + r_2 - \\ell}`, for the edge + whose end points are at (x1, y1, z1) and (x2, y2, z2) relative to the + observation point. + + Parameters + ---------- + x1, y1, z1, x2, y2, z2 : (...) numpy.ndarray + Locations of the edge's two end points relative to the observation + point. + + Returns + ------- + (...) numpy.ndarray + Infinite where the observation point lies on the edge. + + Notes + ----- + :math:`r_1 + r_2 - \\ell` cancels catastrophically near the edge and near + its end points, so it is instead evaluated as + :math:`\\frac{2(r_1 r_2 + \\mathbf{r}_1\\cdot\\mathbf{r}_2)}{r_1 + r_2 + \\ell}` when + :math:`\\mathbf{r}_1\\cdot\\mathbf{r}_2 \\geq 0`, and as + :math:`\\frac{2|\\mathbf{r}_1\\times\\mathbf{r}_2|^2}{(r_1 r_2 - \\mathbf{r}_1\\cdot\\mathbf{r}_2)(r_1 + r_2 + \\ell)}` + otherwise, which are exact algebraically and free of cancellation. + """ + x1, y1, z1, x2, y2, z2 = np.broadcast_arrays( + *(np.asarray(v, dtype=float) for v in (x1, y1, z1, x2, y2, z2)) + ) + n1 = np.sqrt(x1 * x1 + y1 * y1 + z1 * z1) + n2 = np.sqrt(x2 * x2 + y2 * y2 + z2 * z2) + dx, dy, dz = x2 - x1, y2 - y1, z2 - z1 + length = np.sqrt(dx * dx + dy * dy + dz * dz) + dot = x1 * x2 + y1 * y2 + z1 * z2 + s = n1 + n2 + cx = y1 * z2 - z1 * y2 + cy = z1 * x2 - x1 * z2 + cz = x1 * y2 - y1 * x2 + with np.errstate(divide="ignore", invalid="ignore"): + diff = np.where( + dot >= 0, + 2.0 * (n1 * n2 + dot) / (s + length), + 2.0 * (cx * cx + cy * cy + cz * cz) / ((n1 * n2 - dot) * (s + length)), + ) + out = np.full(s.shape, np.inf) + ok = diff > 0 + out[ok] = np.log((s[ok] + length[ok]) / diff[ok]) + return out + + +def _triangle_solid_angle(x1, y1, z1, x2, y2, z2, x3, y3, z3): + """ + Evaluates the signed solid angle subtended by a triangle. + + Uses the formula of van Oosterom and Strackee (1983) for the triangle whose + vertices are at (x1, y1, z1), (x2, y2, z2), (x3, y3, z3) relative to the + observation point. The sign is positive when the vertices appear + counterclockwise from the observation point. + + Parameters + ---------- + x1, y1, z1, x2, y2, z2, x3, y3, z3 : (...) numpy.ndarray + Vertex locations relative to the observation point. + + Returns + ------- + (...) numpy.ndarray + Solid angle in steradians, in :math:`[-2\\pi, 2\\pi]`. Zero when the + observation point is in the triangle's plane, including on the triangle + itself, where zero is the mean of the limits from either side. + """ + x1, y1, z1, x2, y2, z2, x3, y3, z3 = np.broadcast_arrays( + *(np.asarray(v, dtype=float) for v in (x1, y1, z1, x2, y2, z2, x3, y3, z3)) + ) + n1 = np.sqrt(x1 * x1 + y1 * y1 + z1 * z1) + n2 = np.sqrt(x2 * x2 + y2 * y2 + z2 * z2) + n3 = np.sqrt(x3 * x3 + y3 * y3 + z3 * z3) + num = ( + x1 * (y2 * z3 - z2 * y3) + + y1 * (z2 * x3 - x2 * z3) + + z1 * (x2 * y3 - y2 * x3) + ) + den = ( + n1 * n2 * n3 + + n1 * (x2 * x3 + y2 * y3 + z2 * z3) + + n2 * (x3 * x1 + y3 * y1 + z3 * z1) + + n3 * (x1 * x2 + y1 * y2 + z1 * z2) + ) + return np.where(num == 0, 0.0, 2.0 * np.arctan2(num, den)) + + +def _face_edge_solid_angle(x1, y1, z1, x2, y2, z2, nx, ny, nz, h): + """ + Evaluates the signed solid angle subtended by one edge of a planar face. + + This is the solid angle of the triangle formed by the edge and the foot of + the perpendicular from the observation point to the face's plane. Summed + over the directed boundary edges of a planar polygon, it gives the solid + angle the polygon subtends, without the polygon's internal diagonals, and + two faces that share an edge in opposite directions have exactly opposite + terms for it. + + Parameters + ---------- + x1, y1, z1, x2, y2, z2 : (...) numpy.ndarray + Locations of the edge's start and end points relative to the + observation point. + nx, ny, nz : (...) numpy.ndarray + Unit normal of the face; the edge runs counterclockwise about it. + h : (...) numpy.ndarray + Distance from the observation point to the face's plane along the + normal, i.e. :math:`\\hat{n}\\cdot\\mathbf{r}` for any point + :math:`\\mathbf{r}` on the face relative to the observation point. + + Returns + ------- + (...) numpy.ndarray + Solid angle in steradians, in :math:`[-\\pi, \\pi]`. Zero when ``h`` is + zero, so the polygon's solid angle is zero on the polygon itself, the + mean of its limits from either side. + + Notes + ----- + With :math:`c = \\hat{n}\\cdot(\\mathbf{r}_1\\times\\mathbf{r}_2)`, the solid + angle is + :math:`2\\operatorname{atan2}(\\operatorname{sign}(h) c, r_1 r_2 + \\mathbf{r}_1\\cdot\\mathbf{r}_2 + |h|(r_1 + r_2))` + (van Oosterom and Strackee, 1983, with one vertex at the foot of the + perpendicular). Near the edge :math:`r_1 r_2 + \\mathbf{r}_1\\cdot\\mathbf{r}_2` + cancels, so there it is evaluated as + :math:`\\frac{|\\mathbf{r}_1\\times\\mathbf{r}_2|^2}{r_1 r_2 - \\mathbf{r}_1\\cdot\\mathbf{r}_2}`. + """ + x1, y1, z1, x2, y2, z2, nx, ny, nz, h = np.broadcast_arrays( + *(np.asarray(v, dtype=float) for v in (x1, y1, z1, x2, y2, z2, nx, ny, nz, h)) + ) + n1 = np.sqrt(x1 * x1 + y1 * y1 + z1 * z1) + n2 = np.sqrt(x2 * x2 + y2 * y2 + z2 * z2) + dot = x1 * x2 + y1 * y2 + z1 * z2 + cx = y1 * z2 - z1 * y2 + cy = z1 * x2 - x1 * z2 + cz = x1 * y2 - y1 * x2 + c = nx * cx + ny * cy + nz * cz + with np.errstate(divide="ignore", invalid="ignore"): + den = np.where( + dot >= 0, n1 * n2 + dot, (cx * cx + cy * cy + cz * cz) / (n1 * n2 - dot) + ) + sign = np.sign(h) + out = 2.0 * np.arctan2(sign * c, den + np.abs(h) * (n1 + n2)) + return np.where(h == 0, 0.0, out) + + +try: + from geoana.kernels._extensions.potential_field_polyhedron import ( + polyhedron_edge_log, + triangle_solid_angle, + face_edge_solid_angle, + ) +except ImportError: + polyhedron_edge_log = _polyhedron_edge_log + triangle_solid_angle = _triangle_solid_angle + face_edge_solid_angle = _face_edge_solid_angle + + +def _canonical_face_normals(w): + """Unit normals of triangles (..., 3 vertices, 3), wound as given. + + Each normal is computed from the triangle's vertices in lexicographic order, + so any body with the same face, in either orientation, gets exactly the same + normal up to sign, and their contributions for a shared face cancel exactly. + + Returns the normals (..., 3), the order (..., 3) that sorts each triangle's + vertices lexicographically, and twice the triangles' areas (...). + """ + n = np.cross(w[..., 1, :] - w[..., 0, :], w[..., 2, :] - w[..., 0, :]) + area2 = np.linalg.norm(n, axis=-1) + order = np.lexsort((w[..., 2], w[..., 1], w[..., 0]), axis=-1) + ws = np.take_along_axis(w, order[..., None], axis=-2) + n_c = np.cross(ws[..., 1, :] - ws[..., 0, :], ws[..., 2, :] - ws[..., 0, :]) + with np.errstate(invalid="ignore", divide="ignore"): + n_c = n_c / np.linalg.norm(n_c, axis=-1)[..., None] + n = np.where((np.einsum("...i,...i->...", n_c, n) > 0)[..., None], n_c, -n_c) + return n, order, area2 + + +def _edge_dyads(t, n_a, n_b): + """Edge dyads E = n_A ne_A^T + n_B ne_B^T and edge lengths. + + ``t`` (..., 3) runs from the edge's first end point to its second, face A + traverses it in that direction and face B in the other; ``n_a`` and ``n_b`` + are their unit outward normals. + """ + length = np.linalg.norm(t, axis=-1) + t = t / length[..., None] + # In-plane outward edge normals. + ne_a = np.cross(t, n_a) + ne_b = np.cross(-t, n_b) + E = n_a[..., :, None] * ne_a[..., None, :] + n_b[..., :, None] * ne_b[..., None, :] + return E, length + + +def _combine_newtonian(order, r_a, r_b, L, edge_lengths, E, h, omega, n, F): + """V, grad V or the Hessian of V from the edge and face terms. + + Leading dimensions broadcast. ``r_a``, ``r_b`` (..., n_edges, 3) point to + each edge's end points, ``L`` (..., n_edges) is its line integral, + ``edge_lengths`` and ``E`` (..., n_edges[, 3, 3]) its length and dyad; + ``h`` and ``omega`` (..., n_faces) are each face's height and solid angle, + and ``n``, ``F`` (..., n_faces, 3[, 3]) its normal and dyad. + """ + on_edge = np.isinf(L) + if order < 2: + # On an edge L is infinite, but it multiplies E . r_a, which vanishes + # there as the distance d to the edge, and d ln(d) -> 0. + L = np.where(on_edge, 0.0, L) + elif np.any(on_edge): + # The Hessian diverges as -2 E ln(d); keep the finite part, as Prism + # does: ln(4 r1 r2) on the edge, ln(2 l) at its end points. + r12 = np.linalg.norm(r_a, axis=-1) * np.linalg.norm(r_b, axis=-1) + with np.errstate(divide="ignore"): + finite = np.where(r12 > 0, np.log(4 * r12), np.log(2 * edge_lengths)) + L = np.where(on_edge, finite, L) + if order == 0: + er = np.einsum("...ei,...eij,...ej->...e", r_a, E, r_a) + return 0.5 * (er * L).sum(axis=-1) - 0.5 * (h * h * omega).sum(axis=-1) + if order == 1: + return -np.einsum("...eij,...ej,...e->...i", E, r_a, L) + np.einsum( + "...fi,...f,...f->...i", n, h, omega + ) + if order == 2: + return np.einsum("...eij,...e->...ij", E, L) - np.einsum("...fij,...f->...ij", F, omega) + raise ValueError(f"order must be 0, 1 or 2, got {order}") + + +# Inside fractions this close to 0 or 1 are taken to be exactly 0 or 1. +_FRACTION_TOL = 1e-12 + + +def _inside_fraction(omega): + """Fraction of a small sphere inside a body from its faces' solid angles + (..., n_faces): their sum over 4 pi, with roundoff snapped so points off + the surface are exactly inside (1) or outside (0).""" + frac = omega.sum(axis=-1) / (4.0 * np.pi) + frac = np.where(np.abs(frac) < _FRACTION_TOL, 0.0, frac) + return np.where(np.abs(frac - 1.0) < _FRACTION_TOL, 1.0, frac) + + +# Outward faces of a positively oriented tetrahedron, its edges, and for each +# edge the faces traversing it forwards and backwards. +_TET_FACES = np.array([[0, 2, 1], [0, 1, 3], [1, 2, 3], [0, 3, 2]]) +_TET_EDGES = np.array([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]) +_TET_EDGE_FACES = np.array([ + [ + next(i for i, f in enumerate(_TET_FACES) if (a, b) in zip(f, np.roll(f, -1))) + for a, b in (edge, edge[::-1]) + ] + for edge in _TET_EDGES +]) + + +def tetrahedron_integrals(vertices, xyz, order=0): + r"""Evaluates the volume integrals of 1/r over tetrahedra in closed form. + + Computes :math:`V = \int_\Omega \frac{dV'}{|\mathbf{r} - \mathbf{r}'|}`, its + gradient or its Hessian over each tetrahedron, with the conventions of + :class:`geoana.shapes.BasePolyhedron`. The leading dimensions of + ``vertices`` and ``xyz`` broadcast against each other, so this evaluates one + tetrahedron at many points, many tetrahedra at one point, or both. + + Parameters + ---------- + vertices : (..., 4, 3) array_like of float + The four vertex locations of each tetrahedron, in any order. + xyz : (..., 3) array_like of float + Observation locations. + order : {0, 1, 2} + 0 for :math:`V`, 1 for :math:`\nabla V` and 2 for + :math:`\nabla\nabla V`. + + Returns + ------- + (...) or (..., 3) or (..., 3, 3) numpy.ndarray + With leading dimensions ``np.broadcast_shapes(vertices.shape[:-2], + xyz.shape[:-1])``. + + Examples + -------- + Many tetrahedra at one point: + + >>> import numpy as np + >>> from geoana.kernels import tetrahedron_integrals + >>> tets = np.random.default_rng(0).uniform(size=(100, 4, 3)) + >>> tetrahedron_integrals(tets, [0.5, 0.5, 2.0], order=1).shape + (100, 3) + + Every tetrahedron at every one of 20 points: + + >>> xyz = np.random.default_rng(1).uniform(size=(20, 3)) + >>> tetrahedron_integrals(tets, xyz[:, None, :], order=2).shape + (20, 100, 3, 3) + """ + if order not in (0, 1, 2): + raise ValueError(f"order must be 0, 1 or 2, got {order}") + return _combine_newtonian(order, *_tetrahedron_terms(vertices, xyz)) + + +def tetrahedron_inside_fraction(vertices, xyz): + """Evaluates the fraction of a small sphere about each point inside tetrahedra. + + This is 1 inside a tetrahedron, 0 outside, and on its surface the solid + angle it subtends from the point over :math:`4\\pi`: 1/2 on a face, and + the dihedral angle over :math:`2\\pi` on an edge. It weights the + magnetization in :math:`\\mathbf{B} = \\mu_0(\\mathbf{H} + f\\mathbf{M})`, + which makes the normal component of B exact on a face (it is continuous + there) and the tangential component the mean of its limits from either + side, consistent with the Hessian from :func:`tetrahedron_integrals`. The + fractions of tetrahedra that tile a region sum to that region's. + + Parameters + ---------- + vertices : (..., 4, 3) array_like of float + The four vertex locations of each tetrahedron, in any order. + xyz : (..., 3) array_like of float + Observation locations. + + Returns + ------- + (...) numpy.ndarray + With shape ``np.broadcast_shapes(vertices.shape[:-2], xyz.shape[:-1])``. + + Examples + -------- + >>> from geoana.kernels import tetrahedron_inside_fraction + >>> tet = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]] + >>> tetrahedron_inside_fraction(tet, [[0.1, 0.1, 0.1], [0.2, 0.2, 0.0], [2.0, 0.0, 0.0]]) + array([1. , 0.5, 0. ]) + """ + return _inside_fraction(_tetrahedron_terms(vertices, xyz)[6]) + + +def _tetrahedron_terms(vertices, xyz): + """Edge and face terms of tetrahedra (..., 4, 3) at points (..., 3), in the + argument order of ``_combine_newtonian`` after ``order``.""" + v = np.array(vertices, dtype=float) + xyz = np.asarray(xyz, dtype=float) + if v.shape[-2:] != (4, 3): + raise ValueError(f"vertices must have shape (..., 4, 3), got {v.shape}") + if xyz.shape[-1] != 3: + raise ValueError(f"xyz must have shape (..., 3), got {xyz.shape}") + # Orient every tetrahedron positively. + e1, e2, e3 = (v[..., k, :] - v[..., 0, :] for k in (1, 2, 3)) + volume = np.einsum("...i,...i->...", e1, np.cross(e2, e3)) + if np.any(volume == 0): + raise ValueError("vertices include a tetrahedron with zero volume") + v = np.where((volume < 0)[..., None, None], v[..., [0, 2, 1, 3], :], v) + + w = v[..., _TET_FACES, :] + n, sort, _ = _canonical_face_normals(w) + ref = np.take_along_axis(w, sort[..., :1, None], axis=-2)[..., 0, :] + F = n[..., :, None] * n[..., None, :] + a, b = _TET_EDGES[:, 0], _TET_EDGES[:, 1] + E, length = _edge_dyads( + v[..., b, :] - v[..., a, :], n[..., _TET_EDGE_FACES[:, 0], :], n[..., _TET_EDGE_FACES[:, 1], :] + ) + + x = xyz[..., None, :] + r = v - x + r_a, r_b = r[..., a, :], r[..., b, :] + L = polyhedron_edge_log(*np.moveaxis(r_a, -1, 0), *np.moveaxis(r_b, -1, 0)) + h = np.einsum("...fi,...fi->...f", ref - x, n) + r1 = r[..., _TET_FACES, :] + r2 = np.roll(r1, -1, axis=-2) + omega = face_edge_solid_angle( + *np.moveaxis(r1, -1, 0), + *np.moveaxis(r2, -1, 0), + *np.moveaxis(n[..., None, :], -1, 0), + h[..., None], + ).sum(axis=-1) + return r_a, r_b, L, length, E, h, omega, n, F diff --git a/geoana/kernels/potential_field_prism.py b/geoana/kernels/potential_field_prism.py index 40d8ce6e..37f16987 100644 --- a/geoana/kernels/potential_field_prism.py +++ b/geoana/kernels/potential_field_prism.py @@ -14,6 +14,12 @@ ] +def _plus_r(a, b, c, r): + """a + r, with r = sqrt(a**2 + b**2 + c**2), without cancellation for a < 0.""" + with np.errstate(divide="ignore", invalid="ignore"): + return np.where(a < 0, (b * b + c * c) / (r - a), a + r) + + def _prism_f(x, y, z): """ Evaluates the indefinite volume integral for the 1/r kernel. @@ -36,15 +42,15 @@ def _prism_f(x, y, z): nz_y = y != 0.0 nz_z = z != 0.0 - temp = z + r + temp = _plus_r(z, x, y, r) nz = nz_x & nz_y & (temp > 0.0) out[nz] -= x[nz] * y[nz] * np.log(temp[nz]) - temp = x + r + temp = _plus_r(x, y, z, r) nz = nz_y & nz_z & (temp > 0.0) out[nz] -= y[nz] * z[nz] * np.log(temp[nz]) - temp = y + r + temp = _plus_r(y, x, z, r) nz = nz_x & nz_z & (temp > 0.0) out[nz] -= x[nz] * z[nz] * np.log(temp[nz]) @@ -76,11 +82,11 @@ def _prism_fz(x, y, z): r = np.sqrt(x * x + y * y + z * z) out = np.zeros_like(r) - temp = y + r + temp = _plus_r(y, x, z, r) nz = (x != 0.0) & (temp > 0) out[nz] += x[nz] * np.log(temp[nz]) - temp = x + r + temp = _plus_r(x, y, z, r) nz = (y != 0.0) & (temp > 0) out[nz] += y[nz] * np.log(temp[nz]) @@ -139,13 +145,19 @@ def _prism_fzx(x, y, z): r = np.sqrt(x * x + y * y + z * z) out = np.zeros_like(r) - v = y + r - - nz = (v == 0) & (y < 0) - out[nz] = np.log(-2 * y[nz]) + # y + r cancels near the negative y axis; there it equals + # (x**2 + z**2) / (r - y). On the axis the kernel diverges as -2 ln(d) + # with the distance d to it; keep the finite part. + neg = y < 0 + temp = x * x + z * z + on = neg & (temp == 0) + out[on] = np.log(-2 * y[on]) + near = neg & (temp != 0) + out[near] = np.log((r[near] - y[near]) / temp[near]) - nz = v != 0 - out[nz] = -np.log(v[nz]) + v = y + r + pos = ~neg & (v != 0) + out[pos] = -np.log(v[pos]) return out @@ -171,13 +183,19 @@ def _prism_fzy(x, y, z): r = np.sqrt(x * x + y * y + z * z) out = np.zeros_like(r) - v = x + r + # x + r cancels near the negative x axis; there it equals + # (y**2 + z**2) / (r - x). On the axis the kernel diverges as -2 ln(d) + # with the distance d to it; keep the finite part. + neg = x < 0 + temp = y * y + z * z + on = neg & (temp == 0) + out[on] = np.log(-2 * x[on]) + near = neg & (temp != 0) + out[near] = np.log((r[near] - x[near]) / temp[near]) - nz = (v == 0) & (x < 0) - out[nz] = np.log(-2 * x[nz]) - - nz = v != 0 - out[nz] = -np.log(v[nz]) + v = x + r + pos = ~neg & (v != 0) + out[pos] = -np.log(v[pos]) return out diff --git a/geoana/shapes.py b/geoana/shapes.py index 0fda9ecf..200337bd 100644 --- a/geoana/shapes.py +++ b/geoana/shapes.py @@ -13,13 +13,32 @@ :toctree: generated/ BasePrism + BasePolyhedron + BaseTetrahedron """ import numpy as np +from scipy.sparse import coo_array +from scipy.sparse.csgraph import connected_components + +from geoana.kernels.potential_field_polyhedron import ( + polyhedron_edge_log, + face_edge_solid_angle, + _canonical_face_normals, + _combine_newtonian, + _edge_dyads, + _inside_fraction, +) + __all__ = [ "BasePrism", + "BasePolyhedron", + "BaseTetrahedron", ] +# Faces whose unit normals differ by less than this are treated as coplanar. +_COPLANAR_TOL = 1e-12 + class BasePrism: """Class for basic geometry of a prism. @@ -145,3 +164,289 @@ def _eval_def_int(self, func, x, y, z, cycle=0): val = (v111 - v110 - v101 + v100 - v011 + v010 + v001 - v000) return val + + +class BasePolyhedron: + r"""Class for basic geometry of a closed polyhedron with triangular faces. + + The ``BasePolyhedron`` class defines and validates a closed, consistently + oriented triangulated surface, and evaluates the volume integrals of the + Newtonian kernel :math:`1/|\mathbf{r} - \mathbf{r}'|` over the enclosed body + in closed form, following Werner and Scheeres (1996): + + .. math:: + + V(\mathbf{r}) &= \int_\Omega \frac{dV'}{|\mathbf{r} - \mathbf{r}'|} + = \frac{1}{2}\sum_e \mathbf{r}_e \cdot \mathbf{E}_e \cdot \mathbf{r}_e L_e + - \frac{1}{2}\sum_f \mathbf{r}_f \cdot \mathbf{F}_f \cdot \mathbf{r}_f \omega_f + + \nabla V &= -\sum_e \mathbf{E}_e \cdot \mathbf{r}_e L_e + + \sum_f \mathbf{F}_f \cdot \mathbf{r}_f \omega_f + + \nabla\nabla V &= \sum_e \mathbf{E}_e L_e - \sum_f \mathbf{F}_f \omega_f + + where :math:`\mathbf{r}_e` and :math:`\mathbf{r}_f` point from the + observation point to any point on edge :math:`e` or face :math:`f`, + :math:`\mathbf{F}_f = \hat{n}_f \hat{n}_f^T` is the face dyad, + :math:`\mathbf{E}_e = \hat{n}_A \hat{n}^A_e{}^T + \hat{n}_B \hat{n}^B_e{}^T` is + the edge dyad built from the two faces sharing the edge and their in-plane + edge normals, :math:`L_e = \ln\frac{r_1 + r_2 + \ell_e}{r_1 + r_2 - \ell_e}` is + the edge's line integral, and :math:`\omega_f` is the signed solid angle the + face subtends (van Oosterom and Strackee, 1983). The solid angles sum to + :math:`4\pi` inside the body and to zero outside, so + :math:`\nabla^2 V = -4\pi` inside and zero outside. + + Adjacent coplanar triangles are merged into planar polygonal faces, whose + solid angles are summed edge by edge over their boundaries, so the + diagonals of a triangulated flat face play no part. + + :math:`V` and :math:`\nabla V` are continuous everywhere. On the surface, + :math:`\nabla\nabla V` takes the same values as + :class:`geoana.gravity.Prism`: on a face, the mean of its limits from either + side, and on an edge, where it diverges as :math:`-2\mathbf{E}_e\ln d` with + the distance :math:`d` to the edge, the finite part left by dropping that + term, :math:`L_e = \ln(4 r_1 r_2)`, or :math:`\ln(2\ell_e)` at the edge's + end points. These conventions are additive, so bodies that tile a region sum + to that region's values on their shared boundaries as well. + + Parameters + ---------- + vertices : (n_vertices, 3) array_like of float + Vertex locations. + faces : (n_faces, 3) array_like of int + Vertex indices of each triangular face. Every edge must be shared by + exactly two faces traversed in opposite directions, i.e. the surface is + closed and consistently oriented. The orientation may be either inward + or outward; it is made outward on construction. + + References + ---------- + Werner, R. A., and D. J. Scheeres (1996), Exterior gravitation of a + polyhedron derived and compared with harmonic and mascon gravitation + representations of asteroid 4769 Castalia, Celestial Mechanics and Dynamical + Astronomy, 65, 313-344. + + van Oosterom, A., and J. Strackee (1983), The solid angle of a plane + triangle, IEEE Transactions on Biomedical Engineering, BME-30(2), 125-126. + """ + + def __init__(self, vertices, faces, **kwargs): + super().__init__(**kwargs) + vertices = np.asarray(vertices, dtype=float) + faces = np.asarray(faces) + if vertices.ndim != 2 or vertices.shape[1] != 3: + raise ValueError( + f"vertices must have shape (n_vertices, 3), got {vertices.shape}" + ) + if faces.ndim != 2 or faces.shape[1] != 3: + raise ValueError(f"faces must have shape (n_faces, 3), got {faces.shape}") + if not np.issubdtype(faces.dtype, np.integer): + raise TypeError(f"faces must be integer indices, got {faces.dtype}") + if faces.min() < 0 or faces.max() >= len(vertices): + raise ValueError("faces reference a vertex index out of range") + self._vertices = vertices + self._faces = faces.astype(np.intp) + self._build_edges() + if self.volume < 0: + self._faces = self._faces[:, ::-1].copy() + self._build_edges() + if self.volume <= 0: + raise ValueError("polyhedron has zero volume") + self._build_dyads() + + def _build_edges(self): + faces = self._faces + directed = np.concatenate([faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]]]) + owner = np.tile(np.arange(len(faces)), 3) + key = {} + for (a, b), f in zip(map(tuple, directed), owner): + if (a, b) in key: + raise ValueError( + f"edge {a}->{b} is traversed twice in the same direction; " + "faces are not consistently oriented" + ) + key[(a, b)] = f + edges, face_a, face_b = [], [], [] + for (a, b), f in key.items(): + if a < b: + if (b, a) not in key: + raise ValueError(f"edge {a}-{b} belongs to only one face; surface is not closed") + edges.append((a, b)) + face_a.append(f) + face_b.append(key[(b, a)]) + if len(edges) * 2 != len(directed): + raise ValueError("surface is not closed") + self._edges = np.asarray(edges, dtype=np.intp) + # face_a traverses the edge a -> b, face_b traverses it b -> a. + self._edge_faces = np.asarray([face_a, face_b], dtype=np.intp).T + + def _build_dyads(self): + v = self._vertices + f = self._faces + n, order, area2 = _canonical_face_normals(v[f]) + if np.any(area2 == 0): + raise ValueError("polyhedron has a degenerate (zero-area) face") + face_ref = np.take_along_axis(f, order, axis=-1)[:, 0] + + n_a = n[self._edge_faces[:, 0]] + n_b = n[self._edge_faces[:, 1]] + # An edge between coplanar faces (e.g. the diagonal of a triangulated + # flat face) has a vanishing dyad, so it contributes nothing. Its dyad + # is only roundoff, which would make 0 * inf on the edge itself. + coplanar = np.linalg.norm(np.cross(n_a, n_b), axis=-1) < _COPLANAR_TOL + coplanar &= np.einsum("ij,ij->i", n_a, n_b) > 0 + + # Merge coplanar faces into planar polygons. + n_faces = len(f) + ef = self._edge_faces[coplanar] + graph = coo_array( + (np.ones(len(ef)), (ef[:, 0], ef[:, 1])), shape=(n_faces, n_faces) + ) + n_groups, group = connected_components(graph, directed=False) + counts = np.bincount(group, minlength=n_groups) + area_n = np.zeros((n_groups, 3)) + np.add.at(area_n, group, n * area2[:, None]) + n_g = area_n / np.linalg.norm(area_n, axis=-1)[:, None] + single = counts[group] == 1 + n_g[group[single]] = n[single] + # Reference vertex of each polygon: its lexicographically first vertex. + rank = np.empty(len(v), dtype=np.intp) + rank[np.lexsort((v[:, 2], v[:, 1], v[:, 0]))] = np.arange(len(v)) + ref_rank = np.full(n_groups, len(v)) + np.minimum.at(ref_rank, group, rank[face_ref]) + self._face_ref = np.argsort(rank)[ref_rank] + self._face_normals = n_g + self._face_dyads = n_g[:, :, None] * n_g[:, None, :] + + # Directed boundary edges of the polygons, grouped by polygon. + directed = np.concatenate([f[:, [0, 1]], f[:, [1, 2]], f[:, [2, 0]]]) + owner = group[np.tile(np.arange(n_faces), 3)] + n_v = len(v) + key = lambda e: np.minimum(e[:, 0], e[:, 1]) * n_v + np.maximum(e[:, 0], e[:, 1]) + boundary = ~np.isin(key(directed), key(self._edges[coplanar])) + directed, owner = directed[boundary], owner[boundary] + sort = np.argsort(owner, kind="stable") + self._face_edges = directed[sort] + self._face_edge_group = owner[sort] + self._face_edge_starts = np.searchsorted(owner[sort], np.arange(n_groups)) + + self._edges = self._edges[~coplanar] + self._edge_faces = self._edge_faces[~coplanar] + n_a, n_b = n_a[~coplanar], n_b[~coplanar] + + a, b = self._edges[:, 0], self._edges[:, 1] + # Face A traverses the edge a->b, face B b->a. + self._edge_dyads, self._edge_lengths = _edge_dyads(v[b] - v[a], n_a, n_b) + + @property + def vertices(self): + """Vertex locations. + + Returns + ------- + (n_vertices, 3) numpy.ndarray of float + """ + return self._vertices + + @property + def faces(self): + """Vertex indices of each triangular face, ordered so normals point outward. + + Returns + ------- + (n_faces, 3) numpy.ndarray of int + """ + return self._faces + + @property + def volume(self): + """The volume of the polyhedron. + + Returns + ------- + float + """ + v = self._vertices[self._faces] + return float(np.einsum("ij,ij->i", v[:, 0], np.cross(v[:, 1], v[:, 2])).sum() / 6.0) + + @property + def location(self): + """The centroid of the polyhedron. + + Returns + ------- + (3,) numpy.ndarray of float + """ + v = self._vertices[self._faces] + w = np.einsum("ij,ij->i", v[:, 0], np.cross(v[:, 1], v[:, 2])) + return (w[:, None] * v.sum(axis=1)).sum(axis=0) / (4.0 * w.sum()) + + def _kernel_terms(self, xyz): + """Edge and face terms at the (n, 3) observation points. + + Returns r_e (n, n_edges, 3) and r_b (n, n_edges, 3), the vectors to each + edge's two end points, L_e (n, n_edges), h_f (n, n_faces), the distance + along each face normal to the face's plane, and omega_f (n, n_faces). + """ + r = self._vertices[None, :, :] - xyz[:, None, :] + + a, b = self._edges[:, 0], self._edges[:, 1] + r_e, r_b = r[:, a], r[:, b] + L = polyhedron_edge_log( + r_e[..., 0], r_e[..., 1], r_e[..., 2], r_b[..., 0], r_b[..., 1], r_b[..., 2] + ) + + n = self._face_normals + h = np.einsum("nfi,fi->nf", r[:, self._face_ref], n) + grp = self._face_edge_group + r1, r2 = r[:, self._face_edges[:, 0]], r[:, self._face_edges[:, 1]] + n_e = n[grp] + omega = face_edge_solid_angle( + r1[..., 0], r1[..., 1], r1[..., 2], + r2[..., 0], r2[..., 1], r2[..., 2], + n_e[:, 0], n_e[:, 1], n_e[:, 2], + h[:, grp], + ) + omega = np.add.reduceat(omega, self._face_edge_starts, axis=-1) + return r_e, r_b, L, h, omega + + def _newtonian_integrals(self, xyz, order): + """V, grad V and/or the Hessian of V at observation points. + + ``order`` is 0 (V), 1 (grad V) or 2 (Hessian). ``xyz`` is (..., 3). + """ + shape = xyz.shape[:-1] + pts = xyz.reshape(-1, 3) + r_e, r_b, L, h, omega = self._kernel_terms(pts) + out = _combine_newtonian( + order, r_e, r_b, L, self._edge_lengths, self._edge_dyads, + h, omega, self._face_normals, self._face_dyads, + ) + return out.reshape(*shape, *out.shape[1:]) + + def _inside_fraction(self, xyz): + """Fraction of a small sphere about each (..., 3) point inside the body. + + One inside, zero outside, and on the surface the solid angle of the body + seen from the point over 4 pi, e.g. 1/2 on a face. + """ + shape = xyz.shape[:-1] + omega = self._kernel_terms(xyz.reshape(-1, 3))[-1] + return _inside_fraction(omega).reshape(shape) + + +class BaseTetrahedron(BasePolyhedron): + """Class for basic geometry of a tetrahedron. + + Parameters + ---------- + vertices : (4, 3) array_like of float + The four vertex locations, in any order. + """ + + def __init__(self, vertices, **kwargs): + vertices = np.asarray(vertices, dtype=float) + if vertices.shape != (4, 3): + raise ValueError(f"vertices must have shape (4, 3), got {vertices.shape}") + faces = np.array([[0, 2, 1], [0, 1, 3], [1, 2, 3], [0, 3, 2]]) + super().__init__(vertices, faces, **kwargs) diff --git a/tests/em/static/test_freespace.py b/tests/em/static/test_freespace.py index c102f4be..9bbb8543 100644 --- a/tests/em/static/test_freespace.py +++ b/tests/em/static/test_freespace.py @@ -2,9 +2,15 @@ import numpy.testing as npt import pytest +from scipy.constants import mu_0 from scipy.special import roots_legendre -from geoana.em.static import MagneticPrism, MagneticDipoleWholeSpace +from geoana.em.static import ( + MagneticPrism, + MagneticDipoleWholeSpace, + MagneticPolyhedron, + MagneticTetrahedron, +) from geoana.utils import append_ndim @@ -51,4 +57,164 @@ def test_accuracy(self, method, rtol): test_quad = np.sum(test_quad, axis=(0, 1, 2)) atol = rtol * (test_prism.max() - test_prism.min()) - npt.assert_allclose(test_quad, test_prism, atol=atol) \ No newline at end of file + npt.assert_allclose(test_quad, test_prism, atol=atol) + +def _box(lo, hi): + V = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) + quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] + F = [] + for a, b, c, d in quads: + F += [(a, b, c), (a, c, d)] + return V, np.array(F) + + +@pytest.mark.parametrize( + "method", ["scalar_potential", "magnetic_field", "magnetic_flux_density"] +) +def test_magnetic_polyhedron_matches_prism(method): + lo, hi = np.r_[-1.0, -2.0, -3.0], np.r_[2.0, 1.5, 0.5] + m = [-1.0, 2.0, -0.5] + V, F = _box(lo, hi) + poly = MagneticPolyhedron(V, F, magnetization=m) + prism = MagneticPrism(lo, hi, magnetization=m) + rng = np.random.default_rng(1) + out = rng.uniform(-8, 8, (400, 3)) + out = out[~np.all((out >= lo - 0.3) & (out <= hi + 0.3), axis=1)] + ins = rng.uniform(lo + 0.1, hi - 0.1, (100, 3)) + for xyz in (out, ins): + a = getattr(poly, method)(xyz) + b = getattr(prism, method)(xyz) + np.testing.assert_allclose(a, b, rtol=1e-10, atol=1e-12 * np.max(np.abs(b))) + + +@pytest.mark.parametrize("method", ["scalar_potential", "magnetic_field", "magnetic_flux_density"]) +def test_magnetic_polyhedron_on_boundary(method): + # The scalar potential is continuous, so it is defined on the surface too: + # vertices, edge midpoints and face centers (on the face diagonals). The + # fields follow Prism's conventions there. + lo, hi = np.r_[-1.0, -2.0, -3.0], np.r_[2.0, 1.5, 0.5] + m = [-1.0, 2.0, -0.5] + V, F = _box(lo, hi) + poly = MagneticPolyhedron(V, F, magnetization=m) + prism = MagneticPrism(lo, hi, magnetization=m) + c = 0.5 * (lo + hi) + xyz = np.vstack([ + V, + [[hi[0], c[1], hi[2]], [lo[0], lo[1], c[2]], [c[0], hi[1], lo[2]]], + [[c[0], c[1], hi[2]], [lo[0], c[1], c[2]], [c[0], hi[1], c[2]]], + ]) + a = getattr(poly, method)(xyz) + b = getattr(prism, method)(xyz) + assert np.all(np.isfinite(a)) + np.testing.assert_allclose(a, b, rtol=1e-10, atol=1e-12 * np.max(np.abs(b))) + + +def test_magnetic_tetrahedron_potential_continuous(): + v = np.array([[0, 0, 0], [3, 0.5, 0], [1, 2, 0.2], [0.7, 0.4, 1.9]]) + tet = MagneticTetrahedron(v, magnetization=[0.3, -0.2, 1.0]) + # A face centroid, an edge midpoint, a point a third along an edge and a vertex. + xyz = np.array([v[[1, 2, 3]].mean(axis=0), 0.5 * (v[1] + v[3]), v[0] + (v[2] - v[0]) / 3, v[3]]) + step = np.r_[0.31, -0.52, 0.79] / np.linalg.norm([0.31, -0.52, 0.79]) + on = tet.scalar_potential(xyz) + for eps in [1e-9, 1e-12, 1e-15]: + for sign in (1, -1): + near = tet.scalar_potential(xyz + sign * eps * step) + np.testing.assert_allclose(near, on, rtol=0, atol=1e-6 * np.max(np.abs(on))) + + +def test_magnetic_tetrahedron_far_field_is_dipole(): + v = np.array([[0, 0, 0], [3, 0.5, 0], [1, 2, 0.2], [0.7, 0.4, 1.9]]) + m = np.r_[0.3, -0.2, 1.0] + tet = MagneticTetrahedron(v, magnetization=m) + far = np.array([[300.0, 600.0, -900.0], [-1500.0, 30.0, 600.0]]) + moment = tet.moment + r = far - tet.location + rn = np.linalg.norm(r, axis=-1, keepdims=True) + H = (3 * r * (r @ moment)[:, None] / rn**2 - moment) / (4 * np.pi * rn**3) + np.testing.assert_allclose(tet.magnetic_field(far), H, rtol=1e-5, atol=1e-5 * np.abs(H).max()) + + +def _check_flux_density_on_face(body, x0, normal, eps=1e-9, exactly_on=True): + """On a face, the normal component of B is continuous, so it must equal its + limits from either side; the tangential component jumps, and must be their + mean. A point that is on the face only to within roundoff may instead take + either side's limit.""" + B_on = body.magnetic_flux_density(x0[None])[0] + B_in = body.magnetic_flux_density((x0 - eps * normal)[None])[0] + B_out = body.magnetic_flux_density((x0 + eps * normal)[None])[0] + scale = np.abs(B_in).max() + np.testing.assert_allclose(B_on @ normal, B_in @ normal, rtol=0, atol=1e-7 * scale) + np.testing.assert_allclose(B_on @ normal, B_out @ normal, rtol=0, atol=1e-7 * scale) + allowed = [0.5 * (B_in + B_out)] if exactly_on else [0.5 * (B_in + B_out), B_in, B_out] + assert min(np.abs(B_on - b).max() for b in allowed) < 1e-7 * scale + # The limits really do differ tangentially. + assert np.abs(B_in - B_out).max() > 0.1 * scale + + +def test_prism_flux_density_on_face(): + lo, hi = np.r_[-1.0, -2.0, -3.0], np.r_[2.0, 1.5, 0.5] + prism = MagneticPrism(lo, hi, magnetization=[-1.0, 2.0, -0.5]) + _check_flux_density_on_face(prism, np.r_[0.37, -0.61, hi[2]], np.r_[0.0, 0.0, 1.0]) + _check_flux_density_on_face(prism, np.r_[lo[0], 0.2, -1.1], np.r_[-1.0, 0.0, 0.0]) + + +def test_prism_flux_density_inside_fraction(): + # B - mu_0 H is mu_0 M weighted by the fraction of a small sphere inside the + # prism: 1/2 on a face, 1/4 on an edge, 1/8 at a corner. + lo, hi = np.r_[-1.0, -2.0, -3.0], np.r_[2.0, 1.5, 0.5] + m = np.r_[-1.0, 2.0, -0.5] + prism = MagneticPrism(lo, hi, magnetization=m) + xyz = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, hi[2]], [hi[0], 0.0, hi[2]], hi, [5.0, 0.0, 0.0]]) + frac = np.r_[1.0, 0.5, 0.25, 0.125, 0.0] + M = prism.magnetic_flux_density(xyz) / mu_0 - prism.magnetic_field(xyz) + np.testing.assert_allclose(M, frac[:, None] * m, atol=1e-14) + + +def test_tetrahedron_flux_density_on_face(): + v = np.array([[0, 0, 0], [3, 0.5, 0], [1, 2, 0.2], [0.7, 0.4, 1.9]]) + tet = MagneticTetrahedron(v, magnetization=[0.3, -0.2, 1.0]) + normal = np.cross(v[2] - v[1], v[3] - v[1]) + normal /= np.linalg.norm(normal) + normal *= np.sign(normal @ (v[1] - v[0])) + # The centroid of this skewed face is on it only to within roundoff. + _check_flux_density_on_face(tet, v[[1, 2, 3]].mean(axis=0), normal, exactly_on=False) + # A face in the plane z = 0 contains its points exactly. + flat = MagneticTetrahedron( + [[0, 0, 0], [3, 0.5, 0], [1, 2, 0], [0.7, 0.4, 1.9]], magnetization=[0.3, -0.2, 1.0] + ) + _check_flux_density_on_face(flat, np.r_[1.2, 0.8, 0.0], np.r_[0.0, 0.0, -1.0]) + + +def _box_tetrahedra(lo, hi): + """Six tetrahedra that tile an axis-aligned box (Kuhn triangulation).""" + V = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) + tets = [] + for perm in [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]: + idx = [0] + for axis in perm: + idx.append(idx[-1] + (4, 2, 1)[axis]) + tets.append(V[idx]) + return tets + + +def test_tetrahedra_flux_density_tile_prism(): + # Each point on a face shared by two tetrahedra is half inside each, so the + # tetrahedra sum to the prism there, as well as on the prism's own surface. + lo, hi = np.r_[-1.0, -2.0, -3.0], np.r_[2.0, 1.5, 0.5] + m = [-1.0, 2.0, -0.5] + prism = MagneticPrism(lo, hi, magnetization=m) + tets = [MagneticTetrahedron(v, magnetization=m) for v in _box_tetrahedra(lo, hi)] + c = 0.5 * (lo + hi) + xyz = np.array([ + lo + 0.25 * (hi - lo), + lo + np.r_[0.6, 0.3, 0.3] * (hi - lo), + lo + np.r_[0.7, 0.7, 0.2] * (hi - lo), + [c[0], c[1], hi[2]], + [0.37, -0.61, hi[2]], + [hi[0], c[1], hi[2]], + hi, + ]) + a = sum(t.magnetic_flux_density(xyz) for t in tets) + b = prism.magnetic_flux_density(xyz) + np.testing.assert_allclose(a, b, rtol=0, atol=1e-13 * np.abs(b).max()) + diff --git a/tests/kernels/test_potential_polyhedron.py b/tests/kernels/test_potential_polyhedron.py new file mode 100644 index 00000000..c051421f --- /dev/null +++ b/tests/kernels/test_potential_polyhedron.py @@ -0,0 +1,262 @@ +import numpy as np +import numpy.testing as npt +import pytest + +import geoana.kernels.potential_field_polyhedron as pp +try: + from numba import njit +except ImportError: + njit = None + + +class TestCompiledVsNumpy(): + rng = np.random.default_rng(42) + tri = rng.uniform(-10, 10, size=(9, 2000)) + edge = rng.uniform(-10, 10, size=(6, 2000)) + + def test_assert_using_compiled(self): + assert pp._polyhedron_edge_log is not pp.polyhedron_edge_log + assert pp._triangle_solid_angle is not pp.triangle_solid_angle + assert pp._face_edge_solid_angle is not pp.face_edge_solid_angle + + def test_edge_log(self): + v0 = pp._polyhedron_edge_log(*self.edge) + v1 = pp.polyhedron_edge_log(*self.edge) + npt.assert_allclose(v0, v1) + + @pytest.mark.parametrize("func", [pp._polyhedron_edge_log, pp.polyhedron_edge_log]) + def test_edge_log_on_edge(self, func): + # On the edge r1 + r2 == length and the line integral diverges. + assert np.isinf(func(1.0, 0.0, 0.0, -2.0, 0.0, 0.0)) + # At an end point too. + assert np.isinf(func(0.0, 0.0, 0.0, -2.0, 0.0, 0.0)) + # Collinear but beyond the end is finite: the integral of 1/x from 1 to 2. + npt.assert_allclose(func(1.0, 0.0, 0.0, 2.0, 0.0, 0.0), np.log(2.0)) + + @pytest.mark.parametrize("func", [pp._triangle_solid_angle, pp.triangle_solid_angle]) + def test_solid_angle_in_plane(self, func): + # In the triangle's plane, on or off the triangle, the solid angle is zero + # (on the triangle, the mean of its limits from either side). + npt.assert_equal(func(-1, -1, 0, 2, 0, 0, 0, 2, 0), 0.0) + npt.assert_equal(func(-1, -1, 0, 0, 2, 0, 2, 0, 0), 0.0) + npt.assert_equal(func(1, 1, 0, 2, 1, 0, 1, 2, 0), 0.0) + + def test_solid_angle(self): + v0 = pp._triangle_solid_angle(*self.tri) + v1 = pp.triangle_solid_angle(*self.tri) + npt.assert_allclose(v0, v1) + + def test_face_edge_solid_angle(self): + args = _face_edge_args(self.rng) + v0 = pp._face_edge_solid_angle(*args) + v1 = pp.face_edge_solid_angle(*args) + npt.assert_allclose(v0, v1, atol=1e-14) + + +def _face_edge_args(rng, n=2000): + """Random triangles relative to the observation point, split into their + directed edges 0->1, 1->2 and 2->0, each with the triangle's unit normal and + height. Every returned array has shape (3, n), one row per edge.""" + r = rng.uniform(-10, 10, size=(3, n, 3)) + normal = np.cross(r[1] - r[0], r[2] - r[0]) + normal /= np.linalg.norm(normal, axis=-1)[:, None] + h = np.einsum("ij,ij->i", normal, r[0]) + start, end = r, np.roll(r, -1, axis=0) + normal = np.broadcast_to(normal, (3, n, 3)) + return (*np.moveaxis(start, -1, 0), *np.moveaxis(end, -1, 0), *np.moveaxis(normal, -1, 0), + np.broadcast_to(h, (3, n))) + + +class TestKernelValues(): + + @pytest.mark.parametrize("func", [pp._face_edge_solid_angle, pp.face_edge_solid_angle]) + def test_face_edge_terms_sum_to_triangle(self, func): + rng = np.random.default_rng(3) + args = _face_edge_args(rng) + x1, y1, z1, x2, y2, z2 = args[:6] + tri = (x1[0], y1[0], z1[0], x1[1], y1[1], z1[1], x1[2], y1[2], z1[2]) + npt.assert_allclose(func(*args).sum(axis=0), pp.triangle_solid_angle(*tri), atol=1e-12) + + @pytest.mark.parametrize("func", [pp._face_edge_solid_angle, pp.face_edge_solid_angle]) + def test_face_edge_antisymmetric(self, func): + # Faces sharing an edge traverse it in opposite directions; their terms + # must cancel exactly, including right next to the edge. + rng = np.random.default_rng(4) + args = _face_edge_args(rng) + swapped = args[3:6] + args[0:3] + args[6:] + npt.assert_array_equal(func(*swapped), -func(*args)) + # Next to the edge from (-1, 0, 0) to (1, 0, 0) in the plane z = 0. + d = 1e-13 + near = (-1.0, d, d, 1.0, d, d, 0.0, 0.0, 1.0, d) + swapped = near[3:6] + near[0:3] + near[6:] + npt.assert_array_equal(func(*swapped), -func(*near)) + + @pytest.mark.parametrize("func", [pp._face_edge_solid_angle, pp.face_edge_solid_angle]) + def test_face_edge_in_plane(self, func): + npt.assert_equal(func(1.0, -1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0), 0.0) + # Just off the plane, the edge subtends its in-plane angle, here pi / 2, + # negative on the side the normal points to. + npt.assert_allclose(func(1.0, -1.0, -1e-9, 1.0, 1.0, -1e-9, 0.0, 0.0, 1.0, -1e-9), -np.pi / 2) + npt.assert_allclose(func(1.0, -1.0, 1e-9, 1.0, 1.0, 1e-9, 0.0, 0.0, 1.0, 1e-9), np.pi / 2) + + def test_solid_angle_octant(self): + # The unit triangle on the axes subtends one eighth of the sphere. + npt.assert_allclose( + pp.triangle_solid_angle(1, 0, 0, 0, 1, 0, 0, 0, 1), 4 * np.pi / 8 + ) + npt.assert_allclose( + pp.triangle_solid_angle(1, 0, 0, 0, 0, 1, 0, 1, 0), -4 * np.pi / 8 + ) + + @pytest.mark.parametrize("func", [pp._polyhedron_edge_log, pp.polyhedron_edge_log]) + def test_edge_log_is_line_integral(self, func): + # A point on the perpendicular bisector of an edge of length 2 at distance d: + # the integral of 1/r along the edge is 2 asinh(1/d). The small distances + # check that r1 + r2 - length is not lost to cancellation near the edge. + d = np.array([1e-150, 1e-15, 1e-10, 1e-7, 0.1, 1.0, 10.0]) + npt.assert_allclose(func(-1.0, d, 0.0, 1.0, d, 0.0), 2 * np.arcsinh(1 / d), rtol=1e-14) + # Off the bisector: the line integral is asinh(b/d) - asinh(a/d). + a, b = -0.3, 1.7 + npt.assert_allclose( + func(a, d, 0.0, b, d, 0.0), np.arcsinh(b / d) - np.arcsinh(a / d), rtol=1e-14 + ) + # Next to an end point: the line integral is asinh(1 / d). + npt.assert_allclose(func(0.0, d, 0.0, 1.0, d, 0.0), np.arcsinh(1 / d), rtol=1e-14) + + +@pytest.mark.skipif(njit is None, reason="Numba is not installed.") +class TestNumbaCallable(): + + def test_edge_log(self): + @njit + def f(*args): + return pp.polyhedron_edge_log(*args) + args = (-1.0, 0.5, 0.0, 1.0, 0.5, 0.0) + npt.assert_allclose(f(*args), pp._polyhedron_edge_log(*args)) + + def test_solid_angle(self): + @njit + def f(*args): + return pp.triangle_solid_angle(*args) + args = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) + npt.assert_allclose(f(*args), pp._triangle_solid_angle(*args)) + + def test_face_edge_solid_angle(self): + @njit + def f(*args): + return pp.face_edge_solid_angle(*args) + args = (1.0, -1.0, -0.5, 1.0, 1.0, -0.5, 0.0, 0.0, 1.0, -0.5) + npt.assert_allclose(f(*args), pp._face_edge_solid_angle(*args)) + + +def _kuhn_grid(n): + """Tetrahedra tiling the cube [0, n]^3: six per unit cell.""" + cells = np.stack(np.meshgrid(*[np.arange(float(n))] * 3, indexing="ij"), -1).reshape(-1, 3) + corner = np.array([[x, y, z] for x in (0, 1) for y in (0, 1) for z in (0, 1)], float) + paths = [] + for perm in [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]: + idx = [0] + for axis in perm: + idx.append(idx[-1] + (4, 2, 1)[axis]) + paths.append(idx) + return (cells[:, None, None, :] + corner[np.array(paths)][None]).reshape(-1, 4, 3) + + +class TestTetrahedronIntegrals(): + rng = np.random.default_rng(7) + tets = rng.uniform(-2, 2, size=(30, 4, 3)) + xyz = np.vstack([ + rng.uniform(-4, 4, size=(10, 3)), + tets[0], # vertices of the first + tets[0, [1, 2, 3]].mean(axis=0)[None], # a face centroid + 0.5 * (tets[0, 0] + tets[0, 2])[None], # an edge midpoint + ]) + + @pytest.mark.parametrize("order", [0, 1, 2]) + def test_shapes(self, order): + tail = (3,) * order + assert pp.tetrahedron_integrals(self.tets[0], self.xyz, order).shape == (len(self.xyz), *tail) + assert pp.tetrahedron_integrals(self.tets, self.xyz[0], order).shape == (len(self.tets), *tail) + both = pp.tetrahedron_integrals(self.tets, self.xyz[:, None, :], order) + assert both.shape == (len(self.xyz), len(self.tets), *tail) + # Broadcasting either way gives the same values. + one_tet = pp.tetrahedron_integrals(self.tets[3], self.xyz, order) + one_pt = pp.tetrahedron_integrals(self.tets, self.xyz[5], order) + npt.assert_array_equal(both[:, 3], one_tet) + npt.assert_array_equal(both[5], one_pt) + + @pytest.mark.parametrize("order", [0, 1, 2]) + def test_matches_tetrahedron(self, order): + from geoana.shapes import BaseTetrahedron + got = pp.tetrahedron_integrals(self.tets, self.xyz[:, None, :], order) + for i, v in enumerate(self.tets): + want = BaseTetrahedron(v)._newtonian_integrals(self.xyz, order) + npt.assert_allclose(got[:, i], want, rtol=1e-12, atol=1e-12 * np.abs(want).max()) + + @pytest.mark.parametrize("order", [0, 1, 2]) + def test_vertex_order(self, order): + a = pp.tetrahedron_integrals(self.tets, self.xyz[:, None, :], order) + b = pp.tetrahedron_integrals(self.tets[:, [3, 1, 0, 2]], self.xyz[:, None, :], order) + npt.assert_allclose(a, b, rtol=1e-12, atol=1e-12 * np.abs(a).max()) + + @pytest.mark.parametrize("order", [0, 1, 2]) + def test_mesh_sums_to_prism(self, order): + # Many tetrahedra at once, observed on the mesh's surface, at a node, on + # shared edges and faces inside it, and outside. + from geoana.gravity import Prism + from scipy.constants import G + tets = _kuhn_grid(4) + xyz = np.array([ + [1.5, 2.0, 4.0], [4.0, 4.0, 4.0], [2.0, 1.0, 3.0], [1.5, 1.5, 1.5], + [2.25, 1.5, 1.5], [0.7, 0.3, 2.3], [6.0, -1.0, 2.0], + ]) + got = G * pp.tetrahedron_integrals(tets, xyz[:, None, :], order).sum(axis=1) + prism = Prism([0, 0, 0], [4, 4, 4], rho=1.0) + want = getattr(prism, ["gravitational_potential", "gravitational_field", "gravitational_gradient"][order])(xyz) + npt.assert_allclose(got, want, rtol=0, atol=1e-13 * np.abs(want).max()) + + def test_inside_fraction_values(self): + # The corner tetrahedron of the unit cube: its right-angled edges have a + # dihedral angle of pi / 2, its right-angled corner an eighth of a sphere. + tet = np.array([[0.0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]) + xyz = np.array([ + [0.1, 0.1, 0.1], # inside + [0.2, 0.2, 0.0], # on a face + [0.5, 0.0, 0.0], # on a right-angled edge + [0.0, 0.0, 0.0], # at the right-angled corner + [2.0, 0.0, 0.0], # outside + [0.25, 0.25, 0.5], # on the slanted face (exactly, in binary) + ]) + npt.assert_allclose( + pp.tetrahedron_inside_fraction(tet, xyz), [1.0, 0.5, 0.25, 0.125, 0.0, 0.5], atol=1e-14 + ) + + def test_inside_fraction_matches_polyhedron(self): + from geoana.shapes import BaseTetrahedron + got = pp.tetrahedron_inside_fraction(self.tets, self.xyz[:, None, :]) + assert got.shape == (len(self.xyz), len(self.tets)) + for i, v in enumerate(self.tets): + npt.assert_allclose(got[:, i], BaseTetrahedron(v)._inside_fraction(self.xyz), atol=1e-14) + + def test_inside_fraction_mesh_sums_to_cube(self): + # Fractions of tetrahedra tiling a cube sum to the cube's everywhere: + # 1 inside (including on shared nodes, edges and faces), 1/2 on the + # cube's faces, 1/4 on its edges, 1/8 at its corners, 0 outside. + tets = _kuhn_grid(4) + xyz = np.array([ + [2.0, 1.0, 3.0], [1.5, 1.5, 1.5], [2.25, 1.5, 1.5], [0.7, 0.3, 2.3], + [1.5, 2.0, 4.0], [0.0, 1.0, 2.0], [4.0, 4.0, 2.5], [4.0, 4.0, 4.0], [6.0, -1.0, 2.0], + ]) + got = pp.tetrahedron_inside_fraction(tets, xyz[:, None, :]).sum(axis=1) + npt.assert_allclose(got, [1, 1, 1, 1, 0.5, 0.5, 0.25, 0.125, 0], atol=1e-13) + + def test_errors(self): + with pytest.raises(ValueError): + pp.tetrahedron_integrals(self.tets[:, :3], self.xyz) + with pytest.raises(ValueError): + pp.tetrahedron_integrals(self.tets, self.xyz[:, :2]) + with pytest.raises(ValueError): + pp.tetrahedron_integrals(self.tets, self.xyz[0], order=3) + flat = np.array([[0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0]]) + with pytest.raises(ValueError): + pp.tetrahedron_integrals(flat, self.xyz[0]) diff --git a/tests/kernels/test_potential_prism.py b/tests/kernels/test_potential_prism.py index f6a82b30..65dbbf73 100644 --- a/tests/kernels/test_potential_prism.py +++ b/tests/kernels/test_potential_prism.py @@ -162,3 +162,19 @@ def jitted_func(x, y, z): v2 = function(x, y, z) npt.assert_allclose(v1, v2) + + +@pytest.mark.parametrize("compiled", [True, False]) +def test_log_kernels_near_negative_axis(compiled): + # Near the negative y axis y + r cancels; log(y + r) = log(d) + asinh(y / d) + # with d the distance to the axis. On the axis, the finite part is kept. + fzx = pf.prism_fzx if compiled else pf._prism_fzx + fz = pf.prism_fz if compiled else pf._prism_fz + d = np.array([1e-150, 1e-12, 1e-8, 1e-4]) + y = np.full_like(d, -2.0) + zero = np.zeros_like(d) + log_y_r = np.log(d) + np.arcsinh(y / d) + npt.assert_allclose(fzx(d, y, zero), -log_y_r, rtol=1e-14) + # prism_fz = x log(y + r) + y log(x + r) at z = 0. + npt.assert_allclose(fz(d, y, zero), d * log_y_r + y * np.log(d + np.sqrt(d * d + 4)), rtol=1e-14) + npt.assert_allclose(fzx(zero, y, zero), np.log(4.0)) diff --git a/tests/test_gravity.py b/tests/test_gravity.py index 6ddf0ecb..36e41de7 100644 --- a/tests/test_gravity.py +++ b/tests/test_gravity.py @@ -140,4 +140,201 @@ def test_accuracy(self, method, rtol): test_quad = np.sum(test_quad, axis=(0, 1, 2)) atol = rtol * (test_prism.max() - test_prism.min()) - npt.assert_allclose(test_quad, test_prism, atol=atol) \ No newline at end of file + npt.assert_allclose(test_quad, test_prism, atol=atol) + +def _box_polyhedron(lo, hi): + """Vertices and outward triangular faces of an axis-aligned box.""" + V = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) + quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] + F = [] + for a, b, c, d in quads: + F += [(a, b, c), (a, c, d)] + return V, np.array(F) + + +def _box_tetrahedra(lo, hi): + """Six tetrahedra that tile an axis-aligned box (Kuhn triangulation).""" + V = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) + # Paths from vertex 0 (min corner) to vertex 7 (max corner) along the axes. + bit = {0: 4, 1: 2, 2: 1} + tets = [] + for perm in [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]: + idx = [0] + for axis in perm: + idx.append(idx[-1] + bit[axis]) + tets.append(V[idx]) + return tets + + +def _box_boundary_points(lo, hi): + """Points on the surface of a box: its vertices, edge midpoints, face + centers (which lie on the diagonals of the triangulated faces) and + off-center face points.""" + V = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) + c = 0.5 * (lo + hi) + pts = [V] + for axis in range(3): + for side in (lo, hi): + face = c.copy() + face[axis] = side[axis] + pts.append(face) + off = lo + np.r_[0.37, 0.61, 0.23] * (hi - lo) + off[axis] = side[axis] + pts.append(off) + for other in (lo, hi): + edge = c.copy() + edge[axis] = side[axis] + edge[(axis + 1) % 3] = other[(axis + 1) % 3] + pts.append(edge) + return np.vstack(pts) + + +# Edge, face and vertex points of a skewed tetrahedron, with a direction to +# step across them. +_TET = np.array([[0, 0, 0], [3, 0.5, 0], [1, 2, 0.2], [0.7, 0.4, 1.9]]) +_TET_BOUNDARY = np.array([ + _TET[[1, 2, 3]].mean(axis=0), + 0.5 * (_TET[1] + _TET[3]), + _TET[0] + (_TET[2] - _TET[0]) / 3, + _TET[3], +]) +_STEP = np.r_[0.31, -0.52, 0.79] / np.linalg.norm([0.31, -0.52, 0.79]) + + +class TestPolyhedron: + lo = np.r_[-1.0, -2.0, -3.0] + hi = np.r_[2.0, 1.5, 0.5] + rng = np.random.default_rng(0) + outside = rng.uniform(-8, 8, (400, 3)) + outside = outside[~np.all((outside >= lo - 0.3) & (outside <= hi + 0.3), axis=1)] + inside = rng.uniform(lo + 0.1, hi - 0.1, (100, 3)) + boundary = _box_boundary_points(lo, hi) + # The box's main diagonal is an edge of every tetrahedron in its Kuhn + # triangulation, and the other points lie on faces shared by two of them. + shared = np.array([ + lo + 0.25 * (hi - lo), + lo + 0.5 * (hi - lo), + lo + np.r_[0.6, 0.3, 0.3] * (hi - lo), + lo + np.r_[0.7, 0.7, 0.2] * (hi - lo), + ]) + + def test_geometry(self): + V, F = _box_polyhedron(self.lo, self.hi) + p = gravity.Polyhedron(V, F, rho=2.0) + npt.assert_allclose(p.volume, np.prod(self.hi - self.lo)) + npt.assert_allclose(p.location, 0.5 * (self.lo + self.hi)) + npt.assert_allclose(p.mass, 2.0 * p.volume) + + def test_orientation_is_normalized(self): + V, F = _box_polyhedron(self.lo, self.hi) + inward = gravity.Polyhedron(V, F[:, ::-1]) + outward = gravity.Polyhedron(V, F) + npt.assert_allclose( + inward.gravitational_field(self.outside), outward.gravitational_field(self.outside) + ) + + def test_errors(self): + V, F = _box_polyhedron(self.lo, self.hi) + with pytest.raises(ValueError): + gravity.Polyhedron(V, F[:-1]) # not closed + bad = F.copy() + bad[0] = bad[0][::-1] + with pytest.raises(ValueError): + gravity.Polyhedron(V, bad) # inconsistently oriented + with pytest.raises(TypeError): + gravity.Polyhedron(V, F, rho="string") + + @pytest.mark.parametrize("method", METHODS) + def test_box_matches_prism(self, method): + V, F = _box_polyhedron(self.lo, self.hi) + poly = gravity.Polyhedron(V, F, rho=2.5) + prism = gravity.Prism(self.lo, self.hi, rho=2.5) + for xyz in (self.outside, self.inside): + a = getattr(poly, method)(xyz) + b = getattr(prism, method)(xyz) + npt.assert_allclose(a, b, rtol=1e-10, atol=1e-12 * np.max(np.abs(b))) + + @pytest.mark.parametrize("method", METHODS) + def test_tetrahedra_tile_prism(self, method): + prism = gravity.Prism(self.lo, self.hi, rho=1.5) + tets = [gravity.Tetrahedron(v, rho=1.5) for v in _box_tetrahedra(self.lo, self.hi)] + npt.assert_allclose(sum(t.volume for t in tets), prism.volume) + a = sum(getattr(t, method)(self.outside) for t in tets) + b = getattr(prism, method)(self.outside) + npt.assert_allclose(a, b, rtol=1e-10, atol=1e-12 * np.max(np.abs(b))) + + @pytest.mark.parametrize("method", METHODS) + def test_boundary_matches_prism(self, method): + # The potential and field are continuous, so they are defined on the + # surface, including on edges and vertices where the edge terms diverge. + # The gradient follows Prism's conventions there. + V, F = _box_polyhedron(self.lo, self.hi) + poly = gravity.Polyhedron(V, F, rho=2.5) + prism = gravity.Prism(self.lo, self.hi, rho=2.5) + a = getattr(poly, method)(self.boundary) + b = getattr(prism, method)(self.boundary) + assert np.all(np.isfinite(a)) + npt.assert_allclose(a, b, rtol=1e-10, atol=1e-12 * np.max(np.abs(b))) + + @pytest.mark.parametrize("method", METHODS) + @pytest.mark.parametrize("offset", [0.0, 1e-12, -1e-12]) + def test_tetrahedra_tile_prism_on_shared_boundaries(self, method, offset): + # Subtracting the tetrahedra from the prism leaves nothing, on and right + # next to every boundary, shared or not. + prism = gravity.Prism(self.lo, self.hi, rho=1.5) + tets = [gravity.Tetrahedron(v, rho=1.5) for v in _box_tetrahedra(self.lo, self.hi)] + xyz = np.vstack([self.shared, self.boundary]) + offset * _STEP + a = sum(getattr(t, method)(xyz) for t in tets) + b = getattr(prism, method)(xyz) + npt.assert_allclose(a, b, rtol=0, atol=1e-13 * np.max(np.abs(b))) + + @pytest.mark.parametrize("method", METHODS) + def test_split_tetrahedron_sums_to_parent(self, method): + # Four tetrahedra joining the faces of a skewed tetrahedron to an interior + # point: on the parent's boundary and on the shared internal faces and + # edges, the parts sum to the whole. + p = np.r_[0.3, 0.2, 0.25, 0.25] @ _TET + parts = [gravity.Tetrahedron(np.vstack([np.delete(_TET, i, axis=0), p])) for i in range(4)] + whole = gravity.Tetrahedron(_TET) + xyz = np.vstack([ + _TET_BOUNDARY, + p, + 0.5 * (p + _TET[1]), + (p + _TET[0] + _TET[2]) / 3, + ]) + for offset in (0.0, 1e-12, -1e-12): + x = xyz + offset * _STEP + a = sum(getattr(t, method)(x) for t in parts) + b = getattr(whole, method)(x) + npt.assert_allclose(a, b, rtol=0, atol=1e-12 * np.max(np.abs(b))) + + @pytest.mark.parametrize("method", METHODS[:2]) + def test_continuous_across_boundary(self, method): + tet = gravity.Tetrahedron(_TET, rho=3.0) + f = getattr(tet, method) + on = f(_TET_BOUNDARY) + scale = np.max(np.abs(on)) + for eps in [1e-9, 1e-12, 1e-15]: + for sign in (1, -1): + near = f(_TET_BOUNDARY + sign * eps * _STEP) + npt.assert_allclose(near, on, rtol=0, atol=1e-6 * scale) + + def test_far_field_is_point_mass(self): + v = np.array([[0, 0, 0], [3, 0.5, 0], [1, 2, 0.2], [0.7, 0.4, 1.9]]) + tet = gravity.Tetrahedron(v, rho=3.0) + pm = gravity.PointMass(mass=tet.mass, location=tet.location) + # About 300 body sizes away: the quadrupole term is below 1e-5 of the + # monopole, and both this kernel and Prism are still precise there (the + # closed forms lose precision by cancellation past ~1e3 body sizes). + far = np.array([[300.0, 600.0, -900.0], [-1500.0, 30.0, 600.0]]) + g_pm = pm.gravitational_field(far) + npt.assert_allclose(tet.gravitational_field(far), g_pm, rtol=1e-5, atol=1e-5 * np.abs(g_pm).max()) + + def test_laplace(self): + V, F = _box_polyhedron(self.lo, self.hi) + p = gravity.Polyhedron(V, F, rho=2.0) + from scipy.constants import G + tr_out = np.trace(p.gravitational_gradient(self.outside), axis1=-2, axis2=-1) + tr_in = np.trace(p.gravitational_gradient(self.inside), axis1=-2, axis2=-1) + npt.assert_allclose(tr_out, 0.0, atol=1e-12 * G * 2.0) + npt.assert_allclose(tr_in, -4 * np.pi * G * 2.0, rtol=1e-10)