diff --git a/CLAUDE.md b/CLAUDE.md index 5c5a83e..1ea360d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -83,6 +83,7 @@ Browser edits Project ──POST /api/evaluate──▶ Engine.evaluate ─▶ A - Project/API coordinates are λ at the design frequency; the core uses λ/2. Convert only in `project_array()`. - All angle evaluation goes through `EvaluationSettings` built from `project.fov` (`engine.evaluation_settings`); do not call the ±90° bank functions directly from new service code. - Channel names derive from list order (`Tx1…`, `Rx1…`); the client renumbers by (x, y) after every edit, like the desktop tool. +- Imported channel phase (HFSS far-field) already contains the geometric phase, so it is the channel response for its plane in both DBF and array-factor metrics (`_channel_response`); geometric steering is kept only for a plane without imported phase, with the sign from `_imported_phase_sign`. - Non-finite numbers travel as `"Infinity"` / `"-Infinity"` strings; large matrices as `{dtype, shape, data(base64)}`. - Keep core numerics unchanged when refactoring — the analysis tests pin them. - Tests use `examples/case4_5tx7rx_sel.py::build_array()` (also the default project) as the reference layout. diff --git a/src/virtual_array/analysis.py b/src/virtual_array/analysis.py index 1dc44b0..00f131e 100644 --- a/src/virtual_array/analysis.py +++ b/src/virtual_array/analysis.py @@ -260,22 +260,34 @@ def calculate_metrics_and_psf( u = np.sin(az_rad) * np.cos(el_rad) v = np.sin(el_rad) - # A (channels x grid) matrix product avoids the large broadcast temporaries - # of the per-axis formulation; it is ~4x faster for 64+ virtual channels. - uv = np.stack([u.ravel(), v.ravel()]) - steering = unit_phasor((np.pi * virtual_xy) @ uv) - channel_weight = _channel_pattern_weight( - channel_patterns, array, az_grid, el_grid - ) - if np.ndim(channel_weight) == 0: - flat_factor = complex(channel_weight) * ( - np.ones(len(virtual_xy), dtype=complex) @ steering + if _channel_pattern_has_any_phase(channel_patterns, array): + # Imported phase cuts already carry the geometric phase progression of + # their plane; multiplying the steering in again would count it twice. + # Use the same channel response as the DBF signal model. + phase_sign = _imported_phase_sign( + array, channel_patterns, azimuths, elevations ) + flat_factor = _channel_response( + array, az_grid.ravel(), el_grid.ravel(), channel_patterns, phase_sign + ).sum(axis=0) else: - flat_weight = np.asarray(channel_weight, dtype=complex).reshape( - len(virtual_xy), -1 + # A (channels x grid) matrix product avoids the large broadcast + # temporaries of the per-axis formulation; it is ~4x faster for 64+ + # virtual channels. + uv = np.stack([u.ravel(), v.ravel()]) + steering = unit_phasor((np.pi * virtual_xy) @ uv) + channel_weight = _channel_pattern_weight( + channel_patterns, array, az_grid, el_grid ) - flat_factor = np.einsum("ng,ng->g", steering, flat_weight) + if np.ndim(channel_weight) == 0: + flat_factor = complex(channel_weight) * ( + np.ones(len(virtual_xy), dtype=complex) @ steering + ) + else: + flat_weight = np.asarray(channel_weight, dtype=complex).reshape( + len(virtual_xy), -1 + ) + flat_factor = np.einsum("ng,ng->g", steering, flat_weight) array_factor = flat_factor.reshape(az_grid.shape) pattern_weight = _element_pattern_weight(tx_pattern, az_grid, el_grid) pattern_weight *= _element_pattern_weight(rx_pattern, az_grid, el_grid) @@ -546,6 +558,16 @@ def __init__( dbf_dictionary is not None and not dbf_dictionary.uses_auto_ideal_sign ) self._has_phase = _channel_pattern_has_any_phase(channel_patterns, array) + self._phase_sign = ( + _imported_phase_sign( + array, + channel_patterns, + self.scan_azimuths_deg, + self.scan_elevations_deg, + ) + if self._has_phase + else 1 + ) self._dictionaries: dict[int, np.ndarray] = {} def _dictionary(self, steering_sign: int) -> np.ndarray: @@ -610,6 +632,7 @@ def spectrum_db( true_az, true_el, channel_patterns=self.channel_patterns, + phase_sign=self._phase_sign, ) if self._uses_fixed_dictionary: dictionary = self._dictionary(0) @@ -1358,7 +1381,16 @@ def _dbf_2d_signal_vector( true_azimuth_deg: float, true_elevation_deg: float, channel_patterns: ChannelPatternSet | None, + phase_sign: int = 1, ) -> np.ndarray: + if _channel_pattern_has_any_phase(channel_patterns, array): + return _channel_response( + array, + np.asarray([true_azimuth_deg], dtype=float), + np.asarray([true_elevation_deg], dtype=float), + channel_patterns, + phase_sign, + )[:, 0] azimuths = np.asarray([true_azimuth_deg], dtype=float) elevations = np.asarray([true_elevation_deg], dtype=float) channel_weight = _channel_pattern_weight( @@ -1369,44 +1401,87 @@ def _dbf_2d_signal_vector( channel_weight = np.ones(virtual_count, dtype=complex) * complex(channel_weight) else: channel_weight = np.asarray(channel_weight, dtype=complex).reshape(virtual_count) - if _channel_pattern_has_any_phase(channel_patterns, array): - return np.asarray(channel_weight, dtype=complex) return _dbf_2d_steering_vector( array, true_azimuth_deg, true_elevation_deg ) * channel_weight -def _dbf_2d_signal_matrix( +def _channel_response( array: AntennaArray, - true_azimuth_deg: np.ndarray, - true_elevation_deg: np.ndarray, + azimuth_deg: np.ndarray, + elevation_deg: np.ndarray, channel_patterns: ChannelPatternSet | None, + phase_sign: int = 1, ) -> np.ndarray: - azimuths, elevations = np.broadcast_arrays( - np.asarray(true_azimuth_deg, dtype=float), - np.asarray(true_elevation_deg, dtype=float), - ) - flat_az = azimuths.ravel() - flat_el = elevations.ravel() - channel_weight = _channel_pattern_weight(channel_patterns, array, flat_az, flat_el) + """Per-virtual-channel response (channels x directions) with imported phase. + + Imported phase cuts already contain the geometric phase progression of + their plane, so the channel weight alone is the response along that axis. + The geometric steering is kept only for an axis without imported phase, + with the phase sign of the imported data (see :func:`_imported_phase_sign`) + so both axes follow one convention. + """ + flat_az = np.asarray(azimuth_deg, dtype=float).ravel() + flat_el = np.asarray(elevation_deg, dtype=float).ravel() + u, v = _direction_uv(flat_az, flat_el) virtual_count = len(array.tx) * len(array.rx) - if np.isscalar(channel_weight): - weights = np.ones((len(flat_az), virtual_count), dtype=complex) * complex( - channel_weight + channel_weight = _channel_pattern_weight(channel_patterns, array, flat_az, flat_el) + has_azimuth_phase = _channel_pattern_has_phase(channel_patterns, array, "azimuth") + has_elevation_phase = _channel_pattern_has_phase( + channel_patterns, array, "elevation" + ) + if has_azimuth_phase: + # The horizontal cut samples the phase at el = 0, where u = sin(az). + # Off the cut, read it at the same direction cosine u so its geometric + # part stays pi*x*u (the elevation cut already follows v = sin(el)). + # Amplitudes stay at (az, el). + cut_azimuth = np.degrees(np.arcsin(np.clip(u, -1.0, 1.0))) + phase_weight = np.asarray( + _channel_pattern_weight(channel_patterns, array, cut_azimuth, flat_el), + dtype=complex, ) - else: - weights = np.asarray(channel_weight, dtype=complex).reshape( - virtual_count, len(flat_az) - ).T - if _channel_pattern_has_any_phase(channel_patterns, array): - return weights - steering = _dbf_2d_scan_matrix( - array, - flat_az, - flat_el, - steering_sign=1, + channel_weight = np.abs(channel_weight) * phase_weight / np.abs(phase_weight) + response = np.asarray(channel_weight, dtype=complex) * np.ones( + (virtual_count, len(flat_az)), dtype=complex + ) + if has_azimuth_phase and has_elevation_phase: + return response + virtual_xy = array.virtual_xy() + phase = np.zeros_like(response, dtype=float) + if not has_azimuth_phase: + phase += np.outer(virtual_xy[:, 0], u) + if not has_elevation_phase: + phase += np.outer(virtual_xy[:, 1], v) + return response * unit_phasor(phase_sign * np.pi * phase) + + +def _imported_phase_sign( + array: AntennaArray, + channel_patterns: ChannelPatternSet | None, + azimuth_angles_deg: np.ndarray, + elevation_angles_deg: np.ndarray, +) -> int: + """Sign of the phase progression in imported phase cuts (+1: exp(+j*pi*x*u)). + + Only matters when one plane has imported phase and the other keeps the + geometric steering. It is the opposite of the ideal-dictionary sign that + :func:`_select_dbf_steering_sign` picks for the imported axis. + """ + has_azimuth_phase = _channel_pattern_has_phase(channel_patterns, array, "azimuth") + has_elevation_phase = _channel_pattern_has_phase( + channel_patterns, array, "elevation" + ) + if has_azimuth_phase == has_elevation_phase: + return 1 + axis, angles = ( + ("azimuth", np.asarray(azimuth_angles_deg, dtype=float)) + if has_azimuth_phase + else ("elevation", np.asarray(elevation_angles_deg, dtype=float)) + ) + signal_phase = _dbf_signal_matrix(array, angles, axis, channel_patterns) + return -_select_dbf_steering_sign( + array, angles, angles, signal_phase, axis, channel_patterns ) - return steering * weights def _select_dbf_steering_sign( diff --git a/src/virtual_array/performance_report.py b/src/virtual_array/performance_report.py index 1a30bf1..986cd57 100644 --- a/src/virtual_array/performance_report.py +++ b/src/virtual_array/performance_report.py @@ -2129,6 +2129,11 @@ def _method_notes( _label(language, "note_fov"), _label(language, "note_hold"), ] + if any( + pattern.phase_horizontal is not None or pattern.phase_elevation is not None + for pattern in snapshot.channel_patterns.patterns.values() + ): + notes.append(_label(language, "note_imported_phase")) if snapshot.dbf_dictionary.mode == "custom": notes.append(_label(language, "note_custom_dictionary")) notes.extend(_dictionary_coverage_notes(snapshot, options, data)) @@ -2393,6 +2398,11 @@ def _label(language: str, key: str) -> str: "en": "Element-pattern gain affects array-factor metrics; the current 1D DBF does not consume tx/rx element patterns, but it does use configured channel amp/phase and the DBF dictionary.", "ja": "要素パターンはアレイファクタ指標にのみ反映され、1D DBFはチャネル振幅/位相と辞書を使います。", }, + "note_imported_phase": { + "zh": "导入的通道相位已包含几何相位,阵因子指标与 DBF 都直接以其作为该平面的通道响应,不再叠加几何导向矢量;未导入相位的平面沿用几何导向,符号按导入数据自动匹配。", + "en": "Imported channel phase already contains the geometric phase, so array-factor metrics and DBF use it directly as the channel response in that plane without adding the geometric steering again; a plane without imported phase keeps the geometric steering with the sign matched to the imported data.", + "ja": "インポートしたチャネル位相は幾何位相を含むため、アレイファクタ指標とDBFはその面のチャネル応答として直接使用し、幾何ステアリングを重ねません。位相未インポートの面は幾何ステアリングを使い、符号はインポートデータに合わせます。", + }, "note_grid": { "zh": "DBF 真实角与扫描角均为 -90°..+90°、1°步进;峰值取离散栅格最大值,未做亚栅格插值。", "en": "DBF true/scan grids are -90°..+90° in 1° steps; peaks are discrete-grid maxima without sub-bin interpolation.", diff --git a/tests/test_analysis.py b/tests/test_analysis.py index d112d81..483f729 100644 --- a/tests/test_analysis.py +++ b/tests/test_analysis.py @@ -7,6 +7,7 @@ AF_GRID_SIZE, DBF_QUALITY_OK, DBF_SCAN_GRID_SIZE, + Dbf2dScanner, EvaluationSettings, calculate_metrics_and_psf, dbf_2d_normalization_reference, @@ -27,6 +28,7 @@ from virtual_array.element_pattern import ( PATTERN_KIND_AMPLITUDE, PATTERN_KIND_PHASE, + PATTERN_PLANE_ELEVATION, PATTERN_PLANE_HORIZONTAL, ChannelPatternSet, PatternSeries, @@ -572,3 +574,114 @@ def test_refined_peaks_are_exact_for_ideal_array_and_resolve_subdegree_errors() center = int(np.argmin(np.abs(refined.true_angles_deg))) assert coarse.frame_series.errors_deg[center] in (0.0, 1.0, -1.0) assert 0.0 < abs(refined.frame_series.errors_deg[center]) < 1.0 + + +def _geometric_phase_patterns( + array: AntennaArray, + planes: tuple[str, ...], + sign: float = 1.0, + error_deg: float = 0.0, +) -> ChannelPatternSet: + """Per-physical-channel phase cuts holding the geometric phase progression. + + Like HFSS far-field phase, each cut already contains pi*x*sin(theta) + (λ/2 units); ``error_deg`` adds a small smooth per-channel deviation. + """ + angles = np.arange(-90.0, 90.05, 0.1) + patterns = ChannelPatternSet() + for index, point in enumerate([*array.tx, *array.rx]): + for plane in planes: + position = point.x if plane == PATTERN_PLANE_HORIZONTAL else point.y + values = sign * np.degrees(np.pi * position * np.sin(np.radians(angles))) + values += error_deg * np.sin(np.radians(angles) * (index + 1)) + patterns.set_series( + point.name, + PATTERN_KIND_PHASE, + plane, + PatternSeries( + name="phase.csv", + source_path="phase.csv", + angle_column="Theta", + value_column=point.name, + value_kind=PATTERN_KIND_PHASE, + angles_deg=angles, + values=values, + ), + ) + return patterns + + +PHASE_PLANES = [ + (PATTERN_PLANE_HORIZONTAL,), + (PATTERN_PLANE_ELEVATION,), + (PATTERN_PLANE_HORIZONTAL, PATTERN_PLANE_ELEVATION), +] + + +@pytest.mark.parametrize("planes", PHASE_PLANES) +@pytest.mark.parametrize("sign", [1.0, -1.0]) +def test_imported_geometric_phase_matches_ideal_array_metrics( + planes: tuple[str, ...], sign: float +) -> None: + # Imported phase already carries the geometry: the array factor must not + # multiply the geometric steering in again, whichever sign convention the + # data uses and whichever planes were imported. + array = build_array() + patterns = _geometric_phase_patterns(array, planes, sign) + fov = {"azimuth_fov": (-75.0, 75.0), "elevation_fov": (-45.0, 45.0)} + ideal_db, _az, _el, ideal = calculate_metrics_and_psf(array, **fov) + af_db, _az, _el, metrics = calculate_metrics_and_psf( + array, channel_patterns=patterns, **fov + ) + + assert metrics.azimuth_3db_beamwidth == pytest.approx( + ideal.azimuth_3db_beamwidth, abs=1e-3 + ) + assert metrics.elevation_3db_beamwidth == pytest.approx( + ideal.elevation_3db_beamwidth, abs=1e-3 + ) + assert metrics.psl_db == pytest.approx(ideal.psl_db, abs=0.01) + assert metrics.azimuth_psl_db == pytest.approx(ideal.azimuth_psl_db, abs=0.01) + assert metrics.elevation_psl_db == pytest.approx(ideal.elevation_psl_db, abs=0.01) + assert metrics.azimuth_islr_db == pytest.approx(ideal.azimuth_islr_db, abs=0.01) + # The whole 2D pattern, not only the principal cuts. + visible = ideal_db > -40.0 + assert np.max(np.abs(af_db - ideal_db)[visible]) < 0.05 + + +@pytest.mark.parametrize("planes", PHASE_PLANES) +def test_small_imported_phase_errors_only_perturb_array_metrics( + planes: tuple[str, ...], +) -> None: + array = build_array() + patterns = _geometric_phase_patterns(array, planes, error_deg=3.0) + _af, _az, _el, ideal = calculate_metrics_and_psf(array) + _af, _az, _el, metrics = calculate_metrics_and_psf(array, channel_patterns=patterns) + + assert metrics.azimuth_3db_beamwidth == pytest.approx( + ideal.azimuth_3db_beamwidth, rel=0.02 + ) + assert metrics.elevation_3db_beamwidth == pytest.approx( + ideal.elevation_3db_beamwidth, rel=0.02 + ) + assert metrics.psl_db == pytest.approx(ideal.psl_db, abs=0.5) + assert metrics.azimuth_psl_db == pytest.approx(ideal.azimuth_psl_db, abs=0.5) + + +@pytest.mark.parametrize("planes", PHASE_PLANES) +@pytest.mark.parametrize("sign", [1.0, -1.0]) +def test_2d_dbf_keeps_geometric_steering_for_plane_without_imported_phase( + planes: tuple[str, ...], sign: float +) -> None: + array = build_array() + scanner = Dbf2dScanner( + array, + scan_azimuths_deg=np.arange(-60.0, 61.0, 1.0), + scan_elevations_deg=np.arange(-20.0, 21.0, 1.0), + channel_patterns=_geometric_phase_patterns(array, planes, sign), + ) + for true_az, true_el in [(10.0, 5.0), (-30.0, -8.0), (40.0, 12.0)]: + spectrum = scanner.spectrum_db(true_az, true_el) + el_index, az_index = np.unravel_index(np.argmax(spectrum), spectrum.shape) + assert scanner.scan_azimuths_deg[az_index] == true_az + assert scanner.scan_elevations_deg[el_index] == true_el diff --git a/tests/test_element_pattern.py b/tests/test_element_pattern.py index 81e132b..2016367 100644 --- a/tests/test_element_pattern.py +++ b/tests/test_element_pattern.py @@ -528,14 +528,17 @@ def test_element_pattern_weights_array_factor_grid() -> None: def test_physical_channel_phase_pattern_weights_virtual_channels() -> None: array = AntennaArray.from_xy(tx_x=[0], tx_y=[0], rx_x=[0, 1], rx_y=[0, 0]) + angles = np.arange(-90.0, 91.0, 1.0) phase_series = PatternSeries( name="phase", source_path="phase.csv", angle_column="Theta", value_column="phase", value_kind=PATTERN_KIND_PHASE, - angles_deg=np.array([-90.0, 0.0, 90.0]), - values=np.array([180.0, 180.0, 180.0]), + angles_deg=angles, + # Imported phase carries the geometric progression of Rx2 (x = λ/2) + # plus a 180° offset that nulls boresight. + values=180.0 * np.sin(np.radians(angles)) + 180.0, ) channel_patterns = ChannelPatternSet() channel_patterns.set_series( @@ -558,14 +561,17 @@ def test_physical_channel_phase_pattern_weights_virtual_channels() -> None: def test_virtual_channel_phase_pattern_weights_matching_virtual_channel() -> None: array = AntennaArray.from_xy(tx_x=[0], tx_y=[0], rx_x=[0, 1], rx_y=[0, 0]) + angles = np.arange(-90.0, 91.0, 1.0) phase_series = PatternSeries( name="phase", source_path="phase.csv", angle_column="Theta", value_column="phase", value_kind=PATTERN_KIND_PHASE, - angles_deg=np.array([-90.0, 0.0, 90.0]), - values=np.array([180.0, 180.0, 180.0]), + angles_deg=angles, + # Imported phase carries the geometric progression of Rx2 (x = λ/2) + # plus a 180° offset that nulls boresight. + values=180.0 * np.sin(np.radians(angles)) + 180.0, ) channel_patterns = ChannelPatternSet() channel_patterns.set_series( diff --git a/tests/test_performance_report.py b/tests/test_performance_report.py index 24954c6..d3db830 100644 --- a/tests/test_performance_report.py +++ b/tests/test_performance_report.py @@ -857,3 +857,26 @@ def test_performance_report_import_does_not_import_pyplot() -> None: ) result = subprocess.run([sys.executable, "-c", code], cwd=project_root, check=False) assert result.returncode == 0 + + +def test_method_notes_explain_imported_phase_only_when_present() -> None: + options = SimpleNamespace(language="en") + data = SimpleNamespace(array_metrics=SimpleNamespace(warning_messages=())) + note = performance_report_module._label("en", "note_imported_phase") + patterns = ChannelPatternSet() + patterns.set_series( + "Rx2", + PATTERN_KIND_PHASE, + PATTERN_PLANE_HORIZONTAL, + _phase_series("Rx2", -90.0, 90.0), + ) + + without = performance_report_module._method_notes( + _angle_error_snapshot(), options, data + ) + with_phase = performance_report_module._method_notes( + _angle_error_snapshot(patterns), options, data + ) + + assert note not in without + assert note in with_phase