phased-array-modeling 1.4.0__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.4.0 → phased_array_modeling-1.4.1}/PKG-INFO +8 -3
  2. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/README.md +7 -2
  3. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/__init__.py +1 -1
  4. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/core.py +206 -14
  5. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/PKG-INFO +8 -3
  6. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/SOURCES.txt +1 -0
  7. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/pyproject.toml +1 -1
  8. phased_array_modeling-1.4.1/tests/test_directivity.py +439 -0
  9. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_docstrings.py +17 -0
  10. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/LICENSE +0 -0
  11. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/beamforming.py +0 -0
  12. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/coordinates.py +0 -0
  13. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/export.py +0 -0
  14. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/geometry.py +0 -0
  15. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/impairments.py +0 -0
  16. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/polarization.py +0 -0
  17. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/utils.py +0 -0
  18. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/vector_patterns.py +0 -0
  19. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/visualization.py +0 -0
  20. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array/wideband.py +0 -0
  21. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/dependency_links.txt +0 -0
  22. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/requires.txt +0 -0
  23. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/phased_array_modeling.egg-info/top_level.txt +0 -0
  24. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/setup.cfg +0 -0
  25. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_beamforming.py +0 -0
  26. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_coordinates.py +0 -0
  27. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_core.py +0 -0
  28. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_export.py +0 -0
  29. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_geometry.py +0 -0
  30. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_impairments.py +0 -0
  31. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_polarization.py +0 -0
  32. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_utils.py +0 -0
  33. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_vector_patterns.py +0 -0
  34. {phased_array_modeling-1.4.0 → phased_array_modeling-1.4.1}/tests/test_visualization.py +0 -0
  35. {phased_array_modeling-1.4.0 → 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.4.0
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
@@ -48,7 +48,7 @@ Dynamic: license-file
48
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)
49
49
  [![PyPI version](https://img.shields.io/pypi/v/phased-array-modeling.svg)](https://pypi.org/project/phased-array-modeling/)
50
50
  [![PyPI downloads](https://img.shields.io/pypi/dm/phased-array-modeling.svg)](https://pypi.org/project/phased-array-modeling/)
51
- [![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/)
52
52
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
53
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)
54
54
  [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://phased-array-antenna-model.streamlit.app/)
@@ -56,6 +56,11 @@ Dynamic: license-file
56
56
 
57
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.
58
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
+
59
64
  ## Features
60
65
 
61
66
  - **High Performance**: Vectorized array factor computation (50-100x faster than naive loops)
@@ -248,7 +253,7 @@ phased_array/
248
253
 
249
254
  ## Requirements
250
255
 
251
- - Python 3.8+
256
+ - Python 3.9+
252
257
  - NumPy >= 1.20.0
253
258
  - Matplotlib >= 3.5.0
254
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,6 +11,11 @@
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)
@@ -203,7 +208,7 @@ phased_array/
203
208
 
204
209
  ## Requirements
205
210
 
206
- - Python 3.8+
211
+ - Python 3.9+
207
212
  - NumPy >= 1.20.0
208
213
  - Matplotlib >= 3.5.0
209
214
  - SciPy >= 1.7.0
@@ -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.0"
36
+ __version__ = "1.4.1"
37
37
 
38
38
  # Beamforming functions
39
39
  from .beamforming import ( # Amplitude tapers; Null steering; Multiple beams; Beam spoiling; Adaptive
@@ -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(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: phased-array-modeling
3
- Version: 1.4.0
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
@@ -48,7 +48,7 @@ Dynamic: license-file
48
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)
49
49
  [![PyPI version](https://img.shields.io/pypi/v/phased-array-modeling.svg)](https://pypi.org/project/phased-array-modeling/)
50
50
  [![PyPI downloads](https://img.shields.io/pypi/dm/phased-array-modeling.svg)](https://pypi.org/project/phased-array-modeling/)
51
- [![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/)
52
52
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
53
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)
54
54
  [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://phased-array-antenna-model.streamlit.app/)
@@ -56,6 +56,11 @@ Dynamic: license-file
56
56
 
57
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.
58
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
+
59
64
  ## Features
60
65
 
61
66
  - **High Performance**: Vectorized array factor computation (50-100x faster than naive loops)
@@ -248,7 +253,7 @@ phased_array/
248
253
 
249
254
  ## Requirements
250
255
 
251
- - Python 3.8+
256
+ - Python 3.9+
252
257
  - NumPy >= 1.20.0
253
258
  - Matplotlib >= 3.5.0
254
259
  - SciPy >= 1.7.0
@@ -21,6 +21,7 @@ phased_array_modeling.egg-info/top_level.txt
21
21
  tests/test_beamforming.py
22
22
  tests/test_coordinates.py
23
23
  tests/test_core.py
24
+ tests/test_directivity.py
24
25
  tests/test_docstrings.py
25
26
  tests/test_export.py
26
27
  tests/test_geometry.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "phased-array-modeling"
7
- version = "1.4.0"
7
+ version = "1.4.1"
8
8
  description = "Comprehensive Python library for phased array antenna modeling and visualization"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -0,0 +1,439 @@
1
+ """
2
+ Tests for compute_directivity.
3
+
4
+ Acceptance tests exercise the public API on grids built by
5
+ create_theta_phi_grid. Regression tests pin the behavior corrected in this
6
+ change: the rectangular-grid failure, convergence toward analytic answers,
7
+ partial-sphere support, and grid validation.
8
+
9
+ Analytic directivities used throughout (amplitude patterns, since the
10
+ function squares its input):
11
+
12
+ amplitude 1 -> D = 1
13
+ amplitude sin(theta) -> D = 3/2 (short dipole)
14
+ amplitude cos(theta)**10 -> D = 21 (cos(theta)**20 power)
15
+ amplitude sqrt(1 + 0.5 sin^2(theta) cos(2 phi)) -> D = 3/2
16
+ """
17
+
18
+ import ast
19
+ import inspect
20
+
21
+ import numpy as np
22
+ import pytest
23
+ from scipy.integrate import trapezoid
24
+
25
+ import phased_array as pa
26
+
27
+
28
+ def _grid(d_theta_deg, theta_range=(0, np.pi), phi_range=(0, 2 * np.pi)):
29
+ """Build an ij-indexed grid with the given angular step in degrees."""
30
+ theta_span = np.rad2deg(theta_range[1] - theta_range[0])
31
+ phi_span = np.rad2deg(phi_range[1] - phi_range[0])
32
+ n_theta = int(round(theta_span / d_theta_deg)) + 1
33
+ n_phi = int(round(phi_span / d_theta_deg)) + 1
34
+ return pa.create_theta_phi_grid(
35
+ theta_range=theta_range,
36
+ phi_range=phi_range,
37
+ n_theta=n_theta,
38
+ n_phi=n_phi,
39
+ )
40
+
41
+
42
+ def _isotropic(theta):
43
+ return np.ones_like(theta)
44
+
45
+
46
+ def _dipole(theta):
47
+ return np.sin(theta)
48
+
49
+
50
+ def _pole_peaked(theta):
51
+ return np.cos(theta) ** 10
52
+
53
+
54
+ def _azimuth_dependent(theta, phi):
55
+ return np.sqrt(1 + 0.5 * np.sin(theta) ** 2 * np.cos(2 * phi))
56
+
57
+
58
+ class TestDirectivityAcceptance:
59
+ """Public-API behavior on the grids create_theta_phi_grid produces."""
60
+
61
+ def test_isotropic_on_default_grid(self):
62
+ _, _, theta, phi = pa.create_theta_phi_grid()
63
+ assert theta.shape == (181, 361)
64
+
65
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
66
+
67
+ assert np.isfinite(directivity)
68
+ assert abs(directivity - 1.0) < 1e-12
69
+
70
+ def test_short_dipole_on_default_grid(self):
71
+ _, _, theta, phi = pa.create_theta_phi_grid()
72
+
73
+ directivity = pa.compute_directivity(theta, phi, _dipole(theta))
74
+
75
+ assert abs(directivity - 1.5) < 1e-3
76
+
77
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64])
78
+ @pytest.mark.parametrize("theta_max, expected", [(np.pi, 1.0), (np.pi / 2, 2.0)])
79
+ def test_isotropic_grid_storage_precision(self, dtype, theta_max, expected):
80
+ _, _, theta, phi = pa.create_theta_phi_grid(theta_range=(0, theta_max))
81
+ theta, phi = theta.astype(dtype), phi.astype(dtype)
82
+
83
+ directivity = pa.compute_directivity(theta, phi, np.ones_like(theta))
84
+
85
+ assert np.isclose(directivity, expected, rtol=1e-6)
86
+
87
+ @pytest.mark.parametrize("steering_angle", [0, 90])
88
+ def test_half_wavelength_linear_array(self, steering_angle):
89
+ n = 64
90
+ x = y = np.zeros(n)
91
+ z = np.arange(n) * 0.5
92
+ k = 2 * np.pi
93
+ weights = pa.steering_vector(k, x, y, steering_angle, 0, z=z)
94
+ _, _, theta, phi = pa.create_theta_phi_grid(n_theta=361, n_phi=3)
95
+ pattern = pa.array_factor_vectorized(theta, phi, x, y, weights, k, z=z)
96
+
97
+ directivity = pa.compute_directivity(theta, phi, pattern)
98
+
99
+ # Half-wavelength-separated cross terms integrate to zero, so the
100
+ # total power is 4*pi*n and exact directivity is n at either steering.
101
+ assert abs(10 * np.log10(directivity / n)) < 0.002
102
+
103
+ def test_pole_peaked_on_default_grid(self):
104
+ _, _, theta, phi = pa.create_theta_phi_grid()
105
+
106
+ directivity = pa.compute_directivity(theta, phi, _pole_peaked(theta))
107
+
108
+ assert abs(directivity - 21.0) < 0.01
109
+
110
+ def test_azimuth_dependent_pattern(self):
111
+ _, _, theta, phi = pa.create_theta_phi_grid()
112
+
113
+ pattern = _azimuth_dependent(theta, phi)
114
+ directivity = pa.compute_directivity(theta, phi, pattern)
115
+
116
+ # Peak power 1.5 sits at theta = pi/2, phi in {0, pi, 2 pi}, all of
117
+ # which are grid points, and the mean power over the sphere is 1.
118
+ assert abs(directivity - 1.5) < 1e-12
119
+
120
+ def test_array_pattern_exceeds_isotropic(self):
121
+ geom = pa.create_rectangular_array(8, 8, dx=0.5, dy=0.5)
122
+ k = pa.wavelength_to_k(1.0)
123
+ weights = pa.steering_vector(k, geom.x, geom.y, 0, 0)
124
+ _, _, theta, phi = pa.create_theta_phi_grid(n_theta=91, n_phi=181)
125
+ pattern = pa.array_factor_vectorized(
126
+ theta, phi, geom.x, geom.y, weights, k
127
+ )
128
+
129
+ directivity = pa.compute_directivity(theta, phi, pattern)
130
+
131
+ assert np.isfinite(directivity)
132
+ assert directivity > 1.0
133
+
134
+ def test_unsupported_grid_raises_instead_of_returning_a_number(self):
135
+ theta_1d, phi_1d, _, _ = pa.create_theta_phi_grid()
136
+
137
+ with pytest.raises(ValueError, match="2D grid"):
138
+ pa.compute_directivity(theta_1d, phi_1d, np.ones_like(theta_1d))
139
+
140
+
141
+ class TestDirectivityRegression:
142
+ """Behavior corrected in this change."""
143
+
144
+ def test_rectangular_grid_with_unequal_axis_counts(self):
145
+ # Theta weights must be a 1D vector of length n_theta. Building them
146
+ # from the 2D theta grid instead broadcasts against n_phi, which is
147
+ # only silent when n_theta == n_phi.
148
+ _, _, theta, phi = pa.create_theta_phi_grid(n_theta=37, n_phi=181)
149
+ assert theta.shape[0] != theta.shape[1]
150
+
151
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
152
+
153
+ assert abs(directivity - 1.0) < 1e-12
154
+
155
+ def test_grid_dtype_does_not_change_acceptance(self):
156
+ # The uniformity tolerance must key off the axis span, not the array
157
+ # dtype: upcasting a valid float32 grid changes no coordinate value
158
+ # and must not turn an accepted grid into a ValueError.
159
+ _, _, theta, phi = pa.create_theta_phi_grid()
160
+ theta32, phi32 = theta.astype(np.float32), phi.astype(np.float32)
161
+ pattern = np.ones(theta.shape)
162
+
163
+ as_float32 = pa.compute_directivity(theta32, phi32, pattern)
164
+ upcast = pa.compute_directivity(
165
+ theta32.astype(np.float64), phi32.astype(np.float64), pattern
166
+ )
167
+
168
+ assert np.isclose(as_float32, 1.0, rtol=1e-6)
169
+ assert np.isclose(upcast, 1.0, rtol=1e-6)
170
+
171
+ def test_array_like_input_is_accepted(self):
172
+ theta_1d = np.linspace(0, np.pi, 19)
173
+ phi_1d = np.linspace(0, 2 * np.pi, 37)
174
+ theta, phi = np.meshgrid(theta_1d, phi_1d, indexing="ij")
175
+
176
+ directivity = pa.compute_directivity(
177
+ theta.tolist(), phi.tolist(), np.ones_like(theta).tolist()
178
+ )
179
+
180
+ assert abs(directivity - 1.0) < 1e-12
181
+
182
+ def test_integration_avoids_numpy_only_trapezoid_names(self):
183
+ # np.trapz was removed in NumPy 2.4 and np.trapezoid does not exist on
184
+ # NumPy 1.x, so neither name can appear in the integration path. The
185
+ # original PR also called np.trapezoidz, which never existed.
186
+ tree = ast.parse(inspect.getsource(pa.core.compute_directivity))
187
+ numpy_attrs = {
188
+ node.attr
189
+ for node in ast.walk(tree)
190
+ if isinstance(node, ast.Attribute)
191
+ and isinstance(node.value, ast.Name)
192
+ and node.value.id == "np"
193
+ }
194
+
195
+ assert numpy_attrs.isdisjoint({"trapz", "trapezoid", "trapezoidz"})
196
+
197
+ _, _, theta, phi = _grid(5.0)
198
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
199
+ assert np.isfinite(directivity)
200
+
201
+ def test_isotropic_exact_at_every_spacing(self):
202
+ for d_theta_deg in (10.0, 5.0, 2.5, 1.25):
203
+ _, _, theta, phi = _grid(d_theta_deg)
204
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
205
+ assert abs(directivity - 1.0) < 1e-12, d_theta_deg
206
+
207
+ def test_dipole_converges(self):
208
+ errors = []
209
+ for d_theta_deg in (10.0, 5.0, 2.5, 1.25):
210
+ _, _, theta, phi = _grid(d_theta_deg)
211
+ directivity = pa.compute_directivity(theta, phi, _dipole(theta))
212
+ errors.append(abs(directivity - 1.5))
213
+
214
+ assert all(b < a for a, b in zip(errors, errors[1:])), errors
215
+ assert errors[-1] < 5e-5, errors[-1]
216
+
217
+ def test_pole_peaked_converges(self):
218
+ errors = []
219
+ for d_theta_deg in (10.0, 5.0, 2.5, 1.25):
220
+ _, _, theta, phi = _grid(d_theta_deg)
221
+ pattern = _pole_peaked(theta)
222
+ directivity = pa.compute_directivity(theta, phi, pattern)
223
+ errors.append(abs(directivity - 21.0))
224
+
225
+ assert all(b < a for a, b in zip(errors, errors[1:])), errors
226
+ assert errors[-1] < 0.01, errors[-1]
227
+
228
+ def test_pole_peaked_quadrature_improves_at_coarse_resolution(self):
229
+ # This particular coarse-grid pattern benefits from cell weighting;
230
+ # the improvement is not a universal property of the quadrature.
231
+ _, _, theta, phi = _grid(10.0)
232
+ pattern = _pole_peaked(theta)
233
+
234
+ power = np.abs(pattern) ** 2
235
+ legacy_total = trapezoid(
236
+ trapezoid(power * np.sin(theta), x=phi[0, :], axis=1),
237
+ x=theta[:, 0],
238
+ )
239
+ legacy = 4 * np.pi * power.max() / legacy_total
240
+
241
+ directivity = pa.compute_directivity(theta, phi, pattern)
242
+
243
+ assert legacy > 21.0 + 1.0
244
+ assert abs(directivity - 21.0) < abs(legacy - 21.0)
245
+
246
+ def test_hemisphere_grid_is_supported(self):
247
+ # compute_full_pattern defaults to theta_range=(0, pi/2); a hemisphere
248
+ # grid must integrate the sampled solid angle, not raise.
249
+ _, _, theta, phi = _grid(1.0, theta_range=(0, np.pi / 2))
250
+
251
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
252
+
253
+ # 4 pi / 2 pi: isotropic power confined to the sampled hemisphere.
254
+ assert abs(directivity - 2.0) < 1e-12
255
+
256
+ def test_partial_theta_band_is_supported(self):
257
+ theta_range = (np.pi / 6, np.pi / 3)
258
+ _, _, theta, phi = _grid(0.5, theta_range=theta_range)
259
+
260
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
261
+
262
+ cap = np.cos(theta_range[0]) - np.cos(theta_range[1])
263
+ solid_angle = 2 * np.pi * cap
264
+ assert abs(directivity - 4 * np.pi / solid_angle) < 1e-9
265
+
266
+ def test_narrow_polar_cap_avoids_cancellation(self):
267
+ theta_max = 1e-8
268
+ _, _, theta, phi = pa.create_theta_phi_grid(
269
+ theta_range=(0, theta_max), n_theta=19, n_phi=37
270
+ )
271
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
272
+ expected = 1 / np.sin(theta_max / 2) ** 2
273
+ assert np.isclose(directivity, expected, rtol=1e-12)
274
+
275
+ def test_partial_azimuth_sector_is_supported(self):
276
+ _, _, theta, phi = _grid(1.0, phi_range=(0, np.pi))
277
+
278
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
279
+
280
+ assert abs(directivity - 2.0) < 1e-12
281
+
282
+ def test_invariant_under_amplitude_scaling(self):
283
+ _, _, theta, phi = _grid(2.5)
284
+ pattern = _pole_peaked(theta)
285
+
286
+ reference = pa.compute_directivity(theta, phi, pattern)
287
+
288
+ for scale in (1e-6, 0.5, 3.0, 1e6):
289
+ scaled = pa.compute_directivity(theta, phi, scale * pattern)
290
+ assert np.isclose(scaled, reference, rtol=1e-12)
291
+
292
+ def test_invariant_under_complex_phase(self):
293
+ _, _, theta, phi = _grid(2.5)
294
+ pattern = _pole_peaked(theta)
295
+
296
+ reference = pa.compute_directivity(theta, phi, pattern)
297
+ phased = pattern * np.exp(1j * (2 * theta + 3 * phi))
298
+
299
+ assert np.isclose(
300
+ pa.compute_directivity(theta, phi, phased), reference, rtol=1e-12
301
+ )
302
+
303
+ def test_zero_pattern_falls_back_to_unity(self):
304
+ _, _, theta, phi = _grid(5.0)
305
+
306
+ assert pa.compute_directivity(theta, phi, np.zeros_like(theta)) == 1.0
307
+
308
+ def test_returns_builtin_float(self):
309
+ _, _, theta, phi = _grid(5.0)
310
+
311
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
312
+ assert type(directivity) is float
313
+
314
+
315
+ class TestDirectivityValidation:
316
+ """Unsupported grids raise ValueError with an actionable message."""
317
+
318
+ def test_one_dimensional_input(self):
319
+ theta = np.linspace(0, np.pi, 19)
320
+ phi = np.linspace(0, 2 * np.pi, 37)
321
+
322
+ with pytest.raises(ValueError, match="2D grid"):
323
+ pa.compute_directivity(theta, phi, np.ones(19))
324
+
325
+ def test_mismatched_shapes(self):
326
+ _, _, theta, phi = _grid(5.0)
327
+
328
+ with pytest.raises(ValueError, match="same shape"):
329
+ pa.compute_directivity(theta, phi, np.ones((3, 4)))
330
+
331
+ def test_single_sample_axis(self):
332
+ theta, phi = np.meshgrid(
333
+ np.array([0.5]), np.linspace(0, 2 * np.pi, 37), indexing="ij"
334
+ )
335
+
336
+ with pytest.raises(ValueError, match="at least two samples"):
337
+ pa.compute_directivity(theta, phi, np.ones_like(theta))
338
+
339
+ def test_nonuniform_theta_spacing(self):
340
+ theta_1d = np.concatenate(
341
+ [
342
+ np.linspace(0, np.pi / 2, 10),
343
+ np.linspace(np.pi / 2, np.pi, 40)[1:],
344
+ ]
345
+ )
346
+ theta, phi = np.meshgrid(
347
+ theta_1d, np.linspace(0, 2 * np.pi, 37), indexing="ij"
348
+ )
349
+
350
+ with pytest.raises(ValueError, match="uniformly spaced"):
351
+ pa.compute_directivity(theta, phi, np.ones_like(theta))
352
+
353
+ @pytest.mark.parametrize("axis", ["theta", "phi"])
354
+ def test_float32_nonuniform_grid_is_still_rejected(self, axis):
355
+ _, _, theta, phi = pa.create_theta_phi_grid()
356
+ theta, phi = theta.astype(np.float32), phi.astype(np.float32)
357
+ if axis == "theta":
358
+ theta[90, :] += 1e-3
359
+ else:
360
+ phi[:, 180] += 1e-3
361
+
362
+ with pytest.raises(ValueError, match="uniformly spaced"):
363
+ pa.compute_directivity(theta, phi, np.ones_like(theta))
364
+
365
+ def test_ragged_nested_sequence(self):
366
+ with pytest.raises(ValueError):
367
+ pa.compute_directivity([[0.0, 1.0], [2.0]], [[0.0]], [[1.0]])
368
+
369
+ def test_degree_valued_phi_grid(self):
370
+ # A grid built in degrees spans 360 "radians" and would otherwise
371
+ # return D = 0.017, which is not physically reachable.
372
+ _, _, theta, phi = pa.create_theta_phi_grid(
373
+ phi_range=(0, 360.0), n_phi=361
374
+ )
375
+
376
+ with pytest.raises(ValueError, match="span at most"):
377
+ pa.compute_directivity(theta, phi, np.ones_like(theta))
378
+
379
+ def test_phi_spanning_more_than_one_turn(self):
380
+ _, _, theta, phi = pa.create_theta_phi_grid(
381
+ phi_range=(0, 4 * np.pi), n_phi=721
382
+ )
383
+
384
+ with pytest.raises(ValueError, match="span at most"):
385
+ pa.compute_directivity(theta, phi, np.ones_like(theta))
386
+
387
+ def test_full_turn_phi_is_accepted(self):
388
+ # The boundary case must not be caught by the span check.
389
+ _, _, theta, phi = pa.create_theta_phi_grid()
390
+
391
+ directivity = pa.compute_directivity(theta, phi, _isotropic(theta))
392
+
393
+ assert abs(directivity - 1.0) < 1e-12
394
+
395
+ def test_descending_theta(self):
396
+ theta, phi = np.meshgrid(
397
+ np.linspace(np.pi, 0, 19),
398
+ np.linspace(0, 2 * np.pi, 37),
399
+ indexing="ij",
400
+ )
401
+
402
+ with pytest.raises(ValueError, match="strictly increasing"):
403
+ pa.compute_directivity(theta, phi, np.ones_like(theta))
404
+
405
+ def test_xy_indexed_mesh_is_rejected(self):
406
+ theta, phi = np.meshgrid(
407
+ np.linspace(0, np.pi, 19),
408
+ np.linspace(0, 2 * np.pi, 37),
409
+ indexing="xy",
410
+ )
411
+
412
+ with pytest.raises(ValueError, match="constant along axis"):
413
+ pa.compute_directivity(theta, phi, np.ones_like(theta))
414
+
415
+ def test_theta_outside_zero_to_pi(self):
416
+ theta, phi = np.meshgrid(
417
+ np.linspace(0, 1.5 * np.pi, 19),
418
+ np.linspace(0, 2 * np.pi, 37),
419
+ indexing="ij",
420
+ )
421
+
422
+ with pytest.raises(ValueError, match=r"within \[0, pi\]"):
423
+ pa.compute_directivity(theta, phi, np.ones_like(theta))
424
+
425
+ def test_non_finite_pattern(self):
426
+ _, _, theta, phi = _grid(5.0)
427
+ pattern = _isotropic(theta)
428
+ pattern[0, 0] = np.nan
429
+
430
+ with pytest.raises(ValueError, match="non-finite"):
431
+ pa.compute_directivity(theta, phi, pattern)
432
+
433
+ def test_non_finite_grid(self):
434
+ _, _, theta, phi = _grid(5.0)
435
+ theta = theta.copy()
436
+ theta[0, 0] = np.inf
437
+
438
+ with pytest.raises(ValueError, match="non-finite"):
439
+ pa.compute_directivity(theta, phi, _isotropic(theta))
@@ -3,6 +3,7 @@
3
3
  import doctest
4
4
  import importlib
5
5
 
6
+ import numpy as np
6
7
  import pytest
7
8
 
8
9
  MODULES = [
@@ -19,6 +20,22 @@ MODULES = [
19
20
  ]
20
21
 
21
22
 
23
+ @pytest.fixture(autouse=True)
24
+ def numpy_legacy_repr():
25
+ """NumPy 2 prints scalars as np.float64(16.0); the docstring examples
26
+ use the classic repr. legacy='1.25' restores it for the doctest run.
27
+
28
+ NumPy 1.x must not receive the option at all: it warns instead of
29
+ raising and stores the invalid value, corrupting later printing.
30
+ """
31
+ if int(np.__version__.split(".")[0]) >= 2:
32
+ np.set_printoptions(legacy="1.25")
33
+ yield
34
+ np.set_printoptions(legacy=False)
35
+ else:
36
+ yield
37
+
38
+
22
39
  @pytest.mark.parametrize("module_name", MODULES)
23
40
  def test_module_doctests(module_name):
24
41
  module = importlib.import_module(f"phased_array.{module_name}")