phased-array-modeling 1.4.1__tar.gz → 1.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/PKG-INFO +1 -1
  2. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/__init__.py +12 -6
  3. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/beamforming.py +108 -63
  4. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/coordinates.py +74 -91
  5. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/core.py +291 -75
  6. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/export.py +55 -7
  7. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/geometry.py +105 -76
  8. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/impairments.py +401 -105
  9. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/vector_patterns.py +42 -11
  10. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/visualization.py +2 -1
  11. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/wideband.py +34 -18
  12. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array_modeling.egg-info/PKG-INFO +1 -1
  13. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array_modeling.egg-info/SOURCES.txt +1 -0
  14. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/pyproject.toml +1 -1
  15. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_beamforming.py +137 -0
  16. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_coordinates.py +47 -0
  17. phased_array_modeling-1.6.0/tests/test_core.py +381 -0
  18. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_export.py +52 -0
  19. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_geometry.py +121 -0
  20. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_impairments.py +214 -0
  21. phased_array_modeling-1.6.0/tests/test_textbook_benchmarks.py +220 -0
  22. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_vector_patterns.py +36 -4
  23. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_wideband.py +67 -0
  24. phased_array_modeling-1.4.1/tests/test_core.py +0 -225
  25. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/LICENSE +0 -0
  26. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/README.md +0 -0
  27. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/polarization.py +0 -0
  28. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array/utils.py +0 -0
  29. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array_modeling.egg-info/dependency_links.txt +0 -0
  30. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array_modeling.egg-info/requires.txt +0 -0
  31. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/phased_array_modeling.egg-info/top_level.txt +0 -0
  32. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/setup.cfg +0 -0
  33. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_directivity.py +0 -0
  34. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_docstrings.py +0 -0
  35. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_polarization.py +0 -0
  36. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_utils.py +0 -0
  37. {phased_array_modeling-1.4.1 → phased_array_modeling-1.6.0}/tests/test_visualization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: phased-array-modeling
3
- Version: 1.4.1
3
+ Version: 1.6.0
4
4
  Summary: Comprehensive Python library for phased array antenna modeling and visualization
5
5
  Author-email: John Hodge <jah70@vt.edu>
6
6
  License: MIT
@@ -33,7 +33,7 @@ Example
33
33
  >>> theta, phi, pattern_dB = pa.compute_full_pattern(geom.x, geom.y, weights, k)
34
34
  """
35
35
 
36
- __version__ = "1.4.1"
36
+ __version__ = "1.6.0"
37
37
 
38
38
  # Beamforming functions
39
39
  from .beamforming import ( # Amplitude tapers; Null steering; Multiple beams; Beam spoiling; Adaptive
@@ -55,10 +55,11 @@ from .coordinates import (antenna_to_cone, antenna_to_radar, cone_to_antenna,
55
55
  rotation_matrix_yaw)
56
56
  # Core computation functions
57
57
  from .core import (array_factor_fft, array_factor_uv, array_factor_vectorized,
58
- compute_directivity, compute_full_pattern,
58
+ array_manifold, compute_directivity, compute_full_pattern,
59
59
  compute_half_power_beamwidth, compute_pattern_cuts,
60
- element_pattern, element_pattern_cosine_tapered,
61
- steering_vector, total_pattern)
60
+ compute_peak_sidelobe_level, element_pattern,
61
+ element_pattern_cosine_tapered, steering_vector,
62
+ total_pattern)
62
63
  # Export functions
63
64
  from .export import (export_array_config_json, export_coupling_matrix_csv,
64
65
  export_geometry_csv, export_pattern_2d_csv,
@@ -81,8 +82,9 @@ from .impairments import ( # Mutual coupling; Phase quantization; Element failu
81
82
  active_scan_impedance_matrix, analyze_graceful_degradation,
82
83
  analyze_quantization_effect, apply_mutual_coupling, apply_scan_blindness,
83
84
  compute_scan_loss, mismatch_loss, mutual_coupling_matrix_measured,
84
- mutual_coupling_matrix_theoretical, quantization_rms_error,
85
- quantization_sidelobe_increase, quantize_phase, scan_blindness_model,
85
+ mutual_coupling_matrix_theoretical, quantization_lobes,
86
+ quantization_rms_error, quantization_sidelobe_increase,
87
+ quantization_sidelobe_level, quantize_phase, scan_blindness_model,
86
88
  simulate_element_failures, surface_wave_scan_angle, vswr_vs_scan)
87
89
  # Polarization functions
88
90
  from .polarization import (axial_ratio, co_pol_pattern,
@@ -127,6 +129,7 @@ __all__ = [
127
129
  "__version__",
128
130
  # Core
129
131
  "steering_vector",
132
+ "array_manifold",
130
133
  "array_factor_vectorized",
131
134
  "array_factor_uv",
132
135
  "array_factor_fft",
@@ -137,6 +140,7 @@ __all__ = [
137
140
  "compute_full_pattern",
138
141
  "compute_directivity",
139
142
  "compute_half_power_beamwidth",
143
+ "compute_peak_sidelobe_level",
140
144
  # Utils
141
145
  "deg2rad",
142
146
  "rad2deg",
@@ -218,6 +222,8 @@ __all__ = [
218
222
  "quantize_phase",
219
223
  "quantization_rms_error",
220
224
  "quantization_sidelobe_increase",
225
+ "quantization_sidelobe_level",
226
+ "quantization_lobes",
221
227
  "analyze_quantization_effect",
222
228
  "simulate_element_failures",
223
229
  "analyze_graceful_degradation",
@@ -4,6 +4,7 @@ Beamforming functions for phased arrays.
4
4
  Includes amplitude tapering, null steering, and multiple simultaneous beams.
5
5
  """
