phased-array-modeling 1.3.2__tar.gz → 1.4.1__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 (35) hide show
  1. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/PKG-INFO +11 -5
  2. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/README.md +9 -2
  3. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/__init__.py +26 -1
  4. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/core.py +206 -14
  5. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/geometry.py +27 -5
  6. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/polarization.py +4 -4
  7. phased_array_modeling-1.4.1/phased_array/vector_patterns.py +725 -0
  8. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/PKG-INFO +11 -5
  9. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/SOURCES.txt +3 -0
  10. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/pyproject.toml +2 -3
  11. phased_array_modeling-1.4.1/tests/test_directivity.py +439 -0
  12. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_docstrings.py +17 -0
  13. phased_array_modeling-1.4.1/tests/test_vector_patterns.py +382 -0
  14. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/LICENSE +0 -0
  15. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/beamforming.py +0 -0
  16. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/coordinates.py +0 -0
  17. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/export.py +0 -0
  18. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/impairments.py +0 -0
  19. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/utils.py +0 -0
  20. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/visualization.py +0 -0
  21. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array/wideband.py +0 -0
  22. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/dependency_links.txt +0 -0
  23. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/requires.txt +0 -0
  24. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/top_level.txt +0 -0
  25. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/setup.cfg +0 -0
  26. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_beamforming.py +0 -0
  27. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_coordinates.py +0 -0
  28. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_core.py +0 -0
  29. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_export.py +0 -0
  30. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_geometry.py +0 -0
  31. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_impairments.py +0 -0
  32. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_polarization.py +0 -0
  33. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_utils.py +0 -0
  34. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_visualization.py +0 -0
  35. {phased_array_modeling-1.3.2 → phased_array_modeling-1.4.1}/tests/test_wideband.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: phased-array-modeling
3
- Version: 1.3.2
3
+ Version: 1.4.1
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
@@ -15,14 +15,13 @@ Classifier: Intended Audience :: Education
15
15
  Classifier: License :: OSI Approved :: MIT License
16
16
  Classifier: Operating System :: OS Independent
17
17
  Classifier: Programming Language :: Python :: 3
18
- Classifier: Programming Language :: Python :: 3.8
19
18
  Classifier: Programming Language :: Python :: 3.9
20
19
  Classifier: Programming Language :: Python :: 3.10
21
20
  Classifier: Programming Language :: Python :: 3.11
22
21
  Classifier: Programming Language :: Python :: 3.12
23
22
  Classifier: Topic :: Scientific/Engineering
24
23
  Classifier: Topic :: Scientific/Engineering :: Physics
25
- Requires-Python: >=3.8
24
+ Requires-Python: >=3.9
26
25
  Description-Content-Type: text/markdown
27
26
  License-File: LICENSE
28
27
  Requires-Dist: numpy>=1.20.0
