phased-array-modeling 1.4.0__tar.gz → 1.5.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 (35) hide show
  1. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/PKG-INFO +8 -3
  2. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/README.md +7 -2
  3. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/__init__.py +1 -1
  4. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/core.py +237 -22
  5. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/geometry.py +5 -1
  6. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array_modeling.egg-info/PKG-INFO +8 -3
  7. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array_modeling.egg-info/SOURCES.txt +1 -0
  8. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/pyproject.toml +1 -1
  9. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_core.py +42 -3
  10. phased_array_modeling-1.5.0/tests/test_directivity.py +439 -0
  11. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_docstrings.py +17 -0
  12. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_vector_patterns.py +5 -4
  13. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/LICENSE +0 -0
  14. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/beamforming.py +0 -0
  15. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/coordinates.py +0 -0
  16. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/export.py +0 -0
  17. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/impairments.py +0 -0
  18. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/polarization.py +0 -0
  19. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/utils.py +0 -0
  20. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/vector_patterns.py +0 -0
  21. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/visualization.py +0 -0
  22. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array/wideband.py +0 -0
  23. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array_modeling.egg-info/dependency_links.txt +0 -0
  24. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array_modeling.egg-info/requires.txt +0 -0
  25. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/phased_array_modeling.egg-info/top_level.txt +0 -0
  26. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/setup.cfg +0 -0
  27. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_beamforming.py +0 -0
  28. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_coordinates.py +0 -0
  29. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_export.py +0 -0
  30. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_geometry.py +0 -0
  31. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_impairments.py +0 -0
  32. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_polarization.py +0 -0
  33. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_utils.py +0 -0
  34. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/tests/test_visualization.py +0 -0
  35. {phased_array_modeling-1.4.0 → phased_array_modeling-1.5.0}/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.5.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
@@ -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.5.0"
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
 
