"""
Enhanced gap source (Ding et al., 2013, eq. 7): a uniform field V/W over a
gap of width W around a feed point, feeding every RWG function that has a
triangle in the gap.
enhanced_gap_port(...) -> EnhancedGapPort gives the port as a real vector b_p
on the RWG edges, like the delta-gap Port (core.py): V = b_p v_p and the port
current i_p = b_p^T I. Eq. (7) is linear in the gap voltage, which is why one
vector describes the port. The high-level solvers take the specification
EnhancedGap (specs.py), resolved with this function once the mesh exists.
Partial triangles (exact integration)
-------------------------------------
E^i = (V/W) e_hat inside the window, so eq. (7) is
V_m = (V/W) e_hat . integral over (T_m^+- inside the window) of f_m dS.
f_m is linear on each triangle, so the integral over the clipped part of a
triangle (area A_c, centroid r_cc) is exact with one point:
integral = (l_m / 2A) A_c (r_cc - v^+) on T^+,
(l_m / 2A) A_c (v^- - r_cc) on T^-.
For a triangle entirely inside, A_c = A and r_cc is its centroid: the
centroid rule of the paper. The two differ only on triangles cut by the edge
of the window. The centroid rule (removed with multiple_gap_sources) fed such
a triangle wholly or not at all depending on where its centroid fell, so the
applied voltage jumped from one mesh to the next: on a gmsh dipole whose gap
edges were not mesh lines, the input resistance ranged from 63 to 182 Ohm
instead of 72 Ohm (documentation, user guide "Choosing the mesh size").
Gap localisation (a cube, not a band)
-------------------------------------
The gap window is a cube of side `gap_width` centred on the feed point,
tested on all three coordinates -- not just the excitation axis. For a simple
1D wire/strip (the case eq. 7 was derived for), the structure's cross-section
is already far smaller than gap_width, so this is equivalent to testing the
excitation axis alone. It stops being equivalent at a junction between
differently oriented surfaces sharing the feed point (e.g. a monopole blade
standing on a ground plane): testing only the excitation-axis coordinate
would then also catch far-away triangles that merely share that coordinate
with the feed point (a whole band of the ground plane), spuriously exciting
geometry unrelated to the feed. The cube keeps the excitation local.
"""
from __future__ import annotations
import warnings
from dataclasses import dataclass
import numpy as np
from harmolab.utils.ports.core import PortDefinitionError
_AXES = {'x': 0, 'y': 1, 'z': 2}
[docs]
class GapSourceError(PortDefinitionError):
"""Raised when a gap-source excitation finds no RWG edge to feed.
A PortDefinitionError (hence a ValueError): one exception type covers every
port model.
"""
[docs]
class GapSourceWarning(UserWarning):
"""Emitted when the conductor crosses the gap outside the gap window (part of it is not fed)."""
def _clip_polygon_to_box(polygon, lower, upper):
"""
Sutherland-Hodgman clipping of a planar polygon (list of (3,) points) by the
axis-aligned box lower <= r <= upper. Returns the clipped polygon (possibly empty).
"""
poly = list(polygon)
for axis in range(3):
for bound, keep_above in ((lower[axis], True), (upper[axis], False)):
if not poly:
return poly
out = []
n = len(poly)
for k in range(n):
a, b = poly[k], poly[(k + 1) % n]
da = (a[axis] - bound) if keep_above else (bound - a[axis])
db = (b[axis] - bound) if keep_above else (bound - b[axis])
if da >= 0:
out.append(a)
if (da >= 0) != (db >= 0):
t = da / (da - db)
out.append(a + t * (b - a))
poly = out
return poly
def _polygon_area_centroid(polygon):
"""Area and centroid of a planar polygon in 3D (fan triangulation from its first vertex)."""
if len(polygon) < 3:
return 0.0, None
p0 = polygon[0]
area = 0.0
moment = np.zeros(3)
for k in range(1, len(polygon) - 1):
a = 0.5 * np.linalg.norm(np.cross(polygon[k] - p0, polygon[k + 1] - p0))
area += a
moment += a * (p0 + polygon[k] + polygon[k + 1]) / 3.0
if area <= 0.0:
return 0.0, None
return area, moment / area
def _gap_fractions(tri_vertices, tri_area, centroids, feed_pt, half_W):
"""
For every triangle: the fraction of its area inside the gap cube, and the
centroid of that part (equal to the triangle centroid when it is entirely
inside). Only triangles whose bounding box meets the cube are clipped.
tri_vertices : (N_tri, 3, 3) vertex coordinates, [triangle, vertex, xyz]
"""
lower, upper = feed_pt - half_W, feed_pt + half_W
vmin = tri_vertices.min(axis=1) # (N_tri, 3)
vmax = tri_vertices.max(axis=1)
fraction = np.zeros(tri_vertices.shape[0])
part_centroid = centroids.T.copy() # (N_tri, 3)
inside = np.all((vmin >= lower) & (vmax <= upper), axis=1)
fraction[inside] = 1.0
touching = np.all((vmax >= lower) & (vmin <= upper), axis=1) & ~inside
for t in np.flatnonzero(touching):
area, centroid = _polygon_area_centroid(
_clip_polygon_to_box([tri_vertices[t, k] for k in range(3)], lower, upper))
if area > 0.0:
fraction[t] = min(area / tri_area[t], 1.0)
part_centroid[t] = centroid
return fraction, part_centroid
def _warn_if_conductor_crosses_gap_outside_window(label, tri_vertices, fraction, ax_idx, feed_pt, half_W,
triangles_plus, triangles_minus, stacklevel=3):
"""
`label` names the port in the message ("Port 0", "Port 'feed'"); stacklevel
makes the warning point at the caller's code.
Warn when the conductor runs ACROSS the gap outside the cube: a triangle that
lies in the gap slab along the excitation axis, reaches beyond the cube on a
transverse coordinate, belongs to a surface that contains the excitation
direction, and shares an RWG edge with a fed triangle. The part of the gap
cross-section it covers is not fed, which the input impedance does not show.
Surfaces perpendicular to the excitation direction (a ground plane under a
monopole fed along its axis) carry no current across the gap and are ignored.
"""
tol = 1e-9 * max(half_W, 1e-30)
in_slab = ((tri_vertices[:, :, ax_idx].max(axis=1) > feed_pt[ax_idx] - half_W + tol)
& (tri_vertices[:, :, ax_idx].min(axis=1) < feed_pt[ax_idx] + half_W - tol))
transverse = [k for k in range(3) if k != ax_idx]
beyond = np.zeros(tri_vertices.shape[0], dtype=bool)
for k in transverse:
beyond |= np.abs(tri_vertices[:, :, k] - feed_pt[k]).max(axis=1) > half_W + tol
normals = np.cross(tri_vertices[:, 1] - tri_vertices[:, 0], tri_vertices[:, 2] - tri_vertices[:, 0])
norm = np.linalg.norm(normals, axis=1)
along = np.ones_like(norm, dtype=bool)
ok = norm > 0
along[ok] = np.abs(normals[ok, ax_idx] / norm[ok]) < 0.9 # the surface contains the excitation axis
fed = fraction > 0
neighbour_of_fed = np.zeros(tri_vertices.shape[0], dtype=bool)
pair_fed = fed[triangles_plus] | fed[triangles_minus]
neighbour_of_fed[triangles_plus[pair_fed]] = True
neighbour_of_fed[triangles_minus[pair_fed]] = True
suspicious = in_slab & beyond & along & neighbour_of_fed
if np.any(suspicious):
warnings.warn(
f"Port {label}: the conductor crosses the gap outside the gap window "
f"(gap_width={2 * half_W:.4g} m, a cube centred on feed_point={feed_pt}): "
f"{int(np.count_nonzero(suspicious))} triangle(s) in the gap reach beyond it "
f"across the conductor and are not fed, so only part of the gap cross-section "
f"is excited and the input impedance is wrong. Make gap_width at least as wide "
f"as the conductor at the feed.",
GapSourceWarning, stacklevel=stacklevel)
def _triangle_vertices(points, triangles):
"""(num_triangles, 3 vertices, 3 xyz) vertex coordinates and the triangle areas."""
pts = np.asarray(points.points if hasattr(points, "points") else points, dtype=float)
tri_idx = np.asarray(triangles.triangles)[:3].astype(int) # (3, num_triangles)
tri_vertices = np.transpose(pts[:, tri_idx], (2, 1, 0)) # (num_triangles, 3 vertices, 3 xyz)
tri_area = np.asarray(triangles.triangles_area, dtype=float)
return tri_vertices, tri_area
def _gap_window(label, feed_pt, ax_idx, half_W, triangles, tri_vertices, tri_area, stacklevel):
"""
Weights of eq. (7) for one gap: (window_p, window_n, shift_p, shift_n), each
per RWG edge. window = fraction of T+/T- inside the cube; shift = correction
of rho . e_hat when only part of the triangle is inside (see "Partial
triangles" above): the rho vectors are taken at the centroid of that part.
"""
centroids = triangles.triangles_center # (3, num_triangles)
tri_plus_idx = triangles.triangles_plus # (num_edges,)
tri_minus_idx= triangles.triangles_minus # (num_edges,)
fraction, part_centroid = _gap_fractions(tri_vertices, tri_area, centroids, feed_pt, half_W)
window_p = fraction[tri_plus_idx]
window_n = fraction[tri_minus_idx]
offset = part_centroid.T - centroids # (3, num_triangles)
shift_p = offset[ax_idx, tri_plus_idx] # r_cc - r_c on T+
shift_n = -offset[ax_idx, tri_minus_idx] # -(r_cc - r_c) on T-
_warn_if_conductor_crosses_gap_outside_window(
label, tri_vertices, fraction, ax_idx, feed_pt, half_W,
np.asarray(tri_plus_idx).astype(int), np.asarray(tri_minus_idx).astype(int),
stacklevel=stacklevel + 1)
return window_p, window_n, shift_p, shift_n
def _no_edge_message(label, feed_pt, axis, gap_width):
return (
f"Port {label} (feed_point={feed_pt}, axis='{axis}', "
f"gap_width={gap_width:.4g}): no RWG edge found within the gap. "
f"Check that feed_point lies on (or very near) the mesh, that "
f"gap_width is large enough to reach at least one triangle on every "
f"side of the feed you intend to excite, and that the axis matches "
f"the actual direction current should flow at this feed (e.g. the "
f"antenna's own axis at a junction, not just the axis you happen to "
f"be thinking of)."
)
[docs]
@dataclass(frozen=True, eq=False)
class EnhancedGapPort:
"""
One enhanced gap source, as a port: the real vector b_p on the RWG edges.
Attributes
----------
name : str label used in results
edge_indices : (n_p,) int RWG edges with a triangle in the gap (the "feeding edges")
weights : (n_p,) float b_p on those edges: l_m / (2W) [chi+ (rho+ . e + shift+)
+ chi- (rho- . e + shift-)]
feed_point : (3,) float centre of the gap cube (m)
axis : 'x' | 'y' | 'z' excitation direction e_hat
gap_width : float W, side of the gap cube (m)
V = b_p v_p (eq. 7 for a gap voltage v_p) and i_p = b_p^T I. A weight may
be 0 on a feeding edge (rho . e = 0 there); the edge still belongs to the
port (it has a triangle in the gap).
"""
name: str
edge_indices: np.ndarray
weights: np.ndarray
feed_point: np.ndarray
axis: str
gap_width: float
def __post_init__(self):
idx = np.array(self.edge_indices, dtype=np.int64).reshape(-1)
w = np.array(self.weights, dtype=np.float64).reshape(-1)
p = np.array(self.feed_point, dtype=np.float64).reshape(-1)
if idx.size == 0:
raise PortDefinitionError(f"Port '{self.name}' has no edge.")
if w.shape != idx.shape:
raise PortDefinitionError(
f"Port '{self.name}': {idx.size} edge indices but {w.size} weights.")
if not np.all(np.isfinite(w)):
raise PortDefinitionError(f"Port '{self.name}': non-finite weight in {w}.")
if np.any(idx < 0) or np.unique(idx).size != idx.size:
raise PortDefinitionError(
f"Port '{self.name}': edge indices must be distinct and >= 0, got {idx}.")
if p.shape != (3,) or not np.all(np.isfinite(p)):
raise PortDefinitionError(f"Port '{self.name}': feed_point must be a finite 3-vector.")
if self.axis not in _AXES:
raise PortDefinitionError(
f"Port '{self.name}': axis must be 'x', 'y' or 'z', got {self.axis!r}.")
if not (np.isfinite(self.gap_width) and self.gap_width > 0):
raise PortDefinitionError(
f"Port '{self.name}': gap_width must be > 0, got {self.gap_width!r}.")
for arr in (idx, w, p):
arr.setflags(write=False)
object.__setattr__(self, "edge_indices", idx)
object.__setattr__(self, "weights", w)
object.__setattr__(self, "feed_point", p)
object.__setattr__(self, "gap_width", float(self.gap_width))
@property
def n_edges(self) -> int:
return int(self.edge_indices.size)
[docs]
def incidence_vector(self, edges) -> np.ndarray:
"""b_p, shape (N,): the weights on the feeding edges, 0 elsewhere."""
n_total = int(edges.total_number_of_edges)
if self.edge_indices.max() >= n_total:
raise PortDefinitionError(
f"Port '{self.name}' refers to edge {int(self.edge_indices.max())} but the mesh "
f"has only {n_total} RWG edges. Was the port built on a different mesh?")
b = np.zeros(n_total, dtype=np.float64)
b[self.edge_indices] = self.weights
return b
[docs]
def enhanced_gap_port(points, triangles, edges, vecteurs_rho, feed_point, axis, gap_width,
name) -> EnhancedGapPort:
"""
Enhanced gap source at `feed_point` as a port (see EnhancedGapPort).
Cube of side `gap_width` centred on `feed_point`, eq. (7) integrated
exactly over the part of each triangle inside it. For a gap voltage v the
excitation is V = v * port.incidence_vector(edges).
Raises PortDefinitionError for an invalid axis, gap_width or feed_point,
and GapSourceError (a PortDefinitionError) if no RWG edge is in the gap.
Emits GapSourceWarning when the conductor crosses the gap outside the cube.
"""
if axis not in _AXES:
raise PortDefinitionError(f"Port '{name}': axis must be 'x', 'y' or 'z', got {axis!r}.")
gap_width = float(gap_width)
if not (np.isfinite(gap_width) and gap_width > 0):
raise PortDefinitionError(f"Port '{name}': gap_width must be > 0, got {gap_width!r}.")
feed_pt = np.asarray(feed_point, dtype=float).reshape(-1)
if feed_pt.shape != (3,) or not np.all(np.isfinite(feed_pt)):
raise PortDefinitionError(f"Port '{name}': feed_point must be a finite 3-vector.")
ax_idx = _AXES[axis]
tri_vertices, tri_area = _triangle_vertices(points, triangles)
window_p, window_n, shift_p, shift_n = _gap_window(
f"'{name}'", feed_pt, ax_idx, gap_width / 2.0, triangles, tri_vertices, tri_area,
stacklevel=3)
port_indices = np.where((window_p > 0) | (window_n > 0))[0]
if port_indices.size == 0:
raise GapSourceError(_no_edge_message(f"'{name}'", feed_pt, axis, gap_width))
# eq. (7) with v = 1.
rho_p_dot = vecteurs_rho.vecteur_rho_plus[ax_idx, :]
rho_n_dot = vecteurs_rho.vecteur_rho_minus[ax_idx, :]
b = (edges.edges_length / (2.0 * gap_width)) * (
window_p * (rho_p_dot + shift_p) + window_n * (rho_n_dot + shift_n))
return EnhancedGapPort(name=name, edge_indices=port_indices, weights=b[port_indices],
feed_point=feed_pt, axis=axis, gap_width=gap_width)