@@ -49,7 +48,7 @@ Dynamic: license-file
49
48
  [![CI](https://github.com/jman4162/Phased-Array-Antenna-Model/actions/workflows/ci.yml/badge.svg)](https://github.com/jman4162/Phased-Array-Antenna-Model/actions/workflows/ci.yml)
50
49
  [![PyPI version](https://img.shields.io/pypi/v/phased-array-modeling.svg)](https://pypi.org/project/phased-array-modeling/)
51
50
  [![PyPI downloads](https://img.shields.io/pypi/dm/phased-array-modeling.svg)](https://pypi.org/project/phased-array-modeling/)
52
- [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
51
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
53
52
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
54
53
  [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jman4162/Phased-Array-Antenna-Model/blob/main/Phased_Array_Demo.ipynb)
55
54
  [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://phased-array-antenna-model.streamlit.app/)
@@ -57,12 +56,18 @@ Dynamic: license-file
57
56
 
58
57
  A comprehensive Python library for computing and visualizing phased array antenna radiation patterns. Features vectorized computations (50-100x faster than naive loops), multiple array geometries, advanced beamforming, and interactive 3D visualization.
59
58
 
59
+ Full walkthrough of the physics and API:
60
+ [Modeling phased arrays in Python, from physics to trade study](https://john-hodge.com/blog/modeling-phased-arrays-in-python/).
61
+ What's new in v1.4.0:
62
+ [polarized patterns for phased arrays](https://john-hodge.com/blog/phased-array-modeling-1-4-0/).
63
+
60
64
  ## Features
61
65
 
62
66
  - **High Performance**: Vectorized array factor computation (50-100x faster than naive loops)
63
67
  - **Multiple Geometries**: Rectangular, triangular, circular, cylindrical, spherical, sparse/thinned arrays
64
68
  - **Beamforming**: Amplitude tapering (Taylor, Chebyshev, etc.), null steering, multi-beam
65
69
  - **Realistic Impairments**: Mutual coupling, phase quantization, element failures, scan blindness
70
+ - **Polarized Patterns**: Vector (E-theta, E-phi) patterns with dipole/patch/CP element models, co/cross-pol cuts, axial ratio and XPD maps, measured element pattern import
66
71
  - **Visualization**: 2D matplotlib, interactive 3D Plotly, UV-space representation
67
72
  - **Subarray Support**: Subarray-level beamforming with quantized phase shifters
68
73
  - **Data Export**: CSV, JSON, and NumPy formats for patterns, weights, and geometry
@@ -239,6 +244,7 @@ phased_array/
239
244
  ├── impairments.py # Coupling, quantization, failures, scan blindness
240
245
  ├── wideband.py # True-time-delay steering, beam squint, bandwidth
241
246
  ├── polarization.py # Jones/Stokes, axial ratio, XPD, Ludwig-3
247
+ ├── vector_patterns.py # Polarized elements, vector AF, co/cross patterns
242
248
  ├── coordinates.py # Antenna/radar/cone frames, pattern rotation
243
249
  ├── export.py # CSV/JSON/NPZ export, summary reports
244
250
  ├── visualization.py # 2D, 3D Plotly, UV-space plotting
@@ -247,7 +253,7 @@ phased_array/
247
253
 
248
254
  ## Requirements
249
255
 
250
- - Python 3.8+
256
+ - Python 3.9+
251
257
  - NumPy >= 1.20.0
252
258
  - Matplotlib >= 3.5.0
253
259
  - SciPy >= 1.7.0
@@ -3,7 +3,7 @@
3
3
  [![CI](https://github.com/jman4162/Phased-Array-Antenna-Model/actions/workflows/ci.yml/badge.svg)](https://github.com/jman4162/Phased-Array-Antenna-Model/actions/workflows/ci.yml)
4
4
  [![PyPI version](https://img.shields.io/pypi/v/phased-array-modeling.svg)](https://pypi.org/project/phased-array-modeling/)
5
5
  [![PyPI downloads](https://img.shields.io/pypi/dm/phased-array-modeling.svg)](https://pypi.org/project/phased-array-modeling/)
6
- [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
6
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
7
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
8
  [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/jman4162/Phased-Array-Antenna-Model/blob/main/Phased_Array_Demo.ipynb)
9
9
  [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://phased-array-antenna-model.streamlit.app/)
@@ -11,12 +11,18 @@
11
11
 
12
12
  A comprehensive Python library for computing and visualizing phased array antenna radiation patterns. Features vectorized computations (50-100x faster than naive loops), multiple array geometries, advanced beamforming, and interactive 3D visualization.
13
13
 
14
+ Full walkthrough of the physics and API:
15
+ [Modeling phased arrays in Python, from physics to trade study](https://john-hodge.com/blog/modeling-phased-arrays-in-python/).
16
+ What's new in v1.4.0:
17
+ [polarized patterns for phased arrays](https://john-hodge.com/blog/phased-array-modeling-1-4-0/).
18
+
14
19
  ## Features
15
20
 
16
21
  - **High Performance**: Vectorized array factor computation (50-100x faster than naive loops)
17
22
  - **Multiple Geometries**: Rectangular, triangular, circular, cylindrical, spherical, sparse/thinned arrays
18
23
  - **Beamforming**: Amplitude tapering (Taylor, Chebyshev, etc.), null steering, multi-beam
19
24
  - **Realistic Impairments**: Mutual coupling, phase quantization, element failures, scan blindness
25
+ - **Polarized Patterns**: Vector (E-theta, E-phi) patterns with dipole/patch/CP element models, co/cross-pol cuts, axial ratio and XPD maps, measured element pattern import
20
26
  - **Visualization**: 2D matplotlib, interactive 3D Plotly, UV-space representation
21
27
  - **Subarray Support**: Subarray-level beamforming with quantized phase shifters
22
28
  - **Data Export**: CSV, JSON, and NumPy formats for patterns, weights, and geometry
@@ -193,6 +199,7 @@ phased_array/
193
199
  ├── impairments.py # Coupling, quantization, failures, scan blindness
194
200
  ├── wideband.py # True-time-delay steering, beam squint, bandwidth
195
201
  ├── polarization.py # Jones/Stokes, axial ratio, XPD, Ludwig-3
202
+ ├── vector_patterns.py # Polarized elements, vector AF, co/cross patterns
196
203
  ├── coordinates.py # Antenna/radar/cone frames, pattern rotation
197
204
  ├── export.py # CSV/JSON/NPZ export, summary reports
198
205
  ├── visualization.py # 2D, 3D Plotly, UV-space plotting
@@ -201,7 +208,7 @@ phased_array/
201
208
 
202
209
  ## Requirements
203
210
 
204
- - Python 3.8+
211
+ - Python 3.9+
205
212
  - NumPy >= 1.20.0
206
213
  - Matplotlib >= 3.5.0
207
214
  - SciPy >= 1.7.0
@@ -9,6 +9,7 @@ antenna radiation patterns, including:
9
9
  - Various array geometries (rectangular, circular, conformal, sparse)
10
10
  - Beamforming techniques (tapering, null steering, multi-beam)
11
11
  - Realistic impairments (mutual coupling, quantization, failures, scan blindness)
12
+ - Vector (polarized) patterns: co/cross-pol, axial ratio, XPD, conformal
12
13
  - Interactive 3D visualization with Plotly
13
14
  - UV-space pattern representation
14
15
 
@@ -32,7 +33,7 @@ Example
32
33
  >>> theta, phi, pattern_dB = pa.compute_full_pattern(geom.x, geom.y, weights, k)
33
34
  """
34
35
 
35
- __version__ = "1.3.2"
36
+ __version__ = "1.4.1"
36
37
 
37
38
  # Beamforming functions
38
39
  from .beamforming import ( # Amplitude tapers; Null steering; Multiple beams; Beam spoiling; Adaptive
@@ -95,6 +96,16 @@ from .utils import (azel_to_thetaphi, create_theta_phi_grid, create_uv_grid,
95
96
  frequency_to_wavelength, is_visible_region, linear_to_db,
96
97
  normalize_pattern, rad2deg, theta_phi_to_uv,
97
98
  thetaphi_to_azel, uv_to_theta_phi, wavelength_to_k)
99
+ # Vector (polarized) pattern functions
100
+ from .vector_patterns import (GriddedElementPattern, VectorPattern,
101
+ compute_co_cross_pattern_cuts,
102
+ compute_full_vector_pattern,
103
+ cos_q_polarized_element, crossed_dipole_element,
104
+ dipole_element, dual_pol_weights,
105
+ element_rotation_matrices,
106
+ global_to_local_angles, ideal_patch_element,
107
+ vector_array_factor_conformal,
108
+ vector_total_pattern)
98
109
  # Visualization functions
99
110
  from .visualization import ( # 2D matplotlib plots; UV-space; 3D Plotly plots; Wideband
100
111
  compute_pattern_uv_space, create_pattern_animation_plotly,
@@ -278,4 +289,18 @@ __all__ = [
278
289
  "rotation_matrix_pitch",
279
290
  "rotation_matrix_yaw",
280
291
  "rotate_pattern",
292
+ # Vector (polarized) patterns
293
+ "VectorPattern",
294
+ "GriddedElementPattern",
295
+ "dipole_element",
296
+ "ideal_patch_element",
297
+ "cos_q_polarized_element",
298
+ "crossed_dipole_element",
299
+ "vector_total_pattern",
300
+ "compute_full_vector_pattern",
301
+ "compute_co_cross_pattern_cuts",
302
+ "dual_pol_weights",
303
+ "element_rotation_matrices",
304
+ "global_to_local_angles",
305
+ "vector_array_factor_conformal",
281
306
  ]
@@ -9,6 +9,7 @@ import warnings
9
9
  from typing import Optional, Tuple, Union
10
10
 
11
11
  import numpy as np
12
+ from scipy.integrate import trapezoid
12
13
 
13
14
  from .utils import create_theta_phi_grid, linear_to_db, theta_phi_to_uv
14
15
 
@@ -602,47 +603,238 @@ def compute_full_pattern(
602
603
  return theta_1d, phi_1d, pattern_dB
603
604
 
604
605
 
606
+ def _angle_axes(
607
+ theta: np.ndarray,
608
+ phi: np.ndarray,
609
+ pattern: np.ndarray
610
+ ) -> Tuple[np.ndarray, np.ndarray]:
611
+ """
612
+ Validate a (theta, phi) meshgrid and return its 1D axes.
613
+
614
+ Parameters
615
+ ----------
616
+ theta, phi : ndarray
617
+ 2D angle grids in radians, as produced by
618
+ :func:`~phased_array.utils.create_theta_phi_grid`
619
+ (``np.meshgrid(..., indexing='ij')``)
620
+ pattern : ndarray
621
+ Pattern sampled on the same grid
622
+
623
+ Returns
624
+ -------
625
+ theta_1d : ndarray
626
+ Theta samples, shape (n_theta,)
627
+ phi_1d : ndarray
628
+ Phi samples, shape (n_phi,)
629
+
630
+ Raises
631
+ ------
632
+ ValueError
633
+ If the arrays are not 2D and identically shaped, contain non-finite
634
+ values, have fewer than two samples on an axis, are not separable in
635
+ the ``indexing='ij'`` sense, are not strictly increasing with uniform
636
+ spacing, or sample theta outside [0, pi].
637
+ """
638
+ theta, phi, pattern = (np.asarray(a) for a in (theta, phi, pattern))
639
+
640
+ for name, arr in (("theta", theta), ("phi", phi), ("pattern", pattern)):
641
+ if np.ndim(arr) != 2:
642
+ raise ValueError(
643
+ f"{name} must be a 2D grid, got ndim={np.ndim(arr)}. Pass the "
644
+ "theta_grid/phi_grid outputs of create_theta_phi_grid(), not "
645
+ "the 1D axes."
646
+ )
647
+ if not np.all(np.isfinite(arr)):
648
+ raise ValueError(f"{name} contains non-finite values (NaN or inf)")
649
+
650
+ if theta.shape != phi.shape or theta.shape != pattern.shape:
651
+ raise ValueError(
652
+ "theta, phi and pattern must have the same shape, got "
653
+ f"{theta.shape}, {phi.shape} and {pattern.shape}"
654
+ )
655
+
656
+ n_theta, n_phi = theta.shape
657
+ if n_theta < 2 or n_phi < 2:
658
+ raise ValueError(
659
+ "at least two samples are required on each axis, got shape "
660
+ f"{theta.shape}. A single-sample axis carries no integration span."
661
+ )
662
+
663
+ # Separability: theta must vary along axis 0 only, phi along axis 1 only.
664
+ if not np.allclose(theta, theta[:, :1]):
665
+ raise ValueError(
666
+ "theta must be constant along axis 1. The grid looks transposed "
667
+ "or built with indexing='xy'; use indexing='ij'."
668
+ )
669
+ if not np.allclose(phi, phi[:1, :]):
670
+ raise ValueError(
671
+ "phi must be constant along axis 0. The grid looks transposed "
672
+ "or built with indexing='xy'; use indexing='ij'."
673
+ )
674
+
675
+ axes = []
676
+ tolerances = []
677
+ for name, samples in (("theta", theta[:, 0]), ("phi", phi[0, :])):
678
+ axis = samples.astype(np.float64)
679
+ # Compare positions to a uniform axis rather than successive
680
+ # differences, which amplify rounding error. The tolerance scales
681
+ # with the axis span, not the array dtype, so a float32 grid and
682
+ # the same grid upcast to float64 are judged identically.
683
+ span = float(axis[-1] - axis[0])
684
+ tol = max(1e-12, 1e-6 * abs(span))
685
+ if not np.all(np.diff(axis) > 0):
686
+ raise ValueError(
687
+ f"{name} must be strictly increasing, got samples from "
688
+ f"{axis[0]:.6g} to {axis[-1]:.6g} rad"
689
+ )
690
+ uniform = np.linspace(axis[0], axis[-1], axis.size)
691
+ deviation = float(np.max(np.abs(axis - uniform)))
692
+ if deviation > tol:
693
+ raise ValueError(
694
+ f"{name} must be uniformly spaced; samples deviate from a "
695
+ f"uniform axis by up to {deviation:.3g} rad, tolerance "
696
+ f"{tol:.3g} rad"
697
+ )
698
+ axes.append(axis)
699
+ tolerances.append(tol)
700
+
701
+ theta_1d, phi_1d = axes
702
+ theta_tol, phi_tol = tolerances
703
+ if theta_1d[0] < -theta_tol or theta_1d[-1] > np.pi + theta_tol:
704
+ raise ValueError(
705
+ "theta must lie within [0, pi] radians, got samples from "
706
+ f"{theta_1d[0]:.6g} to {theta_1d[-1]:.6g} rad. Angles in "
707
+ "degrees are a common cause."
708
+ )
709
+
710
+ # A span wider than a full turn counts some directions more than once.
711
+ phi_span = float(phi_1d[-1] - phi_1d[0])
712
+ if phi_span > 2 * np.pi + phi_tol:
713
+ raise ValueError(
714
+ f"phi must span at most 2*pi radians, got {phi_span:.6g} rad "
715
+ f"from {phi_1d[0]:.6g} to {phi_1d[-1]:.6g}. Angles in degrees "
716
+ "are a common cause."
717
+ )
718
+
719
+ # float32(pi) lies slightly above pi; clamp only permitted roundoff.
720
+ return np.clip(theta_1d, 0, np.pi), phi_1d
721
+
722
+
605
723
  def compute_directivity(
606
724
  theta: np.ndarray,
607
725
  phi: np.ndarray,
608
726
  pattern: np.ndarray
609
727
  ) -> float:
610
728
  """
611
- Compute directivity from a full-sphere pattern.
729
+ Compute peak directivity by integrating a pattern over solid angle.
730
+
731
+ Power is treated as constant over each theta cell. Cell boundaries are
732
+ the midpoints of adjacent theta samples, clipped at the first and last
733
+ samples. The weight of row i is
734
+
735
+ w_i = cos(theta_edge_i) - cos(theta_edge_{i+1})
736
+
737
+ so that ``sum(w_i) * (phi span)`` reproduces the sampled solid angle
738
+ within floating-point error. Azimuth is integrated with the trapezoidal
739
+ rule. Midpoint boundaries keep neighboring cells contiguous even when
740
+ single-precision coordinates have small rounding differences.
741
+
742
+ The spherical Jacobian sin(theta) correctly vanishes at the poles,
743
+ which individually have zero solid angle. Numerical error arises from
744
+ approximating power over finite angular regions. Cell weighting can
745
+ reduce that error for pole-peaked patterns and exactly integrates an
746
+ isotropic pattern on a full sphere, but does not eliminate quadrature
747
+ bias generally. For smooth patterns that vanish at the poles, the
748
+ previous sin(theta) trapezoidal rule can be more accurate. Both rules
749
+ are generally second order, with higher-order convergence possible for
750
+ special patterns. Refine the angular grid to check convergence.
612
751
 
613
752
  Parameters
614
753
  ----------
615
754
  theta : ndarray
616
- 2D theta grid in radians
755
+ 2D theta grid in radians, shape (n_theta, n_phi). Must be uniformly
756
+ spaced, strictly increasing along axis 0, constant along axis 1,
757
+ and contained in [0, pi] - the ``theta_grid`` output of
758
+ :func:`~phased_array.utils.create_theta_phi_grid`.
617
759
  phi : ndarray
618
- 2D phi grid in radians
760
+ 2D phi grid in radians, same shape. Must be uniformly spaced,
761
+ strictly increasing along axis 1, constant along axis 0, and span
762
+ at most 2*pi.
619
763
  pattern : ndarray
620
- Complex or magnitude pattern, same shape
764
+ Complex or magnitude (amplitude) pattern on the same grid. Power is
765
+ taken as ``|pattern|**2``, so pass amplitude - not power, and not
766
+ dB.
621
767
 
622
768
  Returns
623
769
  -------
624
770
  directivity : float
625
- Directivity in linear scale
771
+ Peak directivity in linear scale (not dB)
772
+
773
+ Raises
774
+ ------
775
+ ValueError
776
+ If theta, phi and pattern are not 2D arrays of matching shape, hold
777
+ non-finite values, have fewer than two samples on an axis, are not
778
+ separable in the ``indexing='ij'`` sense, are not strictly increasing
779
+ with uniform spacing, sample theta outside [0, pi], or span more
780
+ than 2*pi in phi
781
+
782
+ Notes
783
+ -----
784
+ The grid need not cover the full sphere. A partial grid integrates only
785
+ the solid angle it samples, which is equivalent to assuming the pattern
786
+ radiates no power outside that region. A hemisphere grid
787
+ (``theta_range=(0, np.pi/2)``) therefore gives the expected answer for a
788
+ ground-plane backed array.
789
+
790
+ :func:`compute_full_pattern` output cannot be passed here directly: it
791
+ returns 1D theta and phi axes and a normalized dB pattern. Build the
792
+ grid with :func:`~phased_array.utils.create_theta_phi_grid` and evaluate
793
+ amplitude on it with :func:`total_pattern` or
794
+ :func:`array_factor_vectorized` instead. A dB-valued pattern is not
795
+ detectable here and integrates to a meaningless result.
796
+
797
+ Examples
798
+ --------
799
+ An isotropic pattern has unit directivity:
800
+
801
+ >>> import numpy as np
802
+ >>> import phased_array as pa
803
+ >>> _, _, theta, phi = pa.create_theta_phi_grid()
804
+ >>> d = pa.compute_directivity(theta, phi, np.ones_like(theta))
805
+ >>> f"{d:.9f}"
806
+ '1.000000000'
807
+
808
+ A short dipole, amplitude sin(theta), has directivity 3/2:
809
+
810
+ >>> d = pa.compute_directivity(theta, phi, np.sin(theta))
811
+ >>> f"{d:.4f}"
812
+ '1.5000'
626
813
  """
627
- power = np.abs(pattern)**2
814
+ theta_1d, phi_1d = _angle_axes(theta, phi, pattern)
628
815
 
629
- # Find peak
816
+ power = np.abs(pattern)**2
630
817
  peak_power = np.max(power)
631
818
 
632
- # Integrate over sphere: integral of P(theta,phi) * sin(theta) dtheta dphi
633
- # Using trapezoidal integration
634
- d_theta = theta[1, 0] - theta[0, 0] if theta.shape[0] > 1 else np.pi
635
- d_phi = phi[0, 1] - phi[0, 0] if phi.shape[1] > 1 else 2*np.pi
819
+ # Shared midpoint boundaries avoid gaps/overlaps from rounded spacing.
820
+ edges = np.concatenate((theta_1d[:1],
821
+ (theta_1d[:-1] + theta_1d[1:]) / 2,
822
+ theta_1d[-1:]))
823
+ lower, upper = edges[:-1], edges[1:]
824
+ # Equivalent to cos(lower) - cos(upper), without polar cancellation.
825
+ theta_weights = 2 * np.sin((upper + lower) / 2) * np.sin((upper - lower) / 2)
636
826
 
637
- integrand = power * np.sin(theta)
638
- total_power = np.trapz(np.trapz(integrand, dx=d_phi, axis=1), dx=d_theta)
827
+ # trapezoid() rather than np.trapz(), which NumPy 2.4 removed, or
828
+ # np.trapezoid(), which NumPy 1.x does not have.
829
+ azimuth_integral = trapezoid(power, x=phi_1d, axis=1)
830
+ total_power = float(np.sum(theta_weights * azimuth_integral))
639
831
 
640
832
  if total_power > 0:
641
833
  directivity = 4 * np.pi * peak_power / total_power
642
834
  else:
643
835
  directivity = 1.0
644
836
 
645
- return directivity
837
+ return float(directivity)
646
838
 
647
839
 
648
840
  def compute_half_power_beamwidth(
@@ -32,6 +32,13 @@ class ArrayGeometry:
32
32
  Element normal z-components
33
33
  element_indices : ndarray, optional
34
34
  Original indices before any thinning (for tracking)
35
+ tx : ndarray, optional
36
+ Element tangent x-components (local x-axis / polarization
37
+ reference for conformal vector patterns)
38
+ ty : ndarray, optional
39
+ Element tangent y-components
40
+ tz : ndarray, optional
41
+ Element tangent z-components
35
42
  """
36
43
  x: np.ndarray
37
44
  y: np.ndarray
@@ -40,6 +47,9 @@ class ArrayGeometry:
40
47
  ny: Optional[np.ndarray] = None
41
48
  nz: Optional[np.ndarray] = None
42
49
  element_indices: Optional[np.ndarray] = None
50
+ tx: Optional[np.ndarray] = None
51
+ ty: Optional[np.ndarray] = None
52
+ tz: Optional[np.ndarray] = None
43
53
 
44
54
  @property
45
55
  def n_elements(self) -> int:
@@ -74,7 +84,10 @@ class ArrayGeometry:
74
84
  nx=self.nx.copy() if self.nx is not None else None,
75
85
  ny=self.ny.copy() if self.ny is not None else None,
76
86
  nz=self.nz.copy() if self.nz is not None else None,
77
- element_indices=self.element_indices.copy() if self.element_indices is not None else None
87
+ element_indices=self.element_indices.copy() if self.element_indices is not None else None,
88
+ tx=self.tx.copy() if self.tx is not None else None,
89
+ ty=self.ty.copy() if self.ty is not None else None,
90
+ tz=self.tz.copy() if self.tz is not None else None
78
91
  )
79
92
 
80
93
 
@@ -997,6 +1010,13 @@ def array_factor_conformal(
997
1010
  obs_y = np.sin(theta_flat) * np.sin(phi_flat)
998
1011
  obs_z = np.cos(theta_flat)
999
1012
 
1013
+ has_normals = (geometry.nx is not None and geometry.ny is not None
1014
+ and geometry.nz is not None)
1015
+ if has_normals and element_pattern_func is not None:
1016
+ from .vector_patterns import (element_rotation_matrices,
1017
+ global_to_local_angles)
1018
+ R = element_rotation_matrices(geometry)
1019
+
1000
1020
  AF = np.zeros(n_angles, dtype=complex)
1001
1021
 
1002
1022
  for i in range(geometry.n_elements):
@@ -1006,7 +1026,7 @@ def array_factor_conformal(
1006
1026
  phase += k * geometry.z[i] * obs_z
1007
1027
 
1008
1028
  # Element pattern correction for orientation
1009
- if geometry.nx is not None and geometry.ny is not None and geometry.nz is not None:
1029
+ if has_normals:
1010
1030
  # Cosine of angle between observation direction and element normal
1011
1031
  cos_angle = (geometry.nx[i] * obs_x +
1012
1032
  geometry.ny[i] * obs_y +
@@ -1014,9 +1034,11 @@ def array_factor_conformal(
1014
1034
  cos_angle = np.maximum(cos_angle, 0) # Only forward hemisphere
1015
1035
 
1016
1036
  if element_pattern_func is not None:
1017
- # Local theta for this element (angle from its normal)
1018
- local_theta = np.arccos(np.clip(cos_angle, -1, 1))
1019
- element_gain = element_pattern_func(local_theta, phi_flat, **element_kwargs)
1037
+ # Observation angles in the element's local frame
1038
+ local_theta, local_phi = global_to_local_angles(
1039
+ R[i], theta_flat, phi_flat
1040
+ )
1041
+ element_gain = element_pattern_func(local_theta, local_phi, **element_kwargs)
1020
1042
  else:
1021
1043
  element_gain = cos_angle # Simple cosine pattern
1022
1044
  else:
@@ -81,13 +81,13 @@ def stokes_parameters(jones: np.ndarray) -> Tuple[float, float, float, float]:
81
81
  Returns
82
82
  -------
83
83
  S0 : float or ndarray
84
- Total intensity: |Ex|^2 + |Ey|^2
84
+ Total intensity: ``|Ex|^2 + |Ey|^2``
85
85
  S1 : float or ndarray
86
- Linear horizontal-vertical: |Ex|^2 - |Ey|^2
86
+ Linear horizontal-vertical: ``|Ex|^2 - |Ey|^2``
87
87
  S2 : float or ndarray
88
- Linear +45/-45: 2*Re(Ex*Ey*)
88
+ Linear +45/-45: ``2*Re(Ex*conj(Ey))``
89
89
  S3 : float or ndarray
90
- Circular right-left: 2*Im(Ex*Ey*)
90
+ Circular right-left: ``2*Im(Ex*conj(Ey))``
91
91
 
92
92
  Examples
93
93
  --------