@@ -303,6 +304,12 @@ def element_pattern(
303
304
  """
304
305
  Compute element pattern using raised cosine model.
305
306
 
307
+ The model is specified as a power pattern,
308
+ ``G(theta) = G0 * cos(theta)**cos_exp_theta``, but returned as the
309
+ corresponding field amplitude ``sqrt(G(theta))`` so it can be
310
+ multiplied directly into the (field) array factor. Pattern utilities
311
+ then form power as ``|EP * AF|**2``, which recovers ``G(theta)``.
312
+
306
313
  Parameters
307
314
  ----------
308
315
  theta : ndarray
@@ -310,18 +317,31 @@ def element_pattern(
310
317
  phi : ndarray
311
318
  Azimuthal angle in radians (not used; the model is phi-symmetric)
312
319
  cos_exp_theta : float
313
- Cosine exponent for theta dependence (1.0 = simple cosine)
320
+ Cosine exponent of the power pattern (1.0 = cos(theta) power
321
+ roll-off). The returned field uses half this exponent.
314
322
  cos_exp_phi : float
315
323
  Deprecated and unused. The basic model has no phi dependence;
316
324
  for polarized/phi-dependent element models see the v1.4 vector
317
325
  pattern API.
318
326
  max_gain_dBi : float
319
- Peak element gain in dBi
327
+ Peak element gain in dBi, applied as the field scale factor
328
+ ``10**(max_gain_dBi / 20)``.
320
329
 
321
330
  Returns
322
331
  -------
323
332
  pattern : ndarray
324
- Element pattern (linear scale, same shape as theta)
333
+ Element field amplitude (linear scale, same shape as theta). Zero
334
+ behind the element (theta > 90 degrees). Square it to get the
335
+ power pattern.
336
+
337
+ Examples
338
+ --------
339
+ >>> import numpy as np
340
+ >>> import phased_array as pa
341
+ >>> ep = pa.element_pattern(np.array([0.0]), np.array([0.0]),
342
+ ... max_gain_dBi=6.0)
343
+ >>> round(float(10 * np.log10(ep[0] ** 2)), 6)
344
+ 6.0
325
345
  """
326
346
  if cos_exp_phi != 1.0:
327
347
  warnings.warn(
@@ -333,14 +353,17 @@ def element_pattern(
333
353
  stacklevel=2,
334
354
  )
335
355
 
336
- # Convert max gain to linear
337
- max_gain_linear = 10 ** (max_gain_dBi / 10)
356
+ # Peak gain (power) -> peak field amplitude
357
+ max_field_linear = 10 ** (max_gain_dBi / 20)
338
358
 
339
- # Raised cosine pattern (only valid for forward hemisphere)
359
+ # Raised cosine pattern (only valid for forward hemisphere). Clip the
360
+ # base before exponentiating: np.where evaluates both branches, and a
361
+ # negative base with a fractional exponent would emit a NaN warning.
340
362
  cos_theta = np.cos(theta)
363
+ cos_forward = np.clip(cos_theta, 0.0, None)
341
364
  pattern = np.where(
342
365
  cos_theta > 0,
343
- max_gain_linear * (cos_theta ** cos_exp_theta),
366
+ max_field_linear * cos_forward ** (cos_exp_theta / 2.0),
344
367
  0.0
345
368
  )
346
369
 
@@ -375,7 +398,8 @@ def element_pattern_cosine_tapered(
375
398
  Element pattern (linear scale)
376
399
  """
377
400
  # Compute cosine exponent for desired beamwidth
378
- # At theta_3dB, pattern = 0.5 * max
401
+ # At theta_3dB, power pattern = 0.5 * max (element_pattern takes the
402
+ # power exponent and returns the field, so |EP|^2 is -3 dB here)
379
403
  # cos(theta_3dB)^n = 0.5
380
404
  # n = log(0.5) / log(cos(theta_3dB))
381
405
  theta_3dB = np.deg2rad(theta_3dB_deg)
@@ -602,47 +626,238 @@ def compute_full_pattern(
602
626
  return theta_1d, phi_1d, pattern_dB
603
627
 
604
628
 
629
+ def _angle_axes(
630
+ theta: np.ndarray,
631
+ phi: np.ndarray,
632
+ pattern: np.ndarray
633
+ ) -> Tuple[np.ndarray, np.ndarray]:
634
+ """
635
+ Validate a (theta, phi) meshgrid and return its 1D axes.
636
+
637
+ Parameters
638
+ ----------
639
+ theta, phi : ndarray
640
+ 2D angle grids in radians, as produced by
641
+ :func:`~phased_array.utils.create_theta_phi_grid`
642
+ (``np.meshgrid(..., indexing='ij')``)
643
+ pattern : ndarray
644
+ Pattern sampled on the same grid
645
+
646
+ Returns
647
+ -------
648
+ theta_1d : ndarray
649
+ Theta samples, shape (n_theta,)
650
+ phi_1d : ndarray
651
+ Phi samples, shape (n_phi,)
652
+
653
+ Raises
654
+ ------
655
+ ValueError
656
+ If the arrays are not 2D and identically shaped, contain non-finite
657
+ values, have fewer than two samples on an axis, are not separable in
658
+ the ``indexing='ij'`` sense, are not strictly increasing with uniform
659
+ spacing, or sample theta outside [0, pi].
660
+ """
661
+ theta, phi, pattern = (np.asarray(a) for a in (theta, phi, pattern))
662
+
663
+ for name, arr in (("theta", theta), ("phi", phi), ("pattern", pattern)):
664
+ if np.ndim(arr) != 2:
665
+ raise ValueError(
666
+ f"{name} must be a 2D grid, got ndim={np.ndim(arr)}. Pass the "
667
+ "theta_grid/phi_grid outputs of create_theta_phi_grid(), not "
668
+ "the 1D axes."
669
+ )
670
+ if not np.all(np.isfinite(arr)):
671
+ raise ValueError(f"{name} contains non-finite values (NaN or inf)")
672
+
673
+ if theta.shape != phi.shape or theta.shape != pattern.shape:
674
+ raise ValueError(
675
+ "theta, phi and pattern must have the same shape, got "
676
+ f"{theta.shape}, {phi.shape} and {pattern.shape}"
677
+ )
678
+
679
+ n_theta, n_phi = theta.shape
680
+ if n_theta < 2 or n_phi < 2:
681
+ raise ValueError(
682
+ "at least two samples are required on each axis, got shape "
683
+ f"{theta.shape}. A single-sample axis carries no integration span."
684
+ )
685
+
686
+ # Separability: theta must vary along axis 0 only, phi along axis 1 only.
687
+ if not np.allclose(theta, theta[:, :1]):
688
+ raise ValueError(
689
+ "theta must be constant along axis 1. The grid looks transposed "
690
+ "or built with indexing='xy'; use indexing='ij'."
691
+ )
692
+ if not np.allclose(phi, phi[:1, :]):
693
+ raise ValueError(
694
+ "phi must be constant along axis 0. The grid looks transposed "
695
+ "or built with indexing='xy'; use indexing='ij'."
696
+ )
697
+
698
+ axes = []
699
+ tolerances = []
700
+ for name, samples in (("theta", theta[:, 0]), ("phi", phi[0, :])):
701
+ axis = samples.astype(np.float64)
702
+ # Compare positions to a uniform axis rather than successive
703
+ # differences, which amplify rounding error. The tolerance scales
704
+ # with the axis span, not the array dtype, so a float32 grid and
705
+ # the same grid upcast to float64 are judged identically.
706
+ span = float(axis[-1] - axis[0])
707
+ tol = max(1e-12, 1e-6 * abs(span))
708
+ if not np.all(np.diff(axis) > 0):
709
+ raise ValueError(
710
+ f"{name} must be strictly increasing, got samples from "
711
+ f"{axis[0]:.6g} to {axis[-1]:.6g} rad"
712
+ )
713
+ uniform = np.linspace(axis[0], axis[-1], axis.size)
714
+ deviation = float(np.max(np.abs(axis - uniform)))
715
+ if deviation > tol:
716
+ raise ValueError(
717
+ f"{name} must be uniformly spaced; samples deviate from a "
718
+ f"uniform axis by up to {deviation:.3g} rad, tolerance "
719
+ f"{tol:.3g} rad"
720
+ )
721
+ axes.append(axis)
722
+ tolerances.append(tol)
723
+
724
+ theta_1d, phi_1d = axes
725
+ theta_tol, phi_tol = tolerances
726
+ if theta_1d[0] < -theta_tol or theta_1d[-1] > np.pi + theta_tol:
727
+ raise ValueError(
728
+ "theta must lie within [0, pi] radians, got samples from "
729
+ f"{theta_1d[0]:.6g} to {theta_1d[-1]:.6g} rad. Angles in "
730
+ "degrees are a common cause."
731
+ )
732
+
733
+ # A span wider than a full turn counts some directions more than once.
734
+ phi_span = float(phi_1d[-1] - phi_1d[0])
735
+ if phi_span > 2 * np.pi + phi_tol:
736
+ raise ValueError(
737
+ f"phi must span at most 2*pi radians, got {phi_span:.6g} rad "
738
+ f"from {phi_1d[0]:.6g} to {phi_1d[-1]:.6g}. Angles in degrees "
739
+ "are a common cause."
740
+ )
741
+
742
+ # float32(pi) lies slightly above pi; clamp only permitted roundoff.
743
+ return np.clip(theta_1d, 0, np.pi), phi_1d
744
+
745
+
605
746
  def compute_directivity(
606
747
  theta: np.ndarray,
607
748
  phi: np.ndarray,
608
749
  pattern: np.ndarray
609
750
  ) -> float:
610
751
  """
611
- Compute directivity from a full-sphere pattern.
752
+ Compute peak directivity by integrating a pattern over solid angle.
753
+
754
+ Power is treated as constant over each theta cell. Cell boundaries are
755
+ the midpoints of adjacent theta samples, clipped at the first and last
756
+ samples. The weight of row i is
757
+
758
+ w_i = cos(theta_edge_i) - cos(theta_edge_{i+1})
759
+
760
+ so that ``sum(w_i) * (phi span)`` reproduces the sampled solid angle
761
+ within floating-point error. Azimuth is integrated with the trapezoidal
762
+ rule. Midpoint boundaries keep neighboring cells contiguous even when
763
+ single-precision coordinates have small rounding differences.
764
+
765
+ The spherical Jacobian sin(theta) correctly vanishes at the poles,
766
+ which individually have zero solid angle. Numerical error arises from
767
+ approximating power over finite angular regions. Cell weighting can
768
+ reduce that error for pole-peaked patterns and exactly integrates an
769
+ isotropic pattern on a full sphere, but does not eliminate quadrature
770
+ bias generally. For smooth patterns that vanish at the poles, the
771
+ previous sin(theta) trapezoidal rule can be more accurate. Both rules
772
+ are generally second order, with higher-order convergence possible for
773
+ special patterns. Refine the angular grid to check convergence.
612
774
 
613
775
  Parameters
614
776
  ----------
615
777
  theta : ndarray
616
- 2D theta grid in radians
778
+ 2D theta grid in radians, shape (n_theta, n_phi). Must be uniformly
779
+ spaced, strictly increasing along axis 0, constant along axis 1,
780
+ and contained in [0, pi] - the ``theta_grid`` output of
781
+ :func:`~phased_array.utils.create_theta_phi_grid`.
617
782
  phi : ndarray
618
- 2D phi grid in radians
783
+ 2D phi grid in radians, same shape. Must be uniformly spaced,
784
+ strictly increasing along axis 1, constant along axis 0, and span
785
+ at most 2*pi.
619
786
  pattern : ndarray
620
- Complex or magnitude pattern, same shape
787
+ Complex or magnitude (amplitude) pattern on the same grid. Power is
788
+ taken as ``|pattern|**2``, so pass amplitude - not power, and not
789
+ dB.
621
790
 
622
791
  Returns
623
792
  -------
624
793
  directivity : float
625
- Directivity in linear scale
794
+ Peak directivity in linear scale (not dB)
795
+
796
+ Raises
797
+ ------
798
+ ValueError
799
+ If theta, phi and pattern are not 2D arrays of matching shape, hold
800
+ non-finite values, have fewer than two samples on an axis, are not
801
+ separable in the ``indexing='ij'`` sense, are not strictly increasing
802
+ with uniform spacing, sample theta outside [0, pi], or span more
803
+ than 2*pi in phi
804
+
805
+ Notes
806
+ -----
807
+ The grid need not cover the full sphere. A partial grid integrates only
808
+ the solid angle it samples, which is equivalent to assuming the pattern
809
+ radiates no power outside that region. A hemisphere grid
810
+ (``theta_range=(0, np.pi/2)``) therefore gives the expected answer for a
811
+ ground-plane backed array.
812
+
813
+ :func:`compute_full_pattern` output cannot be passed here directly: it
814
+ returns 1D theta and phi axes and a normalized dB pattern. Build the
815
+ grid with :func:`~phased_array.utils.create_theta_phi_grid` and evaluate
816
+ amplitude on it with :func:`total_pattern` or
817
+ :func:`array_factor_vectorized` instead. A dB-valued pattern is not
818
+ detectable here and integrates to a meaningless result.
819
+
820
+ Examples
821
+ --------
822
+ An isotropic pattern has unit directivity:
823
+
824
+ >>> import numpy as np
825
+ >>> import phased_array as pa
826
+ >>> _, _, theta, phi = pa.create_theta_phi_grid()
827
+ >>> d = pa.compute_directivity(theta, phi, np.ones_like(theta))
828
+ >>> f"{d:.9f}"
829
+ '1.000000000'
830
+
831
+ A short dipole, amplitude sin(theta), has directivity 3/2:
832
+
833
+ >>> d = pa.compute_directivity(theta, phi, np.sin(theta))
834
+ >>> f"{d:.4f}"
835
+ '1.5000'
626
836
  """
627
- power = np.abs(pattern)**2
837
+ theta_1d, phi_1d = _angle_axes(theta, phi, pattern)
628
838
 
629
- # Find peak
839
+ power = np.abs(pattern)**2
630
840
  peak_power = np.max(power)
631
841
 
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
842
+ # Shared midpoint boundaries avoid gaps/overlaps from rounded spacing.
843
+ edges = np.concatenate((theta_1d[:1],
844
+ (theta_1d[:-1] + theta_1d[1:]) / 2,
845
+ theta_1d[-1:]))
846
+ lower, upper = edges[:-1], edges[1:]
847
+ # Equivalent to cos(lower) - cos(upper), without polar cancellation.
848
+ theta_weights = 2 * np.sin((upper + lower) / 2) * np.sin((upper - lower) / 2)
636
849
 
637
- integrand = power * np.sin(theta)
638
- total_power = np.trapz(np.trapz(integrand, dx=d_phi, axis=1), dx=d_theta)
850
+ # trapezoid() rather than np.trapz(), which NumPy 2.4 removed, or
851
+ # np.trapezoid(), which NumPy 1.x does not have.
852
+ azimuth_integral = trapezoid(power, x=phi_1d, axis=1)
853
+ total_power = float(np.sum(theta_weights * azimuth_integral))
639
854
 
640
855
  if total_power > 0:
641
856
  directivity = 4 * np.pi * peak_power / total_power
642
857
  else:
643
858
  directivity = 1.0
644
859
 
645
- return directivity
860
+ return float(directivity)
646
861
 
647
862
 
648
863
  def compute_half_power_beamwidth(
@@ -991,7 +991,11 @@ def array_factor_conformal(
991
991
  k : float
992
992
  Wavenumber
993
993
  element_pattern_func : callable, optional
994
- Element pattern function
994
+ Element pattern function returning a field amplitude, evaluated
995
+ in each element's local frame. When omitted, elements with
996
+ normals use a cos(angle-to-normal) field pattern, which is a
997
+ cos^2 power pattern and matches
998
+ ``element_pattern_func=element_pattern, cos_exp_theta=2.0``.
995
999
  **element_kwargs
996
1000
  Arguments for element pattern function
997
1001
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: phased-array-modeling
3
- Version: 1.4.0
3
+ Version: 1.5.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
@@ -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.5.0"
8
8
  description = "Comprehensive Python library for phased array antenna modeling and visualization"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -2,6 +2,8 @@
2
2
  Unit tests for phased_array.core module.
3
3
  """
4
4
 
5
+ import warnings
6
+
5
7
  import numpy as np
6
8
  import pytest
7
9
  import phased_array as pa
@@ -165,9 +167,46 @@ class TestElementPattern:
165
167
 
166
168
  pattern = pa.element_pattern(theta, phi, max_gain_dBi=6.0)
167
169
 
168
- # 6 dBi = 10^0.6 ~ 3.98 linear
169
- expected_gain = 10 ** (6.0 / 10)
170
- assert np.isclose(pattern[0], expected_gain)
170
+ # 6 dBi power gain = 10^(6/20) ~ 2.00 field amplitude
171
+ expected_field = 10 ** (6.0 / 20)
172
+ assert np.isclose(pattern[0], expected_field)
173
+ assert np.isclose(10 * np.log10(pattern[0] ** 2), 6.0)
174
+
175
+ def test_element_pattern_power_rolloff(self):
176
+ """cos_exp_theta is the power exponent: cos^1 power is -3 dB at 60 deg."""
177
+ theta = np.deg2rad(np.array([0.0, 60.0]))
178
+ phi = np.zeros_like(theta)
179
+
180
+ pattern = pa.element_pattern(theta, phi, cos_exp_theta=1.0)
181
+
182
+ rel_dB = 10 * np.log10(pattern[1] ** 2 / pattern[0] ** 2)
183
+ assert np.isclose(rel_dB, 10 * np.log10(0.5))
184
+
185
+ def test_element_pattern_rear_hemisphere_no_warning(self):
186
+ """Rear hemisphere is zero and emits no NaN RuntimeWarning."""
187
+ theta = np.linspace(0, np.pi, 181)
188
+ phi = np.zeros_like(theta)
189
+
190
+ with warnings.catch_warnings():
191
+ warnings.simplefilter("error", RuntimeWarning)
192
+ pattern = pa.element_pattern(theta, phi, cos_exp_theta=1.3)
193
+
194
+ assert np.all(np.isfinite(pattern))
195
+ assert np.all(pattern[theta > np.pi / 2] == 0.0)
196
+ # cos(pi/2) is ~6e-17 in floating point, so endfire is ~0, not exact
197
+ assert np.isclose(pattern[90], 0.0, atol=1e-6) # theta[90] = 90 deg
198
+
199
+ def test_cosine_tapered_half_power_beamwidth(self):
200
+ """element_pattern_cosine_tapered is -3 dB (power) at theta_3dB."""
201
+ theta = np.deg2rad(np.array([0.0, 65.0]))
202
+ phi = np.zeros_like(theta)
203
+
204
+ pattern = pa.element_pattern_cosine_tapered(
205
+ theta, phi, theta_3dB_deg=65.0
206
+ )
207
+
208
+ rel_dB = 10 * np.log10(pattern[1] ** 2 / pattern[0] ** 2)
209
+ assert np.isclose(rel_dB, 10 * np.log10(0.5))
171
210
 
172
211
 
173
212
  class TestPatternComputation:
@@ -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}")
@@ -96,7 +96,7 @@ class TestElementFactories:
96
96
  phi = np.deg2rad(np.linspace(0, 340, 20))
97
97
  E_theta, E_phi = f(theta, phi)
98
98
  power = np.abs(E_theta) ** 2 + np.abs(E_phi) ** 2
99
- scalar = pa.element_pattern(theta, phi, cos_exp_theta=2 * q)
99
+ scalar = np.abs(pa.element_pattern(theta, phi, cos_exp_theta=2 * q))**2
100
100
  assert np.allclose(power, scalar, atol=1e-12)
101
101
 
102
102
  def test_cos_q_gain_scale(self):
@@ -329,8 +329,9 @@ class TestConformalVector:
329
329
  )
330
330
 
331
331
  def test_scalar_conformal_regression(self):
332
- # array_factor_conformal default cos-pattern and cos^1 element
333
- # func agree after the local-frame fix
332
+ # array_factor_conformal's default cos(angle) field pattern is a
333
+ # cos^2 power pattern, so it matches element_pattern with the
334
+ # power exponent cos_exp_theta=2 (evaluated in the local frame)
334
335
  cyl = pa.create_cylindrical_array(8, 4, radius=1.0, height=2.0)
335
336
  k = pa.wavelength_to_k(1.0)
336
337
  w = np.ones(cyl.n_elements, dtype=complex)
@@ -339,7 +340,7 @@ class TestConformalVector:
339
340
  )
340
341
  af_cos = pa.array_factor_conformal(
341
342
  np.array([0.3]), np.array([0.1]), cyl, w, k,
342
- element_pattern_func=pa.element_pattern, cos_exp_theta=1.0,
343
+ element_pattern_func=pa.element_pattern, cos_exp_theta=2.0,
343
344
  )
344
345
  assert np.allclose(af_default, af_cos, atol=1e-9)
345
346