6
6
 
7
+ import warnings
7
8
  from typing import List, Optional, Tuple, Union
8
9
 
9
10
  import numpy as np
@@ -30,7 +31,8 @@ def taylor_taper_1d(
30
31
  n : int
31
32
  Number of elements
32
33
  sidelobe_dB : float
33
- Desired peak sidelobe level in dB (negative)
34
+ Desired peak sidelobe level in dB. Either sign is accepted
35
+ (-30 and 30 both mean sidelobes 30 dB below the peak).
34
36
  nbar : int
35
37
  Number of nearly equal-level sidelobes
36
38
 
@@ -38,9 +40,18 @@ def taylor_taper_1d(
38
40
  -------
39
41
  taper : ndarray
40
42
  Amplitude taper weights (n,)
43
+
44
+ Notes
45
+ -----
46
+ The weights sample the continuous Taylor line-source distribution
47
+ (``scipy.signal.windows.taylor``), so the achieved peak sidelobe level
48
+ is close to, but not exactly, the design value. Choose
49
+ ``nbar >= 2*A**2 + 0.5`` with ``A = arccosh(10**(|sidelobe_dB|/20))/pi``
50
+ (about 7 for -40 dB). Small arrays with deep sidelobes fall short:
51
+ N = 16 designed for -40 dB reaches about -39.3 dB with nbar = 7.
41
52
  """
42
53
  # Use scipy's Taylor window
43
- return signal.windows.taylor(n, nbar=nbar, sll=-sidelobe_dB, norm=True)
54
+ return signal.windows.taylor(n, nbar=nbar, sll=abs(sidelobe_dB), norm=True)
44
55
 
45
56
 
46
57
  def taylor_taper_2d(
@@ -107,14 +118,27 @@ def chebyshev_taper_1d(
107
118
  n : int
108
119
  Number of elements
109
120
  sidelobe_dB : float
110
- Desired sidelobe level in dB (negative)
121
+ Desired sidelobe level in dB. Either sign is accepted.
111
122
 
112
123
  Returns
113
124
  -------
114
125
  taper : ndarray
115
126
  Amplitude taper weights
127
+
128
+ Notes
129
+ -----
130
+ For large arrays with modest sidelobe levels the edge elements carry
131
+ noticeably more weight than their neighbors (Haupt Fig. 3.11); prefer
132
+ a Taylor taper there.
116
133
  """
117
- return signal.windows.chebwin(n, at=-sidelobe_dB)
134
+ with warnings.catch_warnings():
135
+ # SciPy warns that chebwin is unsuitable for spectral analysis
136
+ # above -45 dB; that concern does not apply to array tapers.
137
+ warnings.filterwarnings(
138
+ "ignore", message=".*not suitable for spectral analysis.*",
139
+ category=UserWarning,
140
+ )
141
+ return signal.windows.chebwin(n, at=abs(sidelobe_dB))
118
142
 
119
143
 
120
144
  def chebyshev_taper_2d(
@@ -723,13 +747,21 @@ def monopulse_weights(
723
747
  Nominal beam direction phi
724
748
  mode : str
725
749
  'sum' - sum pattern (normal beam)
726
- 'delta_az' - azimuth difference pattern
727
- 'delta_el' - elevation difference pattern
750
+ 'delta_az' - azimuth difference pattern (split in x)
751
+ 'delta_el' - elevation difference pattern (split in y)
728
752
 
729
753
  Returns
730
754
  -------
731
755
  weights : ndarray
732
756
  Complex weights for the specified mode
757
+
758
+ Notes
759
+ -----
760
+ The difference halves are split about the array centroid, and
761
+ elements lying on the split line (the center column or row of an
762
+ odd-sized array) get zero weight, giving an exact boresight null.
763
+ The difference weights are amplitude-uniform; multiply by a taper
764
+ for lower difference-pattern sidelobes.
733
765
  """
734
766
  # Base steering vector
735
767
  sv = steering_vector(
@@ -740,16 +772,22 @@ def monopulse_weights(
740
772
  if mode == 'sum':
741
773
  return sv
742
774
 
743
- elif mode == 'delta_az':
744
- # Difference in azimuth: flip sign for half the array in x
745
- sign = np.sign(geometry.x)
746
- sign[sign == 0] = 1 # Handle elements at x=0
747
- return sv * sign
748
-
749
- elif mode == 'delta_el':
750
- # Difference in elevation: flip sign for half the array in y
751
- sign = np.sign(geometry.y)
752
- sign[sign == 0] = 1
775
+ elif mode in ('delta_az', 'delta_el'):
776
+ # Difference pattern: opposite signs on the two halves of the
777
+ # aperture, split about the array centroid. Elements on the split
778
+ # line get zero weight so the halves cancel exactly on boresight.
779
+ coord = np.asarray(geometry.x if mode == 'delta_az' else geometry.y,
780
+ dtype=float)
781
+ if np.ptp(coord) == 0:
782
+ axis = 'x' if mode == 'delta_az' else 'y'
783
+ raise ValueError(
784
+ f"{mode} needs element positions that vary in {axis}; this "
785
+ "array has no extent in that direction, so it has no "
786
+ "difference pattern in that plane"
787
+ )
788
+ offset = coord - coord.mean()
789
+ tol = 1e-9 * max(float(np.ptp(coord)), 1e-30)
790
+ sign = np.where(np.abs(offset) <= tol, 0.0, np.sign(offset))
753
791
  return sv * sign
754
792
 
755
793
  else:
@@ -1037,8 +1075,10 @@ def adaptive_weights_smi(
1037
1075
  phi_desired_deg : float
1038
1076
  Desired signal direction phi in degrees
1039
1077
  interference_data : ndarray
1040
- Interference-plus-noise data matrix (n_snapshots x n_elements)
1041
- Each row is a snapshot of received signals
1078
+ Interference-plus-noise data matrix (n_snapshots x n_elements).
1079
+ Each row is a snapshot of received signals. A plane wave from
1080
+ direction u contributes ``amplitude * array_manifold(...)``
1081
+ (``exp(+j k r . u)``), not ``steering_vector``.
1042
1082
  diagonal_loading : float
1043
1083
  Diagonal loading factor for robustness.
1044
1084
  Adds diagonal_loading * I to the covariance matrix.
@@ -1046,7 +1086,10 @@ def adaptive_weights_smi(
1046
1086
  Returns
1047
1087
  -------
1048
1088
  weights : ndarray
1049
- Adaptive complex weights
1089
+ Adaptive complex weights, applied without conjugation: the array
1090
+ output is ``weights @ x`` and the pattern is
1091
+ ``array_factor_vectorized(..., weights, ...)``. The look-direction
1092
+ response ``weights @ array_manifold(look)`` equals 1.
1050
1093
 
1051
1094
  Examples
1052
1095
  --------
@@ -1068,9 +1111,12 @@ def adaptive_weights_smi(
1068
1111
  Notes
1069
1112
  -----
1070
1113
  The SMI weight vector is:
1071
- w = R^(-1) @ s / (s^H @ R^(-1) @ s)
1114
+ w = R~^(-1) @ s / (s^H @ R~^(-1) @ s)
1072
1115
 
1073
- where R is the sample covariance matrix and s is the steering vector.
1116
+ where ``s = steering_vector(...)`` and ``R~ = X^H X / K`` for the
1117
+ snapshot matrix X (rows are snapshots). ``R~`` is the conjugate of the
1118
+ usual covariance ``E[x x^H]``, so ``w`` is the conjugate of the
1119
+ textbook MVDR weight and is applied as ``w @ x``.
1074
1120
  Diagonal loading improves robustness when snapshots are limited.
1075
1121
  """
1076
1122
  n = geometry.n_elements
@@ -1115,14 +1161,15 @@ def adaptive_weights_gsc(
1115
1161
  phi_desired_deg: float,
1116
1162
  interference_data: np.ndarray,
1117
1163
  n_blocking_vectors: Optional[int] = None,
1118
- mu: float = 0.01
1164
+ mu: float = 0.1
1119
1165
  ) -> Tuple[np.ndarray, np.ndarray]:
1120
1166
  """
1121
1167
  Compute adaptive weights using Generalized Sidelobe Canceller (GSC).
1122
1168
 
1123
1169
  GSC provides a constrained adaptive filter structure that maintains
1124
1170
  distortionless response in the look direction while minimizing
1125
- interference and noise.
1171
+ interference and noise. The adaptive branch uses normalized LMS
1172
+ (NLMS) over one pass through the snapshots.
1126
1173
 
1127
1174
  Parameters
1128
1175
  ----------
@@ -1135,18 +1182,23 @@ def adaptive_weights_gsc(
1135
1182
  phi_desired_deg : float
1136
1183
  Desired signal direction phi in degrees
1137
1184
  interference_data : ndarray
1138
- Interference-plus-noise data (n_snapshots x n_elements)
1185
+ Interference-plus-noise data (n_snapshots x n_elements). A plane
1186
+ wave from direction u contributes ``amplitude * array_manifold``.
1139
1187
  n_blocking_vectors : int, optional
1140
1188
  Number of blocking matrix columns. Default: n_elements - 1
1141
1189
  mu : float
1142
- Adaptation step size for LMS algorithm
1190
+ Normalized LMS step size, stable for ``0 < mu < 2``. Each update
1191
+ is scaled by ``1 / ||x_b||^2``, so the step does not depend on the
1192
+ input power. Larger values adapt faster with more misadjustment.
1143
1193
 
1144
1194
  Returns
1145
1195
  -------
1146
1196
  weights : ndarray
1147
- Adaptive weights (n_elements,)
1197
+ Adaptive weights (n_elements,), applied without conjugation like
1198
+ :func:`adaptive_weights_smi`; the look-direction response is 1.
1148
1199
  blocking_matrix : ndarray
1149
- Blocking matrix used (n_elements x n_blocking_vectors)
1200
+ Blocking matrix used (n_elements x n_blocking_vectors), with
1201
+ ``B.T @ array_manifold(look) = 0``
1150
1202
 
1151
1203
  Examples
1152
1204
  --------
@@ -1169,59 +1221,50 @@ def adaptive_weights_gsc(
1169
1221
  w = w_q - B @ w_a
1170
1222
 
1171
1223
  where:
1172
- - w_q is the quiescent (non-adaptive) steering weight
1173
- - B is a blocking matrix orthogonal to the steering vector
1174
- - w_a are adaptive weights that minimize output power
1175
-
1176
- The blocking matrix satisfies: s^H @ B = 0 (nulls the look direction)
1224
+ - ``w_q = s / ||s||^2`` is the quiescent steering weight (unit
1225
+ look-direction response), with ``s = steering_vector(...)``
1226
+ - B is a blocking matrix with ``s^H @ B = 0``, equivalently
1227
+ ``B.T @ a0 = 0`` for the look-direction manifold ``a0``
1228
+ - ``w_a`` minimizes the output power ``|w.T @ x|^2``
1229
+
1230
+ With ``y_q = w_q @ x``, ``x_b = B.T @ x`` and ``e = y_q - w_a @ x_b``,
1231
+ the NLMS update is ``w_a += mu * e * conj(x_b) / (eps + ||x_b||^2)``.
1177
1232
  """
1178
1233
  n = geometry.n_elements
1179
1234
 
1180
1235
  if n_blocking_vectors is None:
1181
1236
  n_blocking_vectors = n - 1
1182
1237
 
1183
- # Quiescent steering vector
1238
+ # Quiescent steering vector, scaled for unit look-direction response
1184
1239
  s = steering_vector(
1185
1240
  k, geometry.x, geometry.y,
1186
1241
  theta_desired_deg, phi_desired_deg, geometry.z
1187
1242
  )
1188
- w_q = s / np.sqrt(np.sum(np.abs(s)**2)) # Normalize
1189
-
1190
- # Construct blocking matrix B orthogonal to s
1191
- # Use SVD of s to get orthogonal complement
1192
- s_normalized = s / np.linalg.norm(s)
1193
- s_col = s_normalized.reshape(-1, 1)
1243
+ w_q = s / np.sum(np.abs(s)**2)
1194
1244
 
1195
- # Create orthonormal basis for null space of s^H
1196
- # Using Householder or Gram-Schmidt
1245
+ # Blocking matrix: orthonormal columns orthogonal to s (s^H B = 0),
1246
+ # which is B.T @ conj(s) = 0, i.e. the look-direction manifold is
1247
+ # rejected by the w.T convention used here.
1248
+ s_col = (s / np.linalg.norm(s)).reshape(-1, 1)
1197
1249
  Q, _ = np.linalg.qr(np.hstack([s_col, np.eye(n)[:, :n_blocking_vectors]]))
1198
- B = Q[:, 1:n_blocking_vectors + 1] # Take columns orthogonal to s
1250
+ B = Q[:, 1:n_blocking_vectors + 1]
1199
1251
 
1200
- # Process data through GSC
1201
1252
  interference_data = np.asarray(interference_data, dtype=complex)
1202
1253
  n_snapshots = interference_data.shape[0]
1203
1254
 
1204
- # Initialize adaptive weights
1205
1255
  w_a = np.zeros(n_blocking_vectors, dtype=complex)
1256
+ eps = 1e-12
1206
1257
 
1207
- # LMS adaptation through data
1258
+ # NLMS adaptation, output y = w.T @ x (no conjugation)
1208
1259
  for snapshot_idx in range(n_snapshots):
1209
1260
  x = interference_data[snapshot_idx, :]
1210
1261
 
1211
- # Upper path output (reference)
1212
- y_q = w_q.conj() @ x
1213
-
1214
- # Lower path (blocking matrix output)
1215
- x_b = B.conj().T @ x
1216
-
1217
- # Error signal
1218
- y_a = w_a.conj() @ x_b
1219
- e = y_q - y_a
1262
+ y_q = w_q @ x # upper (quiescent) branch
1263
+ x_b = B.T @ x # blocked branch
1264
+ e = y_q - w_a @ x_b # GSC output
1220
1265
 
1221
- # LMS update
1222
- w_a = w_a + mu * e.conj() * x_b
1266
+ w_a = w_a + (mu / (eps + np.vdot(x_b, x_b).real)) * e * x_b.conj()
1223
1267
 
1224
- # Final weights
1225
1268
  weights = w_q - B @ w_a
1226
1269
 
1227
1270
  return weights, B
@@ -1300,7 +1343,7 @@ def compute_sinr_improvement(
1300
1343
  phi_s = np.array([[np.deg2rad(signal_direction[1])]])
1301
1344
  AF_signal = array_factor_vectorized(
1302
1345
  theta_s, phi_s,
1303
- geometry.x, geometry.y, weights, k
1346
+ geometry.x, geometry.y, weights, k, geometry.z
1304
1347
  )
1305
1348
  signal_out = signal_power * np.abs(AF_signal.item())**2
1306
1349
 
@@ -1311,7 +1354,7 @@ def compute_sinr_improvement(
1311
1354
  phi_int = np.array([[np.deg2rad(phi_i)]])
1312
1355
  AF_int = array_factor_vectorized(
1313
1356
  theta_int, phi_int,
1314
- geometry.x, geometry.y, weights, k
1357
+ geometry.x, geometry.y, weights, k, geometry.z
1315
1358
  )
1316
1359
  interference_out += power_i * np.abs(AF_int.item())**2
1317
1360
 
@@ -1390,19 +1433,21 @@ def plot_adapted_pattern(
1390
1433
 
1391
1434
  # Compute patterns
1392
1435
  theta = np.linspace(-np.pi/2, np.pi/2, n_points)
1393
- phi = np.full_like(theta, np.deg2rad(phi_cut_deg))
1436
+ # Negative theta is the opposite side of the cut plane (phi + 180)
1437
+ phi = np.where(theta >= 0, np.deg2rad(phi_cut_deg),
1438
+ np.deg2rad(phi_cut_deg) + np.pi)
1394
1439
 
1395
- theta_grid = theta.reshape(-1, 1)
1440
+ theta_grid = np.abs(theta).reshape(-1, 1)
1396
1441
  phi_grid = phi.reshape(-1, 1)
1397
1442
 
1398
1443
  AF_quiescent = array_factor_vectorized(
1399
1444
  theta_grid, phi_grid,
1400
- geometry.x, geometry.y, weights_quiescent, k
1445
+ geometry.x, geometry.y, weights_quiescent, k, geometry.z
1401
1446
  ).ravel()
1402
1447
 
1403
1448
  AF_adapted = array_factor_vectorized(
1404
1449
  theta_grid, phi_grid,
1405
- geometry.x, geometry.y, weights_adapted, k
1450
+ geometry.x, geometry.y, weights_adapted, k, geometry.z
1406
1451
  ).ravel()
1407
1452
 
1408
1453
  # Convert to dB
@@ -24,9 +24,14 @@ def antenna_to_radar(
24
24
  - theta: angle from boresight (z-axis), 0 at boresight
25
25
  - phi: azimuthal angle in x-y plane, 0 along x-axis
26
26
 
27
- Radar coordinates:
28
- - az: azimuth in horizontal plane, 0 at boresight
29
- - el: elevation from horizon, 0 at horizon, positive up
27
+ Radar coordinates (array face pointing at zenith):
28
+ - az: azimuth in the array (x-y) plane, measured from the x-axis,
29
+ ``atan2(v, u)``
30
+ - el: elevation above the array plane, ``90 deg - theta``; the
31
+ array boresight (+z) is at el = 90 deg
32
+
33
+ For az/el angles centred on boresight (boresight at az = el = 0), use
34
+ :func:`~phased_array.utils.thetaphi_to_azel` instead.
30
35
 
31
36
  Parameters
32
37
  ----------
@@ -44,7 +49,7 @@ def antenna_to_radar(
44
49
 
45
50
  Examples
46
51
  --------
47
- Boresight in antenna coords is also boresight in radar:
52
+ Array boresight maps to the zenith (el = 90 deg):
48
53
 
49
54
  >>> import numpy as np
50
55
  >>> import phased_array as pa
@@ -359,12 +364,20 @@ def rotate_pattern(
359
364
 
360
365
  Returns
361
366
  -------
362
- theta_new : ndarray
363
- New theta coordinates after rotation
364
- phi_new : ndarray
365
- New phi coordinates after rotation
367
+ theta_out : ndarray
368
+ Theta grid of the output, equal to the input ``theta``
369
+ phi_out : ndarray
370
+ Phi grid of the output, equal to the input ``phi``
366
371
  pattern_interp : ndarray
367
- Pattern values interpolated onto the new grid
372
+ Rotated pattern sampled on ``(theta_out, phi_out)``: the value at
373
+ each grid direction is the original pattern at the direction that
374
+ the rotation maps onto it
375
+
376
+ Raises
377
+ ------
378
+ ValueError
379
+ If ``theta``, ``phi`` and ``pattern`` are not 2D grids of the same
380
+ shape (``np.meshgrid(..., indexing='ij')``)
368
381
 
369
382
  Examples
370
383
  --------
@@ -385,19 +398,19 @@ def rotate_pattern(
385
398
 
386
399
  Notes
387
400
  -----
388
- For points that rotate outside the original grid, extrapolation
389
- may produce artifacts. Consider padding the original pattern.
401
+ Directions whose source lies outside the original grid are filled
402
+ with zero. Before v1.6.0 the first two outputs were the input points
403
+ rotated forward, which did not correspond to ``pattern_interp``.
390
404
  """
391
405
  theta = np.asarray(theta)
392
406
  phi = np.asarray(phi)
393
407
  pattern = np.asarray(pattern)
394
-
395
- original_shape = theta.shape
396
-
397
- # Flatten for processing
398
- theta_flat = theta.ravel()
399
- phi_flat = phi.ravel()
400
- pattern_flat = pattern.ravel()
408
+ if theta.ndim != 2 or theta.shape != phi.shape or theta.shape != pattern.shape:
409
+ raise ValueError(
410
+ "theta, phi and pattern must be 2D grids of the same shape "
411
+ "(np.meshgrid(..., indexing='ij')), got shapes "
412
+ f"{theta.shape}, {phi.shape} and {pattern.shape}"
413
+ )
401
414
 
402
415
  # Create rotation matrix (yaw * pitch * roll)
403
416
  R_roll = rotation_matrix_roll(np.deg2rad(roll_deg))
@@ -405,80 +418,50 @@ def rotate_pattern(
405
418
  R_yaw = rotation_matrix_yaw(np.deg2rad(yaw_deg))
406
419
  R = R_yaw @ R_pitch @ R_roll
407
420
 
408
- # Convert theta/phi to Cartesian direction vectors
409
- x = np.sin(theta_flat) * np.cos(phi_flat)
410
- y = np.sin(theta_flat) * np.sin(phi_flat)
411
- z = np.cos(theta_flat)
412
-
413
- # Stack into (3, N) array and rotate
414
- vectors = np.vstack([x, y, z])
415
- vectors_rot = R @ vectors
416
-
417
- # Convert back to theta/phi
418
- x_rot = vectors_rot[0]
419
- y_rot = vectors_rot[1]
420
- z_rot = vectors_rot[2]
421
-
422
- theta_new_flat = np.arccos(np.clip(z_rot, -1, 1))
423
- phi_new_flat = np.arctan2(y_rot, x_rot)
424
-
425
- # For interpolation, we need the inverse rotation to find where
426
- # each output point came from in the original pattern
427
- R_inv = R.T
428
-
429
- # Create output grid at original theta/phi locations
430
- theta_out_flat = theta_flat.copy()
431
- phi_out_flat = phi_flat.copy()
432
-
433
- # Convert output grid to Cartesian
434
- x_out = np.sin(theta_out_flat) * np.cos(phi_out_flat)
435
- y_out = np.sin(theta_out_flat) * np.sin(phi_out_flat)
436
- z_out = np.cos(theta_out_flat)
437
-
438
- # Apply inverse rotation to find source locations
439
- vectors_out = np.vstack([x_out, y_out, z_out])
440
- vectors_src = R_inv @ vectors_out
421
+ # Each output grid direction takes the value of the original pattern at
422
+ # the direction that R maps onto it, i.e. R^T applied to the output.
423
+ theta_flat = theta.ravel()
424
+ phi_flat = phi.ravel()
425
+ vectors_out = np.vstack([np.sin(theta_flat) * np.cos(phi_flat),
426
+ np.sin(theta_flat) * np.sin(phi_flat),
427
+ np.cos(theta_flat)])
428
+ vectors_src = R.T @ vectors_out
429
+
430
+ theta_1d = theta[:, 0]
431
+ phi_1d = phi[0, :]
432
+
433
+ # Wrap source phi into the grid's own range, and close an open
434
+ # full-turn grid ([0, 2*pi) without the endpoint) at the seam.
435
+ two_pi = 2 * np.pi
436
+ phi_min = float(phi_1d[0])
437
+ grid_phi = phi_1d
438
+ close_seam = False
439
+ if phi_1d.size > 1:
440
+ span = float(phi_1d[-1] - phi_1d[0])
441
+ step = float(np.median(np.diff(phi_1d)))
442
+ tol = 1e-6 * two_pi
443
+ close_seam = span < two_pi - tol and span + step >= two_pi - tol
444
+ if close_seam:
445
+ grid_phi = np.append(phi_1d, phi_min + two_pi)
441
446
 
442
- # Convert source locations to theta/phi
443
447
  theta_src = np.arccos(np.clip(vectors_src[2], -1, 1))
444
- phi_src = np.arctan2(vectors_src[1], vectors_src[0])
445
-
446
- # Normalize phi to [0, 2*pi]
447
- phi_src = np.mod(phi_src, 2 * np.pi)
448
-
449
- # Interpolate pattern values
450
- # Create interpolator from original pattern
451
- if pattern.ndim == 2:
452
- # 2D grid case - use theta_1d, phi_1d for interpolation
453
- theta_1d = theta[:, 0] if theta.ndim == 2 else np.unique(theta)
454
- phi_1d = phi[0, :] if phi.ndim == 2 else np.unique(phi)
455
-
456
- # Handle complex patterns
457
- if np.iscomplexobj(pattern):
458
- interp_real = interpolate.RegularGridInterpolator(
459
- (theta_1d, phi_1d), np.real(pattern),
460
- method='linear', bounds_error=False, fill_value=0
461
- )
462
- interp_imag = interpolate.RegularGridInterpolator(
463
- (theta_1d, phi_1d), np.imag(pattern),
464
- method='linear', bounds_error=False, fill_value=0
465
- )
466
- points = np.column_stack([theta_src, phi_src])
467
- pattern_interp_flat = interp_real(points) + 1j * interp_imag(points)
468
- else:
469
- interp = interpolate.RegularGridInterpolator(
470
- (theta_1d, phi_1d), pattern,
471
- method='linear', bounds_error=False, fill_value=0
472
- )
473
- points = np.column_stack([theta_src, phi_src])
474
- pattern_interp_flat = interp(points)
448
+ phi_src = phi_min + np.mod(
449
+ np.arctan2(vectors_src[1], vectors_src[0]) - phi_min, two_pi)
450
+ points = np.column_stack([theta_src, phi_src])
451
+
452
+ def sample(values):
453
+ if close_seam:
454
+ values = np.concatenate([values, values[:, :1]], axis=1)
455
+ interp = interpolate.RegularGridInterpolator(
456
+ (theta_1d, grid_phi), values,
457
+ method='linear', bounds_error=False, fill_value=0
458
+ )
459
+ return interp(points)
460
+
461
+ if np.iscomplexobj(pattern):
462
+ pattern_interp = sample(np.real(pattern)) + 1j * sample(np.imag(pattern))
475
463
  else:
476
- # 1D case - just do nearest neighbor or simple interpolation
477
- pattern_interp_flat = pattern_flat.copy()
478
-
479
- # Reshape outputs
480
- theta_new = theta_new_flat.reshape(original_shape)
481
- phi_new = phi_new_flat.reshape(original_shape)
482
- pattern_interp = pattern_interp_flat.reshape(original_shape)
464
+ pattern_interp = sample(pattern)
465
+ pattern_interp = pattern_interp.reshape(theta.shape)
483
466
 
484
- return theta_new, phi_new, pattern_interp
467
+ return theta.copy(), phi.copy(), pattern_interp