From 1ab9404457a262af76fea1e648b8aee5708cdc08 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 11:18:10 +0000 Subject: [PATCH 1/5] =?UTF-8?q?=E9=87=8D=E6=9E=84=EF=BC=9A=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=20PySide6=20=E6=A1=8C=E9=9D=A2=E5=B1=82=EF=BC=8C?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E9=A1=B9=E7=9B=AE=E6=A8=A1=E5=9E=8B=E3=80=81?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=B1=82=E4=B8=8E=20FastAPI=20=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 删除 gui/qt_tk/qt_plot/native_theme/报告对话框等 Qt 界面层及对应测试 - 新增 project.py(v2 项目文档,兼容 v1 布局 JSON 导入导出) - 新增 assets.py(按 SHA-256 存储导入文件)与 engine.py(缓存计算服务) - 新增 server/(REST API、项目库、报告后台任务、CLI) - analysis:阵列因子改为矩阵乘法、新增可复用的 Dbf2dScanner,结果与原实现一致 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TgRQxvYJLtrCkPBUDGPWAw --- .opencode/skills/python-gui/SKILL.md | 38 - ELEMENT_PATTERN_PLAN.md | 97 - EXE_PACKAGING_PLAN.md | 98 - GUI.py | 56 - GUI_MOD_VISUAL_GUIDELINES.md | 135 - GUI_mod.py | 58 - MIMOArrayVisualizer.spec | 68 - OPTIMIZATION_IDEAS.md | 206 - UI_SKILL_INTEGRATION.md | 137 - design-qa.md | 127 - pyproject.toml | 24 +- scripts/build_exe.ps1 | 25 - scripts/capture_ui_review.py | 689 -- scripts/run_case4.ps1 | 8 - scripts/run_gui.ps1 | 17 - scripts/setup.ps1 | 11 - src/virtual_array/analysis.py | 223 +- src/virtual_array/app_state.py | 46 - src/virtual_array/assets.py | 118 + src/virtual_array/dbf_dictionary.py | 3 +- src/virtual_array/engine.py | 744 ++ src/virtual_array/gui.py | 10275 ---------------- src/virtual_array/gui_mod.py | 16 - src/virtual_array/native_theme.py | 833 -- .../performance_report_dialog.py | 900 -- src/virtual_array/phasor.py | 17 + src/virtual_array/project.py | 341 + src/virtual_array/qt_plot.py | 1917 --- src/virtual_array/qt_tk.py | 3419 ----- src/virtual_array/server/__init__.py | 5 + src/virtual_array/server/app.py | 515 + src/virtual_array/server/cli.py | 69 + src/virtual_array/server/jobs.py | 141 + src/virtual_array/server/store.py | 104 + src/virtual_array/user_manual.py | 1647 --- src/virtual_array/version.py | 2 +- tests/test_analysis.py | 62 - tests/test_app_state.py | 26 - tests/test_apple_switch.py | 100 - tests/test_gui_element_editing.py | 582 - tests/test_interactive_cursors.py | 189 - tests/test_layout_export.py | 46 - tests/test_logging_config.py | 6 +- tests/test_performance_report_dialog.py | 650 - tests/test_project.py | 146 + tests/test_qt_gui_smoke.py | 1424 --- tests/test_server.py | 398 + tests/test_toplevel_first_frame.py | 70 - tests/test_user_manual.py | 92 - 49 files changed, 2753 insertions(+), 24167 deletions(-) delete mode 100644 .opencode/skills/python-gui/SKILL.md delete mode 100644 ELEMENT_PATTERN_PLAN.md delete mode 100644 EXE_PACKAGING_PLAN.md delete mode 100644 GUI.py delete mode 100644 GUI_MOD_VISUAL_GUIDELINES.md delete mode 100644 GUI_mod.py delete mode 100644 MIMOArrayVisualizer.spec delete mode 100644 OPTIMIZATION_IDEAS.md delete mode 100644 UI_SKILL_INTEGRATION.md delete mode 100644 design-qa.md delete mode 100644 scripts/build_exe.ps1 delete mode 100644 scripts/capture_ui_review.py delete mode 100644 scripts/run_case4.ps1 delete mode 100644 scripts/run_gui.ps1 delete mode 100644 scripts/setup.ps1 delete mode 100644 src/virtual_array/app_state.py create mode 100644 src/virtual_array/assets.py create mode 100644 src/virtual_array/engine.py delete mode 100644 src/virtual_array/gui.py delete mode 100644 src/virtual_array/gui_mod.py delete mode 100644 src/virtual_array/native_theme.py delete mode 100644 src/virtual_array/performance_report_dialog.py create mode 100644 src/virtual_array/phasor.py create mode 100644 src/virtual_array/project.py delete mode 100644 src/virtual_array/qt_plot.py delete mode 100644 src/virtual_array/qt_tk.py create mode 100644 src/virtual_array/server/__init__.py create mode 100644 src/virtual_array/server/app.py create mode 100644 src/virtual_array/server/cli.py create mode 100644 src/virtual_array/server/jobs.py create mode 100644 src/virtual_array/server/store.py delete mode 100644 src/virtual_array/user_manual.py delete mode 100644 tests/test_app_state.py delete mode 100644 tests/test_apple_switch.py delete mode 100644 tests/test_gui_element_editing.py delete mode 100644 tests/test_interactive_cursors.py delete mode 100644 tests/test_layout_export.py delete mode 100644 tests/test_performance_report_dialog.py create mode 100644 tests/test_project.py delete mode 100644 tests/test_qt_gui_smoke.py create mode 100644 tests/test_server.py delete mode 100644 tests/test_toplevel_first_frame.py delete mode 100644 tests/test_user_manual.py diff --git a/.opencode/skills/python-gui/SKILL.md b/.opencode/skills/python-gui/SKILL.md deleted file mode 100644 index 83d5e29..0000000 --- a/.opencode/skills/python-gui/SKILL.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -name: python-gui -description: Tkinter + Matplotlib GUI patterns, THEME conventions, figure sizing, font handling for desktop Python apps ---- -## Tkinter layout patterns - -- 使用 `grid()` 做比例布局:`grid_columnconfigure(col, weight=N)` 控制列宽比 -- 固定比例用 `place()` + `` 事件(grid weight 受内容 min size 干扰时) -- `ttk.Notebook` 做多子页,`ttk.PanedWindow` 做可拖拽分割,但用户已明确不要拖拽线 -- `ttk.LabelFrame` 做分组卡片,`ttk.Frame(padding=(L,T,R,B))` 控制内边距 -- 面板间距统一:左右面板内侧 padding 各 2px,总间隙 4px -- `TkDefaultFont` / `TkFixedFont` 跨平台系统字体 -- macOS Tk 使用 Cocoa 后端,`geometry("WxH")` 单位是逻辑点 - -## Matplotlib embedding - -- `Figure(figsize=(w, h), dpi=FIG_DPI)` 创建 figure,`FIG_DPI=100` -- `FigureCanvasTkAgg(fig, master=parent)` 嵌入 Tk -- `canvas.get_tk_widget().grid(row, col, sticky="nsew")` 放置 canvas -- 不要设置 canvas widget 的固定 `width/height`,用 `sticky="nsew"` 自动填充 -- `_configure_axis_chrome(ax)` 统一设置 spine/tick 颜色和字体 -- `fig.subplots_adjust(top, left, right, bottom)` 控制图表边距 -- 中文跨平台字体链:`["PingFang SC", "Heiti SC", "STHeiti", "Microsoft YaHei", "SimHei", "WenQuanYi Micro Hei", "Noto Sans CJK SC", "DejaVu Sans"]` -- `rcParams["axes.unicode_minus"] = False` 避免负号乱码 - -## THEME conventions - -- THEME dict 集中所有颜色/字体/间距,构建时用 `_f = THEME["font_family"]` 引用 -- style 用 ttk.Style + `style.configure("Name.TFrame", ...)` 定义 -- 按钮用 `style.map()` 控制 hover/pressed/disabled 状态 -- 不要用 `tk` 原生 widget(用 `ttk`),除非 matplotlib canvas - -## Figure size guideline - -- 窗口宽度 / 100 DPI / 列数 ≈ 每个 figure 的英寸宽度 -- 物理/虚拟阵列图:~0.35×窗口宽度/100 英寸宽 -- 响应曲线图:比上面略高 -- 2D DBF 热图:方图,约 100 + 窗口剩余/100 英寸 diff --git a/ELEMENT_PATTERN_PLAN.md b/ELEMENT_PATTERN_PLAN.md deleted file mode 100644 index e7be394..0000000 --- a/ELEMENT_PATTERN_PLAN.md +++ /dev/null @@ -1,97 +0,0 @@ -# 单元方向图输入功能 — 开发方案 - -> 创建日期:2026-05-14 - ---- - -## 一档:基础功能(建议首轮完成) - -### 1.1 方向图数据输入 - -- 界面加一块区域,标题 **Element Pattern** -- 两个输入通道:**Tx Pattern** 和 **Rx Pattern**(可各自载入文件或共用) -- 输入方式: - - 文件选择按钮 + 路径显示,支持 `.csv` / `.tsv` - - 附一个 **Clear** 按钮,清空后恢复默认全向假设 -- 文件格式约定: - - ``` - # Angle(deg) Gain(dBi) - -90 -12.5 - -75 -6.3 - ... - 0 5.2 - ... - 75 -6.3 - 90 -12.5 - ``` - - - 两列:角度(deg)、增益(dBi 或线性值) - - 自动检测列序(先找 header 关键词 angle / azimuth / gain / dBi) - - 角度范围不必对称,代码自动插值 - -### 1.2 内部存储和插值 - -- 加载后存为 `np.interp` 可用的一维 `(angles, gains)` 数组 -- 计算阵列因子时,对每个方位角 `az` 查询对应的单元增益 `g_tx(az)` 和 `g_rx(az)` -- 第一版仅支持一维 azimuth-only 方向图(elevation=0° 切片) - -### 1.3 计算结果变化 - -修改 `_calculate_metrics_and_psf()` 中的阵列因子计算: - -``` -当前:AF = |Σ exp(j·phase)| -加载后:AF = |Σ g_tx(az) · g_rx(az) · exp(j·phase)| -``` - -- 如果 Tx 和 Rx 用同一天线,只加载一次即可 -- 如果有 2D 方向图则在后续版本扩展到 (az, el) 二维查询 - -### 1.4 显示反馈 - -- 加载成功后在 PSF 图上叠加一条**半透明虚线**显示单元方向图(归一化到 0 dB 峰值) -- 图例标注 "Tx pattern" / "Rx pattern" -- Array Evaluation 的 NOTES 区域追加一行: - - `"Element pattern: loaded (Tx: xxx.csv, Rx: xxx.csv)"` - - 或 `"Element pattern: isotropic"`(未加载时) - ---- - -## 二档:增强功能(后续迭代) - -### 2.1 俯仰向方向图支持 - -- 输入文件扩展为三列:`Az(deg), El(deg), Gain(dBi)`,支持完整 2D 方向图 -- 计算 (az, el) 二维阵列因子时用 `scipy.interpolate.RegularGridInterpolator` 做二维查询 - -### 2.2 相位方向图 - -- 支持复增益格式 (Re, Im) 或 (Mag, Phase) -- 单元复增益直接乘入复阵列因子,同时影响幅度和相位 - -### 2.3 方向图预览窗口 - -- 单独弹一个小 Figure 查看加载的方向图形状 -- 方便确认导入数据正确 - -### 2.4 方向图对指标影响的对比显示 - -- Array Evaluation 里并列显示 "With pattern" / "Isotropic" 的关键指标对比 -- 或加一个 toggle 按钮切换,实时刷新 - ---- - -## 三档:可选扩展(按需添加) - -### 3.1 方向图归一化选项 - -- 是否把最大增益归一化到 0 dBi(有些数据自带绝对增益,有些需要归一化) - -### 3.2 波束扫描场景的方向图加权 - -- 当前固定 Steering = 0°,若后续要仿真扫描场景,方向图查询角需加上扫描角偏移 - -### 3.3 常见仿真软件导出格式 - -- HFSS `.csv`、CST `.txt` 的自动解析 diff --git a/EXE_PACKAGING_PLAN.md b/EXE_PACKAGING_PLAN.md deleted file mode 100644 index 5dc6433..0000000 --- a/EXE_PACKAGING_PLAN.md +++ /dev/null @@ -1,98 +0,0 @@ -# 封装为可执行文件 (.exe) 方案 - -> 创建日期:2026-05-14 - ---- - -## 方案选择:PyInstaller(推荐) - -PySide6 + pyqtgraph 组合下继续使用 PyInstaller 打包;项目已在 -`MIMOArrayVisualizer.spec` 中显式包含 Qt 绑定与 pyqtgraph。 - -| 工具 | 难度 | .exe 大小 | 启动速度 | 推荐度 | -|------|------|-----------|----------|--------| -| **PyInstaller** | 低 | 80~120 MB | 3~5 秒 | ★★★ | -| Nuitka | 中 | 40~80 MB | 1~2 秒 | ★★ | -| cx_Freeze | 低 | 类似 | 类似 | ★ | - ---- - -## 实施步骤 - -### 1. 确保入口可用 - -`GUI.py` 位于项目根目录,`pip install -e .` 已完成即可。 - -### 2. 推荐打包命令 - -```powershell -cd E:\WORK\antenna_layout - -# 测试版(带控制台,方便排查问题) -pyinstaller --onedir --console --name "MIMOArrayVisualizer" --paths src GUI.py - -# 发布版(无控制台) -pyinstaller --onedir --noconsole --name "MIMOArrayVisualizer" --paths src GUI.py -``` - -### 3. spec 文件关键配置 - -如需精细控制,写 `.spec` 文件: - -```python -a = Analysis( - ['GUI.py'], - pathex=['src'], # 让 PyInstaller 找到 virtual_array - hiddenimports=[ - 'virtual_array', - 'virtual_array.gui', - 'virtual_array.geometry', - 'virtual_array.grid', - 'virtual_array.plotting', - 'virtual_array.examples', - 'virtual_array.examples.case4_5tx7rx_sel', - 'openpyxl', - 'openpyxl.cell._writer', - 'PySide6', - 'pyqtgraph', - ], - datas=[ - ('src/virtual_array/examples/*.py', 'virtual_array/examples/'), # 示例数据 - # 中文字体(按实际路径调整) - ], - excludes=['pytest', 'unittest'], -) -``` - -### 4. 常见问题及解法 - -| 问题 | 原因 | 解法 | -|------|------|------| -| `ModuleNotFoundError: virtual_array` | PyInstaller 不扫描 `-e` 安装路径 | 用 `--paths src` 或 spec 中 `pathex=['src']` | -| `Reading XLSX ... requires openpyxl` | `openpyxl` 是动态导入,PyInstaller 可能漏收 | 在 spec 的 `hiddenimports` 加入 `openpyxl` 和 `openpyxl.cell._writer` | -| 中文字体丢失 | Matplotlib 找不到 `Microsoft YaHei` | 把 `C:/Windows/Fonts/msyh.ttc` 打包进 datas | -| exe 闪退 | Qt 插件、Matplotlib 后端或资源路径未被打包 | 先用 `--console` 版本测试 | -| 杀软误报 | 单文件模式解压行为触发 | 用 `--onedir`(文件夹模式),误报率极低 | - ---- - -## 分发方式 - -| 模式 | 用户体验 | 启动速度 | 杀软友好 | 推荐场景 | -|------|----------|----------|----------|----------| -| `--onefile` | 一个 .exe | 慢(解压) | 差 | 只发一个文件 | -| `--onedir` | 文件夹压缩包 | 快 | 好 | 推荐 | - -建议:先调通 `--onedir`,把输出文件夹打成 `.zip` 发给同事。 - ---- - -## 预估 - -| 维度 | 数值 | -|------|------| -| 首次调通耗时 | 30 分钟 | -| 字体/路径踩坑 | 30 分钟 | -| .exe 大小 (`--onedir`) | ~100 MB | -| 首次启动 | 3~5 秒 | -| 同事所需环境 | 无,Windows 10/11 直接运行 | diff --git a/GUI.py b/GUI.py deleted file mode 100644 index adf9c2f..0000000 --- a/GUI.py +++ /dev/null @@ -1,56 +0,0 @@ -from __future__ import annotations - -import sys -import subprocess -from pathlib import Path - - -PROJECT_ROOT = Path(__file__).resolve().parent -SRC_DIR = PROJECT_ROOT / "src" -VENV_PYTHON = PROJECT_ROOT / ".venv" / "Scripts" / "python.exe" -VENV_PYTHONW = PROJECT_ROOT / ".venv" / "Scripts" / "pythonw.exe" - - -def _workspace_python_executables() -> set[Path]: - executables = {VENV_PYTHON.resolve()} - if VENV_PYTHONW.exists(): - executables.add(VENV_PYTHONW.resolve()) - return executables - - -def _relaunch_with_workspace_python() -> None: - launcher = VENV_PYTHONW if sys.platform == "win32" and VENV_PYTHONW.exists() else VENV_PYTHON - command = [str(launcher), str(Path(__file__).resolve()), *sys.argv[1:]] - if sys.platform == "win32" and launcher == VENV_PYTHONW: - subprocess.Popen( - command, - cwd=str(PROJECT_ROOT), - stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - close_fds=True, - ) - raise SystemExit(0) - raise SystemExit(subprocess.call(command, cwd=str(PROJECT_ROOT))) - -if ( - not getattr(sys, "frozen", False) - and VENV_PYTHON.exists() - and Path(sys.executable).resolve() not in _workspace_python_executables() -): - _relaunch_with_workspace_python() - -if str(SRC_DIR) not in sys.path: - sys.path.insert(0, str(SRC_DIR)) - -from virtual_array.logging_config import configure_logging, install_excepthook # noqa: E402 - - -configure_logging() -install_excepthook() - -from virtual_array.gui import main # noqa: E402 - - -if __name__ == "__main__": - main() diff --git a/GUI_MOD_VISUAL_GUIDELINES.md b/GUI_MOD_VISUAL_GUIDELINES.md deleted file mode 100644 index 64e22f4..0000000 --- a/GUI_MOD_VISUAL_GUIDELINES.md +++ /dev/null @@ -1,135 +0,0 @@ -# MIMO Array Visualizer Carbon-led 原生 GUI 约束 - -> 适用范围:唯一正式 GUI 实现 `src/virtual_array/gui.py`。`GUI.py` 是正式启动器,`GUI_mod.py` 仅为兼容别名,两者必须打开完全相同的界面。 - -## 设计定位 - -MIMO Array Visualizer 使用原生 PySide6 控件和 Qt 绘图适配层。视觉结构与信息密度以 [Carbon Design System](https://carbondesignsystem.com/) 为主;交互层保留 [apple-design skill](https://github.com/emilkowalski/skills/tree/main/skills/apple-design) 的立即反馈、直接操控、可中断和克制动效原则。 - -这是 **Carbon-led、Apple-interaction 的产品级 Qt 工作台**,不是在 Qt 中嵌入 Carbon Web 组件,也不是仿制 macOS 外壳。保留平台原生窗口行为、Qt 控件语义和 Windows 用户习惯,能降低跨技术栈依赖并保持工程工具所需的信息密度。 - -可靠性约束: - -- GUI 只维护 `virtual_array.gui` 一套实现,禁止在兼容启动器中复制布局或业务逻辑。 -- 视觉和交互改造不得改变分析算法、文件格式、图表颜色语义或最终数值结果。 -- 颜色、圆角、字体和状态必须来自 `src/virtual_array/native_theme.py` 的集中 token;不得在页面和弹窗中重复硬编码近似值。 -- 使用 Qt 原生布局与尺寸策略适配 DPI 和窗口变化,不依赖固定像素坐标拼接界面。 - -## 窗口与响应式布局 - -- 默认尺寸为 **1366 × 768**,最小尺寸为 **1024 × 650 逻辑像素**,推荐工作尺寸不低于 **1100 × 650**,允许缩放和最大化。 -- 恢复历史窗口位置和尺寸前,必须将几何范围限制在当前屏幕可用区域内。 -- 主内容与 Overview 使用可拖动 `QSplitter`,默认比例约 78:22;Overview 目标宽度为 280–360 px。 -- resize 触发的高成本图表刷新使用约 100 ms 防抖;阵元拖动刷新按约 16 ms 合并,避免事件风暴阻塞主线程。 -- 不得因长文件名、翻译文本或 100%/125%/150% 缩放产生重叠、裁切或非预期滚动条。 - -## Carbon-led 主题与 token - -界面使用 Carbon Gray 10 / White 的浅色中性层级,以 Blue 60 表达主操作、选择和焦点: - -| 用途 | Token / 颜色 | -| --- | --- | -| 页面背景 | `#F4F4F4` | -| 卡片 / 表面 | `#FFFFFF` | -| 次级表面 | `#E8E8E8` | -| 选择底色 | `#D0E2FF` | -| 正文 | `#161616` | -| 次级文字 | `#525252` | -| 三级文字 | `#6F6F6F` | -| 分隔边框 | `#E0E0E0` | -| 交互边框 | `#8D8D8D` | -| 选择 / 焦点 / 图表强调 | `#0F62FE` | -| 主操作填充 | `#0F62FE` | -| 主操作 hover | `#0353E9` | -| 主操作 pressed | `#002D9C` | - -- 使用 8 px 间距网格;普通控件与工作台表面采用 4 px 小圆角,避免卡片套卡片和胶囊化。 -- 字体遵循平台并优先保证本地化字形完整:Windows 使用 Microsoft YaHei UI / Segoe UI,macOS 使用 SF Pro / PingFang,Linux 使用 Noto Sans CJK / Noto Sans,并保留后备链。 -- 普通正文和关键按钮文字对比度至少 4.5:1;控件边界与相邻背景至少 3:1。 -- 键盘焦点使用清晰的 2 px 系统蓝轮廓,不能只依赖轻微背景变化。 -- hover 与 pressed 必须即时响应;不使用厚重阴影、拟物凸起、循环呼吸或装饰性弹跳。 -- 红色只用于无效输入、加载失败、破坏性动作或明确风险;普通能力不足使用中性灰,边界风险使用琥珀色。 - -## 品牌、菜单与 Header - -- 左上角和窗口/任务栏图标统一使用 MAV 资产:48 px PNG 用于界面,256 px PNG/ICO/ICNS 用于运行时和打包。 -- 使用原生 `QMenuBar`/`QAction`,保留“文件、编辑、视图、帮助”结构及现有快捷键。 -- 打开、保存、播放、停止等通用动作优先使用 Qt 标准图标,不增加新的图标依赖。 -- Header 紧凑显示产品身份与三个全局状态:**频率、DBF 字典、通道幅相**;状态使用扁平单行标签和值,右对齐并支持省略。 -- 虚拟通道、分辨率等阵列指标只在 Overview 显示,避免重复。 -- 长文件名必须单行省略,并通过 tooltip 提供完整内容,不能撑高 Header。 - -## 标签页、表面与图表 - -中文、英文和日文页签都使用 Carbon 式线性标签页:未选中项与工作台表面融合,选中项使用浅蓝底和 3 px Blue 60 底边;键盘焦点必须清晰,不得使用原生立体标签或胶囊分段槽。 - -- **Physical & Virtual**:物理阵列与虚拟阵列并排。 -- **1D DBF**:方位和俯仰响应谱并排。 -- **2D DBF**:二维 DBF 热图及播放控制。 - -图表区约束: - -- 卡片使用白色或近白背景与细描边;网格线使用低对比中性灰,不能压过数据。 -- Tx/Rx、唯一点/重复点、真实角、峰值和风险的既有颜色语义保持稳定。 -- 1T1R 或某方向无有效孔径时,使用中性空状态说明需要增加阵元或自动排阵,不绘制平直角谱或整片伪热图。 -- 仅一个方向有效时,1D 页保留有效图表,另一侧显示能力提示;2D 页提示转到 1D 查看。 -- 热图信息采用轻量徽标,不使用遮挡数据的大面积深色浮层。 - -## 直接操控与性能 - -物理阵元拖拽必须遵守以下完整生命周期: - -1. `press`:记录指针与阵元中心的 grab offset,并捕获指针。 -2. `move`:按该 offset 连续更新位置,只做边界裁切;不得每一帧吸附网格。 -3. `move` 重绘:通过约 16 ms 的单次定时任务合并高频事件,已排队时不重复排队。 -4. `release`:取消待处理重绘、执行一次网格吸附、生成虚拟阵列,并释放指针捕获。 -5. Esc 取消、系统撤销鼠标捕获、切页或销毁窗口时也必须走同一清理路径:恢复按下前快照、释放捕获并取消定时任务,避免“粘住”或延迟回调访问无效控件。 - -这一顺序很重要:grab offset 消除阵元跳到指针中心的问题,指针捕获保证移出图表后仍能可靠结束拖拽,松手吸附消除逐格抖动,16 ms 合并刷新减少冗余计算并保持即时感。 - -1D 真实角引导线和 2D 十字线同样在按下时捕获、释放时归还指针。数据播放是用户主动启动的工程动画,不增加额外弹簧或惯性;停止、拖动和切页应立即打断播放。 - -## Overview、Command Bar 与状态栏 - -- Overview 是工程诊断摘要,按“阵列概览”和“测角评估”分组,并保持一列纵向扫描结构。 -- Overview 展示通道数、虚拟通道、口径、分辨率、不模糊范围、最大误差、峰值裕量和截断原因。 -- 底部操作区是一条连续 command bar,不给每个功能模块增加独立外框。 -- 频率、峰值裕量、自动排阵、DBF 显示模式等控件应在同一垂直基线上。 -- “应用阵列”是唯一显著的蓝色主按钮,其高度与相邻输入框一致。 -- 普通运行状态移入原生 `QStatusBar`,保持低噪声,不占用 Header 或图表空间。 - -## 原生弹窗、键盘与可访问性 - -- DBF 字典、通道幅相、方向图确认和使用说明统一使用原生 `QDialog`。 -- 数据预览使用 `QAbstractTableModel + QTableView`:少量列自动拉伸,多列使用横向滚动。 -- 提示区使用带标题的中性、警告或风险 callout;文本自动换行,非阻断项明确标注“仅提示”。 -- 按钮使用 `QDialogButtonBox` 的平台顺序;“应用/导入”为主按钮,“完成/取消”为次按钮。 -- 使用说明使用 `QTextBrowser`;文件选择和普通消息使用 `QFileDialog`/`QMessageBox`。 -- 所有控件必须有合理的 Tab 顺序、可见键盘焦点、accessible name 和本地化 tooltip。 -- 颜色不能是唯一状态信号;危险、警告、选中和禁用状态同时使用文本、边框、图标或控件状态表达。 -- 尊重系统字体缩放和高对比需求。当前产品不添加装饰性连续动画,因此“减少动态效果”用户不会丢失功能;DBF 播放仍由用户显式控制。 - -## 状态与兼容 - -- 继续读取 `state.json` v1;`window.active_tab` 和 `window.splitter_sizes` 为可选字段,缺失时使用默认值。 -- 布局 JSON、DBF 字典、方向图、通道幅相格式不得因视觉改造改变。 -- `main() -> None`、`VirtualArrayGui` 和 `virtual_array.gui` 已公开的纯计算辅助函数保持可导入。 -- `GUI.py`、`GUI_mod.py`、console script 与 PyInstaller EXE 必须启动同一套三页界面。 - -## 修改验收清单 - -每次调整界面后至少验证: - -- 1024×650、1100×650、1280×720、1366×768、1920×1080 逻辑窗口尺寸,以及 Windows 100%/125%/150% 缩放下无裁切或重叠。 -- 中文、英文、日文页签、空状态、tooltip 和 accessible name 完整。 -- 首启 1T1R 不显示红色错误、平直伪角谱或整片伪热图。 -- 阵元按下时不跳位,移出图表后仍能正常释放,拖动过程连续,松手后才吸附网格。 -- 1D 引导线和 2D 十字线的指针捕获、暂停播放与释放行为一致。 -- Overview 可拖动且保持可读;应用阵列仍是唯一显著主操作。 -- MAV 图标在窗口、任务栏和 PyInstaller 包中正常。 -- 四个自定义弹窗、菜单快捷键、Tab 顺序、hover/pressed/focus/disabled 状态可用。 -- 长文件名单行省略且 tooltip 完整。 -- 运行静态检查:`.venv\Scripts\python.exe -m compileall -q GUI.py GUI_mod.py src\virtual_array`。 -- 运行测试:`.venv\Scripts\python.exe -m pytest tests -q`。 - -重复截图验收必须通过 `scripts/capture_ui_review.py` 自动完成,并使用隔离的 `APPDATA` 生成三页和全部弹窗的编号截图,避免依赖个人历史状态。 diff --git a/GUI_mod.py b/GUI_mod.py deleted file mode 100644 index 0117109..0000000 --- a/GUI_mod.py +++ /dev/null @@ -1,58 +0,0 @@ -from __future__ import annotations - -import sys -import subprocess -from pathlib import Path - - -PROJECT_ROOT = Path(__file__).resolve().parent -SRC_DIR = PROJECT_ROOT / "src" -VENV_PYTHON = PROJECT_ROOT / ".venv" / "Scripts" / "python.exe" -VENV_PYTHONW = PROJECT_ROOT / ".venv" / "Scripts" / "pythonw.exe" - - -def _workspace_python_executables() -> set[Path]: - executables = {VENV_PYTHON.resolve()} - if VENV_PYTHONW.exists(): - executables.add(VENV_PYTHONW.resolve()) - return executables - - -def _relaunch_with_workspace_python() -> None: - launcher = VENV_PYTHONW if sys.platform == "win32" and VENV_PYTHONW.exists() else VENV_PYTHON - command = [str(launcher), str(Path(__file__).resolve()), *sys.argv[1:]] - if sys.platform == "win32" and launcher == VENV_PYTHONW: - subprocess.Popen( - command, - cwd=str(PROJECT_ROOT), - stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - close_fds=True, - ) - raise SystemExit(0) - raise SystemExit(subprocess.call(command, cwd=str(PROJECT_ROOT))) - -if ( - not getattr(sys, "frozen", False) - and VENV_PYTHON.exists() - and Path(sys.executable).resolve() not in _workspace_python_executables() -): - _relaunch_with_workspace_python() - -if str(SRC_DIR) not in sys.path: - sys.path.insert(0, str(SRC_DIR)) - -from virtual_array.logging_config import configure_logging, install_excepthook # noqa: E402 - - -configure_logging() -install_excepthook() - -# Compatibility launcher: the maintained GUI lives exclusively in -# virtual_array.gui. Keep this filename for existing shortcuts and scripts. -from virtual_array.gui import main # noqa: E402 - - -if __name__ == "__main__": - main() diff --git a/MIMOArrayVisualizer.spec b/MIMOArrayVisualizer.spec deleted file mode 100644 index 8fb2d12..0000000 --- a/MIMOArrayVisualizer.spec +++ /dev/null @@ -1,68 +0,0 @@ -# -*- mode: python ; coding: utf-8 -*- - -import sys - - -# GUI.py is the packaging launcher; it delegates to the single maintained -# implementation in virtual_array.gui. GUI_mod.py is a compatibility alias only. -app_entry_script = 'GUI.py' -app_icon = None -if sys.platform == 'win32': - app_icon = 'src/virtual_array/assets/mimo_array_logo.ico' -elif sys.platform == 'darwin': - app_icon = 'src/virtual_array/assets/mimo_array_logo.icns' - -a = Analysis( - [app_entry_script], - pathex=['src'], - binaries=[], - datas=[ - ('src/virtual_array/assets/mimo_array_logo_48.png', 'virtual_array/assets'), - ('src/virtual_array/assets/mimo_array_logo_256.png', 'virtual_array/assets'), - ('src/virtual_array/assets/mimo_array_logo.ico', 'virtual_array/assets'), - ('src/virtual_array/assets/mimo_array_logo.icns', 'virtual_array/assets'), - ], - hiddenimports=[ - 'virtual_array.gui', - 'pyparsing.testing', - 'openpyxl', - 'openpyxl.cell._writer', - 'PySide6', - 'pyqtgraph', - ], - hookspath=[], - hooksconfig={}, - runtime_hooks=[], - excludes=['pytest', '_pytest', 'numpy.tests', 'matplotlib.tests'], - noarchive=False, - optimize=0, -) -pyz = PYZ(a.pure) - -exe = EXE( - pyz, - a.scripts, - [], - exclude_binaries=True, - name='MIMOArrayVisualizer', - debug=False, - bootloader_ignore_signals=False, - strip=False, - upx=True, - console=False, - disable_windowed_traceback=False, - argv_emulation=False, - target_arch=None, - codesign_identity=None, - entitlements_file=None, - icon=app_icon, -) -coll = COLLECT( - exe, - a.binaries, - a.datas, - strip=False, - upx=True, - upx_exclude=[], - name='MIMOArrayVisualizer', -) diff --git a/OPTIMIZATION_IDEAS.md b/OPTIMIZATION_IDEAS.md deleted file mode 100644 index 7f1a4b5..0000000 --- a/OPTIMIZATION_IDEAS.md +++ /dev/null @@ -1,206 +0,0 @@ -# 项目优化建议 - -> 创建日期:2026-05-15 -> 基于对全部源码的完整阅读 - ---- - -## 项目现状概述 - -| 维度 | 评价 | -|------|------| -| **核心算法** | 扎实。天线阵列、虚拟阵列、阵列因子、波束指标计算准确 | -| **数据模型** | 清晰。`geometry.py` 简洁精炼,类职责单一 | -| **GUI 重建** | 进行中。pyqtgraph 负责 GUI 绘图,PySide6/Qt 负责桌面控件;旧 ttk 风格由兼容层承接 | -| **测试** | 薄弱。仅 68 行,只测了 `geometry.py` 和 `snap_to_grid` | -| **可扩展性** | 当前硬编码偏多,加新功能需要较多改动 | - ---- - -## 一、架构优化 - -### 1.1 拆分 `gui.py`(1812 行 → 多个模块) - -当前 `gui.py` 承担了所有职责,建议拆为: - -``` -src/virtual_array/ -├── gui.py (~400 行) 只用 PySide6/Qt 兼容控件做布局和事件绑定 -├── plots.py (~400 行) 三个 Figure 的绘制逻辑 -├── analysis.py (~300 行) 阵列因子计算 + 指标提取(从 gui.py 迁出) -├── widgets.py (~200 行) Array Evaluation 面板构建 -└── events.py (~300 行) 拖拽、hover、键盘事件 -``` - -好处:每个文件职责明确,加功能时不会在 1800 行里翻找。 - -### 1.2 提取 `analysis.py` - -把 `_calculate_metrics_and_psf()`、`_azimuth_cut_metrics()`、`_azimuth_first_sidelobe()`、`_evaluate_front_radar()` 等函数从 `gui.py` 移到一个独立模块。这些是纯计算逻辑,不依赖 PySide6/pyqtgraph,天然可单测。 - ---- - -## 二、功能扩展 - -### 2.1 布局管理(高优先级) - -| 功能 | 现状 | 建议 | -|------|------|------| -| 新建空白布局 | 不支持 | 加 "New Layout" 按钮,输入 Tx/Rx 数量 | -| 增加/删除阵元 | 不支持 | 右键菜单:Remove element | -| 预设配置切换 | 只有一个 case4 | 下拉菜单选择预设,内置 3~5 个典型阵列 | -| 多布局对比 | 不支持 | 加一个 "Compare" 标签页,并列显示两套指标 | - -**实现难度**:中。核心数据结构已准备好,主要是 UI 工作量。 - -### 2.2 自定义频率 - -当前只有 77/92/60 GHz 三个选项。建议在 Combobox 末尾加一项 "Custom...",弹出输入框让用户输入任意频率(GHz),自动换算波长。 - -### 2.3 波束扫描(Steering) - -当前固定 Az=0°、El=0°。扫描场景下需要在阵列因子计算中引入线性相位偏移: - -``` -phase = π × [virtual_xy[:, 0] × (u - sin(θ_scan)×cos(φ_scan)) - + virtual_xy[:, 1] × (v - sin(φ_scan))] -``` - -界面上加两个 Spinbox:Azimuth Steering (°) 和 Elevation Steering (°)。 - -### 2.4 批处理导出 - -加一个 "Batch Export" 面板: -- 选一个目录,批量导入 `.json` 布局文件 -- 对每个布局计算全套指标 -- 导出为单个 CSV/Excel 汇总表(排名、对比) - -这正好对接你之前做的 Import/Export Layout 功能。 - ---- - -## 三、交互体验 - -### 3.1 撤销 / 重做 - -拖拽阵元后 `Ctrl+Z` 撤销、`Ctrl+Y` 重做。实现方式:维护一个 `deque` 存最近 50 个 `elements` 快照。 - -### 3.2 实时刷新开关 - -当前拖拽释放后才刷新虚拟阵列。加一个 Checkbutton "Auto-refresh",勾选后拖拽过程中实时更新右侧面板和 PSF 图。 - -**注意**:这会显著增加计算负载。可加节流(throttle):移动过程中每 200ms 最多刷新一次。 - -### 3.3 键盘快捷键 - -| 快捷键 | 功能 | -|--------|------| -| `Ctrl+Z` | 撤销 | -| `Ctrl+Y` | 重做 | -| `Ctrl+S` | 导出布局 | -| `Ctrl+E` | 导出图片 | -| `Ctrl+G` | 刷新虚拟阵列 | -| `Delete` | 删除选中单元 | -| `Escape` | 取消选中 | - -### 3.4 窗口状态记忆 - -退出时保存窗口位置和大小到 `%APPDATA%/antenna-array/layout.ini`,下次启动恢复。当前通过 Qt 兼容层的 `winfo_geometry()` + `protocol("WM_DELETE_WINDOW")` 保持原状态读写逻辑。 - -### 3.5 标签重叠处理 - -当物理阵列中阵元间距很小时,姓名标签会重叠。可加一个简单的贪心避让算法,或在标签重叠时自动隐藏部分标签,hover 时才显示。 - ---- - -## 四、工程健壮性 - -### 4.1 补充测试(高优先级) - -当前只有 68 行测试。建议至少补齐: - -| 测试对象 | 优先级 | -|----------|--------| -| `geometry.py` 的 `unique_virtual_xy` 边界情况(全重叠、零重叠) | 高 | -| `analysis.py` 提取后的所有指标计算函数 | 高 | -| 方向图计算(含已知结果的校验案例) | 高 | -| Import/Export Layout 的 JSON 解析 | 中 | -| 坐标吸附加密测试(边界、负值) | 低 | - -### 4.2 日志系统 - -当前异常直接弹 `messagebox` 或 `print`。建议引入 `logging` 模块,输出到 `%APPDATA%/antenna-array/logs/`,方便排查用户环境中偶发问题。 - -### 4.3 `.gitignore` - -当前缺少 `.gitignore`,建议添加排除 `__pycache__/`、`.pytest_cache/`、`*.egg-info/`、`outputs/`、`.venv/`。 - ---- - -## 五、数值/算法增强 - -### 5.1 二维 PSF 预览 - -当前 Azimuth Response 只画一维方向切面。可考虑在 PSF 图旁边加一个小二维 heatmap(Az × El),直观展示栅瓣和旁瓣的二维分布。这会增加计算量但视觉收益大。 - -### 5.2 峰值旁瓣角度可视化 - -在二维 heatmap 上标记最差旁瓣的位置(叉号 + 坐标标注),比纯数字直观。 - -### 5.3 D/λ 比值显示 - -在 Array Evaluation 或信息栏中显示阵元平均间距(以波长计),方便判断是否会出现栅瓣(经验值 `d/λ < 0.5`)。 - -### 5.4 幅度加权 - -当前假设所有阵元等幅同相。可加一组权重输入(每个 Tx/Rx 独立幅值),模拟幅度加权对旁瓣的影响(如 Chebyshev、Taylor 加权)。 - ---- - -## 六、文件组织 - -### 6.1 清理 - -| 文件/目录 | 状态 | 建议 | -|-----------|------|------| -| `examples/case4_5tx7rx_sel.py` | 与 `src/virtual_array/examples/` 重复 | 删除外层,统一从包内引用 | -| `src/virtual_array/examples/__init__.py` | 空文件 | 可删除 | -| `__pycache__/` (多个) | 缓存 | 加入 `.gitignore` | -| `.venv/` | 旧虚拟环境 | 清理或加入 `.gitignore` | - -### 6.2 README 更新 - -当前 README 描述了安装和运行,但落后于代码实际。建议补充: -- GUI 各区域的截图和标注说明 -- 指标含义速查表 -- 拖拽操作的 GIF 演示 - ---- - -## 优先级排序(建议顺序) - -``` -第一轮(质量基础): - ├─ 补充核心测试 - ├─ 加 .gitignore - ├─ 提取 analysis.py - └─ 日志系统 - -第二轮(功能完善): - ├─ 布局管理(新建/删除阵元) - ├─ 自定义频率 - ├─ 撤销/重做 - └─ 实时刷新开关 - -第三轮(体验提升): - ├─ 键盘快捷键 - ├─ 窗口状态记忆 - ├─ 二维 PSF heatmap - └─ 标签重叠处理 - -第四轮(深度扩展): - ├─ 波束扫描 - ├─ 幅度加权 - ├─ 批处理导出 - └─ 多布局对比 -``` diff --git a/UI_SKILL_INTEGRATION.md b/UI_SKILL_INTEGRATION.md deleted file mode 100644 index 663357a..0000000 --- a/UI_SKILL_INTEGRATION.md +++ /dev/null @@ -1,137 +0,0 @@ -# UI Skill Integration Notes - -This note records the professional UI skills and references integrated into the -desktop GUI. The current interface is a Carbon-led native Qt application with -Apple-inspired direct-manipulation and feedback behavior; -older passes are retained below as implementation history rather than current -theme guidance. - -## Current Carbon-Led Native Qt Pass (2026-07-31) - -Structural reference: [Carbon Design System](https://carbondesignsystem.com/). -Interaction reference: [emilkowalski/skills — apple-design](https://github.com/emilkowalski/skills/tree/main/skills/apple-design). - -The skill is installed locally for Codex reuse, but the product does not depend -on the skill at runtime. Its principles were translated into PySide6/Qt instead -of copying web animation code or drawing a fake macOS shell. - -| Principle | Current implementation | Product impact | -| --- | --- | --- | -| Immediate response | Buttons, line tabs, hover, pressed, selected, disabled, and focus states come from one native token/QSS theme. | Users receive clear feedback without ornamental motion; centralized tokens keep future changes consistent. | -| Direct manipulation | A physical element keeps its pointer-to-element grab offset, captures the pointer on press, and uses one cleanup path for release, Esc, or OS capture loss. | The element no longer jumps to the cursor center, and interrupted drags cannot leave the application mouse-grabbed. | -| Continuous movement | Drag positions update continuously within bounds; grid snap runs once on release. | Removes stepwise grid jitter while preserving the exact stored, snapped layout after the gesture. | -| Efficient redraw | High-frequency physical-drag events are coalesced behind an approximately 16 ms redraw task. | Reduces redundant plot work and main-thread stalls while retaining frame-rate-level feedback. | -| Interruptibility | 1D true-angle guides and the 2D crosshair capture/release the pointer; manual movement pauses user-started playback. | Direct input remains authoritative and playback never fights the user. | -| Restrained motion | The redesign adds no bounce, inertia, ambient loops, or data-obscuring transitions. | Engineering data stays stable and reduced-motion users lose no functionality. | -| Layered hierarchy | `#F4F4F4` canvas, white work surfaces, flat header states, Carbon line tabs, and low-contrast separators replace nested rounded cards. | The interface scans more calmly without hiding dense diagnostics. | -| Accessibility | Native Qt semantics, visible `#0F62FE` keyboard focus and primary fill, localized accessible names/tooltips, contrast-aware borders, and non-color-only status cues remain required. | Keyboard and assistive-technology paths stay dependable across supported languages and DPI settings. | - -Implementation rule: all current visual guidance lives in -`GUI_MOD_VISUAL_GUIDELINES.md`; the tables below describe earlier design work -that led to the same canonical `virtual_array.gui` implementation. - -## Researched Professional UI Skills - -| Skill | Source | Useful principle | -| --- | --- | --- | -| Visual hierarchy | [Nielsen Norman Group, Visual Design](https://www.nngroup.com/topic/visual-design/) | Use scale, contrast, grouping, and consistency so users can scan the most important information first. | -| Responsive grid layout | [Material Design, Responsive Layout Grid](https://m2.material.io/design/layout/responsive-layout-grid.html) | Use grid columns, margins, and responsive sizing to keep layouts stable across window sizes. | -| Dashboard information density | [Carbon Design System, Dashboards](https://carbondesignsystem.com/data-visualization/dashboards/) | Reduce distraction, limit nonessential information, and keep metric/color semantics consistent. | -| Chart anatomy and interaction affordances | [Carbon Design System, Chart Anatomy](https://carbondesignsystem.com/data-visualization/chart-anatomy/) | Keep chart title, axes, legends, frames, tooltips, and controls legible and consistently placed. | -| Non-text contrast and component states | [W3C WAI, Non-text Contrast](https://www.w3.org/WAI/WCAG21/Understanding/non-text-contrast.html) | UI component boundaries, states, and graphical marks need enough contrast to be distinguishable. | -| Gestalt grouping and proximity | [Nielsen Norman Group, Visual Design Principles](https://www.nngroup.com/videos/visual-design-principles-in-action/) | Related controls and metrics should live in clear groups so the interface can be read without extra explanation. | - -## Integrated Into This Project - -| Integrated skill | Implementation in `src/virtual_array/gui.py` | -| --- | --- | -| Visual hierarchy | Promoted the physical-array actions into a native toolbar, introduced KPI-style metric tiles, and separated primary metrics from angle diagnostics. | -| Responsive grid layout | Added explicit minimum widths and row weights for plot columns and the evaluation side panel. The main plot area now receives predictable space before the footer controls. | -| Dashboard information density | Reworked the evaluation panel into a compact overview plus Az/El diagnostic groups, keeping dense engineering data without a single crowded table. | -| Chart anatomy | Freed the physical plot header by moving edit controls out of Matplotlib canvas buttons; preserved chart labels, legends, hover behavior, and DBF playback controls. | -| Component states and contrast | Added status-aware metric styles and a danger-state delete button so risky modes and diagnostic conditions are visually distinct. | -| Proximity and grouping | Converted the bottom control strip to a grid of stable toolbar groups, keeping configuration, language, frequency, margin, auto layout, and pattern status in predictable areas. | - -## Historical Design Passes - -The following entries document earlier iterations (including the former dark -workbench and Fluent 2 directions). They are useful provenance, but they do not -override the current Carbon-led token system or Apple-inspired interaction rules. - -### Earlier Product-Grade UI Pass - -| Area | Improvement | -| --- | --- | -| Workspace shell | Added a dark professional workbench header with product identity and live state chips for frequency, DBF dictionary, and pattern mode. | -| Plot surfaces | Unified the physical array, virtual array, and response charts as bordered plot surfaces with consistent gutters and white chart backgrounds. | -| Curve styling | Added a subtle low-alpha underlay to response and DBF curves so the plots feel more polished while preserving exact line readability. | -| Status discipline | Removed repeated status text from the physical-array toolbar; global state now lives in the header chips and bottom status row. | -| High-DPI stability | Moved header chips below the title so they remain visible on smaller or scaled Windows displays. | - -### Interaction Layout Pass - -| Area | Improvement | -| --- | --- | -| Draggable workspace | Replaced the fixed plot/evaluation columns with a horizontal ttk PanedWindow so users can resize plots versus diagnostics. | -| Evaluation hierarchy | Converted the right-side evaluation stack into Overview, Angle, and 2D DBF tabs to reduce vertical crowding. | -| Header KPI rail | Added live KPI chips for virtual-channel utilization, Az/El resolution, and peak-margin status. | -| Localization cleanup | Moved element-pattern import, preview, status, and dialog strings into UI_TEXT for consistent Chinese/English/Japanese switching. | -| 2D DBF anatomy | Added a fixed normalized-gain colorbar and peak-delta badge to the DBF heatmap while reusing the same colorbar axis on redraw. | - -### Codex-Style Menu Pass - -| Area | Improvement | -| --- | --- | -| Top menu bar | Moved configuration and language dropdowns into a Codex-style top menu row with File, Edit, View, and Help groups. | -| Footer cleanup | Removed the bottom configuration/language dropdown groups so the footer focuses on frequency, margin, auto layout, pattern state, and status. | -| Header order | Placed the product/KPI information below the new menu bar and kept state chips right-aligned with KPI chips left-aligned. | -| Evaluation merge | Combined Overview and Angle diagnostics into one right-panel tab, leaving 2D DBF as the second tab. | - -### Readability And Button Polish Pass - -| Area | Improvement | -| --- | --- | -| Default split | Set the initial draggable workspace split to about 50/50 so the four plot modules and the 2D DBF heatmap are both readable. | -| Default DBF focus | Selected the 2D DBF tab by default to match the wide heatmap-oriented startup layout. | -| Button consistency | Unified same-row action buttons to white-background compact buttons with hover/focus highlighting instead of mixed filled blocks. | -| Help manual | Added a scrollable Help > User Manual window covering menus, layout, editing, DBF controls, pattern/dictionary configuration, and save/restore behavior. | - -### Direct Angle Manipulation Pass - -| Area | Improvement | -| --- | --- | -| 1D DBF spectra | Removed progress sliders and made the orange true-angle guide line draggable for manual scan positioning. | -| 2D DBF heatmap | Removed azimuth/elevation progress sliders and made the heatmap crosshair draggable to set both true-angle coordinates. | -| Interaction clarity | Kept play/pause/stop buttons, with manual dragging pausing active scan playback at the selected angle. | - -### Hover And Import Affordance Pass - -| Area | Improvement | -| --- | --- | -| 2D DBF heatmap | Added a hover tooltip that reports the nearest azimuth, elevation, and normalized gain value. | -| Drag affordance | Added hand cursors when hovering near the 1D true-angle guide or 2D true-angle crosshair. | -| 1T2R channel phase import | Allowed RX-only summary files so two data columns map to Rx1/Rx2 while three data columns map to Tx1/Rx1/Rx2. | - -### Dialog Readability Pass - -| Area | Improvement | -| --- | --- | -| Angle evaluation | Reduced metric typography, removed forced label wrapping, and shortened long cut-reason text so values are less likely to wrap. | -| Secondary dialogs | Enlarged default channel-pattern and DBF-dictionary dialogs so tables, preview panes, and action rows have readable space. | -| Dialog buttons | Unified same-row dialog actions to white Codex-style buttons with gray hover states, reserving danger only for red text. | -| Help manual | Rewrote the manual as a plain-language guide to modules, menu commands, and the typical workflow instead of mirroring the layout. | - -## Not Integrated Yet - -| Skill | Reason | -| --- | --- | -| Full design-system component migration | The app is now a PySide6 desktop tool with a retained ttk-style compatibility layer, so a wholesale Carbon or Material component migration would add churn without matching the current stack. | -| Icon-library toolbar | The current project has no icon dependency, and the safest product-level improvement was to preserve text controls while improving placement, state, and spacing. | -| CI pixel-diff visual regression | `scripts/capture_ui_review.py` already generates repeatable native Qt screenshots with isolated state. A fixed-threshold pixel-diff gate is intentionally not in CI because font rasterization and DPI vary by runner; human comparison remains the reliable release check. | - -## Verification - -- `python -m compileall src tests GUI.py` -- `python -m pytest` — current repository-wide result: `253 passed`. -- Native Qt smoke check: run with `QT_QPA_PLATFORM=offscreen`, instantiate `VirtualArrayGui`, complete first render, inspect workspace/dialog geometry and accessibility state, then close the window. -- Accepted current visual evidence: `outputs/carbon-apple-v1-final-20260731` (three pages plus five dialogs), with responsive/dialog follow-ups under `outputs/responsive-audit-20260731`, `outputs/ui-fix-20260731-title-dbf`, and `outputs/radio-dialog-layout-fix-20260731-final-native`. The earlier `outputs/apple-design-pass-20260730` captures remain historical interaction evidence only. diff --git a/design-qa.md b/design-qa.md deleted file mode 100644 index 51247db..0000000 --- a/design-qa.md +++ /dev/null @@ -1,127 +0,0 @@ -# Design QA — Carbon-led native PySide6 workbench - -> 当前视觉方向是 Carbon-led 工作台,并保留 Apple 的直接操控与可中断反馈原则;2026-07-30 Apple-inspired 版本作为历史基线保留。当前实机截图位于 `outputs/carbon-apple-v1-final-20260731`,最终 Logo 检查位于 `outputs/logo-review-20260731`。 - -## Current review target (2026-07-31) - -The current product direction uses Carbon's dense neutral hierarchy and Blue 60 -state language while translating the -[apple-design skill](https://github.com/emilkowalski/skills/tree/main/skills/apple-design) -into direct manipulation, immediate feedback, visible focus, interruptibility, -and restrained motion. It retains native PySide6/Qt controls and does not -recreate a macOS window shell on Windows. - -The previous Fluent 2 and Apple-inspired screenshots below remain historical -baseline evidence. Current screenshots are generated with -`scripts/capture_ui_review.py`; do not relabel an older capture as current -Carbon-led evidence. - -**Accepted current evidence** - -- Carbon-led native Qt, Simplified Chinese, 1366×768: `outputs/carbon-apple-v1-final-20260731` (three pages and five custom dialogs). -- Responsive and localized follow-up evidence: `outputs/responsive-audit-20260731`, `outputs/ui-fix-20260731-title-dbf`, and `outputs/radio-dialog-layout-fix-20260731-final-native`. -- Performance-report angle controls, enabled 2T2R state: `outputs/ui-review-report-angle-20260731-enabled/08-performance-report.png` (Simplified Chinese) and `outputs/ui-review-report-angle-20260731-en/08-performance-report.png` (English). -- Final black-and-white MAV Logo in the real Header: `outputs/logo-review-20260731/01-physical-virtual.png`; an isolated PyInstaller build confirmed the packaged PNG/ICO/ICNS assets match their sources. -- Functional verification: `253 passed` from the complete `tests` suite with Qt's offscreen platform; native captures above separately verify real Windows font and layout rendering. - -**Current acceptance criteria** - -- Theme uses centralized Carbon-led canvas, surface, typography, separator, - control-border, Blue 60 primary/focus, radius, and state tokens. -- Header state labels remain compact and readable at supported widths; line tabs - use a clear selected underline without fake platform chrome. -- Pressing a physical element preserves its grab offset instead of centering it - under the pointer. -- Pointer capture keeps physical-element, 1D guide, and 2D crosshair drags - reliable outside the originating plot, and every release/cancel path returns - capture. Esc and unexpected OS `UngrabMouse` events use explicit cancellation - paths so the app cannot remain mouse-grabbed. -- Physical movement stays continuous during the gesture, redraws are coalesced - to about 16 ms, and grid snap happens once on release. -- No decorative bounce, inertia, ambient animation, or large translucent - overlay obscures plots. User-controlled DBF playback remains interruptible. -- Keyboard focus is visible, control boundaries preserve non-text contrast, - localized accessible names/tooltips remain present, and status is not encoded - by color alone. -- Calculated values, imported formats, state compatibility, and plot color - semantics are unchanged. - -## Historical Fluent 2 baseline (2026-07-15) - -**Original source visual truth** - -- `C:\Users\junzhe.yu\AppData\Local\Temp\mimo-array-ui-audit-20260710\02-gui-mod-physical-virtual.png` -- `C:\Users\junzhe.yu\AppData\Local\Temp\mimo-array-ui-audit-20260710\03-gui-mod-1d-dbf.png` -- `C:\Users\junzhe.yu\AppData\Local\Temp\mimo-array-ui-audit-20260710\04-gui-mod-2d-dbf.png` -- `C:\Users\junzhe.yu\AppData\Local\Temp\mimo-array-ui-audit-20260710\05-gui-mod-dbf-dictionary-dialog.png` - -**Fluent 2 rendered implementation** - -- `D:\HFSS数据整理\mimo-array-visualizer\outputs\ui-modern-pass-20260715\after-final-1366-native\01-physical-virtual.png` -- `D:\HFSS数据整理\mimo-array-visualizer\outputs\ui-modern-pass-20260715\after-final-1366-native\02-1d-dbf.png` -- `D:\HFSS数据整理\mimo-array-visualizer\outputs\ui-modern-pass-20260715\after-final-1366-native\03-2d-dbf.png` -- Dialog evidence continues through `07-user-manual.png` in the same directory. -- Minimum-size 2T2R evidence: `outputs\ui-modern-pass-20260715\after-final-1100-2t2r`. -- Minimum-size English evidence: `outputs\ui-modern-pass-20260715\english-1100-after-fix`. -- Chaptered manual evidence at 1100×650: `outputs\manual-chapters-20260715-1100\07-user-manual.png`, with corresponding English and Japanese folders. - -**Previous rendered implementation** - -- `D:\HFSS数据整理\mimo-array-visualizer\outputs\ui-review-final\01-physical-virtual.png` -- `D:\HFSS数据整理\mimo-array-visualizer\outputs\ui-review-final\02-1d-dbf.png` -- `D:\HFSS数据整理\mimo-array-visualizer\outputs\ui-review-final\03-2d-dbf.png` -- `D:\HFSS数据整理\mimo-array-visualizer\outputs\ui-review-final\04-dbf-dictionary.png` -- Dialog evidence continues through `07-user-manual.png` in the same directory. - -**Historical comparison setup** - -- Viewport: 1366×768 logical pixels; Windows 125% capture is 1708×960 physical pixels. -- Dialog viewport: 1120×700 logical pixels; 1400×875 physical pixels. -- State: Fluent 2 light theme, Simplified Chinese, first-run 1T1R, ideal geometric DBF dictionary. -- Full-view comparison: `D:\HFSS数据整理\mimo-array-visualizer\outputs\design-qa\comparison-full.png`. -- Focused comparison: `D:\HFSS数据整理\mimo-array-visualizer\outputs\design-qa\comparison-focused.png`. -- Additional responsive evidence: `outputs\ui-review-1100-final`, `outputs\ui-review-1920`, `outputs\dpi-native-100`, and `outputs\dpi-native-150-final`. -- Additional state evidence: `outputs\lang-en-final`, `outputs\lang-ja-final`, `outputs\scenario-2t2r`, `outputs\scenario-8t8r`, and `outputs\scenario-full-2d`. - -**Historical findings** - -- No actionable P0, P1, or P2 visual differences remain. The implementation intentionally improves the audited source rather than reproducing its misleading capability states. -- Fonts and typography: common UI and plot text is at least 9 pt, CJK/system fallbacks remain sharp at 100%/125%/150%, headings have clear weight hierarchy, and long global status text is elided with a full tooltip. -- Spacing and layout rhythm: the 8 px rhythm, 8 px control radius, 12 px card radius, draggable 78:22 splitter, compact command bar, and stacked Overview groups remain coherent from 1100×650 through 1920×1080. -- Colors and tokens: the implementation consistently uses the Fluent canvas/surface/text/MAV-blue tokens. Neutral capability gaps are gray-blue, capability/quality cautions are amber, and red is reserved for destructive or genuinely dangerous states. Focus and interactive borders meet the specified semantic contrast intent. -- Image quality and assets: the repository MAV raster asset is used directly, remains crisp at 150%, and is also embedded as the packaged executable icon. No visible asset was replaced with text, emoji, CSS art, or a handcrafted substitute. -- Copy and content: all three page labels, empty states, global status, evaluation values, menus, and dialog actions were checked in Chinese, English, and Japanese. The numerical content is unchanged from the calculation layer. - -**Historical open questions** - -- None blocking. Screen-reader output and a hardware-assisted accessibility pass remain useful release checks, but the native accessible names/descriptions and keyboard focus paths are present and covered by smoke assertions. - -**Comparison history** - -1. Initial comparison found a P1 misleading-state issue: 1T1R rendered flat 1D spectra and a full yellow 2D heatmap. Fixed with localized neutral capability overlays, disabled playback, and no generated 2D heatmap when either aperture is absent. Post-fix evidence: `outputs\ui-review-final\02-1d-dbf.png` and `03-2d-dbf.png`. -2. Initial comparison found P2 hierarchy and density issues: duplicate header KPIs, undersized plot/status text, untranslated tabs, and a fixed-size shell. Fixed with three global chips, visible localized native tabs, minimum 9 pt text, a native splitter, and exact 1100×650 resizing. Post-fix evidence: `outputs\ui-review-1100-final\01-physical-virtual.png` and `tests\test_qt_gui_smoke.py`. -3. Initial comparison found a P2 dialog issue: the ideal one-channel dictionary used an alarming red callout, weak action hierarchy, and a widget-backed table. Fixed with severity-aware neutral/amber/risk callouts, a visible blue primary Apply button, `QDialogButtonBox`, and `QTableView` plus `QAbstractTableModel`. Post-fix evidence: `outputs\ui-review-final\04-dbf-dictionary.png`. -4. Responsive comparison found P2 clipping at 1100×650 and language-dependent minimum widths up to 1309 px. Fixed by removing fixed plot minima, compacting the Overview rhythm, shortening command-bar copy, and allowing locale-aware intrinsic widths. Post-fix evidence: `outputs\ui-review-1100-final` and the exact-size smoke test. -5. Focused comparison found P2 polish regressions: plot axes peeking around empty overlays, English/Japanese evaluation values remaining Chinese, a high-DPI logo capture gap, and duplicate-point legend overlap. Fixed with full-canvas overlays, localized dynamic metric values, device-pixel-ratio-aware logo rendering, and separated legend placement. Post-fix evidence: `outputs\lang-en-final`, `outputs\lang-ja-final`, `outputs\dpi-native-150-final`, and `outputs\scenario-full-2d`. -6. The 2026-07-15 desktop-app pass reduced P1 engineering-tool density: tabs now use a quiet pivot treatment, nested metric borders are flattened, controls expose hover/focus/checked states, capability overlays hide meaningless transport controls, dialogs clamp to the parent work area, tables and scrollbars use the shared Fluent tokens, and the manual is searchable HTML. A follow-up English 1100×650 audit then fixed header/action truncation, narrow-dialog action reflow and its safe resize breakpoint, virtual-plot legend overlap, 3:1 interactive borders, danger checked-state semantics, localized accessibility names, and repeated callout-QSS growth. Post-fix evidence: `outputs\ui-modern-pass-20260715\after-final-1366-native`, `outputs\ui-modern-pass-20260715\after-final-1100-2t2r`, and `outputs\ui-modern-pass-20260715\english-1100-after-fix`. -7. The help manual now uses 12 stable task-oriented chapters in Chinese, English, and Japanese. Help exposes direct chapter entries plus an F1 full-manual action; the dialog adds a resizable contents pane, cross-chapter search, result navigation, explicit no-result feedback, and keyboard-safe Enter handling. Content focuses on procedures, expected feedback, limits, persistence boundaries, and recovery rather than formulas. Post-fix evidence: `outputs\manual-chapters-20260715-1100`, `outputs\manual-chapters-20260715-en-1100-retry`, and `outputs\manual-chapters-20260715-ja-1100`. - -**Historical implementation checklist** - -- [x] Canonical implementation lives in `virtual_array.gui`; legacy module and root launcher are aliases. -- [x] Native menu bar, splitter, tabs, status bar, dialogs, table models, standard icons, and Qt canvas are present. -- [x] 1T1R, one-axis-only, complete 2D, repeated virtual point, 2T2R, and 8T8R states render without misleading data. -- [x] 1100×650, 1366×768, 1920×1080 and Windows 100%/125%/150% captures have no clipping or persistent overflow. -- [x] Chinese, English, and Japanese labels and dynamic states are localized. -- [x] Automated screenshots and native Qt smoke tests cover the three pages and five custom dialogs, including the performance-report settings window. -- [x] The help manual has stable multilingual chapters, direct menu navigation, full-text chapter search, and content/schema regression tests. - -**Follow-up Polish** - -- [P3] A future release may add OS-level screen-reader and keyboard-only test automation beyond the current native accessibility metadata and focus-policy smoke checks. - -Historical Fluent 2 result: passed. - -Current Carbon-led native Windows visual QA result: **passed**. Functional, -interaction, asset, responsive-layout, and packaging coverage also passed in -the repository-wide validation run. diff --git a/pyproject.toml b/pyproject.toml index 0105bed..f6a92d3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,32 +4,30 @@ build-backend = "setuptools.build_meta" [project] name = "mimo-array-visualizer" -version = "0.2.0" -description = "Desktop visualizer and evaluator for MIMO Tx/Rx antenna array layouts." +version = "1.0.0" +description = "Web workbench for editing and evaluating MIMO Tx/Rx antenna array layouts." readme = "README.md" license = "MIT" -requires-python = ">=3.9" +requires-python = ">=3.10" dependencies = [ "numpy>=1.23", "matplotlib>=3.7", "openpyxl>=3.1", - "PySide6>=6.6", - "pyqtgraph>=0.13.7", + "fastapi>=0.110", + "uvicorn[standard]>=0.27", + "python-multipart>=0.0.9", + "pydantic>=2.5", ] [project.optional-dependencies] dev = [ "pytest>=7.0", -] -packaging = [ - "pyinstaller>=6.20", + "httpx>=0.26", ] [project.scripts] -mimo-array-visualizer = "virtual_array.gui:main" +mimo-array-server = "virtual_array.server.cli:main" mimo-array-case4 = "virtual_array.examples.case4_5tx7rx_sel:main" -virtual-array-gui = "virtual_array.gui:main" -virtual-array-case4 = "virtual_array.examples.case4_5tx7rx_sel:main" [tool.setuptools.packages.find] where = ["src"] @@ -39,11 +37,13 @@ virtual_array = [ "assets/*.png", "assets/*.ico", "assets/*.icns", + "server/static/**/*", ] [tool.ruff] line-length = 100 -target-version = "py39" +target-version = "py310" +extend-exclude = ["web"] [tool.ruff.lint] select = ["E", "F", "W", "I", "N", "UP", "B", "SIM"] diff --git a/scripts/build_exe.ps1 b/scripts/build_exe.ps1 deleted file mode 100644 index bb33c32..0000000 --- a/scripts/build_exe.ps1 +++ /dev/null @@ -1,25 +0,0 @@ -$ErrorActionPreference = "Stop" - -$Root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path -Set-Location $Root - -$Python = Join-Path $Root ".venv\Scripts\python.exe" -if (-not (Test-Path -LiteralPath $Python)) { - Write-Error "Missing .venv. Run .\scripts\setup.ps1 first." -} - -& $Python -m PyInstaller --noconfirm --clean .\MIMOArrayVisualizer.spec -if ($LASTEXITCODE -ne 0) { - exit $LASTEXITCODE -} - -$BuildPath = Join-Path $Root "build" -if (Test-Path -LiteralPath $BuildPath) { - $ResolvedBuildPath = (Resolve-Path -LiteralPath $BuildPath).Path - if (-not $ResolvedBuildPath.StartsWith($Root, [System.StringComparison]::OrdinalIgnoreCase)) { - throw "Refusing to remove build path outside project: $ResolvedBuildPath" - } - Remove-Item -LiteralPath $ResolvedBuildPath -Recurse -Force -} - -Write-Host "Built .\dist\MIMOArrayVisualizer\MIMOArrayVisualizer.exe" diff --git a/scripts/capture_ui_review.py b/scripts/capture_ui_review.py deleted file mode 100644 index 6830601..0000000 --- a/scripts/capture_ui_review.py +++ /dev/null @@ -1,689 +0,0 @@ -"""Capture repeatable GUI review screenshots with an isolated application state. - -The script deliberately drives the public ``virtual_array.gui`` entrypoint. It -supports both the current Qt-backed compatibility widgets and the native -PySide6 shell that is replacing them. Screenshots are painted with -``QWidget.render`` instead of relying on a real desktop or screen-grab API. -""" - -from __future__ import annotations - -import argparse -import importlib -import inspect -import os -import sys -import tempfile -from dataclasses import dataclass -from pathlib import Path -from typing import Any, Callable, Sequence - - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -SRC_DIR = PROJECT_ROOT / "src" -DEFAULT_OUTPUT_DIR = PROJECT_ROOT / "outputs" / "ui-review" -DEFAULT_SIZE = (1366, 768) -MAX_NEAR_BLACK_FRACTION = 0.08 -RENDER_ATTEMPTS = 3 - -PAGE_SCREENSHOTS = ( - "01-physical-virtual.png", - "02-1d-dbf.png", - "03-2d-dbf.png", -) - - -@dataclass -class GuiSession: - """Objects needed to exercise and clean up one GUI instance.""" - - app: Any - gui_module: Any - controller: Any - owner: Any - window: Any - - -@dataclass -class PageNavigator: - """Small adapter over QTabWidget or QTabBar/QStackedWidget navigation.""" - - controller: Any - tab_widget: Any = None - tab_bar: Any = None - stack: Any = None - - @property - def count(self) -> int: - counts = [] - for widget in (self.tab_widget, self.tab_bar, self.stack): - if widget is not None and hasattr(widget, "count"): - counts.append(int(widget.count())) - return max(counts, default=0) - - @property - def current_index(self) -> int: - for widget in (self.stack, self.tab_widget, self.tab_bar): - if widget is not None and hasattr(widget, "currentIndex"): - return int(widget.currentIndex()) - return -1 - - def select(self, index: int) -> None: - """Select a main page while preserving controller side effects.""" - - for method_name in ("_select_main_tab", "select_main_tab", "set_active_tab"): - method = getattr(self.controller, method_name, None) - if callable(method): - method(index) - break - else: - notebook = getattr(self.controller, "main_notebook", None) - select = getattr(notebook, "select", None) - if callable(select): - select(index) - - if self.tab_widget is not None: - self.tab_widget.setCurrentIndex(index) - if self.tab_bar is not None: - self.tab_bar.setCurrentIndex(index) - if self.stack is not None: - self.stack.setCurrentIndex(index) - - -def _qt_modules() -> tuple[Any, Any, Any]: - from PySide6 import QtCore, QtGui, QtWidgets - - return QtCore, QtGui, QtWidgets - - -def configure_capture_environment(appdata_dir: Path) -> None: - """Configure Qt and persistent state before importing the GUI module. - - Windows keeps its native Qt platform for useful CJK font fallback in visual - review images. CI/tests can explicitly set ``QT_QPA_PLATFORM=offscreen``; - non-Windows hosts default to offscreen when no platform was requested. - """ - - if sys.platform != "win32": - os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") - os.environ["APPDATA"] = str(appdata_dir) - os.environ["LOCALAPPDATA"] = str(appdata_dir) - - -def _ensure_import_path() -> None: - source = str(SRC_DIR) - if source not in sys.path: - sys.path.insert(0, source) - - -def _constructor_owner(gui_module: Any, gui_class: type[Any]) -> Any: - """Build the QMainWindow or legacy Qt/Tk root expected by VirtualArrayGui.""" - - _QtCore, _QtGui, QtWidgets = _qt_modules() - parameters = list(inspect.signature(gui_class).parameters.values()) - required = [ - parameter - for parameter in parameters - if parameter.kind - in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) - and parameter.default is inspect.Parameter.empty - ] - if not required: - return None - - first = required[0] - annotation = str(first.annotation).lower() - if "qmainwindow" in annotation or "qwidget" in annotation: - return QtWidgets.QMainWindow() - - legacy_tk = getattr(gui_module, "tk", None) - legacy_root = getattr(legacy_tk, "Tk", None) - if legacy_root is not None and ("tk" in annotation or first.name in {"root", "master"}): - return legacy_root() - return QtWidgets.QMainWindow() - - -def _unwrap_qwidget(value: Any) -> Any: - """Return a QWidget hidden behind a compatibility wrapper, if present.""" - - _QtCore, _QtGui, QtWidgets = _qt_modules() - pending = [value] - visited: set[int] = set() - while pending: - candidate = pending.pop(0) - if candidate is None or id(candidate) in visited: - continue - visited.add(id(candidate)) - if isinstance(candidate, QtWidgets.QWidget): - return candidate - for name in ("_window", "_qt", "window", "main_window", "root"): - nested = getattr(candidate, name, None) - if nested is not None and nested is not candidate: - pending.append(nested) - return None - - -def _resolve_main_window(controller: Any, owner: Any, app: Any) -> Any: - _QtCore, _QtGui, QtWidgets = _qt_modules() - candidates = [ - controller, - getattr(controller, "window", None), - getattr(controller, "main_window", None), - getattr(controller, "root", None), - owner, - ] - widgets = [widget for value in candidates if (widget := _unwrap_qwidget(value)) is not None] - for widget in widgets: - if isinstance(widget, QtWidgets.QMainWindow): - return widget - top_level = widget.window() - if isinstance(top_level, QtWidgets.QMainWindow): - return top_level - if widgets: - return widgets[0].window() - for widget in app.topLevelWidgets(): - if isinstance(widget, QtWidgets.QMainWindow): - return widget - raise RuntimeError("VirtualArrayGui did not expose a QWidget/QMainWindow") - - -def process_events(app: Any, cycles: int = 4) -> None: - QtCore, _QtGui, _QtWidgets = _qt_modules() - for _ in range(cycles): - app.processEvents() - QtCore.QCoreApplication.sendPostedEvents( - None, QtCore.QEvent.Type.DeferredDelete - ) - - -def create_gui_session(size: tuple[int, int] = DEFAULT_SIZE) -> GuiSession: - """Instantiate the canonical GUI without entering QApplication.exec().""" - - _ensure_import_path() - _QtCore, _QtGui, QtWidgets = _qt_modules() - app = QtWidgets.QApplication.instance() or QtWidgets.QApplication( - ["capture-ui-review"] - ) - gui_module = importlib.import_module("virtual_array.gui") - gui_class = gui_module.VirtualArrayGui - owner = _constructor_owner(gui_module, gui_class) - controller = gui_class() if owner is None else gui_class(owner) - window = _resolve_main_window(controller, owner, app) - window.resize(*size) - window.show() - process_events(app) - return GuiSession(app, gui_module, controller, owner, window) - - -def close_gui_session(session: GuiSession) -> None: - """Close top-level widgets without terminating a shared QApplication.""" - - _QtCore, _QtGui, QtWidgets = _qt_modules() - for widget in list(session.app.topLevelWidgets()): - if isinstance(widget, QtWidgets.QDialog): - widget.reject() - session.window.close() - process_events(session.app, cycles=2) - - -def _as_qt_widget(value: Any, expected_type: type[Any]) -> Any: - widget = _unwrap_qwidget(value) - return widget if isinstance(widget, expected_type) else None - - -def locate_page_navigator(session: GuiSession) -> PageNavigator | None: - """Find the three-page workspace without depending on one implementation.""" - - _QtCore, _QtGui, QtWidgets = _qt_modules() - controller = session.controller - - for name in ("main_notebook", "main_tabs", "tab_widget", "main_tab_widget"): - tab_widget = _as_qt_widget(getattr(controller, name, None), QtWidgets.QTabWidget) - if tab_widget is not None and tab_widget.count() >= 3: - return PageNavigator(controller=controller, tab_widget=tab_widget) - - tab_bar = None - stack = None - for name in ("main_tab_bar", "tab_bar", "workspace_tab_bar"): - candidate = _as_qt_widget(getattr(controller, name, None), QtWidgets.QTabBar) - if candidate is not None: - tab_bar = candidate - break - for name in ("main_stack", "stacked_widget", "main_stacked_widget", "workspace_stack"): - candidate = _as_qt_widget( - getattr(controller, name, None), QtWidgets.QStackedWidget - ) - if candidate is not None: - stack = candidate - break - if stack is not None and stack.count() >= 3: - return PageNavigator(controller=controller, tab_bar=tab_bar, stack=stack) - - tab_widgets = sorted( - session.window.findChildren(QtWidgets.QTabWidget), - key=lambda widget: widget.count(), - reverse=True, - ) - if tab_widgets and tab_widgets[0].count() >= 3: - return PageNavigator(controller=controller, tab_widget=tab_widgets[0]) - - stacks = sorted( - session.window.findChildren(QtWidgets.QStackedWidget), - key=lambda widget: widget.count(), - reverse=True, - ) - if stacks and stacks[0].count() >= 3: - bars = [bar for bar in session.window.findChildren(QtWidgets.QTabBar) if bar.count() >= 3] - return PageNavigator( - controller=controller, - tab_bar=bars[0] if bars else None, - stack=stacks[0], - ) - return None - - -def _prepare_widget_for_capture(widget: Any) -> None: - """Flush layouts and paints for every visible child after a page switch.""" - - _QtCore, _QtGui, QtWidgets = _qt_modules() - app = QtWidgets.QApplication.instance() - widgets = [widget, *widget.findChildren(QtWidgets.QWidget)] - for child in widgets: - if not child.isVisible(): - continue - child.ensurePolished() - layout = child.layout() - if layout is not None: - layout.activate() - child.updateGeometry() - child.update() - if app is not None: - process_events(app, cycles=4) - - -def _render_widget_image(widget: Any) -> Any: - """Capture a complete, opaque QWidget image with a render fallback. - - ``QWidget.grab`` composites backing-store children correctly after page - switches. Some headless or RDP platforms still return a non-null black - pixmap, so direct ``QWidget.render`` is compared when the grab looks bad. - """ - - QtCore, QtGui, QtWidgets = _qt_modules() - pixmap = widget.grab() - grabbed_image = None - if not pixmap.isNull(): - grabbed_image = pixmap.toImage().convertToFormat( - QtGui.QImage.Format.Format_RGB32 - ) - if _near_black_fraction(grabbed_image) <= MAX_NEAR_BLACK_FRACTION: - return grabbed_image - - size = widget.size() - if size.width() <= 0 or size.height() <= 0: - widget.adjustSize() - size = widget.size() - ratio = max(1.0, float(widget.devicePixelRatioF())) - image = QtGui.QImage( - max(1, round(size.width() * ratio)), - max(1, round(size.height() * ratio)), - QtGui.QImage.Format.Format_RGB32, - ) - image.setDevicePixelRatio(ratio) - image.fill(widget.palette().color(QtGui.QPalette.ColorRole.Window)) - painter = QtGui.QPainter(image) - flags = ( - QtWidgets.QWidget.RenderFlag.DrawWindowBackground - | QtWidgets.QWidget.RenderFlag.DrawChildren - | QtWidgets.QWidget.RenderFlag.IgnoreMask - ) - widget.render( - painter, - QtCore.QPoint(0, 0), - QtGui.QRegion(widget.rect()), - flags, - ) - painter.end() - if grabbed_image is None: - return image - return min((grabbed_image, image), key=_near_black_fraction) - - -def _near_black_fraction(image: Any) -> float: - """Estimate whether a light-theme capture contains an unpainted black area.""" - - width = image.width() - height = image.height() - step = max(1, min(width, height) // 180) - near_black = 0 - samples = 0 - for y in range(0, height, step): - for x in range(0, width, step): - color = image.pixelColor(x, y) - samples += 1 - if color.red() < 16 and color.green() < 16 and color.blue() < 16: - near_black += 1 - return near_black / max(samples, 1) - - -def render_widget(widget: Any, output_path: Path) -> Path: - """Capture and validate a QWidget PNG with grab/render fallbacks.""" - - output_path.parent.mkdir(parents=True, exist_ok=True) - best_image = None - best_black_fraction = 1.0 - for _attempt in range(RENDER_ATTEMPTS): - _prepare_widget_for_capture(widget) - image = _render_widget_image(widget) - black_fraction = _near_black_fraction(image) - if black_fraction < best_black_fraction: - best_image = image - best_black_fraction = black_fraction - if black_fraction <= MAX_NEAR_BLACK_FRACTION: - break - - if best_image is None or best_black_fraction > MAX_NEAR_BLACK_FRACTION: - raise RuntimeError( - "GUI capture contains an unexpectedly large near-black area " - f"({best_black_fraction:.1%}): {output_path}" - ) - if not best_image.save(str(output_path), "PNG"): - raise OSError(f"Failed to save GUI screenshot: {output_path}") - return output_path - - -def capture_main_pages(session: GuiSession, output_dir: Path) -> list[Path]: - """Capture the three canonical pages, or a transitional main-window image.""" - - navigator = locate_page_navigator(session) - if navigator is None or navigator.count < 3: - fallback = output_dir / "01-main-window.png" - return [render_widget(session.window, fallback)] - - captured = [] - for index, filename in enumerate(PAGE_SCREENSHOTS): - navigator.select(index) - process_events(session.app, cycles=6) - captured.append(render_widget(session.window, output_dir / filename)) - return captured - - -def _visible_dialogs(session: GuiSession) -> list[Any]: - _QtCore, _QtGui, QtWidgets = _qt_modules() - dialogs: list[Any] = [] - for widget in [ - *session.app.topLevelWidgets(), - *session.window.findChildren(QtWidgets.QDialog), - ]: - if ( - isinstance(widget, QtWidgets.QDialog) - and widget.isVisible() - and widget not in dialogs - ): - dialogs.append(widget) - return dialogs - - -def _capture_dialog_invocation( - session: GuiSession, - invocation: Callable[[], Any], - output_path: Path, - prepare_dialog: Callable[[Any], None] | None = None, - timeout_ms: int = 5000, -) -> bool: - """Capture modal or modeless dialog calls without blocking on exec().""" - - QtCore, _QtGui, _QtWidgets = _qt_modules() - baseline = {id(dialog) for dialog in _visible_dialogs(session)} - loop = QtCore.QEventLoop() - watcher = QtCore.QTimer() - watcher.setInterval(25) - timeout = QtCore.QTimer() - timeout.setSingleShot(True) - captured = False - candidate = None - settled_polls = 0 - error: BaseException | None = None - - def invoke() -> None: - nonlocal error - try: - invocation() - except BaseException as exc: # surfaced after the nested event loop exits - error = exc - loop.quit() - - def poll() -> None: - nonlocal captured, candidate, settled_polls - available = [dialog for dialog in _visible_dialogs(session) if id(dialog) not in baseline] - if not available: - return - current = available[-1] - if current is not candidate: - candidate = current - settled_polls = 0 - if prepare_dialog is not None: - prepare_dialog(current) - process_events(session.app, cycles=2) - return - settled_polls += 1 - if settled_polls < 2: - return - process_events(session.app, cycles=2) - render_widget(current, output_path) - captured = True - current.reject() - loop.quit() - - watcher.timeout.connect(poll) - timeout.timeout.connect(loop.quit) - watcher.start() - timeout.start(timeout_ms) - QtCore.QTimer.singleShot(0, invoke) - loop.exec() - watcher.stop() - timeout.stop() - process_events(session.app, cycles=2) - if error is not None: - raise error - return captured - - -def _first_callable(controller: Any, names: Sequence[str]) -> Callable[..., Any] | None: - for name in names: - method = getattr(controller, name, None) - if callable(method): - return method - return None - - -def _sample_element_pattern() -> Any: - import numpy as np - - from virtual_array.element_pattern import ElementPattern - - angles = np.linspace(-90.0, 90.0, 181) - horizontal = -np.minimum((angles / 27.0) ** 2 * 3.0, 35.0) - elevation = -np.minimum((angles / 34.0) ** 2 * 3.0, 35.0) - return ElementPattern( - name="Automated review pattern", - source_path="isolated-review-pattern.csv", - angle_column="Angle", - horizontal_column="Az Gain", - elevation_column="El Gain", - angles_deg=angles, - horizontal_gain_db=horizontal, - elevation_gain_db=elevation, - ) - - -def _select_dbf_import_mode(dialog: Any) -> None: - """Expose the import rail and both visual switch states for review.""" - - _QtCore, _QtGui, QtWidgets = _qt_modules() - custom_mode = dialog.findChild(QtWidgets.QRadioButton, "dbfMode_custom") - if custom_mode is not None: - custom_mode.click() - phase_reverse = dialog.findChild(QtWidgets.QCheckBox, "dbfPhaseReverseToggle") - if phase_reverse is not None: - phase_reverse.setChecked(True) - - -def capture_dialogs( - session: GuiSession, - output_dir: Path, - *, - dbf_import_mode: bool = False, -) -> list[Path]: - """Capture the five custom dialogs named in the visual acceptance plan.""" - - controller = session.controller - specs: list[ - tuple[ - str, - Sequence[str], - Callable[[Callable[..., Any]], Callable[[], Any]], - Callable[[Any], None] | None, - ] - ] = [ - ( - ( - "04-dbf-dictionary-import.png" - if dbf_import_mode - else "04-dbf-dictionary.png" - ), - ("open_dbf_dictionary_dialog", "show_dbf_dictionary_dialog"), - lambda method: method, - _select_dbf_import_mode if dbf_import_mode else None, - ), - ( - "05-channel-amplitude-phase.png", - ("open_channel_patterns_dialog", "show_channel_patterns_dialog"), - lambda method: method, - None, - ), - ( - "06-element-pattern-confirmation.png", - ( - "_confirm_element_pattern_import", - "show_element_pattern_confirmation", - ), - lambda method: lambda: method(_sample_element_pattern()), - None, - ), - ( - "07-user-manual.png", - ("_show_user_manual_dialog", "show_user_manual_dialog"), - lambda method: method, - None, - ), - ( - "08-performance-report.png", - ("open_performance_report_dialog",), - lambda method: method, - None, - ), - ] - captured: list[Path] = [] - for filename, method_names, invocation_factory, prepare_dialog in specs: - method = _first_callable(controller, method_names) - if method is None: - continue - output_path = output_dir / filename - if _capture_dialog_invocation( - session, - invocation_factory(method), - output_path, - prepare_dialog=prepare_dialog, - ): - captured.append(output_path) - return captured - - -def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: - parser = argparse.ArgumentParser( - description="Capture canonical PySide6 GUI pages and dialogs for visual review." - ) - parser.add_argument( - "--output-dir", - type=Path, - default=DEFAULT_OUTPUT_DIR, - help=f"PNG destination (default: {DEFAULT_OUTPUT_DIR})", - ) - parser.add_argument( - "--skip-dialogs", - action="store_true", - help="Capture only the three main pages.", - ) - parser.add_argument( - "--dbf-import-mode", - action="store_true", - help="Show the DBF CSV/XLSX import rail in its dialog screenshot.", - ) - parser.add_argument( - "--width", - type=int, - default=DEFAULT_SIZE[0], - help=f"Logical window width (default: {DEFAULT_SIZE[0]}).", - ) - parser.add_argument( - "--height", - type=int, - default=DEFAULT_SIZE[1], - help=f"Logical window height (default: {DEFAULT_SIZE[1]}).", - ) - parser.add_argument( - "--language", - choices=("zh", "en", "ja"), - default="zh", - help="UI language for the captured scenario (default: zh).", - ) - parser.add_argument( - "--auto-tx", - type=int, - default=1, - help="Auto-layout Tx count for the captured scenario (default: 1).", - ) - parser.add_argument( - "--auto-rx", - type=int, - default=1, - help="Auto-layout Rx count for the captured scenario (default: 1).", - ) - return parser.parse_args(argv) - - -def main(argv: Sequence[str] | None = None) -> int: - args = parse_args(argv) - output_dir = args.output_dir.expanduser().resolve() - output_dir.mkdir(parents=True, exist_ok=True) - - with tempfile.TemporaryDirectory(prefix="mimo-array-ui-review-") as appdata: - configure_capture_environment(Path(appdata)) - session = create_gui_session((max(1, args.width), max(1, args.height))) - try: - session.controller.set_language(args.language) - if args.auto_tx != 1 or args.auto_rx != 1: - session.controller.auto_tx_count.set(str(max(1, args.auto_tx))) - session.controller.auto_rx_count.set(str(max(1, args.auto_rx))) - session.controller.apply_auto_array_layout() - process_events(session.app, cycles=8) - captured = capture_main_pages(session, output_dir) - if not args.skip_dialogs: - captured.extend( - capture_dialogs( - session, - output_dir, - dbf_import_mode=args.dbf_import_mode, - ) - ) - finally: - close_gui_session(session) - - for path in captured: - print(path) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/run_case4.ps1 b/scripts/run_case4.ps1 deleted file mode 100644 index e0119af..0000000 --- a/scripts/run_case4.ps1 +++ /dev/null @@ -1,8 +0,0 @@ -$ErrorActionPreference = "Stop" - -if (-not (Test-Path ".\.venv\Scripts\python.exe")) { - Write-Error "Missing .venv. Run .\scripts\setup.ps1 first." -} - -.\.venv\Scripts\python.exe .\examples\case4_5tx7rx_sel.py - diff --git a/scripts/run_gui.ps1 b/scripts/run_gui.ps1 deleted file mode 100644 index 78f0dca..0000000 --- a/scripts/run_gui.ps1 +++ /dev/null @@ -1,17 +0,0 @@ -$ErrorActionPreference = "Stop" - -$ProjectRoot = Split-Path -Parent $PSScriptRoot -$Python = Join-Path $ProjectRoot ".venv\Scripts\python.exe" - -if (-not (Test-Path -LiteralPath $Python)) { - Write-Error "Missing .venv. Run .\scripts\setup.ps1 first." -} - -Push-Location $ProjectRoot -try { - & $Python -m virtual_array.gui @args -} -finally { - Pop-Location -} - diff --git a/scripts/setup.ps1 b/scripts/setup.ps1 deleted file mode 100644 index 60b9339..0000000 --- a/scripts/setup.ps1 +++ /dev/null @@ -1,11 +0,0 @@ -$ErrorActionPreference = "Stop" - -if (-not (Get-Command py -ErrorAction SilentlyContinue)) { - python -m venv .venv -} else { - py -3 -m venv .venv -} - -.\.venv\Scripts\python.exe -m pip install --upgrade pip -.\.venv\Scripts\python.exe -m pip install -e ".[dev]" - diff --git a/src/virtual_array/analysis.py b/src/virtual_array/analysis.py index a7cc502..6bc692d 100644 --- a/src/virtual_array/analysis.py +++ b/src/virtual_array/analysis.py @@ -8,6 +8,7 @@ from .dbf_dictionary import DbfDictionaryConfig from .element_pattern import ChannelPatternSet, ElementPattern, virtual_channel_names from .geometry import AntennaArray +from .phasor import unit_phasor AZIMUTH_FOV = (-75.0, 75.0) @@ -243,15 +244,23 @@ def calculate_metrics_and_psf( u = np.sin(az_rad) * np.cos(el_rad) v = np.sin(el_rad) - phase = np.pi * ( - virtual_xy[:, 0, None, None] * u[None, :, :] - + virtual_xy[:, 1, None, None] * v[None, :, :] - ) - steering = np.exp(1j * phase) + # 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 ) - array_factor = (steering * channel_weight).sum(axis=0) + 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) af = np.abs(array_factor * pattern_weight) @@ -446,52 +455,127 @@ def dbf_2d_spectrum( normalization_max: float | None = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Return one normalized-correlation 2D DBF spectrum for a true az/el angle.""" - if scan_azimuths_deg is None: - scan_azimuths_deg = _default_dbf_angles() - else: - scan_azimuths_deg = np.asarray(scan_azimuths_deg, dtype=float) - - if scan_elevations_deg is None: - scan_elevations_deg = _default_dbf_angles() - else: - scan_elevations_deg = np.asarray(scan_elevations_deg, dtype=float) - - signal = _dbf_2d_signal_vector( + _ = tx_pattern, rx_pattern, normalization_max + scanner = Dbf2dScanner( array, - true_azimuth_deg, - true_elevation_deg, + scan_azimuths_deg=scan_azimuths_deg, + scan_elevations_deg=scan_elevations_deg, channel_patterns=channel_patterns, + dbf_dictionary=dbf_dictionary, ) - az_grid, el_grid = np.meshgrid(scan_azimuths_deg, scan_elevations_deg) - if dbf_dictionary is not None and not dbf_dictionary.uses_auto_ideal_sign: - dictionary = dbf_dictionary.scan_matrix_2d( - array, - az_grid.ravel(), - el_grid.ravel(), - axis="azimuth", - channel_patterns=channel_patterns, + spectra_db = scanner.spectrum_db(true_azimuth_deg, true_elevation_deg) + return scanner.scan_azimuths_deg, scanner.scan_elevations_deg, spectra_db + + +class Dbf2dScanner: + """Evaluate 2D DBF spectra for many true angles with one scan dictionary. + + Building the (scan points x channels) dictionary dominates the cost of a + 2D spectrum. The dictionary depends only on the array, channel patterns + and dictionary configuration, so animation and batch callers reuse it + across true angles. Results are identical to :func:`dbf_2d_spectrum`. + """ + + def __init__( + self, + array: AntennaArray, + scan_azimuths_deg: np.ndarray | None = None, + scan_elevations_deg: np.ndarray | None = None, + channel_patterns: ChannelPatternSet | None = None, + dbf_dictionary: DbfDictionaryConfig | None = None, + ) -> None: + self.array = array + self.scan_azimuths_deg = ( + _default_dbf_angles() + if scan_azimuths_deg is None + else np.asarray(scan_azimuths_deg, dtype=float) ) - else: - steering_sign = _select_dbf_2d_steering_sign( - array, - float(true_azimuth_deg), - float(true_elevation_deg), - scan_azimuths_deg, - scan_elevations_deg, - signal, - channel_patterns=channel_patterns, + self.scan_elevations_deg = ( + _default_dbf_angles() + if scan_elevations_deg is None + else np.asarray(scan_elevations_deg, dtype=float) ) - dictionary = _dbf_2d_scan_matrix( - array, - az_grid.ravel(), - el_grid.ravel(), - steering_sign=steering_sign, + self.channel_patterns = channel_patterns + self.dbf_dictionary = dbf_dictionary + az_grid, el_grid = np.meshgrid(self.scan_azimuths_deg, self.scan_elevations_deg) + self._flat_az = az_grid.ravel() + self._flat_el = el_grid.ravel() + self._uses_fixed_dictionary = ( + dbf_dictionary is not None and not dbf_dictionary.uses_auto_ideal_sign ) - _ = tx_pattern, rx_pattern, normalization_max - spectra = _dbf_correlation_response(dictionary, signal)[:, 0] - spectra = spectra.reshape(len(scan_elevations_deg), len(scan_azimuths_deg)) - spectra_db = 20.0 * np.log10(np.maximum(spectra, 1e-6)) - return scan_azimuths_deg, scan_elevations_deg, spectra_db + self._has_phase = _channel_pattern_has_any_phase(channel_patterns, array) + self._dictionaries: dict[int, np.ndarray] = {} + + def _dictionary(self, steering_sign: int) -> np.ndarray: + key = 0 if self._uses_fixed_dictionary else steering_sign + cached = self._dictionaries.get(key) + if cached is not None: + return cached + if self._uses_fixed_dictionary: + assert self.dbf_dictionary is not None + dictionary = self.dbf_dictionary.scan_matrix_2d( + self.array, + self._flat_az, + self._flat_el, + axis="azimuth", + channel_patterns=self.channel_patterns, + ) + else: + dictionary = _dbf_2d_scan_matrix( + self.array, + self._flat_az, + self._flat_el, + steering_sign=steering_sign, + ) + self._dictionaries[key] = dictionary + return dictionary + + def _steering_sign( + self, + true_azimuth_deg: float, + true_elevation_deg: float, + signal: np.ndarray, + ) -> int: + if not self._has_phase: + return DBF_DEFAULT_STEERING_SIGN + candidates: list[tuple[float, int]] = [] + for steering_sign in (DBF_DEFAULT_STEERING_SIGN, 1): + score = np.abs(self._dictionary(steering_sign) @ signal) ** 2 + peak = int(np.argmax(score)) + error = math.hypot( + float(self._flat_az[peak]) - true_azimuth_deg, + float(self._flat_el[peak]) - true_elevation_deg, + ) + candidates.append((error, steering_sign)) + return min( + candidates, + key=lambda item: ( + item[0], + 0 if item[1] == DBF_DEFAULT_STEERING_SIGN else 1, + ), + )[1] + + def spectrum_db( + self, + true_azimuth_deg: float, + true_elevation_deg: float, + ) -> np.ndarray: + """Return the (elevation x azimuth) correlation spectrum in dB.""" + true_az = float(true_azimuth_deg) + true_el = float(true_elevation_deg) + signal = _dbf_2d_signal_vector( + self.array, + true_az, + true_el, + channel_patterns=self.channel_patterns, + ) + if self._uses_fixed_dictionary: + dictionary = self._dictionary(0) + else: + dictionary = self._dictionary(self._steering_sign(true_az, true_el, signal)) + spectra = _dbf_correlation_response(dictionary, signal)[:, 0] + spectra = spectra.reshape(len(self.scan_elevations_deg), len(self.scan_azimuths_deg)) + return 20.0 * np.log10(np.maximum(spectra, 1e-6)) def dbf_2d_normalization_reference( @@ -943,7 +1027,7 @@ def _steering_matrix( raise ValueError(f"Unknown DBF axis: {axis!r}") u = np.sin(np.radians(angles_deg)) phase = np.pi * positions[:, None] * u[None, :] - return np.exp(1j * phase) + return unit_phasor(phase) def _dbf_scan_matrix( @@ -961,7 +1045,7 @@ def _dbf_scan_matrix( raise ValueError(f"Unknown DBF axis: {axis!r}") u = np.sin(np.radians(angles_deg)) phase = steering_sign * np.pi * u[:, None] * positions[None, :] - return np.exp(1j * phase) + return unit_phasor(phase) def _direction_uv( @@ -986,11 +1070,9 @@ def _dbf_2d_scan_matrix( np.asarray(azimuth_deg, dtype=float), np.asarray(elevation_deg, dtype=float), ) - phase = steering_sign * np.pi * ( - u[:, None] * virtual_xy[None, :, 0] - + v[:, None] * virtual_xy[None, :, 1] - ) - return np.exp(1j * phase) + uv = np.column_stack([np.ravel(u), np.ravel(v)]) + phase = uv @ (steering_sign * np.pi * virtual_xy.T) + return unit_phasor(phase.reshape(*np.shape(u), len(virtual_xy))) def _dbf_2d_steering_vector( @@ -1004,7 +1086,7 @@ def _dbf_2d_steering_vector( np.asarray([elevation_deg], dtype=float), ) phase = np.pi * (virtual_xy[:, 0] * float(u[0]) + virtual_xy[:, 1] * float(v[0])) - return np.exp(1j * phase) + return unit_phasor(phase) def _axis_pattern_angles( @@ -1121,39 +1203,6 @@ def _select_dbf_steering_sign( return min(candidates, key=lambda item: (item[0], 0 if item[1] == DBF_DEFAULT_STEERING_SIGN else 1))[1] -def _select_dbf_2d_steering_sign( - array: AntennaArray, - true_azimuth_deg: float, - true_elevation_deg: float, - scan_azimuths_deg: np.ndarray, - scan_elevations_deg: np.ndarray, - signal: np.ndarray, - channel_patterns: ChannelPatternSet | None, -) -> int: - if not _channel_pattern_has_any_phase(channel_patterns, array): - return DBF_DEFAULT_STEERING_SIGN - - az_grid, el_grid = np.meshgrid(scan_azimuths_deg, scan_elevations_deg) - candidates: list[tuple[float, int]] = [] - for steering_sign in (DBF_DEFAULT_STEERING_SIGN, 1): - dictionary = _dbf_2d_scan_matrix( - array, - az_grid.ravel(), - el_grid.ravel(), - steering_sign=steering_sign, - ) - score = np.abs(dictionary @ signal) ** 2 - peak = int(np.argmax(score)) - estimate_az = float(az_grid.ravel()[peak]) - estimate_el = float(el_grid.ravel()[peak]) - error = math.hypot( - estimate_az - true_azimuth_deg, - estimate_el - true_elevation_deg, - ) - candidates.append((error, steering_sign)) - return min(candidates, key=lambda item: (item[0], 0 if item[1] == DBF_DEFAULT_STEERING_SIGN else 1))[1] - - def _channel_pattern_weight( patterns: ChannelPatternSet | None, array: AntennaArray, diff --git a/src/virtual_array/app_state.py b/src/virtual_array/app_state.py deleted file mode 100644 index 917c86d..0000000 --- a/src/virtual_array/app_state.py +++ /dev/null @@ -1,46 +0,0 @@ -from __future__ import annotations - -import json -import os -from pathlib import Path -from typing import Any - - -APP_DIR_NAME = "antenna-array" -STATE_FILE_NAME = "state.json" - - -def default_app_dir() -> Path: - appdata = os.environ.get("APPDATA") - if appdata: - return Path(appdata) / APP_DIR_NAME - - local_appdata = os.environ.get("LOCALAPPDATA") - if local_appdata: - return Path(local_appdata) / APP_DIR_NAME - - return Path.home() / f".{APP_DIR_NAME}" - - -def state_path() -> Path: - return default_app_dir() / STATE_FILE_NAME - - -def load_state(path: str | Path | None = None) -> dict[str, Any]: - target = Path(path) if path is not None else state_path() - if not target.exists(): - return {} - with target.open("r", encoding="utf-8") as file: - data = json.load(file) - return data if isinstance(data, dict) else {} - - -def save_state(state: dict[str, Any], path: str | Path | None = None) -> Path: - target = Path(path) if path is not None else state_path() - target.parent.mkdir(parents=True, exist_ok=True) - tmp_path = target.with_suffix(target.suffix + ".tmp") - with tmp_path.open("w", encoding="utf-8") as file: - json.dump(state, file, ensure_ascii=False, indent=2) - file.write("\n") - tmp_path.replace(target) - return target diff --git a/src/virtual_array/assets.py b/src/virtual_array/assets.py new file mode 100644 index 0000000..6d13933 --- /dev/null +++ b/src/virtual_array/assets.py @@ -0,0 +1,118 @@ +"""Content-addressed store for imported data files. + +Uploaded files are kept verbatim under ``//`` so +the existing file loaders (which rely on the file suffix to choose CSV/TSV/XLSX +parsing) work unchanged, and so a report can name the original file. The +SHA-256 digest is the asset ID referenced from project documents; the same +file uploaded twice resolves to the same asset. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import threading +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path + +ALLOWED_SUFFIXES = {".csv", ".tsv", ".txt", ".xlsx", ".xlsm"} +MAX_ASSET_BYTES = 32 * 1024 * 1024 +_ASSET_ID_RE = re.compile(r"^[0-9a-f]{64}$") +_META_NAME = "meta.json" + + +@dataclass(frozen=True) +class AssetInfo: + id: str + filename: str + size: int + uploaded_at: str + + +class AssetNotFoundError(KeyError): + pass + + +class AssetStore: + def __init__(self, root: str | Path) -> None: + self.root = Path(root) + self.root.mkdir(parents=True, exist_ok=True) + self._lock = threading.Lock() + + def add(self, filename: str, content: bytes) -> AssetInfo: + safe_name = sanitize_filename(filename) + suffix = Path(safe_name).suffix.lower() + if suffix not in ALLOWED_SUFFIXES: + allowed = ", ".join(sorted(ALLOWED_SUFFIXES)) + raise ValueError(f"Unsupported file type {suffix or '(none)'}; use {allowed}.") + if not content: + raise ValueError("The uploaded file is empty.") + if len(content) > MAX_ASSET_BYTES: + raise ValueError(f"The uploaded file exceeds {MAX_ASSET_BYTES // (1024 * 1024)} MB.") + asset_id = hashlib.sha256(content).hexdigest() + directory = self.root / asset_id + with self._lock: + existing = self._read_meta(directory) + if existing is not None: + return existing + directory.mkdir(parents=True, exist_ok=True) + temporary = directory / f".{safe_name}.tmp" + temporary.write_bytes(content) + temporary.replace(directory / safe_name) + info = AssetInfo( + id=asset_id, + filename=safe_name, + size=len(content), + uploaded_at=datetime.now(timezone.utc).isoformat(timespec="seconds"), + ) + (directory / _META_NAME).write_text( + json.dumps(asdict(info), ensure_ascii=False), encoding="utf-8" + ) + return info + + def info(self, asset_id: str) -> AssetInfo: + info = self._read_meta(self._directory(asset_id)) + if info is None: + raise AssetNotFoundError(asset_id) + return info + + def path(self, asset_id: str) -> Path: + info = self.info(asset_id) + return self._directory(asset_id) / info.filename + + def read_bytes(self, asset_id: str) -> bytes: + return self.path(asset_id).read_bytes() + + def exists(self, asset_id: str) -> bool: + try: + self.info(asset_id) + except AssetNotFoundError: + return False + return True + + def _directory(self, asset_id: str) -> Path: + if not _ASSET_ID_RE.fullmatch(asset_id or ""): + raise AssetNotFoundError(asset_id) + return self.root / asset_id + + @staticmethod + def _read_meta(directory: Path) -> AssetInfo | None: + meta_path = directory / _META_NAME + if not meta_path.is_file(): + return None + data = json.loads(meta_path.read_text(encoding="utf-8")) + return AssetInfo(**data) + + +def sanitize_filename(filename: str) -> str: + name = Path(str(filename or "")).name.strip() + name = re.sub(r"[\x00-\x1f/\\:*?\"<>|]", "_", name) + name = name.lstrip(".") + if not name: + name = "upload.csv" + if len(name) > 160: + stem, suffix = Path(name).stem, Path(name).suffix + name = stem[: 160 - len(suffix)] + suffix + return name diff --git a/src/virtual_array/dbf_dictionary.py b/src/virtual_array/dbf_dictionary.py index 28cd423..f91e892 100644 --- a/src/virtual_array/dbf_dictionary.py +++ b/src/virtual_array/dbf_dictionary.py @@ -9,6 +9,7 @@ from .element_pattern import ChannelPatternSet, virtual_channel_names from .geometry import AntennaArray +from .phasor import unit_phasor from .table_io import read_xlsx_rows @@ -770,7 +771,7 @@ def _ideal_scan_matrix( u[:, None] * virtual_xy[None, :, 0] + v[:, None] * virtual_xy[None, :, 1] ) - return np.exp(1j * phase) + return unit_phasor(phase) def _channel_pattern_response( diff --git a/src/virtual_array/engine.py b/src/virtual_array/engine.py new file mode 100644 index 0000000..79d4293 --- /dev/null +++ b/src/virtual_array/engine.py @@ -0,0 +1,744 @@ +"""Service layer between project documents and the computation core. + +The engine turns a :class:`~virtual_array.project.Project` into core objects +(array, element pattern, channel patterns, DBF dictionary), runs the analysis, +and returns JSON-ready dictionaries. Expensive intermediate results are kept +in small LRU caches keyed by the canonical JSON of exactly the project fields +they depend on, so editing the frequency does not recompute DBF spectra and +an animation reuses one 2D scan dictionary. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import math +import threading +from collections import OrderedDict, defaultdict +from collections.abc import Callable, Hashable +from dataclasses import asdict, dataclass +from datetime import datetime +from typing import Any, TypeVar + +import numpy as np + +from .analysis import ( + DBF_CUT_REASON_BOUNDARY, + DBF_CUT_REASON_COMPETITOR, + DBF_CUT_REASON_EDGE, + DBF_CUT_REASON_ERROR_JUMP, + DBF_CUT_REASON_FLAT, + DBF_QUALITY_OK, + DBF_SCAN_FOV, + DBF_SCAN_GRID_SIZE, + ArrayMetrics, + DbfAngleMetrics, + Dbf2dScanner, + calculate_metrics_and_psf, + dbf_angle_frame_series_from_spectra, + dbf_angle_metrics_from_spectra, + dbf_azimuth_spectrum_bank, + dbf_elevation_spectrum_bank, +) +from .assets import AssetStore +from .dbf_dictionary import ( + DBF_DICT_CUSTOM, + DBF_DICTIONARY_QUALITY_DANGER, + DBF_DICTIONARY_QUALITY_OK, + DBF_DICTIONARY_QUALITY_WARNING, + DbfDictionaryConfig, + DbfDictionaryTable, + dictionary_phase_preview, + dictionary_quality_report, + load_dbf_dictionary_table, +) +from .element_pattern import ( + PATTERN_KIND_AMPLITUDE, + PATTERN_KIND_PHASE, + ChannelPatternSet, + ElementPattern, + PatternSeries, + load_element_pattern, + load_hfss_pattern_series_columns, + load_hfss_summary_pattern, + pattern_cut_metrics, +) +from .geometry import AntennaArray +from .project import ( + ChannelPatternBinding, + Project, + json_number, + layout_to_v1, + project_array, +) +from .version import APP_VERSION + +AXES = ("azimuth", "elevation") +HALF_LAMBDA_TO_LAMBDA = 0.5 +ROUND_DECIMALS = 9 + +CUT_REASON_CODES = { + DBF_CUT_REASON_COMPETITOR: "competitor", + DBF_CUT_REASON_ERROR_JUMP: "error_jump", + DBF_CUT_REASON_EDGE: "boundary_limited", + DBF_CUT_REASON_FLAT: "unreliable", + DBF_CUT_REASON_BOUNDARY: "data_boundary", + DBF_QUALITY_OK: "normal", +} + +T = TypeVar("T") + + +class ProjectComputationError(ValueError): + """A project is valid JSON but cannot be evaluated (e.g. mismatched files).""" + + +class _LruCache: + def __init__(self, maxsize: int) -> None: + self.maxsize = maxsize + self._items: OrderedDict[Hashable, Any] = OrderedDict() + self._lock = threading.Lock() + + def get_or_create(self, key: Hashable, factory: Callable[[], T]) -> T: + with self._lock: + if key in self._items: + self._items.move_to_end(key) + return self._items[key] + value = factory() + with self._lock: + self._items[key] = value + self._items.move_to_end(key) + while len(self._items) > self.maxsize: + self._items.popitem(last=False) + return value + + def clear(self) -> None: + with self._lock: + self._items.clear() + + +@dataclass(frozen=True) +class StudyContext: + project: Project + array: AntennaArray + element_pattern: ElementPattern | None + channel_patterns: ChannelPatternSet + dictionary: DbfDictionaryConfig + + +def encode_array(values: np.ndarray, dtype: str = "float32") -> dict[str, Any]: + """Compact binary transport for large numeric matrices.""" + array = np.ascontiguousarray(np.asarray(values, dtype=dtype)) + return { + "dtype": dtype, + "shape": list(array.shape), + "data": base64.b64encode(array.tobytes()).decode("ascii"), + } + + +def num(value: float | None, digits: int | None = None) -> float | str | None: + """JSON-safe number: ±inf become strings, NaN becomes null.""" + if value is None: + return None + number = float(value) + if math.isnan(number): + return None + if math.isinf(number): + return "Infinity" if number > 0 else "-Infinity" + return round(number, digits) if digits is not None else number + + +def num_list(values: np.ndarray, digits: int | None = None) -> list[float | str | None]: + return [num(value, digits) for value in np.asarray(values, dtype=float).tolist()] + + +def _digest(payload: Any) -> str: + text = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + return hashlib.sha1(text.encode("utf-8")).hexdigest() + + +class Engine: + def __init__(self, assets: AssetStore) -> None: + self.assets = assets + self._element_patterns = _LruCache(16) + self._pattern_columns = _LruCache(32) + self._dictionary_tables = _LruCache(16) + self._metrics = _LruCache(16) + self._banks = _LruCache(16) + self._scanners = _LruCache(2) + + # ── Project → core objects ─────────────────────────────────────── + + def context(self, project: Project) -> StudyContext: + self._require_assets(project) + array = project_array(project) + return StudyContext( + project=project, + array=array, + element_pattern=self._element_pattern(project), + channel_patterns=self._channel_pattern_set(project), + dictionary=self._dictionary_config(project, array), + ) + + def _require_assets(self, project: Project) -> None: + missing = sorted(asset for asset in project.asset_ids() if not self.assets.exists(asset)) + if missing: + raise ProjectComputationError( + "Referenced data files are missing on this server: " + + ", ".join(asset[:12] for asset in missing) + ) + + def _element_pattern(self, project: Project) -> ElementPattern | None: + settings = project.element_pattern + if settings is None: + return None + return self.element_pattern(settings.asset, settings.swap_axes) + + def element_pattern(self, asset: str, swap_axes: bool = False) -> ElementPattern: + def build() -> ElementPattern: + pattern = load_element_pattern(self.assets.path(asset)) + return pattern.swapped_axes() if swap_axes else pattern + + return self._element_patterns.get_or_create((asset, swap_axes), build) + + def pattern_columns(self, asset: str, kind: str) -> list[PatternSeries]: + return self._pattern_columns.get_or_create( + (asset, kind), + lambda: load_hfss_pattern_series_columns(self.assets.path(asset), value_kind=kind), + ) + + def _channel_pattern_set(self, project: Project) -> ChannelPatternSet: + patterns = ChannelPatternSet() + for binding in project.channel_patterns: + series = self.pattern_columns(binding.asset, binding.kind) + if binding.column_index >= len(series): + raise ProjectComputationError( + f"Channel pattern for {binding.channel} refers to data column " + f"{binding.column_index + 1}, but the file has {len(series)}." + ) + patterns.set_series( + binding.channel, binding.kind, binding.plane, series[binding.column_index] + ) + return patterns + + def _dictionary_table( + self, asset: str, array: AntennaArray, channel_mode: str + ) -> DbfDictionaryTable: + key = (asset, len(array.tx), len(array.rx), channel_mode) + + def build() -> DbfDictionaryTable: + try: + return load_dbf_dictionary_table( + self.assets.path(asset), array, channel_mode=channel_mode + ) + except ValueError as exc: + raise ProjectComputationError(str(exc)) from exc + + return self._dictionary_tables.get_or_create(key, build) + + def _dictionary_config(self, project: Project, array: AntennaArray) -> DbfDictionaryConfig: + settings = project.dbf_dictionary + if settings.mode != DBF_DICT_CUSTOM: + return DbfDictionaryConfig(mode=settings.mode) + tables = { + axis: ( + self._dictionary_table(asset, array, settings.channel_mode) + if asset is not None + else None + ) + for axis, asset in ( + ("azimuth", settings.azimuth_asset), + ("elevation", settings.elevation_asset), + ) + } + return DbfDictionaryConfig( + mode=DBF_DICT_CUSTOM, + custom_azimuth_table=tables["azimuth"], + custom_elevation_table=tables["elevation"], + custom_phase_reversed=settings.phase_reversed, + custom_zero_phase_calibrated=settings.zero_phase_calibrated, + ) + + # ── Cache keys ─────────────────────────────────────────────────── + + @staticmethod + def _pattern_key(project: Project) -> str: + return _digest( + project.model_dump(include={"layout", "element_pattern", "channel_patterns"}) + ) + + @staticmethod + def _dbf_key(project: Project) -> str: + return _digest( + project.model_dump(include={"layout", "channel_patterns", "dbf_dictionary"}) + ) + + # ── Evaluations ────────────────────────────────────────────────── + + def _array_metrics(self, context: StudyContext) -> tuple[np.ndarray, np.ndarray, np.ndarray, ArrayMetrics]: + def build() -> tuple[np.ndarray, np.ndarray, np.ndarray, ArrayMetrics]: + unique, counts = context.array.unique_virtual_xy(decimals=ROUND_DECIMALS) + return calculate_metrics_and_psf( + context.array, + unique, + counts, + tx_pattern=context.element_pattern, + rx_pattern=context.element_pattern, + channel_patterns=context.channel_patterns, + ) + + return self._metrics.get_or_create(self._pattern_key(context.project), build) + + def _bank(self, context: StudyContext, axis: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + if axis not in AXES: + raise ValueError(f"Unknown DBF axis: {axis!r}") + bank_function = dbf_azimuth_spectrum_bank if axis == "azimuth" else dbf_elevation_spectrum_bank + + def build() -> tuple[np.ndarray, np.ndarray, np.ndarray]: + try: + return bank_function( + context.array, + tx_pattern=context.element_pattern, + rx_pattern=context.element_pattern, + channel_patterns=context.channel_patterns, + dbf_dictionary=context.dictionary, + ) + except ValueError as exc: + raise ProjectComputationError(str(exc)) from exc + + return self._banks.get_or_create((self._dbf_key(context.project), axis), build) + + def evaluate(self, project: Project) -> dict[str, Any]: + context = self.context(project) + array = context.array + af_db, azimuths, elevations, metrics = self._array_metrics(context) + _ = af_db, azimuths, elevations + capability = axis_capability(metrics) + half_wavelength_mm = project.wavelength_mm / 2.0 + + angle: dict[str, Any] = {} + for axis in AXES: + if not capability[axis]: + angle[axis] = None + continue + try: + true_angles, scan_angles, spectra = self._bank(context, axis) + angle[axis] = angle_metrics_payload( + dbf_angle_metrics_from_spectra( + true_angles, + scan_angles, + spectra, + ambiguity_margin_db=project.ambiguity_margin_db, + ) + ) + except ProjectComputationError as exc: + angle[axis] = {"error": str(exc)} + + utilization = metrics.unique_count / metrics.virtual_count if metrics.virtual_count else 0.0 + return { + "wavelength_mm": project.wavelength_mm, + "half_wavelength_mm": half_wavelength_mm, + "summary": { + "tx_count": metrics.tx_count, + "rx_count": metrics.rx_count, + "virtual_count": metrics.virtual_count, + "unique_count": metrics.unique_count, + "duplicate_locations": metrics.duplicate_locations, + "duplicate_excess": metrics.duplicate_excess, + "utilization": utilization, + "x_aperture_lambda": metrics.x_aperture * HALF_LAMBDA_TO_LAMBDA, + "y_aperture_lambda": metrics.y_aperture * HALF_LAMBDA_TO_LAMBDA, + "x_aperture_mm": metrics.x_aperture * half_wavelength_mm, + "y_aperture_mm": metrics.y_aperture * half_wavelength_mm, + }, + "metrics": array_metrics_payload(metrics), + "capability": capability, + "virtual_points": virtual_points_payload(array), + "angle": angle, + "pattern_status": pattern_status(project), + "notes": note_codes(metrics), + } + + def dbf_bank(self, project: Project, axis: str) -> dict[str, Any]: + context = self.context(project) + true_angles, scan_angles, spectra = self._bank(context, axis) + series = dbf_angle_frame_series_from_spectra(true_angles, scan_angles, spectra) + metrics = dbf_angle_metrics_from_spectra( + true_angles, + scan_angles, + spectra, + ambiguity_margin_db=project.ambiguity_margin_db, + ) + return { + "axis": axis, + "true_angles": num_list(true_angles), + "scan_angles": num_list(scan_angles), + "spectra_db": encode_array(spectra), + "frames": { + "estimated": num_list(series.estimated_angles_deg), + "errors": num_list(series.errors_deg, 6), + "main_peak_db": num_list(series.main_peak_db, 4), + "competitor_peak_db": num_list(series.competitor_peak_db, 4), + "margins_db": num_list(series.peak_margins_db, 4), + "quality": [CUT_REASON_CODES.get(flag, flag) for flag in series.quality_flags], + }, + "metrics": angle_metrics_payload(metrics), + } + + def _scanner(self, context: StudyContext) -> Dbf2dScanner: + return self._scanners.get_or_create( + self._dbf_key(context.project), + lambda: Dbf2dScanner( + context.array, + channel_patterns=context.channel_patterns, + dbf_dictionary=context.dictionary, + ), + ) + + def dbf_2d(self, project: Project, frames: list[tuple[float, float]]) -> dict[str, Any]: + context = self.context(project) + scanner = self._scanner(context) + results = [] + for true_az, true_el in frames: + try: + spectrum = scanner.spectrum_db(true_az, true_el) + except ValueError as exc: + raise ProjectComputationError(str(exc)) from exc + peak_el_index, peak_az_index = np.unravel_index(int(np.argmax(spectrum)), spectrum.shape) + results.append( + { + "true_azimuth": float(true_az), + "true_elevation": float(true_el), + "peak_azimuth": float(scanner.scan_azimuths_deg[peak_az_index]), + "peak_elevation": float(scanner.scan_elevations_deg[peak_el_index]), + "peak_db": float(spectrum[peak_el_index, peak_az_index]), + "spectrum_db": encode_array(spectrum), + } + ) + return { + "scan_azimuths": num_list(scanner.scan_azimuths_deg), + "scan_elevations": num_list(scanner.scan_elevations_deg), + "frames": results, + } + + # ── Import helpers ─────────────────────────────────────────────── + + def element_pattern_preview(self, asset: str, swap_axes: bool = False) -> dict[str, Any]: + pattern = self.element_pattern(asset, swap_axes) + horizontal = pattern.horizontal_gain_db + elevation = pattern.elevation_gain_db + return { + "name": pattern.name, + "angle_column": pattern.angle_column, + "horizontal_column": pattern.horizontal_column, + "elevation_column": pattern.elevation_column, + "angles": num_list(pattern.angles_deg), + "horizontal_gain_db": num_list(horizontal, 4), + "elevation_gain_db": None if elevation is None else num_list(elevation, 4), + "horizontal_metrics": asdict(pattern_cut_metrics(pattern.angles_deg, horizontal)), + "elevation_metrics": ( + None + if elevation is None + else asdict(pattern_cut_metrics(pattern.angles_deg, elevation)) + ), + } + + def resolve_channel_patterns( + self, + project: Project, + asset: str, + kind: str, + plane: str, + target: str, + channel: str | None = None, + ) -> list[ChannelPatternBinding]: + """Map the data columns of an HFSS export onto channel names. + + ``channel`` set: the first data column is assigned to that one channel. + Otherwise the file is a summary export whose columns map left-to-right + (or by matching header names) onto the physical or virtual channels. + """ + if kind not in {PATTERN_KIND_AMPLITUDE, PATTERN_KIND_PHASE}: + raise ValueError(f"Unknown pattern kind: {kind!r}") + series = self.pattern_columns(asset, kind) + if channel is not None: + known = {*project.physical_channel_names, *project.virtual_channel_names} + if channel not in known: + raise ValueError(f"Unknown channel: {channel}") + return [ + ChannelPatternBinding( + channel=channel, + kind=kind, + plane=plane, + asset=asset, + column_index=0, + column=series[0].value_column, + ) + ] + channel_names = ( + project.virtual_channel_names if target == "virtual" else project.physical_channel_names + ) + mapping = load_hfss_summary_pattern( + self.assets.path(asset), channel_names, value_kind=kind + ) + column_index = {item.value_column: index for index, item in enumerate(series)} + return [ + ChannelPatternBinding( + channel=channel_name, + kind=kind, + plane=plane, + asset=asset, + column_index=column_index[item.value_column], + column=item.value_column, + ) + for channel_name, item in mapping.items() + ] + + def dictionary_preview(self, project: Project, axis: str) -> dict[str, Any]: + if axis not in AXES: + raise ValueError(f"Unknown DBF axis: {axis!r}") + context = self.context(project) + angles = np.linspace(DBF_SCAN_FOV[0], DBF_SCAN_FOV[1], DBF_SCAN_GRID_SIZE) + try: + matrix = context.dictionary.scan_matrix( + context.array, + angles, + axis=axis, + channel_patterns=context.channel_patterns, + ) + except ValueError as exc: + raise ProjectComputationError(str(exc)) from exc + report = dictionary_quality_report(matrix, angles) + settings = project.dbf_dictionary + capability_limited = report.channel_count <= 1 or settings.mode != DBF_DICT_CUSTOM + severity = report.severity + if severity == DBF_DICTIONARY_QUALITY_DANGER and capability_limited: + severity = DBF_DICTIONARY_QUALITY_WARNING + if severity not in { + DBF_DICTIONARY_QUALITY_OK, + DBF_DICTIONARY_QUALITY_WARNING, + DBF_DICTIONARY_QUALITY_DANGER, + }: + severity = DBF_DICTIONARY_QUALITY_WARNING + tables = { + "azimuth": context.dictionary.custom_azimuth_table, + "elevation": context.dictionary.custom_elevation_table, + } + return { + "axis": axis, + "angles": num_list(angles), + "phase_deg": encode_array(dictionary_phase_preview(matrix)), + "channel_count": int(matrix.shape[1]), + "quality": {**asdict(report), "severity": severity}, + "tables": { + name: ( + None + if table is None + else { + "channel_mode": table.channel_mode, + "value_format": table.value_format, + "rows": int(table.values.shape[0]), + "columns": list(table.column_names), + "is_2d": table.is_2d, + } + ) + for name, table in tables.items() + }, + } + + # ── Exports ────────────────────────────────────────────────────── + + def layout_document(self, project: Project) -> dict[str, Any]: + """Desktop-compatible v1 layout JSON including the evaluation block.""" + context = self.context(project) + _af, _az, _el, metrics = self._array_metrics(context) + return layout_to_v1(project, layout_evaluation(project, metrics, self.assets)) + + def report_snapshot(self, project: Project): # noqa: ANN201 + from .performance_report import PerformanceReportSnapshot + + context = self.context(project) + return PerformanceReportSnapshot( + array=context.array, + frequency_ghz=project.frequency_ghz, + ambiguity_margin_db=project.ambiguity_margin_db, + dbf_dictionary=context.dictionary, + element_pattern=context.element_pattern, + channel_patterns=context.channel_patterns, + current_config=self.layout_document(project), + app_version=APP_VERSION, + created_at=datetime.now().astimezone(), + ) + + +# ── Payload helpers ────────────────────────────────────────────────── + + +def axis_capability(metrics: ArrayMetrics) -> dict[str, bool]: + azimuth = metrics.azimuth_resolution is not None and metrics.x_aperture > 0 + elevation = metrics.elevation_resolution is not None and metrics.y_aperture > 0 + return {"azimuth": azimuth, "elevation": elevation, "two_d": azimuth and elevation} + + +def array_metrics_payload(metrics: ArrayMetrics) -> dict[str, Any]: + payload: dict[str, Any] = {} + for key, value in asdict(metrics).items(): + if isinstance(value, float): + payload[key] = num(value) + elif isinstance(value, tuple): + payload[key] = list(value) + else: + payload[key] = value + return payload + + +def angle_metrics_payload(metrics: DbfAngleMetrics) -> dict[str, Any]: + return { + "no_fold_left": num(metrics.no_fold_left), + "no_fold_right": num(metrics.no_fold_right), + "no_fold_width": num(metrics.no_fold_width), + "no_fold_max_abs_error": num(metrics.no_fold_max_abs_error), + "focus_max_abs_error": num(metrics.focus_max_abs_error), + "center_error": num(metrics.center_error), + "min_peak_margin_db": num(metrics.min_peak_margin_db), + "center_peak_margin_db": num(metrics.center_peak_margin_db), + "negative_cut_reason": CUT_REASON_CODES.get( + metrics.negative_cut_reason, metrics.negative_cut_reason + ), + "positive_cut_reason": CUT_REASON_CODES.get( + metrics.positive_cut_reason, metrics.positive_cut_reason + ), + } + + +def virtual_points_payload(array: AntennaArray) -> list[dict[str, Any]]: + groups: dict[tuple[float, float], list[str]] = defaultdict(list) + for point in array.virtual_points(): + key = (round(point.x, ROUND_DECIMALS), round(point.y, ROUND_DECIMALS)) + groups[key].append(f"{point.tx_name}-{point.rx_name}") + return [ + { + "x": x * HALF_LAMBDA_TO_LAMBDA, + "y": y * HALF_LAMBDA_TO_LAMBDA, + "count": len(pairs), + "pairs": pairs, + } + for (x, y), pairs in sorted(groups.items()) + ] + + +def pattern_status(project: Project) -> dict[str, str]: + """Amplitude/phase source state shown in the header: ideal, imported or mixed.""" + configured: dict[str, set[str]] = {PATTERN_KIND_AMPLITUDE: set(), PATTERN_KIND_PHASE: set()} + for binding in project.channel_patterns: + configured[binding.kind].add(binding.channel) + physical = project.physical_channel_names + virtual = project.virtual_channel_names + status: dict[str, str] = {} + for kind in (PATTERN_KIND_AMPLITUDE, PATTERN_KIND_PHASE): + physical_count = len(configured[kind] & set(physical)) + virtual_count = len(configured[kind] & set(virtual)) + if physical_count == 0 and virtual_count == 0: + imported = kind == PATTERN_KIND_AMPLITUDE and project.element_pattern is not None + status[kind] = "imported" if imported else "ideal" + continue + physical_full = bool(physical) and physical_count == len(physical) + virtual_full = bool(virtual) and virtual_count == len(virtual) + physical_whole = physical_count in (0, len(physical)) + virtual_whole = virtual_count in (0, len(virtual)) + whole = (physical_full or virtual_full) and physical_whole and virtual_whole + status[kind] = "imported" if whole else "mixed" + return status + + +def note_codes(metrics: ArrayMetrics) -> list[str]: + notes = [] + if metrics.duplicate_excess > 0: + notes.append("duplicate_virtual") + if metrics.azimuth_psl_db > -10.0: + notes.append("windowing") + if metrics.elevation_ambiguity_level == "High": + notes.append("ambiguity_high") + elif metrics.elevation_ambiguity_level == "Medium": + notes.append("ambiguity_medium") + return notes + + +_NOTE_TEXT_ZH = { + "duplicate_virtual": "存在重复虚拟通道", + "windowing": "建议加窗降低旁瓣", + "ambiguity_high": "俯仰模糊风险高", + "ambiguity_medium": "俯仰模糊风险中", +} + + +def layout_evaluation(project: Project, metrics: ArrayMetrics, assets: AssetStore) -> dict[str, Any]: + """The ``evaluation`` block of the desktop layout JSON (kept field-compatible).""" + half_wavelength_mm = project.wavelength_mm / 2.0 + utilization = metrics.unique_count / metrics.virtual_count if metrics.virtual_count else 0.0 + settings = project.dbf_dictionary + + def asset_name(asset: str | None) -> str | None: + if asset is None: + return None + try: + return assets.info(asset).filename + except KeyError: + return asset + + element_info: dict[str, Any] = {"mode": "isotropic"} + if project.element_pattern is not None: + element_info = { + "mode": "loaded", + "source": asset_name(project.element_pattern.asset), + "swap_axes": project.element_pattern.swap_axes, + } + channels = sorted({binding.channel for binding in project.channel_patterns}) + return { + "frequency_ghz": json_number(project.frequency_ghz, 6), + "ambiguity_margin_db": json_number(project.ambiguity_margin_db, 3), + "dbf_dictionary": { + "mode": settings.mode, + "custom_sources": { + "azimuth": asset_name(settings.azimuth_asset), + "elevation": asset_name(settings.elevation_asset), + }, + "custom_phase_reversed": settings.phase_reversed, + "custom_zero_phase_calibrated": settings.zero_phase_calibrated, + }, + "virtual_utilization": { + "unique_points": metrics.unique_count, + "virtual_channels": metrics.virtual_count, + "ratio": json_number(utilization, 6), + "duplicate_points": metrics.duplicate_excess, + }, + "az_aperture_mm": json_number(metrics.x_aperture * half_wavelength_mm, 3), + "az_aperture_lambda": json_number(metrics.x_aperture * HALF_LAMBDA_TO_LAMBDA, 9), + "az_resolution_deg": json_number(metrics.azimuth_resolution, 3), + "az_3db_bw_deg": json_number(metrics.azimuth_3db_beamwidth, 3), + "az_psl_db": json_number(metrics.azimuth_psl_db, 3), + "first_sidelobe": { + "level_db": json_number(metrics.azimuth_first_sidelobe_db, 3), + "az_deg": json_number(metrics.azimuth_first_sidelobe_angle, 3), + }, + "az_grating_lobe": { + "level_db": json_number(metrics.azimuth_grating_lobe_db, 3), + "az_deg": json_number(metrics.azimuth_grating_lobe_angle, 3), + }, + "az_islr_db": json_number(metrics.azimuth_islr_db, 3), + "el_3db_bw_deg": json_number(metrics.elevation_3db_beamwidth, 3), + "el_psl_db": json_number(metrics.elevation_psl_db, 3), + "psl_2d_worst_db": json_number(metrics.psl_db, 3), + "psl_2d_location_deg": { + "az": json_number(metrics.sidelobe_azimuth, 3), + "el": json_number(metrics.sidelobe_elevation, 3), + }, + "element_pattern": element_info, + "channel_patterns": { + "mode": "ideal" if not channels else "channel_patterns", + "configured_channels": len(channels), + "configured_series": len(project.channel_patterns), + }, + "notes": [_NOTE_TEXT_ZH[code] for code in note_codes(metrics)], + } diff --git a/src/virtual_array/gui.py b/src/virtual_array/gui.py deleted file mode 100644 index 8e25425..0000000 --- a/src/virtual_array/gui.py +++ /dev/null @@ -1,10275 +0,0 @@ -"""Canonical native PySide6 GUI for the MIMO Array Visualizer.""" - -from __future__ import annotations - -import json -import logging -import math -import re -import sys -from collections import defaultdict, deque -from copy import deepcopy -from dataclasses import dataclass -from datetime import datetime -from pathlib import Path - -import numpy as np -from PySide6 import QtCore, QtGui, QtWidgets - -from .app_state import load_state, save_state, state_path -from .dbf_dictionary import ( - DBF_DICTIONARY_QUALITY_DANGER, - DBF_DICTIONARY_QUALITY_WARNING, - DBF_DICT_CHANNEL_PATTERN, - DBF_DICT_CHANNEL_PATTERN_ZERO_REF, - DBF_DICT_CUSTOM, - DBF_DICT_IDEAL, - DBF_DICT_IDEAL_REVERSED, - CHANNEL_MODE_PHYSICAL, - CHANNEL_MODE_VIRTUAL, - DbfDictionaryConfig, - DbfDictionaryQualityReport, - DbfDictionaryTable, - dictionary_quality_report, - dictionary_phase_preview, - load_dbf_dictionary_table, -) -from .analysis import ( - AZIMUTH_FOV, - DBF_AMBIGUITY_MARGIN_DB, - DBF_SCAN_FOV, - DBF_SCAN_GRID_SIZE, - DBF_SCAN_STEP_DEG, - DbfAngleMetrics, - ELEVATION_FOV, - MAINLOBE_GUARD_AZ, - MAINLOBE_GUARD_EL, - ArrayMetrics, - calculate_metrics_and_psf, - dbf_angle_metrics_from_spectra, - dbf_2d_spectrum, - dbf_azimuth_spectrum_bank, - dbf_elevation_spectrum_bank, - dbf_peak_index as analysis_dbf_peak_index, - local_peak_indices, -) -from .element_pattern import ( - PATTERN_KIND_AMPLITUDE, - PATTERN_KIND_PHASE, - PATTERN_PLANE_ELEVATION, - PATTERN_PLANE_HORIZONTAL, - ChannelPatternSet, - ElementPattern, - format_pattern_cut_metrics, - load_hfss_pattern_series, - load_hfss_summary_pattern, - load_element_pattern, - pattern_cut_metrics, - virtual_channel_names, -) -from .geometry import AntennaArray, ArrayPoint -from .grid import GRID_STEP, snap_to_grid -from .logging_config import configure_logging, current_log_path, install_excepthook -from .native_theme import ( - TOKENS, - apply_native_theme, - fit_dialog_to_parent, - mark_callout, - mark_primary, - mark_quiet, - mark_workbench_role, -) -from .qt_plot import Figure, FigureCanvasTkAgg, MplButton, Rectangle, rcParams -from .qt_tk import filedialog, messagebox, tk, ttk -from .user_manual import ( - manual_chapter_html, - manual_chapter_search_text, - manual_chapters, -) -from .version import APP_VERSION - - -LOGGER = logging.getLogger(__name__) - - -def _resource_path(*parts: str) -> Path: - if hasattr(sys, "_MEIPASS"): - return Path(getattr(sys, "_MEIPASS")) / "virtual_array" / Path(*parts) - return Path(__file__).resolve().parent / Path(*parts) - - -APP_LOGO_UI_PATH = _resource_path("assets", "mimo_array_logo_48.png") -APP_LOGO_PNG_PATH = _resource_path("assets", "mimo_array_logo_256.png") -APP_LOGO_ICO_PATH = _resource_path("assets", "mimo_array_logo.ico") -APP_LOGO_ICNS_PATH = _resource_path("assets", "mimo_array_logo.icns") - -if sys.platform.startswith("win"): - rcParams["font.sans-serif"] = [ - "Microsoft YaHei UI", - "Microsoft YaHei", - "Segoe UI Variable Text", - "Segoe UI", - "SimHei", - "Noto Sans CJK SC", - "DejaVu Sans", - ] -elif sys.platform == "darwin": - rcParams["font.sans-serif"] = [ - "SF Pro Display", - "SF Pro Text", - "PingFang SC", - "Heiti SC", - "STHeiti", - "Arial Unicode MS", - ] -else: - rcParams["font.sans-serif"] = [ - "Noto Sans CJK SC", - "Noto Sans", - "WenQuanYi Micro Hei", - "DejaVu Sans", - ] -rcParams["axes.unicode_minus"] = False - -# ── Global constants ────────────────────────────────────────────────── -ROUND_DECIMALS = 9 -LAYOUT_CONFIG_VERSION = 1 -LOCAL_STATE_VERSION = 1 -LAYOUT_UNIT = "lambda" -LAYOUT_UNITS_LAMBDA = {"lambda", "λ"} -LEGACY_LAYOUT_UNITS_HALF_LAMBDA = {"lambda/2", "λ/2"} -MAX_TX_COUNT = 16 -MAX_RX_COUNT = 16 -MAX_HISTORY_STATES = 50 -AUTO_LAYOUT_SPACING = 2.0 -AUTO_LAYOUT_TX_Y = 4.0 -AUTO_LAYOUT_RX_Y = -4.0 -TITLE_SIZE = 13 -RESPONSE_MODE_AZIMUTH = "az" -RESPONSE_MODE_ELEVATION = "el" -RESPONSE_SIDELOBE_PROMINENCE_DB = 0.5 -RESPONSE_SIDELOBE_GUARD_CLEARANCE_DB = 0.5 -DBF_SCAN_INTERVAL_MS = 55 -DBF_DISPLAY_DB = "db" -DBF_DISPLAY_MAGNITUDE = "magnitude" -SUPPORTED_DBF_DISPLAY_MODES = (DBF_DISPLAY_DB, DBF_DISPLAY_MAGNITUDE) -DBF_MAJOR_ANGLE_TICKS = np.arange(-80.0, 81.0, 20.0) -DBF_MINOR_ANGLE_TICKS = np.arange(-90.0, 91.0, 10.0) -DBF_DB_Y_TICKS = np.arange(-40.0, 1.0, 10.0) -DBF_MAGNITUDE_Y_TICKS = np.linspace(0.0, 1.0, 6) -CHANNEL_PATTERN_TARGET_PHYSICAL = "physical" -CHANNEL_PATTERN_TARGET_VIRTUAL = "virtual" -LANGUAGE_ZH = "zh" -LANGUAGE_EN = "en" -LANGUAGE_JA = "ja" -SUPPORTED_LANGUAGES = (LANGUAGE_ZH, LANGUAGE_EN, LANGUAGE_JA) -LANGUAGE_LABELS = { - LANGUAGE_ZH: "中文", - LANGUAGE_EN: "English", - LANGUAGE_JA: "日本語", -} - -DEFAULT_FREQUENCY_GHZ = 77.0 -LIGHT_SPEED_MM_PER_NS = 299.792458 # mm/ns = GHz·mm - -DISPLAY_SCALE_LAMBDA = 0.5 -DISPLAY_GRID_STEP_LAMBDA = 0.5 -PHYSICAL_MAJOR_GRID_STEP_LAMBDA = 1.0 -PHYSICAL_AXIS_MIN_SPAN_LAMBDA = 4.0 -PHYSICAL_AXIS_PADDING_LAMBDA = 2.0 -TOOLBAR_ENTRY_WIDTH = 6 -TOOLBAR_GROUP_PAD_X = 0 -TOOLBAR_GROUP_PAD_Y = 0 - -# Window geometry -WINDOW_WIDTH = 1366 -WINDOW_HEIGHT = 768 -WINDOW_MIN_WIDTH = 1024 -WINDOW_MIN_HEIGHT = 650 -WINDOW_GEOMETRY_RE = re.compile( - r"^(?P\d+)x(?P\d+)(?:(?P[+-]\d+)(?P[+-]\d+))?$" -) - -# Figure DPI (fixed for consistent rendering across displays) -FIG_DPI = 100 - -# Figure sizes (inches → pixels at FIG_DPI) -PHYS_FIG_W = 5.8 -PHYS_FIG_H = 2.8 -VIRT_FIG_W = 5.8 -VIRT_FIG_H = 4.3 -RESPONSE_FIG_W = 5.8 -RESPONSE_FIG_H = 4.0 -PLOT_COLUMN_MIN_WIDTH = 380 -EVAL_PANEL_MIN_WIDTH = 380 -WORKSPACE_DEFAULT_PANE_WIDTH = WINDOW_WIDTH // 2 -DBF2D_CANVAS_SIZE = 310 -DBF2D_FIG_SIZE = DBF2D_CANVAS_SIZE / FIG_DPI - -NOTE_STYLES = { - "duplicate": ("WARN", "#c2410c"), - "windowing": ("TAPER", "#a16207"), - "ambiguity high": ("RISK", "#b91c1c"), - "ambiguity medium": ("WATCH", "#a16207"), - "none": ("OK", "#15803d"), -} - -UI_TEXT = { - "app_title": { - "zh": "MIMO阵列可视化工具 V{version}", - "en": "MIMO Array Visualizer V{version}", - "ja": "MIMOアレイ可視化ツール V{version}", - }, - "app_name": { - "zh": "MIMO阵列工作台", - "en": "MIMO Array Workbench", - "ja": "MIMOアレイワークベンチ", - }, - "app_subtitle": { - "zh": "阵列布局、虚拟孔径、响应曲线与DBF扫描", - "en": "Array layout, virtual aperture, and DBF response", - "ja": "アレイ配置、仮想開口、応答曲線、DBFスキャン", - }, - "accessibility_workspace_pages": { - "zh": "工作区页面", - "en": "Workspace pages", - "ja": "ワークスペースページ", - }, - "accessibility_plot_capability": { - "zh": "图表能力提示", - "en": "Plot capability message", - "ja": "チャート機能の案内", - }, - "accessibility_status_bar": { - "zh": "应用状态", - "en": "Application status", - "ja": "アプリケーション状態", - }, - "main_tab_physical_virtual": { - "zh": "物理与虚拟阵列", - "en": "Physical && Virtual", - "ja": "物理・仮想アレイ", - }, - "main_tab_1d": {"zh": "1D DBF", "en": "1D DBF", "ja": "1D DBF"}, - "main_tab_2d": {"zh": "2D DBF", "en": "2D DBF", "ja": "2D DBF"}, - "empty_azimuth_title": { - "zh": "当前阵列没有方位孔径", - "en": "No azimuth aperture in the current array", - "ja": "現在のアレイに方位開口がありません", - }, - "empty_elevation_title": { - "zh": "当前阵列没有俯仰孔径", - "en": "No elevation aperture in the current array", - "ja": "現在のアレイに仰角開口がありません", - }, - "empty_2d_title": { - "zh": "当前阵列不具备完整 2D 测角能力", - "en": "The current array has no complete 2D angle capability", - "ja": "現在のアレイは完全な 2D 測角に対応していません", - }, - "empty_array_body": { - "zh": "请增加 TX/RX 通道、拉开阵元间距,或使用底部的自动排阵。", - "en": "Add Tx/Rx channels, spread the elements, or use Auto Array below.", - "ja": "Tx/Rx チャネルを追加するか、素子間隔を広げるか、自動配置を使用してください。", - }, - "empty_2d_body": { - "zh": "方位和俯仰均需要有效孔径;只有一个方向可用时,请切换到 1D DBF。", - "en": "Both axes need aperture. If only one axis is available, use 1D DBF.", - "ja": "両軸に開口が必要です。一方向のみ有効な場合は 1D DBF を使用してください。", - }, - "empty_action_edit_array": { - "zh": "调整阵列", - "en": "Edit array", - "ja": "アレイを調整", - }, - "empty_action_view_1d": { - "zh": "转到 1D DBF", - "en": "Open 1D DBF", - "ja": "1D DBF を開く", - }, - "chip_frequency": {"zh": "频率", "en": "Frequency", "ja": "周波数"}, - "chip_dictionary": {"zh": "DBF", "en": "DBF", "ja": "DBF"}, - "chip_pattern": {"zh": "幅相", "en": "Amp / Phase", "ja": "振幅/位相"}, - "chip_dict_ideal": {"zh": "理想", "en": "Ideal", "ja": "理想"}, - "chip_dict_reversed": {"zh": "反向相位", "en": "Reversed", "ja": "逆位相"}, - "chip_dict_channel": {"zh": "通道校准", "en": "Channel cal", "ja": "チャネル校正"}, - "chip_dict_custom": {"zh": "已导入", "en": "Imported", "ja": "読込済み"}, - "chip_virtual_channels": {"zh": "虚拟通道", "en": "Virtual", "ja": "仮想"}, - "chip_az_resolution": {"zh": "方位分辨率", "en": "Az Res", "ja": "方位分解能"}, - "chip_el_resolution": {"zh": "俯仰分辨率", "en": "El Res", "ja": "仰角分解能"}, - "status_initial": { - "zh": "拖动TX/RX通道调整物理阵列,松开后自动刷新虚拟阵列和响应。", - "en": "Drag Tx/Rx channels in the physical array. Release to refresh the virtual array and responses.", - "ja": "物理アレイ上のTX/RXチャネルをドラッグします。離すと仮想アレイと応答を更新します。", - }, - "status_ready": {"zh": "就绪", "en": "Ready", "ja": "準備完了"}, - "menu_config": {"zh": "配置", "en": "Configuration", "ja": "設定"}, - "menu_import_layout": { - "zh": "导入阵面JSON", - "en": "Import Array JSON", - "ja": "アレイJSONを読み込み", - }, - "menu_export_layout": { - "zh": "导出阵面JSON", - "en": "Export Array JSON", - "ja": "アレイJSONを書き出し", - }, - "menu_export_report": { - "zh": "输出报告…", - "en": "Export Report…", - "ja": "レポートを出力…", - }, - "angle_image_overwrite_title": { - "zh": "覆盖测角误差图片", - "en": "Replace angle-error image", - "ja": "測角誤差画像を置き換え", - }, - "angle_image_overwrite_question": { - "zh": "文件已存在,是否覆盖?\n{file}", - "en": "The file already exists. Replace it?\n{file}", - "ja": "ファイルはすでに存在します。置き換えますか?\n{file}", - }, - "angle_image_exporting_status": { - "zh": "正在生成 ±90° 测角误差图片…", - "en": "Generating the ±90° angle-error image…", - "ja": "±90°測角誤差画像を生成中…", - }, - "angle_image_progress_title": { - "zh": "生成测角误差图片", - "en": "Generate angle-error image", - "ja": "測角誤差画像を生成", - }, - "angle_image_canceling_status": { - "zh": "正在安全取消,当前绘图步骤完成后停止…", - "en": "Cancelling safely after the current rendering step…", - "ja": "現在の描画ステップ完了後に安全に中止します…", - }, - "angle_image_canceled_status": { - "zh": "已取消测角误差图片生成", - "en": "Angle-error image generation cancelled", - "ja": "測角誤差画像の生成をキャンセルしました", - }, - "angle_image_export_failed_title": { - "zh": "测角误差图片生成失败", - "en": "Angle-error image failed", - "ja": "測角誤差画像の生成に失敗", - }, - "angle_image_exported_status": { - "zh": "已输出测角误差图片:{file}", - "en": "Exported angle-error image: {file}", - "ja": "測角誤差画像を出力しました:{file}", - }, - "angle_image_exported_title": { - "zh": "测角误差图片已生成", - "en": "Angle-error image created", - "ja": "測角誤差画像を生成しました", - }, - "angle_image_exported_message": { - "zh": "PNG 图片已保存到:\n{file}", - "en": "The PNG image was saved to:\n{file}", - "ja": "PNG画像を保存しました:\n{file}", - }, - "report_overwrite_title": { - "zh": "覆盖性能报告", - "en": "Replace performance report", - "ja": "性能レポートを置き換え", - }, - "report_overwrite_question": { - "zh": "文件已存在,是否覆盖?\n{file}", - "en": "The file already exists. Replace it?\n{file}", - "ja": "ファイルはすでに存在します。置き換えますか?\n{file}", - }, - "report_exporting_status": { - "zh": "正在生成当前配置性能报告…", - "en": "Generating the current performance report…", - "ja": "現在の設定性能レポートを生成中…", - }, - "report_progress_title": { - "zh": "生成性能报告", - "en": "Generate performance report", - "ja": "性能レポートを生成", - }, - "report_cancel_button": { - "zh": "取消", - "en": "Cancel", - "ja": "キャンセル", - }, - "report_canceling_status": { - "zh": "正在安全取消,当前绘图步骤完成后停止…", - "en": "Cancelling safely after the current rendering step…", - "ja": "現在の描画ステップ完了後に安全に中止します…", - }, - "report_canceled_status": { - "zh": "已取消性能报告生成", - "en": "Performance report generation cancelled", - "ja": "性能レポートの生成をキャンセルしました", - }, - "report_export_failed_title": { - "zh": "性能报告生成失败", - "en": "Performance report failed", - "ja": "性能レポートの生成に失敗", - }, - "report_exported_status": { - "zh": "已输出性能报告:{file}", - "en": "Exported performance report: {file}", - "ja": "性能レポートを出力しました:{file}", - }, - "report_exported_title": { - "zh": "性能报告已生成", - "en": "Performance report created", - "ja": "性能レポートを生成しました", - }, - "report_exported_message": { - "zh": "PDF报告已保存到:\n{file}{data_note}", - "en": "The PDF report was saved to:\n{file}{data_note}", - "ja": "PDFレポートを保存しました:\n{file}{data_note}", - }, - "report_exported_data_note": { - "zh": "\n\n可复现数据包:\n{directory}", - "en": "\n\nReproducibility data package:\n{directory}", - "ja": "\n\n再現用データパッケージ:\n{directory}", - }, - "menu_channel_patterns": { - "zh": "配置通道幅相", - "en": "Configure Channel Amp/Phase", - "ja": "チャネル振幅/位相を設定", - }, - "menu_dbf_dictionary": { - "zh": "配置DBF字典", - "en": "Configure DBF Dictionary", - "ja": "DBF辞書を設定", - }, - "menu_language": {"zh": "语言", "en": "Language", "ja": "言語"}, - "menu_file": {"zh": "文件", "en": "File", "ja": "ファイル"}, - "menu_edit": {"zh": "编辑", "en": "Edit", "ja": "編集"}, - "menu_view": {"zh": "视图", "en": "View", "ja": "表示"}, - "menu_help": {"zh": "帮助", "en": "Help", "ja": "ヘルプ"}, - "menu_undo": {"zh": "撤销阵列编辑", "en": "Undo layout edit", "ja": "配置編集を元に戻す"}, - "menu_redo": {"zh": "重做阵列编辑", "en": "Redo layout edit", "ja": "配置編集をやり直す"}, - "menu_about": {"zh": "关于", "en": "About", "ja": "このアプリについて"}, - "menu_user_manual": {"zh": "使用说明", "en": "User Manual", "ja": "使用説明"}, - "manual_title": {"zh": "MIMO阵列可视化工具使用说明", "en": "MIMO Array Visualizer User Manual", "ja": "MIMOアレイ可視化ツール使用説明"}, - "manual_search_placeholder": { - "zh": "搜索全部章节", - "en": "Search all chapters", - "ja": "すべての章を検索", - }, - "menu_user_manual_open": { - "zh": "打开完整说明", - "en": "Open full manual", - "ja": "完整な説明書を開く", - }, - "manual_contents": {"zh": "章节目录", "en": "Contents", "ja": "目次"}, - "manual_contents_accessible": { - "zh": "使用说明章节目录", - "en": "User manual chapter list", - "ja": "使用説明の章一覧", - }, - "manual_body_accessible": { - "zh": "当前章节内容", - "en": "Current manual chapter", - "ja": "現在の章の内容", - }, - "manual_search_result_count": { - "zh": "匹配 {count} 个章节", - "en": "{count} matching chapters", - "ja": "{count} 章に一致", - }, - "manual_search_position": { - "zh": "{current} / {total}", - "en": "{current} / {total}", - "ja": "{current} / {total}", - }, - "manual_search_no_results": { - "zh": "未找到匹配章节", - "en": "No matching chapters", - "ja": "一致する章がありません", - }, - "manual_search_no_results_detail": { - "zh": "请换用功能名、按钮名、文件格式或状态提示进行搜索。", - "en": "Try a feature, button, file format, or status message.", - "ja": "機能名、ボタン名、ファイル形式、またはステータス表示で検索してください。", - }, - "manual_previous_result": { - "zh": "上一个匹配章节", - "en": "Previous matching chapter", - "ja": "前の一致章", - }, - "manual_next_result": { - "zh": "下一个匹配章节", - "en": "Next matching chapter", - "ja": "次の一致章", - }, - "about_title": {"zh": "关于 MIMO阵列工作台", "en": "About MIMO Array Workbench", "ja": "MIMOアレイワークベンチについて"}, - "about_message": { - "zh": "MIMO阵列工作台 V{version}\n日志文件:{log_path}", - "en": "MIMO Array Workbench V{version}\nLog file: {log_path}", - "ja": "MIMOアレイワークベンチ V{version}\nログファイル:{log_path}", - }, - "language_zh": {"zh": "中文", "en": "Chinese", "ja": "中国語"}, - "language_en": {"zh": "英文", "en": "English", "ja": "英語"}, - "language_ja": {"zh": "日语", "en": "Japanese", "ja": "日本語"}, - "freq_label": {"zh": "频率(GHz)", "en": "Freq (GHz)", "ja": "周波数(GHz)"}, - "margin_label": {"zh": "竞争峰裕量(dB)", "en": "Margin (dB)", "ja": "ピーク余裕(dB)"}, - "auto_label": {"zh": "自动排阵", "en": "Auto", "ja": "自動配置"}, - "auto_apply": {"zh": "应用阵列", "en": "Apply Array", "ja": "配置を適用"}, - "physical_add_tx": {"zh": "+TX", "en": "+TX", "ja": "+TX"}, - "physical_add_rx": {"zh": "+RX", "en": "+RX", "ja": "+RX"}, - "physical_delete": {"zh": "删除", "en": "Delete", "ja": "削除"}, - "physical_clear": {"zh": "清空", "en": "Clear", "ja": "クリア"}, - "dbf_play_compact": {"zh": "播放", "en": "Play", "ja": "再生"}, - "dbf_pause_compact": {"zh": "暂停", "en": "Pause", "ja": "一時停止"}, - "dbf_resume_compact": {"zh": "继续", "en": "Resume", "ja": "再開"}, - "dbf_stop_compact": {"zh": "停止", "en": "Stop", "ja": "停止"}, - "pattern_ideal": { - "zh": "幅度:理想/相位:理想", - "en": "Amp:ideal/Phase:ideal", - "ja": "振幅:理想/位相:理想", - }, - "pattern_amp_phase_status": { - "zh": "幅度:{amplitude}/相位:{phase}", - "en": "Amp:{amplitude}/Phase:{phase}", - "ja": "振幅:{amplitude}/位相:{phase}", - }, - "pattern_state_ideal": {"zh": "理想", "en": "ideal", "ja": "理想"}, - "pattern_state_imported": {"zh": "导入", "en": "imported", "ja": "読込"}, - "pattern_state_mixed": {"zh": "混合", "en": "mixed", "ja": "混在"}, - "overview_title": {"zh": "阵列概览", "en": "Array Overview", "ja": "アレイ概要"}, - "angle_eval_title": {"zh": "测角评估", "en": "Angle Evaluation", "ja": "測角評価"}, - "eval_tab_overview": {"zh": "总览", "en": "Overview", "ja": "概要"}, - "eval_tab_angle": {"zh": "测角", "en": "Angle", "ja": "測角"}, - "eval_tab_dbf2d": {"zh": "2D DBF", "en": "2D DBF", "ja": "2D DBF"}, - "physical_title": {"zh": "物理阵列布局", "en": "Physical Array", "ja": "物理アレイ配置"}, - "virtual_title": {"zh": "虚拟阵列", "en": "Virtual Array", "ja": "仮想アレイ"}, - "virtual_info": { - "zh": "虚拟 {unique}/{total} | 重复 {duplicate} | X {x} | Y {y}", - "en": "Virtual {unique}/{total} | Dup {duplicate} | X {x} | Y {y}", - "ja": "仮想 {unique}/{total} | 重複 {duplicate} | X {x} | Y {y}", - }, - "virtual_pairs_more": {"zh": ", ...(共{count}组)", "en": ", ... ({count} pairs)", "ja": ", ...(計{count}組)"}, - "virtual_hover": { - "zh": "({x:g} λ, {y:g} λ)\n重合数量:{count}\n{pairs}", - "en": "({x:g} λ, {y:g} λ)\nMultiplicity: {count}\n{pairs}", - "ja": "({x:g} λ, {y:g} λ)\n重複数:{count}\n{pairs}", - }, - "unique_point": {"zh": "唯一点", "en": "unique point", "ja": "一意点"}, - "duplicate_point": {"zh": "重复点", "en": "duplicate point", "ja": "重複点"}, - "response_title": {"zh": "{mode}响应", "en": "{mode} Response", "ja": "{mode}応答"}, - "pattern_cut_label": {"zh": "{mode}方向图", "en": "{mode} pattern", "ja": "{mode}パターン"}, - "dbf_title": { - "zh": "{mode}DBF字典角谱", - "en": "{mode} DBF Dictionary Spectrum", - "ja": "{mode}DBF辞書角度スペクトル", - }, - "axis_az_angle": {"zh": "方位角(°)", "en": "Azimuth angle (deg)", "ja": "方位角(°)"}, - "axis_el_angle": {"zh": "俯仰角(°)", "en": "Elevation angle (deg)", "ja": "仰角(°)"}, - "axis_gain": {"zh": "归一化增益(dB)", "en": "Normalized gain (dB)", "ja": "正規化利得(dB)"}, - "axis_magnitude": {"zh": "归一化模值", "en": "Normalized magnitude", "ja": "正規化振幅"}, - "dbf_axis_correlation_db": {"zh": "相关系数(dB)", "en": "Correlation (dB)", "ja": "相関係数(dB)"}, - "dbf_axis_correlation_mag": {"zh": "相关系数模值", "en": "Correlation magnitude", "ja": "相関係数振幅"}, - "max_sidelobe": {"zh": "最大旁瓣", "en": "Max sidelobe", "ja": "最大サイドローブ"}, - "guard_edge_max": {"zh": "保护区边界最大值", "en": "Guard-edge max", "ja": "ガード端最大値"}, - "grating_lobe": {"zh": "栅瓣", "en": "Grating lobe", "ja": "グレーティングローブ"}, - "grating_lobe_max": { - "zh": "栅瓣=最大旁瓣", - "en": "Grating lobe = max sidelobe", - "ja": "グレーティングローブ=最大サイドローブ", - }, - "gain_value": {"zh": "增益 = {value:.2f} dB", "en": "Gain = {value:.2f} dB", "ja": "利得 = {value:.2f} dB"}, - "magnitude_value": {"zh": "模值 = {value:.3f}", "en": "Magnitude = {value:.3f}", "ja": "振幅 = {value:.3f}"}, - "dbf_correlation_db_value": {"zh": "相关系数 = {value:.2f} dB", "en": "Correlation = {value:.2f} dB", "ja": "相関係数 = {value:.2f} dB"}, - "dbf_correlation_mag_value": {"zh": "相关系数 = {value:.3f}", "en": "Correlation = {value:.3f}", "ja": "相関係数 = {value:.3f}"}, - "dbf2d_hover": { - "zh": "方位 = {az:+.1f}°\n俯仰 = {el:+.1f}°\n{value}", - "en": "Az = {az:+.1f} deg\nEl = {el:+.1f} deg\n{value}", - "ja": "方位 = {az:+.1f}°\n仰角 = {el:+.1f}°\n{value}", - }, - "psl_label": {"zh": "{mode} PSL:{value:.2f} dB", "en": "{mode} PSL: {value:.2f} dB", "ja": "{mode} PSL:{value:.2f} dB"}, - "az": {"zh": "方位", "en": "Azimuth", "ja": "方位"}, - "el": {"zh": "俯仰", "en": "Elevation", "ja": "仰角"}, - "az_short": {"zh": "方位", "en": "Az", "ja": "方位"}, - "el_short": {"zh": "俯仰", "en": "El", "ja": "仰角"}, - "legend_true_angle": {"zh": "真实角", "en": "true angle", "ja": "真角度"}, - "legend_peak": {"zh": "峰值", "en": "peak", "ja": "ピーク"}, - "dbf_info": { - "zh": "真实角:{true:+.1f}°\n峰值角:{peak:+.1f}°\n{frame}", - "en": "True angle: {true:+.1f} deg\nPeak angle: {peak:+.1f} deg\n{frame}", - "ja": "真角度:{true:+.1f}°\nピーク角:{peak:+.1f}°\n{frame}", - }, - "reference_frame": {"zh": "参考:0°", "en": "Reference: 0 deg", "ja": "基準:0°"}, - "frame_label": {"zh": "帧:{frame}/{total}", "en": "Frame: {frame}/{total}", "ja": "フレーム:{frame}/{total}"}, - "dbf_play_status": { - "zh": "正在播放{mode}DBF角谱:-90°到+90°。", - "en": "Playing {mode} DBF spectra from -90 deg to +90 deg.", - "ja": "{mode}DBF角度スペクトルを再生中:-90°から+90°。", - }, - "dbf_play_status_invalid": { - "zh": "频率输入已恢复,正在播放{mode}DBF角谱。", - "en": "Invalid frequency restored. Playing {mode} DBF spectra.", - "ja": "無効な周波数を復元し、{mode}DBF角度スペクトルを再生中。", - }, - "dbf_pause_status": { - "zh": "{mode}DBF角谱已暂停在{angle:+.1f}°。", - "en": "Paused {mode} DBF spectrum at {angle:+.1f} deg.", - "ja": "{mode}DBF角度スペクトルを{angle:+.1f}°で一時停止。", - }, - "dbf_resume_status": { - "zh": "继续播放{mode}DBF角谱动画。", - "en": "Resumed {mode} DBF spectrum animation.", - "ja": "{mode}DBF角度スペクトルアニメーションを再開。", - }, - "dbf_complete_status": { - "zh": "{mode}DBF角谱动画播放完成。", - "en": "{mode} DBF spectrum animation complete.", - "ja": "{mode}DBF角度スペクトルアニメーションが完了。", - }, - "dbf2d_title": {"zh": " 2D DBF热图 ", "en": " 2D DBF Heatmap ", "ja": " 2D DBFヒートマップ "}, - "dbf2d_plot_title": {"zh": "2D DBF角谱", "en": "2D DBF Spectrum", "ja": "2D DBF角度スペクトル"}, - "dbf2d_play_az": {"zh": "播放方位", "en": "Play Az", "ja": "方位再生"}, - "dbf2d_pause_az": {"zh": "暂停方位", "en": "Pause Az", "ja": "方位一時停止"}, - "dbf2d_play_el": {"zh": "播放俯仰", "en": "Play El", "ja": "仰角再生"}, - "dbf2d_pause_el": {"zh": "暂停俯仰", "en": "Pause El", "ja": "仰角一時停止"}, - "dbf2d_stop": {"zh": "停止2D", "en": "Stop 2D", "ja": "2D停止"}, - "dbf2d_status": { - "zh": "方位{az:+.0f}° 俯仰{el:+.0f}° {frame}/{total}", - "en": "Az {az:+.0f} deg El {el:+.0f} deg {frame}/{total}", - "ja": "方位{az:+.0f}° 仰角{el:+.0f}° {frame}/{total}", - }, - "dbf2d_heatmap_info": { - "zh": "真值:方位 {az:+.0f}°,俯仰 {el:+.0f}°\n峰值:方位 {peak_az:+.0f}°,俯仰 {peak_el:+.0f}°", - "en": "True: Az {az:+.0f} deg, El {el:+.0f} deg\nPeak: Az {peak_az:+.0f} deg, El {peak_el:+.0f} deg", - "ja": "真値:方位 {az:+.0f}°,仰角 {el:+.0f}°\nピーク:方位 {peak_az:+.0f}°,仰角 {peak_el:+.0f}°", - }, - "dbf2d_peak_delta": { - "zh": "峰值偏差\n方位 {az:+.0f}° | 俯仰 {el:+.0f}°", - "en": "Peak delta\nAz {az:+.0f} deg | El {el:+.0f} deg", - "ja": "ピーク偏差\n方位 {az:+.0f}° | 仰角 {el:+.0f}°", - }, - "dbf2d_colorbar_label": {"zh": "相关系数(dB)", "en": "Correlation (dB)", "ja": "相関係数(dB)"}, - "dbf2d_colorbar_label_mag": {"zh": "相关系数模值", "en": "Correlation magnitude", "ja": "相関係数振幅"}, - "dbf_display_label": {"zh": "DBF显示", "en": "DBF", "ja": "DBF表示"}, - "dbf_display_db": {"zh": "dB", "en": "dB", "ja": "dB"}, - "dbf_display_magnitude": {"zh": "模值", "en": "Mag.", "ja": "振幅"}, - "dbf_display_changed": { - "zh": "DBF显示已切换为{mode}。", - "en": "DBF display switched to {mode}.", - "ja": "DBF表示を{mode}に切り替えました。", - }, - "dbf2d_running": { - "zh": "正在播放2D DBF:{axes}。", - "en": "Playing 2D DBF: {axes}.", - "ja": "2D DBF再生中:{axes}。", - }, - "dbf2d_paused_axis": { - "zh": "已暂停2D DBF的{axis}扫描。", - "en": "Paused 2D DBF {axis} scan.", - "ja": "2D DBFの{axis}走査を一時停止。", - }, - "dbf2d_dragged": { - "zh": "已拖动2D DBF真实角:方位 {az:+.0f}°,俯仰 {el:+.0f}°。", - "en": "Moved 2D DBF true angle: Az {az:+.0f} deg, El {el:+.0f} deg.", - "ja": "2D DBF真角度を移動:方位 {az:+.0f}°,仰角 {el:+.0f}°。", - }, - "dbf2d_stopped": { - "zh": "已停止2D DBF扫描。", - "en": "Stopped 2D DBF scan.", - "ja": "2D DBF走査を停止しました。", - }, - "dbf_dictionary_title": { - "zh": "DBF字典配置", - "en": "DBF Dictionary", - "ja": "DBF辞書設定", - }, - "dbf_dict_source_title": {"zh": "字典来源", "en": "Dictionary Source", "ja": "辞書ソース"}, - "dbf_dict_import_title": {"zh": "导入配置", "en": "Import Setup", "ja": "読込設定"}, - "dbf_dict_calibration_title": {"zh": "校准选项", "en": "Calibration", "ja": "校正オプション"}, - "dbf_dict_locate_angle": {"zh": "定位角度", "en": "Locate angle", "ja": "角度を検索"}, - "dbf_dict_fit_columns": {"zh": "自动列宽", "en": "Auto width", "ja": "自動列幅"}, - "dbf_dict_fit_columns_tooltip": { - "zh": "根据表头和单元格内容重新计算预览列宽;不会修改字典数据。", - "en": "Resize preview columns from their headers and cell contents; dictionary data is unchanged.", - "ja": "見出しとセル内容に合わせてプレビュー列幅を再計算します。辞書データは変更しません。", - }, - "dbf_dict_pending": { - "zh": "待应用:{mode}", - "en": "Pending: {mode}", - "ja": "適用待ち:{mode}", - }, - "dbf_dict_cancel": {"zh": "取消", "en": "Cancel", "ja": "キャンセル"}, - "dbf_dict_builtin_file_state": { - "zh": "文件状态:内置字典 · {rows}行 × {cols}列", - "en": "File status: built-in dictionary · {rows} rows × {cols} columns", - "ja": "ファイル状態:内蔵辞書 · {rows}行 × {cols}列", - }, - "dbf_dict_custom_file_state": { - "zh": "文件状态:方位 {az} · 俯仰 {el}", - "en": "File status: Az {az} · El {el}", - "ja": "ファイル状態:方位 {az} · 仰角 {el}", - }, - "dbf_dictionary_mode_title": {"zh": " 字典模式 ", "en": " Dictionary Mode ", "ja": " 辞書モード "}, - "dbf_dictionary_preview_title": {"zh": " 字典预览 ", "en": " Dictionary Preview ", "ja": " 辞書プレビュー "}, - "dbf_dict_ideal": {"zh": "理想几何字典", "en": "Ideal geometric", "ja": "理想幾何辞書"}, - "dbf_dict_reversed": {"zh": "理想反向相位字典", "en": "Ideal reversed phase", "ja": "理想逆位相辞書"}, - "dbf_dict_channel": {"zh": "通道幅相校准字典", "en": "Channel amp/phase dictionary", "ja": "チャネル振幅/位相辞書"}, - "dbf_dict_custom": {"zh": "导入CSV/XLSX字典", "en": "Imported CSV/XLSX", "ja": "CSV/XLSX辞書"}, - "dbf_dict_custom_options": {"zh": "导入字典选项", "en": "Imported Options", "ja": "読込辞書オプション"}, - "dbf_dict_phase_reverse": { - "zh": "导入字典相位反向", - "en": "Reverse imported phase", - "ja": "読込位相を反転", - }, - "dbf_dict_zero_calibrate": { - "zh": "导入字典按0°相位校准", - "en": "0 deg phase calibrate imported", - "ja": "読込辞書を0°位相校正", - }, - "dbf_dict_axis": {"zh": "预览轴", "en": "Preview axis", "ja": "プレビュー軸"}, - "dbf_dict_load": {"zh": "加载CSV/XLSX", "en": "Load CSV/XLSX", "ja": "CSV/XLSX読込"}, - "dbf_dict_load_az": {"zh": "加载方位字典", "en": "Load Az", "ja": "方位辞書読込"}, - "dbf_dict_load_el": {"zh": "加载俯仰字典", "en": "Load El", "ja": "仰角辞書読込"}, - "dbf_dict_clear": {"zh": "清除导入字典", "en": "Clear imported", "ja": "読込辞書をクリア"}, - "dbf_dict_clear_az": {"zh": "清除方位", "en": "Clear Az", "ja": "方位クリア"}, - "dbf_dict_clear_el": {"zh": "清除俯仰", "en": "Clear El", "ja": "仰角クリア"}, - "dbf_dict_apply": {"zh": "应用字典", "en": "Apply Dictionary", "ja": "辞書を適用"}, - "dbf_dict_preview_phase": {"zh": "字典相位矩阵", "en": "Dictionary phase matrix", "ja": "辞書位相行列"}, - "dbf_dict_preview_status": { - "zh": "{mode} | {rows}角度 × {cols}通道", - "en": "{mode} | {rows} angles × {cols} channels", - "ja": "{mode} | {rows}角度 × {cols}チャネル", - }, - "dbf_dict_quality_unavailable": { - "zh": "质量提示:暂无可评估的字典矩阵。(仅供参考,不影响应用)", - "en": "Quality note: no dictionary matrix to evaluate. (Advisory only; it does not block Apply.)", - "ja": "品質メモ:評価できる辞書行列がありません。(参考表示のみ。適用は妨げません)", - }, - "dbf_dict_quality_ok": { - "zh": "质量提示:正常。竞争峰模糊行 {ambiguous_rows};零范数行 {zeros};非近邻有效秩 {rank}/{rank_rows}。(仅供参考,不影响应用)", - "en": "Quality note: OK. Competitor-ambiguous rows {ambiguous_rows}; zero-norm rows {zeros}; non-neighbor rank {rank}/{rank_rows}. (Advisory only; it does not block Apply.)", - "ja": "品質メモ:正常。競合ピーク曖昧行 {ambiguous_rows};ゼロノルム行 {zeros};非近傍有効ランク {rank}/{rank_rows}。(参考表示のみ。適用は妨げません)", - }, - "dbf_dict_quality_warning": { - "zh": "质量提示:注意。竞争峰模糊行 {ambiguous_rows};零范数行 {zeros};非近邻有效秩 {rank}/{rank_rows}。理想字典多为阵列几何/通道数限制;导入字典可再查角度列、通道顺序或校准设置。(仅供参考,不影响应用)", - "en": "Quality note: Watch. Competitor-ambiguous rows {ambiguous_rows}; zero-norm rows {zeros}; non-neighbor rank {rank}/{rank_rows}. For ideal dictionaries this is usually array geometry/channel count; for imports, check angle columns, channel order, or calibration. (Advisory only; it does not block Apply.)", - "ja": "品質メモ:注意。競合ピーク曖昧行 {ambiguous_rows};ゼロノルム行 {zeros};非近傍有効ランク {rank}/{rank_rows}。理想辞書ではアレイ幾何/チャネル数の制限が主因です。読込辞書では角度列、チャネル順、校正設定を確認してください。(参考表示のみ。適用は妨げません)", - }, - "dbf_dict_quality_danger": { - "zh": "质量提示:风险。竞争峰模糊行 {ambiguous_rows};零范数行 {zeros};非近邻有效秩 {rank}/{rank_rows}。理想字典通常表示阵列几何在这些角度区分度不足;导入字典则建议检查角度列、通道顺序或校准设置。(仅供参考,不影响应用)", - "en": "Quality note: Risk. Competitor-ambiguous rows {ambiguous_rows}; zero-norm rows {zeros}; non-neighbor rank {rank}/{rank_rows}. For ideal dictionaries this means the array geometry has weak separation at those angles; for imports, check angle columns, channel order, or calibration. (Advisory only; it does not block Apply.)", - "ja": "品質メモ:リスク。競合ピーク曖昧行 {ambiguous_rows};ゼロノルム行 {zeros};非近傍有効ランク {rank}/{rank_rows}。理想辞書では該当角度でアレイ幾何の分離が弱いことを示します。読込辞書では角度列、チャネル順、校正設定を確認してください。(参考表示のみ。適用は妨げません)", - }, - "dbf_dict_file_status": { - "zh": "{axis}:{file}", - "en": "{axis}: {file}", - "ja": "{axis}:{file}", - }, - "dbf_dict_no_file": {"zh": "未加载", "en": "not loaded", "ja": "未読込"}, - "dbf_dict_custom_loaded": { - "zh": "已加载{axis}DBF字典:{file}。", - "en": "Loaded {axis} DBF dictionary: {file}.", - "ja": "{axis}DBF辞書を読み込みました:{file}。", - }, - "dbf_dict_custom_failed": { - "zh": "加载DBF字典失败", - "en": "Load DBF dictionary failed", - "ja": "DBF辞書の読み込みに失敗", - }, - "dbf_dict_applied": { - "zh": "已应用DBF字典:{mode}。", - "en": "Applied DBF dictionary: {mode}.", - "ja": "DBF辞書を適用しました:{mode}。", - }, - "dbf_dict_need_file": { - "zh": "请先加载当前预览轴的CSV/XLSX字典文件。", - "en": "Load the CSV/XLSX dictionary for the current preview axis first.", - "ja": "現在のプレビュー軸のCSV/XLSX辞書ファイルを先に読み込んでください。", - }, - "dbf_dict_need_axis_files": { - "zh": "自定义DBF字典至少需要加载方位或俯仰其中一个文件。", - "en": "Custom DBF dictionary requires at least one azimuth or elevation file.", - "ja": "カスタムDBF辞書には方位または仰角の少なくとも1ファイルが必要です。", - }, - "channel_dialog_title": { - "zh": "配置通道幅相", - "en": "Configure Channel Amp/Phase", - "ja": "チャネル振幅/位相を設定", - }, - "summary_csv_title": {"zh": " 汇总文件 ", "en": " Summary Files ", "ja": " 集約ファイル "}, - "summary_target_label": {"zh": "导入目标", "en": "Import target", "ja": "読込先"}, - "summary_target_physical": {"zh": "物理通道", "en": "Physical", "ja": "物理"}, - "summary_target_virtual": {"zh": "虚拟通道", "en": "Virtual", "ja": "仮想"}, - "physical_channels_title": { - "zh": " 通道列表 ", - "en": " Channel List ", - "ja": " チャネル一覧 ", - }, - "load_summary": {"zh": "加载{label}汇总", "en": "Load {label} Summary", "ja": "{label}集約を読み込み"}, - "set_pattern": {"zh": "设置{label}", "en": "Set {label}", "ja": "{label}を設定"}, - "clear_all": {"zh": "全部清空", "en": "Clear All", "ja": "すべてクリア"}, - "clear_channel": {"zh": "清空通道", "en": "Clear Channel", "ja": "チャネルをクリア"}, - "done": {"zh": "完成", "en": "Done", "ja": "完了"}, - "column_channel": {"zh": "通道", "en": "Channel", "ja": "チャネル"}, - "select_channel_first": { - "zh": "请先选择一个通道。", - "en": "Select one channel first.", - "ja": "先にチャネルを1つ選択してください。", - }, - "channel_patterns_title": {"zh": "通道方向图", "en": "Channel patterns", "ja": "チャネルパターン"}, - "channel_cleared": { - "zh": "已清空通道方向图:{channel}。", - "en": "Cleared channel patterns: {channel}.", - "ja": "チャネルパターンをクリア:{channel}。", - }, - "channel_already_ideal": { - "zh": "通道方向图已经是理想状态。", - "en": "Channel patterns already ideal.", - "ja": "チャネルパターンは既に理想状態です。", - }, - "channel_all_cleared": { - "zh": "已清空所有通道方向图。", - "en": "Cleared all channel patterns.", - "ja": "すべてのチャネルパターンをクリアしました。", - }, - "load_summary_title": { - "zh": "加载{label}汇总文件", - "en": "Load {label} summary file", - "ja": "{label}集約ファイルを読み込み", - }, - "load_channel_title": { - "zh": "加载{channel}的{label}", - "en": "Load {label} for {channel}", - "ja": "{channel}の{label}を読み込み", - }, - "summary_loaded": { - "zh": "已加载{label}汇总:{file}。", - "en": "Loaded {label} summary: {file}.", - "ja": "{label}集約を読み込みました:{file}。", - }, - "channel_loaded": { - "zh": "已加载{channel}的{label}:{file}。", - "en": "Loaded {label} for {channel}: {file}.", - "ja": "{channel}の{label}を読み込みました:{file}。", - }, - "load_summary_failed": { - "zh": "加载通道幅相汇总失败", - "en": "Load channel pattern summary failed", - "ja": "チャネル集約の読み込みに失敗", - }, - "load_channel_failed": { - "zh": "加载通道幅相失败", - "en": "Load channel pattern failed", - "ja": "チャネルの読み込みに失敗", - }, - "ideal": {"zh": "理想", "en": "ideal", "ja": "理想"}, - "amp": {"zh": "幅度", "en": "Amp", "ja": "振幅"}, - "phase": {"zh": "相位", "en": "Phase", "ja": "位相"}, - "row_channel_count": {"zh": "通道数量", "en": "Channels", "ja": "チャネル数"}, - "row_virtual_channels": {"zh": "虚拟通道", "en": "Virtual Channels", "ja": "仮想チャネル"}, - "row_az_aperture": {"zh": "方位口径", "en": "Az Aperture", "ja": "方位開口"}, - "row_el_aperture": {"zh": "俯仰口径", "en": "El Aperture", "ja": "仰角開口"}, - "row_az_resolution": {"zh": "方位分辨率", "en": "Az Resolution", "ja": "方位分解能"}, - "row_el_resolution": {"zh": "俯仰分辨率", "en": "El Resolution", "ja": "仰角分解能"}, - "row_az_no_fold": {"zh": "方位不模糊范围", "en": "Az No-Fold Range", "ja": "方位非曖昧範囲"}, - "row_az_no_fold_error": {"zh": "方位范围内最大误差", "en": "Az Max Error in Range", "ja": "方位範囲内最大誤差"}, - "row_az_margin": {"zh": "方位竞争峰裕量", "en": "Az Peak Margin", "ja": "方位競合ピーク余裕"}, - "row_az_cut": {"zh": "方位截断原因", "en": "Az Cut Reason", "ja": "方位打切り理由"}, - "row_el_no_fold": {"zh": "俯仰不模糊范围", "en": "El No-Fold Range", "ja": "仰角非曖昧範囲"}, - "row_el_no_fold_error": {"zh": "俯仰范围内最大误差", "en": "El Max Error in Range", "ja": "仰角範囲内最大誤差"}, - "row_el_margin": {"zh": "俯仰竞争峰裕量", "en": "El Peak Margin", "ja": "仰角競合ピーク余裕"}, - "row_el_cut": {"zh": "俯仰截断原因", "en": "El Cut Reason", "ja": "仰角打切り理由"}, - "metric_no_fold": {"zh": "不模糊范围", "en": "No-Fold", "ja": "非曖昧範囲"}, - "metric_max_error": {"zh": "最大误差", "en": "Max Error", "ja": "最大誤差"}, - "metric_peak_margin": {"zh": "竞争峰裕量", "en": "Peak Margin", "ja": "競合ピーク余裕"}, - "metric_cut_reason": {"zh": "截断原因", "en": "Cut Reason", "ja": "打切り理由"}, - "metric_value_no_competitor": {"zh": "无竞争峰", "en": "No competitor", "ja": "競合ピークなし"}, - "metric_value_unavailable": {"zh": "不可用", "en": "Unavailable", "ja": "利用不可"}, - "cut_reason_peak_blurred": {"zh": "峰模糊", "en": "Peak blurred", "ja": "ピーク曖昧"}, - "cut_reason_data_boundary": {"zh": "边界", "en": "Data edge", "ja": "データ境界"}, - "cut_reason_boundary_limited": {"zh": "边界受限", "en": "At boundary", "ja": "境界制限"}, - "cut_reason_error_jump": {"zh": "误差跳变", "en": "Error jump", "ja": "誤差ジャンプ"}, - "cut_reason_unreliable": {"zh": "谱不可靠", "en": "Unreliable spectrum", "ja": "スペクトル不安定"}, - "cut_reason_normal": {"zh": "正常", "en": "Normal", "ja": "正常"}, - "cut_reason_pair": {"zh": "负:{negative} / 正:{positive}", "en": "Neg: {negative} / Pos: {positive}", "ja": "負:{negative} / 正:{positive}"}, - "undo_empty": {"zh": "没有可撤销的操作。", "en": "Nothing to undo.", "ja": "元に戻す操作はありません。"}, - "undo_done": {"zh": "已撤销阵列编辑。", "en": "Undid layout edit.", "ja": "アレイ編集を元に戻しました。"}, - "redo_empty": {"zh": "没有可重做的操作。", "en": "Nothing to redo.", "ja": "やり直す操作はありません。"}, - "redo_done": {"zh": "已重做阵列编辑。", "en": "Redid layout edit.", "ja": "アレイ編集をやり直しました。"}, - "limit_reached": {"zh": "{prefix}数量已达上限({max_count})。", "en": "{prefix} limit reached ({max_count}).", "ja": "{prefix}数が上限({max_count})に達しました。"}, - "antenna_limit_title": {"zh": "天线数量限制", "en": "Antenna limit", "ja": "アンテナ数制限"}, - "count_limit_detail": {"zh": "{prefix}数量最多为{max_count}。", "en": "{prefix} count is limited to {max_count}.", "ja": "{prefix}数は最大{max_count}です。"}, - "added_element": {"zh": "已添加{element} | x={x:g} λ | y={y:g} λ", "en": "Added {element} | x={x:g} λ | y={y:g} λ", "ja": "{element}を追加 | x={x:g} λ | y={y:g} λ"}, - "delete_mode_on": {"zh": "删除模式:点击TX/RX通道即可删除,按Esc退出。", "en": "Delete mode: click Tx/Rx elements to remove them. Press Esc to exit.", "ja": "削除モード:TX/RXチャネルをクリックして削除、Escで終了。"}, - "delete_mode_off": {"zh": "已退出删除模式。", "en": "Delete mode off.", "ja": "削除モードを終了しました。"}, - "layout_already_clear": {"zh": "阵列已经是初始布局。", "en": "Layout already clear.", "ja": "アレイは既に初期配置です。"}, - "layout_cleared": {"zh": "已清空阵列,保留1T1R初始通道。", "en": "Cleared layout to 1T1R starter points.", "ja": "アレイをクリアし、1T1R初期チャネルを残しました。"}, - "auto_layout_title": {"zh": "自动排阵", "en": "Auto array layout", "ja": "自動アレイ配置"}, - "auto_layout_already": {"zh": "自动排阵已是{tx}T{rx}R。", "en": "Auto layout already applied: {tx}T{rx}R.", "ja": "自動配置は既に{tx}T{rx}Rです。"}, - "auto_layout_done": {"zh": "已应用自动排阵:{tx}T{rx}R。", "en": "Auto layout applied: {tx}T{rx}R.", "ja": "自動配置を適用:{tx}T{rx}R。"}, - "delete_last": {"zh": "不能删除最后一个{prefix}通道。", "en": "Cannot delete the last {prefix} element.", "ja": "最後の{prefix}チャネルは削除できません。"}, - "delete_last_detail": {"zh": "测角分析至少需要一个{prefix}通道。", "en": "At least one {prefix} element is required for analysis.", "ja": "解析には少なくとも1つの{prefix}チャネルが必要です。"}, - "deleted_element": {"zh": "已删除{element},TX/RX编号已自动对齐。{suffix}", "en": "Deleted {element}. Tx/Rx numbering aligned.{suffix}", "ja": "{element}を削除し、TX/RX番号を整列しました。{suffix}"}, - "delete_mode_suffix": {"zh": " 删除模式保持开启。", "en": " Delete mode remains on.", "ja": " 削除モードは継続中。"}, - "frequency_set": {"zh": "频率已设置为{frequency} GHz。", "en": "Frequency set to {frequency} GHz.", "ja": "周波数を{frequency} GHzに設定しました。"}, - "frequency_invalid": {"zh": "频率输入无效,已恢复为{frequency} GHz。", "en": "Invalid frequency. Restored {frequency} GHz.", "ja": "無効な周波数です。{frequency} GHzに戻しました。"}, - "margin_set": {"zh": "竞争峰裕量阈值已设置为{value} dB。", "en": "Peak margin threshold set to {value} dB.", "ja": "競合ピーク余裕しきい値を{value} dBに設定しました。"}, - "margin_invalid": {"zh": "竞争峰裕量输入无效,已恢复为{value} dB。", "en": "Invalid peak margin. Restored {value} dB.", "ja": "競合ピーク余裕の入力が無効です。{value} dBに戻しました。"}, - "refreshed": {"zh": "已刷新。", "en": "Refreshed.", "ja": "更新しました。"}, - "refresh_invalid": {"zh": "频率输入无效,已恢复并刷新。", "en": "Invalid frequency restored and refreshed.", "ja": "無効な周波数を復元して更新しました。"}, - "drag_cancel": {"zh": "已取消拖动。", "en": "Drag canceled.", "ja": "ドラッグをキャンセルしました。"}, - "no_selection": {"zh": "当前没有选中通道。", "en": "No selection.", "ja": "選択中のチャネルはありません。"}, - "selection_cleared": {"zh": "已清除选择。", "en": "Selection cleared.", "ja": "選択を解除しました。"}, - "select_element_hint": {"zh": "已清除选择。点击一个天线通道可重新选择。", "en": "Selection cleared. Click an antenna element to select.", "ja": "選択を解除しました。アンテナチャネルをクリックして再選択できます。"}, - "delete_click_element": {"zh": "删除模式:请直接点击TX/RX通道。", "en": "Delete mode: click directly on a Tx/Rx element.", "ja": "削除モード:TX/RXチャネルを直接クリックしてください。"}, - "selected_element": {"zh": "已选中{element} | x={x:g} λ | y={y:g} λ", "en": "Selected {element} | x={x:g} λ | y={y:g} λ", "ja": "{element}を選択 | x={x:g} λ | y={y:g} λ"}, - "moving_element": {"zh": "移动{element}:x={x:g} λ, y={y:g} λ", "en": "Move {element}: x={x:g} λ, y={y:g} λ", "ja": "{element}を移動:x={x:g} λ, y={y:g} λ"}, - "snap_element": {"zh": "吸附{element}:x={x:g} λ, y={y:g} λ", "en": "Snap {element}: x={x:g} λ, y={y:g} λ", "ja": "{element}をスナップ:x={x:g} λ, y={y:g} λ"}, - "placed_element": {"zh": "{element}:x={x:g} λ, y={y:g} λ", "en": "{element}: x={x:g} λ, y={y:g} λ", "ja": "{element}:x={x:g} λ, y={y:g} λ"}, - "export_layout_title": {"zh": "导出阵面布局", "en": "Export antenna layout", "ja": "アレイ配置を書き出し"}, - "import_layout_title": {"zh": "导入阵面布局", "en": "Import antenna layout", "ja": "アレイ配置を読み込み"}, - "layout_json_type": {"zh": "阵面布局JSON", "en": "Antenna layout JSON", "ja": "アレイ配置JSON"}, - "all_files_type": {"zh": "所有文件", "en": "All files", "ja": "すべてのファイル"}, - "hfss_csv_type": {"zh": "HFSS CSV/TSV/XLSX", "en": "HFSS CSV/TSV/XLSX", "ja": "HFSS CSV/TSV/XLSX"}, - "csv_type": {"zh": "CSV文件", "en": "CSV files", "ja": "CSVファイル"}, - "tsv_type": {"zh": "TSV文件", "en": "TSV files", "ja": "TSVファイル"}, - "element_pattern_import_title": { - "zh": "导入单元方向图", - "en": "Import element pattern", - "ja": "要素パターンを読み込み", - }, - "element_pattern_file_type": { - "zh": "方向图CSV/TSV", - "en": "Pattern CSV/TSV", - "ja": "パターンCSV/TSV", - }, - "element_pattern_import_failed": { - "zh": "导入单元方向图失败", - "en": "Import element pattern failed", - "ja": "要素パターンの読み込みに失敗", - }, - "element_pattern_import_canceled": { - "zh": "已取消导入单元方向图。", - "en": "Element pattern import canceled.", - "ja": "要素パターンの読み込みをキャンセルしました。", - }, - "element_pattern_loaded": { - "zh": "已加载单元方向图:{name}", - "en": "Element pattern loaded: {name}", - "ja": "要素パターンを読み込みました:{name}", - }, - "element_pattern_already_isotropic": { - "zh": "当前已使用理想各向同性单元。", - "en": "Element pattern already isotropic.", - "ja": "要素パターンはすでに等方性です。", - }, - "element_pattern_cleared": { - "zh": "已清除单元方向图,改用理想各向同性单元。", - "en": "Element pattern cleared. Using isotropic elements.", - "ja": "要素パターンをクリアし、等方性要素を使用します。", - }, - "element_pattern_confirm_title": { - "zh": "确认单元方向图", - "en": "Confirm Element Pattern", - "ja": "要素パターンを確認", - }, - "element_pattern_preview_columns": { - "zh": "角度:{angle} | H:{horizontal}{elevation}", - "en": "Angle: {angle} | H: {horizontal}{elevation}", - "ja": "角度:{angle} | H:{horizontal}{elevation}", - }, - "element_pattern_preview_elevation_column": { - "zh": " | V:{column}", - "en": " | V: {column}", - "ja": " | V:{column}", - }, - "element_pattern_horizontal_metrics": { - "zh": "水平:{metrics}", - "en": "Horizontal: {metrics}", - "ja": "水平:{metrics}", - }, - "element_pattern_elevation_metrics": { - "zh": "俯仰:{metrics}", - "en": "Elevation: {metrics}", - "ja": "仰角:{metrics}", - }, - "element_pattern_horizontal_title": { - "zh": "水平方向图", - "en": "Horizontal pattern", - "ja": "水平パターン", - }, - "element_pattern_elevation_title": { - "zh": "俯仰方向图", - "en": "Elevation pattern", - "ja": "仰角パターン", - }, - "element_pattern_no_elevation": { - "zh": "未检测到独立俯仰列,将复用水平方向图。", - "en": "No separate elevation column. Horizontal pattern will be reused.", - "ja": "個別の仰角列がないため、水平パターンを再利用します。", - }, - "element_pattern_elevation_reuse": { - "zh": "俯仰:复用水平方向图", - "en": "Elevation: reuses horizontal pattern", - "ja": "仰角:水平パターンを再利用", - }, - "element_pattern_axis_angle": {"zh": "角度(°)", "en": "Angle (deg)", "ja": "角度(°)"}, - "element_pattern_axis_gain": {"zh": "增益(dB)", "en": "Gain (dB)", "ja": "利得(dB)"}, - "element_pattern_import_button": {"zh": "导入", "en": "Import", "ja": "読み込み"}, - "element_pattern_cancel_button": {"zh": "取消", "en": "Cancel", "ja": "キャンセル"}, - "element_pattern_swap_button": {"zh": "交换H/V", "en": "Swap H/V", "ja": "H/V入替"}, - "exported_layout": {"zh": "已导出阵面布局:{file}", "en": "Exported layout: {file}", "ja": "アレイ配置を書き出しました:{file}"}, - "import_layout_failed": {"zh": "导入阵面布局失败", "en": "Import layout failed", "ja": "アレイ配置の読み込みに失敗"}, - "imported_layout": { - "zh": "已导入:{file} | {tx}=({tx_x:g},{tx_y:g}) λ | {rx}=({rx_x:g},{rx_y:g}) λ | x {x_min:g}..{x_max:g} λ, y {y_min:g}..{y_max:g} λ", - "en": "Imported: {file} | {tx}=({tx_x:g},{tx_y:g}) λ | {rx}=({rx_x:g},{rx_y:g}) λ | x {x_min:g}..{x_max:g} λ, y {y_min:g}..{y_max:g} λ", - "ja": "読み込み完了:{file} | {tx}=({tx_x:g},{tx_y:g}) λ | {rx}=({rx_x:g},{rx_y:g}) λ | x {x_min:g}..{x_max:g} λ, y {y_min:g}..{y_max:g} λ", - }, -} - - -def _text_for_language(key: str, language: str = LANGUAGE_ZH, **kwargs) -> str: - language = language if language in SUPPORTED_LANGUAGES else LANGUAGE_ZH - translations = UI_TEXT.get(key, {}) - template = translations.get(language) or translations.get(LANGUAGE_ZH) or key - return template.format(**kwargs) if kwargs else template - - -def _pattern_slot_label_for_language(kind: str, plane: str, language: str) -> str: - kind_text = _text_for_language( - "amp" if kind == PATTERN_KIND_AMPLITUDE else "phase", - language, - ) - plane_text = _text_for_language( - "el_short" if plane == PATTERN_PLANE_ELEVATION else "az_short", - language, - ) - return f"{plane_text}{kind_text}" if language != LANGUAGE_EN else f"{plane_text} {kind_text}" - - -PRIMARY_EVAL_ROWS = ( - "row_channel_count", - "row_virtual_channels", - "row_az_aperture", - "row_el_aperture", - "row_az_resolution", - "row_el_resolution", -) -ANGLE_EVAL_GROUPS = ( - ( - "az", - ( - ("row_az_no_fold", "metric_no_fold"), - ("row_az_no_fold_error", "metric_max_error"), - ("row_az_margin", "metric_peak_margin"), - ("row_az_cut", "metric_cut_reason"), - ), - ), - ( - "el", - ( - ("row_el_no_fold", "metric_no_fold"), - ("row_el_no_fold_error", "metric_max_error"), - ("row_el_margin", "metric_peak_margin"), - ("row_el_cut", "metric_cut_reason"), - ), - ), -) - -# ── Theme ───────────────────────────────────────────────────────────── -THEME = { - # Base - "bg": TOKENS.canvas, - "card_bg": TOKENS.surface, - # Metric rows belong to one continuous information surface. Using the - # card colour avoids a stack of disconnected gray pills in the overview. - "metric_bg": TOKENS.surface, - "panel_bg": TOKENS.canvas, - "panel_alt_bg": TOKENS.surface_muted, - "card_border": TOKENS.border, - "metric_border": TOKENS.border, - "status_bar_bg": TOKENS.chrome_surface, - "toolbar_group_bg": TOKENS.surface, - "input_bg": TOKENS.surface, - "disabled_bg": TOKENS.disabled, - "app_menu_bg": TOKENS.chrome_surface, - "app_menu_hover": TOKENS.surface_hover, - "app_menu_text": TOKENS.text_secondary, - "app_menu_text_active": TOKENS.accent_pressed, - "header_bg": TOKENS.chrome_surface, - "header_panel_bg": TOKENS.surface_subtle, - "header_border": TOKENS.border, - "chip_bg": TOKENS.surface_muted, - "chip_border": TOKENS.border, - "app_logo_bg": TOKENS.accent, - # Accent - "accent": TOKENS.accent, - "accent_hover": TOKENS.accent_hover, - "accent_pressed": TOKENS.accent_pressed, - "accent_light": TOKENS.accent_tint, - "primary_fill": TOKENS.primary_fill, - "primary_hover": TOKENS.primary_hover, - "primary_pressed": TOKENS.primary_pressed, - "secondary_accent": "#4589ff", - "secondary_light": TOKENS.accent_tint, - "danger": TOKENS.danger, - "danger_hover": "#ba1b23", - "danger_pressed": "#750e13", - "danger_light": TOKENS.danger_fill, - "danger_border": "#fa4d56", - "warning": TOKENS.warning, - "warning_light": TOKENS.warning_fill, - "success": TOKENS.success, - "success_light": TOKENS.success_fill, - # Text - "text_primary": TOKENS.text, - "text_secondary": TOKENS.text_secondary, - "text_muted": TOKENS.text_tertiary, - "text_inverse": "#ffffff", - "text_inverse_muted": "#d6e8ff", - # Typography - "font_family": "Microsoft YaHei UI" if sys.platform.startswith("win") else "sans-serif", - "font_family_mono": "Cascadia Mono" if sys.platform.startswith("win") else "monospace", - "font_size_sm": 9, - "font_size_base": 10, - "font_size_lg": 13, - # Matplotlib - "plot_bg": TOKENS.surface, - "grid_color": "#e0e0e0", - "grid_major_color": "#c6c6c6", - "grid_minor_color": "#f4f4f4", - "grid_alpha": 0.34, - "axis_spine": TOKENS.border_strong, - "tx_color": "#fa4d56", - "tx_edge": "#a2191f", - "rx_color": TOKENS.accent, - "rx_edge": TOKENS.accent_pressed, - "selection": TOKENS.accent, - "selection_fill": TOKENS.accent_tint, - "hover_fill": TOKENS.surface_hover, - "response_line": TOKENS.accent, - "response_secondary_line": "#6f6f6f", - "sidelobe": "#f1c21b", - # MplButton - "mpl_btn_bg": "#ffffff", - "mpl_btn_hover": TOKENS.surface_hover, - "mpl_btn_text": "#171717", - "mpl_btn_border": TOKENS.border, - # ttk buttons - "button_bg": "#ffffff", - "button_hover": TOKENS.surface_hover, - "button_pressed": TOKENS.surface_pressed, - "button_border": TOKENS.control_border, - "dialog_button_hover": TOKENS.surface_hover, - "dialog_button_pressed": TOKENS.surface_pressed, - "menu_hover": TOKENS.surface_hover, - "focus": TOKENS.focus, - "focus_soft": "#78a9ff", -} - - -# ── Data classes ────────────────────────────────────────────────────── -@dataclass -class EditableElement: - kind: str - index: int - name: str - x: float - y: float - - -@dataclass(frozen=True) -class LayoutSnapshot: - elements: tuple[tuple[str, int, str, float, float], ...] - selected_key: tuple[str, int, str] | None - - -@dataclass(frozen=True) -class ResponseCut: - mode: str - label: str - angles: np.ndarray - gains_db: np.ndarray - fov: tuple[float, float] - mainlobe_guard: float - x_label: str - pattern_label: str - - -@dataclass -class ResponseChart: - """Encapsulates per-axis response chart state (fig, axes, canvas, hover, buttons).""" - - fig: Figure - ax: any # matplotlib Axes - canvas: FigureCanvasTkAgg - progress_label: ttk.Label | None = None - play_button: ttk.Button | None = None - stop_button: ttk.Button | None = None - footer_widget: ttk.Frame | None = None - hover_annotation: any = None # matplotlib Annotation - hover_marker: any = None - hover_db: np.ndarray = None - hover_angles: np.ndarray = None - true_angle: float | None = None - buttons: list = None - button_callbacks: list = None - empty_overlay: _EmptyStateOverlay | None = None # type: ignore[name-defined] - - def __post_init__(self) -> None: - if self.hover_db is None: - self.hover_db = np.empty(0, dtype=float) - if self.hover_angles is None: - self.hover_angles = np.empty(0, dtype=float) - if self.buttons is None: - self.buttons = [] - if self.button_callbacks is None: - self.button_callbacks = [] - - -class _DebouncedResizeFilter(QtCore.QObject): - """Coalesce resize storms before asking the plots to relayout.""" - - def __init__(self, parent: QtCore.QObject, callback) -> None: - super().__init__(parent) - self._timer = QtCore.QTimer(self) - self._timer.setSingleShot(True) - self._timer.setInterval(100) - self._timer.timeout.connect(callback) - - def eventFilter(self, watched: QtCore.QObject, event: QtCore.QEvent) -> bool: - if event.type() == QtCore.QEvent.Type.Resize: - self._timer.start() - return super().eventFilter(watched, event) - - -class _PerformanceReportCancelled(RuntimeError): - """Internal cooperative-cancellation signal for report generation.""" - - -class _PerformanceReportWorker(QtCore.QObject): - progress = QtCore.Signal(int, str) - succeeded = QtCore.Signal(object) - failed = QtCore.Signal(str) - cancelled = QtCore.Signal() - finished = QtCore.Signal() - - def __init__(self, generator, snapshot, options) -> None: # noqa: ANN001 - super().__init__() - self._generator = generator - self._snapshot = snapshot - self._options = options - - @QtCore.Slot() - def run(self) -> None: - thread = QtCore.QThread.currentThread() - - def report_progress(percent: int, message: str) -> None: - if percent < 100 and thread.isInterruptionRequested(): - raise _PerformanceReportCancelled - self.progress.emit(int(percent), str(message)) - - try: - artifacts = self._generator( - self._snapshot, - self._options, - progress_callback=report_progress, - ) - except _PerformanceReportCancelled: - self.cancelled.emit() - except Exception as exc: - LOGGER.exception("Performance report worker failed") - self.failed.emit(str(exc)) - else: - self.succeeded.emit(artifacts) - finally: - self.finished.emit() - - -class _PerformanceReportUiBridge(QtCore.QObject): - """Marshal report worker and lifecycle signals onto the GUI thread.""" - - def __init__( - self, - controller, - thread: QtCore.QThread, - parent: QtCore.QObject, - ) -> None: # noqa: ANN001 - super().__init__(parent) - self._controller = controller - self._thread = thread - - @QtCore.Slot(int, str) - def on_progress(self, percent: int, message: str) -> None: - self._controller._on_performance_report_progress(percent, message) - - @QtCore.Slot(object) - def on_succeeded(self, artifacts) -> None: # noqa: ANN001 - self._controller._on_performance_report_succeeded(artifacts) - - @QtCore.Slot(str) - def on_failed(self, message: str) -> None: - self._controller._on_performance_report_failed(message) - - @QtCore.Slot() - def on_cancelled(self) -> None: - self._controller._on_performance_report_cancelled() - - @QtCore.Slot() - def on_cancel_requested(self) -> None: - self._controller._cancel_performance_report_export() - - @QtCore.Slot() - def on_thread_finished(self) -> None: - self._controller._clear_performance_report_thread(self._thread, self) - - -class _EmptyStateOverlay(QtWidgets.QFrame): - """Neutral, accessible capability message layered over a plot canvas.""" - - def __init__(self, host: QtWidgets.QWidget) -> None: - super().__init__(host) - self._host = host - self.setObjectName("plotEmptyState") - self.setAttribute(QtCore.Qt.WidgetAttribute.WA_StyledBackground, True) - self.setStyleSheet( - "#plotEmptyState {" - f"background: {TOKENS.surface};" - f"border: 1px solid {TOKENS.border};" - f"border-radius: {TOKENS.card_radius}px;" - "}" - "#plotEmptyState QLabel {" - "background: transparent;" - "border: 0;" - "}" - ) - layout = QtWidgets.QVBoxLayout(self) - layout.setContentsMargins(36, 28, 36, 28) - layout.setSpacing(10) - layout.addStretch(1) - icon_label = QtWidgets.QLabel(self) - icon = self.style().standardIcon( - QtWidgets.QStyle.StandardPixmap.SP_MessageBoxInformation - ) - icon_label.setPixmap(icon.pixmap(28, 28)) - icon_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - layout.addWidget(icon_label) - self.title_label = QtWidgets.QLabel(self) - title_font = self.title_label.font() - title_font.setPointSize(12) - title_font.setBold(True) - self.title_label.setFont(title_font) - self.title_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - self.title_label.setWordWrap(True) - layout.addWidget(self.title_label) - self.body_label = QtWidgets.QLabel(self) - self.body_label.setStyleSheet(f"color: {TOKENS.text_secondary};") - self.body_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - self.body_label.setWordWrap(True) - layout.addWidget(self.body_label) - self.action_button = QtWidgets.QPushButton(self) - self.action_button.setObjectName("plotEmptyStateAction") - self.action_button.setAccessibleName("") - self.action_button.setMaximumWidth(180) - mark_quiet(self.action_button) - layout.addWidget( - self.action_button, - 0, - QtCore.Qt.AlignmentFlag.AlignHCenter, - ) - self.action_button.hide() - self._action_connected = False - layout.addStretch(1) - self.setAccessibleName("") - self._host.installEventFilter(self) - self.setGeometry(self._host.rect()) - self.hide() - - def set_content(self, title: str, body: str) -> None: - self.title_label.setText(title) - self.body_label.setText(body) - self.setAccessibleDescription(f"{title}. {body}") - - def set_action(self, label: str | None, callback=None) -> None: # noqa: ANN001 - if self._action_connected: - try: - self.action_button.clicked.disconnect() - except (RuntimeError, TypeError): - pass - self._action_connected = False - if label and callback is not None: - self.action_button.setText(label) - self.action_button.setAccessibleName(label) - self.action_button.clicked.connect( - lambda _checked=False, cb=callback: cb() - ) - self._action_connected = True - self.action_button.show() - return - self.action_button.hide() - - def eventFilter(self, watched: QtCore.QObject, event: QtCore.QEvent) -> bool: - if watched is self._host and event.type() == QtCore.QEvent.Type.Resize: - self.setGeometry(self._host.rect()) - return super().eventFilter(watched, event) - - def show_overlay(self, visible: bool) -> None: - self.setVisible(visible) - if visible: - self.raise_() - - -def _response_cut_for_mode( - af_db: np.ndarray, - azimuths: np.ndarray, - elevations: np.ndarray, - mode: str, - language: str = LANGUAGE_ZH, -) -> ResponseCut: - if mode == RESPONSE_MODE_ELEVATION: - az0_index = int(np.argmin(np.abs(azimuths))) - return ResponseCut( - mode=RESPONSE_MODE_ELEVATION, - label=_text_for_language("el_short", language), - angles=elevations, - gains_db=af_db[:, az0_index], - fov=ELEVATION_FOV, - mainlobe_guard=MAINLOBE_GUARD_EL, - x_label=_text_for_language("axis_el_angle", language), - pattern_label=_text_for_language( - "pattern_cut_label", language, mode=_text_for_language("el", language) - ), - ) - - el0_index = int(np.argmin(np.abs(elevations))) - return ResponseCut( - mode=RESPONSE_MODE_AZIMUTH, - label=_text_for_language("az_short", language), - angles=azimuths, - gains_db=af_db[el0_index, :], - fov=AZIMUTH_FOV, - mainlobe_guard=MAINLOBE_GUARD_AZ, - x_label=_text_for_language("axis_az_angle", language), - pattern_label=_text_for_language( - "pattern_cut_label", language, mode=_text_for_language("az", language) - ), - ) - - -def _response_sidelobe_marker( - angles: np.ndarray, - gains_db: np.ndarray, - guard: float, - min_prominence_db: float = RESPONSE_SIDELOBE_PROMINENCE_DB, - min_guard_clearance_db: float = RESPONSE_SIDELOBE_GUARD_CLEARANCE_DB, -) -> tuple[int, bool]: - peak_indices = local_peak_indices(gains_db) - sidelobe_mask = np.abs(angles) > guard - sidelobe_peak_indices = np.array( - [ - index - for index in peak_indices[sidelobe_mask[peak_indices]] - if _peak_prominence_db(gains_db, int(index)) >= min_prominence_db - and _peak_guard_clearance_db(angles, gains_db, guard, int(index)) - >= min_guard_clearance_db - ], - dtype=int, - ) - if len(sidelobe_peak_indices): - index = int(sidelobe_peak_indices[np.argmax(gains_db[sidelobe_peak_indices])]) - return index, True - if np.any(sidelobe_mask): - return int(np.argmax(np.where(sidelobe_mask, gains_db, -np.inf))), False - return int(np.argmax(gains_db)), False - - -def _peak_prominence_db(values_db: np.ndarray, peak_index: int) -> float: - peak_db = float(values_db[peak_index]) - left_min = peak_db - for index in range(peak_index - 1, -1, -1): - value = float(values_db[index]) - if value > peak_db: - break - left_min = min(left_min, value) - - right_min = peak_db - for index in range(peak_index + 1, len(values_db)): - value = float(values_db[index]) - if value > peak_db: - break - right_min = min(right_min, value) - - return peak_db - max(left_min, right_min) - - -def _peak_guard_clearance_db( - angles: np.ndarray, - gains_db: np.ndarray, - guard: float, - peak_index: int, -) -> float: - peak_angle = float(angles[peak_index]) - if peak_angle < 0.0: - side_indices = np.flatnonzero(angles < -guard) - if len(side_indices) == 0: - return 0.0 - guard_index = int(side_indices[np.argmax(angles[side_indices])]) - else: - side_indices = np.flatnonzero(angles > guard) - if len(side_indices) == 0: - return 0.0 - guard_index = int(side_indices[np.argmin(angles[side_indices])]) - return float(gains_db[peak_index] - gains_db[guard_index]) - - -# ── Formatting helpers ──────────────────────────────────────────────── -def _format_float(value: float | None, unit: str = "") -> str: - if value is None or not np.isfinite(value): - return "N/A" - return f"{value:.2f}{unit}" - - -def _format_db(value: float | None) -> str: - if value is None or not np.isfinite(value): - return "N/A" - return f"{value:.2f} dB" - - -def _format_db_at_az(value: float | None, angle: float | None) -> str: - if value is None or angle is None or not np.isfinite(value) or not np.isfinite(angle): - return "N/A" - return f"{value:.2f} dB @ Az {angle:.1f}°" - - -def _format_signed_degree(value: float, digits: int = 0) -> str: - if abs(value) < 0.05: - return "0°" - text = f"{value:+.{digits}f}" - if digits == 0: - text = text.replace(".0", "") - return f"{text}°" - - -def _format_angle_error(value: float | None) -> str: - if value is None or not np.isfinite(value): - return "N/A" - return f"{value:.1f}°" - - -def _format_angle_range(metrics: DbfAngleMetrics | None) -> str: - if ( - metrics is None - or metrics.no_fold_left is None - or metrics.no_fold_right is None - or not np.isfinite(metrics.no_fold_left) - or not np.isfinite(metrics.no_fold_right) - ): - return "N/A" - width = metrics.no_fold_width - width_text = "N/A" if width is None else f"{width:.0f}°" - return ( - f"{_format_signed_degree(metrics.no_fold_left)}~" - f"{_format_signed_degree(metrics.no_fold_right)} / {width_text}" - ) - - -def _format_peak_margin( - value: float | None, - language: str = LANGUAGE_ZH, -) -> str: - if value is None: - return "N/A" - if np.isposinf(value): - return _text_for_language("metric_value_no_competitor", language) - if not np.isfinite(value): - return "N/A" - return f"{value:.1f} dB" - - -def _format_axis_angle_metrics( - metrics: DbfAngleMetrics | None, - field: str, - language: str = LANGUAGE_ZH, -) -> str: - if metrics is None: - return "N/A" - if field == "no_fold_error": - return _format_angle_error(metrics.no_fold_max_abs_error) - if field == "focus_error": - return _format_angle_error(metrics.focus_max_abs_error) - if field == "margin": - if ( - (metrics.no_fold_width or 0.0) <= 0.0 - and ( - metrics.negative_cut_reason in {"边界受限", "谱不可靠"} - or metrics.positive_cut_reason in {"边界受限", "谱不可靠"} - ) - ): - return _text_for_language("metric_value_unavailable", language) - return _format_peak_margin(metrics.min_peak_margin_db, language) - raise ValueError(f"Unknown DBF angle metric field: {field!r}") - - -def _format_mm(value: float) -> str: - return f"{value:.1f} mm" - - -def _parse_frequency_ghz(value: object) -> float | None: - if isinstance(value, bool): - return None - if isinstance(value, (int, float)): - frequency = float(value) - elif isinstance(value, str): - text = value.strip().lower().replace(",", ".") - if text.endswith("ghz"): - text = text[:-3].strip() - elif text.endswith("g"): - text = text[:-1].strip() - if not text: - return None - try: - frequency = float(text) - except ValueError: - return None - else: - return None - return frequency if math.isfinite(frequency) and frequency > 0 else None - - -def _format_frequency_ghz(frequency: float) -> str: - if abs(frequency - round(frequency)) < 1e-9: - return str(int(round(frequency))) - return f"{frequency:.6f}".rstrip("0").rstrip(".") - - -def _parse_margin_db(value: object) -> float | None: - if isinstance(value, bool): - return None - if isinstance(value, (int, float)): - margin = float(value) - elif isinstance(value, str): - text = value.strip().lower().replace(",", ".") - if text.endswith("db"): - text = text[:-2].strip() - if not text: - return None - try: - margin = float(text) - except ValueError: - return None - else: - return None - return margin if math.isfinite(margin) and margin >= 0.0 else None - - -def _format_margin_db(value: float) -> str: - if abs(value - round(value)) < 1e-9: - return str(int(round(value))) - return f"{value:.3f}".rstrip("0").rstrip(".") - - -def _validated_window_geometry(value: object) -> str | None: - if not isinstance(value, str): - return None - geometry = value.strip() - match = WINDOW_GEOMETRY_RE.fullmatch(geometry) - if match is None: - return None - width = int(match.group("width")) - height = int(match.group("height")) - return geometry if width > 0 and height > 0 else None - - -def _default_workspace_sash_position(width: int) -> int | None: - if width <= 1: - return None - return max(1, min(width - 1, width // 2)) - - -def _json_number(value: float | None, digits: int = 6) -> float | int | None: - if value is None or not np.isfinite(value): - return None - rounded = round(float(value), digits) - if abs(rounded - round(rounded)) < 10 ** -digits: - return int(round(rounded)) - return rounded - - -def _layout_config_to_json(config: dict[str, object]) -> str: - lines = [ - "{", - f' "version": {json.dumps(config["version"], ensure_ascii=False)},', - f' "unit": {json.dumps(config["unit"], ensure_ascii=False)},', - ' "tx": [', - ] - tx_points = config["tx"] - rx_points = config["rx"] - if not isinstance(tx_points, list) or not isinstance(rx_points, list): - raise ValueError("Layout config tx/rx must be lists.") - - for index, point in enumerate(tx_points): - suffix = "," if index < len(tx_points) - 1 else "" - lines.append( - " " - + json.dumps(point, ensure_ascii=False, separators=(", ", ": ")) - + suffix - ) - lines.extend([' ],', ' "rx": [']) - for index, point in enumerate(rx_points): - suffix = "," if index < len(rx_points) - 1 else "" - lines.append( - " " - + json.dumps(point, ensure_ascii=False, separators=(", ", ": ")) - + suffix - ) - lines.append(" ],") - - evaluation = json.dumps(config["evaluation"], ensure_ascii=False, indent=2) - evaluation_lines = evaluation.splitlines() - lines.append(' "evaluation": ' + evaluation_lines[0]) - lines.extend(" " + line for line in evaluation_lines[1:]) - lines.append("}") - return "\n".join(lines) + "\n" - - -def _show_unhandled_tk_exception( - exc_type: type[BaseException], - exc_value: BaseException, - exc_traceback, -) -> None: # noqa: ANN001 - LOGGER.critical( - "Unhandled Tk callback exception", - exc_info=(exc_type, exc_value, exc_traceback), - ) - log_path = current_log_path() - details = f"{exc_value}" - if log_path is not None: - details += f"\n\nDetails were saved to:\n{log_path}" - try: - messagebox.showerror("Application error", details) - except Exception: - LOGGER.exception("Failed to show Tk exception dialog") - - -def _to_display_lambda(values): # noqa: ANN001 - return np.asarray(values, dtype=float) * DISPLAY_SCALE_LAMBDA - - -def _to_internal_half_lambda(value: float) -> float: - return value / DISPLAY_SCALE_LAMBDA - - -def _clip_to_bounds(value: float, low: float, high: float) -> float: - return float(min(max(value, low), high)) - - -def _axes_boxes_overlap( - first: tuple[float, float, float, float], - second: tuple[float, float, float, float], - margin: float = 0.015, -) -> bool: - first_left, first_bottom, first_right, first_top = first - second_left, second_bottom, second_right, second_top = second - return not ( - first_right + margin < second_left - or second_right + margin < first_left - or first_top + margin < second_bottom - or second_top + margin < first_bottom - ) - - -def _style_toplevel(window: tk.Toplevel) -> None: - window.configure(bg=THEME["bg"]) - - -def _set_window_icon(root: tk.Tk) -> None: - if sys.platform == "win32" and APP_LOGO_ICO_PATH.exists(): - try: - root.iconbitmap(default=str(APP_LOGO_ICO_PATH)) - except tk.TclError: - LOGGER.warning("Failed to apply Windows ICO icon: %s", APP_LOGO_ICO_PATH, exc_info=True) - if not APP_LOGO_PNG_PATH.exists(): - LOGGER.warning("Application icon PNG is missing: %s", APP_LOGO_PNG_PATH) - return - try: - icon_image = tk.PhotoImage(file=str(APP_LOGO_PNG_PATH)) - root.iconphoto(True, icon_image) - root._mav_app_icon_image = icon_image # type: ignore[attr-defined] - except tk.TclError: - LOGGER.warning("Failed to apply Tk PNG icon: %s", APP_LOGO_PNG_PATH, exc_info=True) - - -def _style_popup_menu(menu: tk.Menu) -> None: - try: - menu.configure( - background=THEME["card_bg"], - foreground=THEME["text_primary"], - activebackground=THEME["menu_hover"], - activeforeground=THEME["text_primary"], - disabledforeground=THEME["text_muted"], - selectcolor=THEME["focus"], - borderwidth=1, - activeborderwidth=0, - relief=tk.SOLID, - font=(THEME["font_family"], THEME["font_size_base"]), - ) - except tk.TclError: - LOGGER.debug("Menu did not accept all themed options", exc_info=True) - - end_index = menu.index(tk.END) - if end_index is None: - return - for index in range(end_index + 1): - entry_type = menu.type(index) - try: - if entry_type == "separator": - menu.entryconfigure(index, background=THEME["card_border"]) - else: - menu.entryconfigure( - index, - background=THEME["card_bg"], - foreground=THEME["text_primary"], - activebackground=THEME["menu_hover"], - activeforeground=THEME["text_primary"], - ) - if entry_type == "cascade": - submenu_name = menu.entrycget(index, "menu") - submenu = menu.nametowidget(submenu_name) - if isinstance(submenu, tk.Menu): - _style_popup_menu(submenu) - except (tk.TclError, KeyError): - LOGGER.debug("Menu entry did not accept themed options", exc_info=True) - - -def _build_popup_menu(parent: tk.Widget) -> tk.Menu: - menu = tk.Menu(parent, tearoff=False) - _style_popup_menu(menu) - return menu - - -def _style_canvas_widget(widget: tk.Widget) -> None: - try: - widget.configure( - background=THEME["card_bg"], - highlightthickness=0, - highlightbackground=THEME["card_border"], - highlightcolor=THEME["card_border"], - takefocus=0, - ) - except tk.TclError: - LOGGER.debug("Canvas widget did not accept themed border options", exc_info=True) - - -def _configure_axis_chrome(ax) -> None: # noqa: ANN001 - ax.set_facecolor(THEME["plot_bg"]) - for spine in ax.spines.values(): - spine.set_color(THEME["axis_spine"]) - spine.set_linewidth(0.8) - ax.tick_params(colors=THEME["text_secondary"], labelsize=9, width=0.8) - - -def _style_legend(legend) -> None: # noqa: ANN001 - if legend is None: - return - legend.set_zorder(20) - frame = legend.get_frame() - frame.set_facecolor("none") - frame.set_edgecolor("none") - frame.set_alpha(0.0) - for text in legend.get_texts(): - text.set_color(THEME["text_primary"]) - - -def _new_response_hover_annotation(ax): # noqa: ANN001 - annotation = ax.annotate( - "", - xy=(0, 0), - xytext=(12, 12), - textcoords="offset points", - bbox={ - "boxstyle": "round,pad=0.35", - "facecolor": THEME["card_bg"], - "edgecolor": THEME["focus_soft"], - "alpha": 1.0, - "linewidth": 0.8, - }, - fontsize=9, - color=THEME["text_primary"], - annotation_clip=False, - zorder=60, - ) - annotation.set_clip_on(False) - annotation.set_visible(False) - return annotation - - -def _configure_pattern_preview_axis(ax, angles: np.ndarray | None = None) -> None: # noqa: ANN001 - _configure_axis_chrome(ax) - if angles is None or np.asarray(angles).size == 0: - low, high = -180.0, 180.0 - else: - finite = np.asarray(angles, dtype=float) - finite = finite[np.isfinite(finite)] - if finite.size == 0: - low, high = -180.0, 180.0 - else: - data_low = float(np.min(finite)) - data_high = float(np.max(finite)) - padding = max(5.0, (data_high - data_low) * 0.05) - low = max(-180.0, math.floor((data_low - padding) / 10.0) * 10.0) - high = min(180.0, math.ceil((data_high + padding) / 10.0) * 10.0) - major_step = 30.0 if high - low > 160.0 else 20.0 - ax.set_xlim(low, high) - ax.set_xticks(np.arange(low, high + 0.1, major_step)) - ax.set_xticks(np.arange(low, high + 0.1, 10.0), minor=True) - ax.grid(True, which="major", alpha=0.32, color=THEME["grid_major_color"], linewidth=0.6) - ax.grid(True, which="minor", alpha=0.18, color=THEME["grid_minor_color"], linewidth=0.45) - - -def _element_prefix(kind: str) -> str: - if kind == "tx": - return "Tx" - if kind == "rx": - return "Rx" - raise ValueError(f"Unknown element kind: {kind!r}") - - -def _max_elements_for_kind(kind: str) -> int: - if kind == "tx": - return MAX_TX_COUNT - if kind == "rx": - return MAX_RX_COUNT - raise ValueError(f"Unknown element kind: {kind!r}") - - -def _validate_element_count(raw_value, kind: str) -> int: # noqa: ANN001 - prefix = _element_prefix(kind) - max_count = _max_elements_for_kind(kind) - try: - count = int(str(raw_value).strip()) - except (TypeError, ValueError): - raise ValueError(f"{prefix} count must be an integer from 1 to {max_count}.") - if count < 1 or count > max_count: - raise ValueError(f"{prefix} count must be from 1 to {max_count}.") - return count - - -def _centered_auto_positions(count: int) -> list[float]: - offset = (count - 1) * AUTO_LAYOUT_SPACING / 2.0 - return [ - float(snap_to_grid(index * AUTO_LAYOUT_SPACING - offset)) - for index in range(count) - ] - - -def _build_auto_layout_elements(tx_count: int, rx_count: int) -> list[EditableElement]: - tx_x = _centered_auto_positions(tx_count) - rx_x = _centered_auto_positions(rx_count) - return [ - *[ - EditableElement( - kind="tx", - index=index, - name=f"Tx{index + 1}", - x=x, - y=AUTO_LAYOUT_TX_Y, - ) - for index, x in enumerate(tx_x) - ], - *[ - EditableElement( - kind="rx", - index=index, - name=f"Rx{index + 1}", - x=x, - y=AUTO_LAYOUT_RX_Y, - ) - for index, x in enumerate(rx_x) - ], - ] - - -def _starter_layout_elements() -> list[EditableElement]: - return [ - EditableElement(kind="tx", index=0, name="Tx1", x=0.0, y=AUTO_LAYOUT_TX_Y), - EditableElement(kind="rx", index=0, name="Rx1", x=0.0, y=AUTO_LAYOUT_RX_Y), - ] - - -def _snap_to_grid_inside(value: float, low: float, high: float) -> float: - snapped = snap_to_grid(value) - if snapped < low: - snapped = np.ceil(low / GRID_STEP) * GRID_STEP - elif snapped > high: - snapped = np.floor(high / GRID_STEP) * GRID_STEP - return _clip_to_bounds(float(snapped), low, high) - - -def _drag_position_with_offset( - pointer_x: float, - pointer_y: float, - grab_offset: tuple[float, float] | None, - bounds: tuple[float, float, float, float] | None, -) -> tuple[float, float]: - """Return a continuous drag position while preserving the grab point. - - Grid snapping is intentionally deferred until release. This keeps the - element glued to the pointer instead of jumping one grid cell per move. - """ - - offset_x, offset_y = grab_offset or (0.0, 0.0) - x = float(pointer_x) + float(offset_x) - y = float(pointer_y) + float(offset_y) - if bounds is None: - return x, y - min_x, max_x, min_y, max_y = bounds - return ( - _clip_to_bounds(x, min_x, max_x), - _clip_to_bounds(y, min_y, max_y), - ) - - -def _drag_axis_bounds_from_limits( - limits: tuple[tuple[float, float], tuple[float, float]], -) -> tuple[float, float, float, float]: - x_limits, y_limits = limits - return ( - _to_internal_half_lambda(x_limits[0]), - _to_internal_half_lambda(x_limits[1]), - _to_internal_half_lambda(y_limits[0]), - _to_internal_half_lambda(y_limits[1]), - ) - - -def _expanded_physical_drag_limits( - limits: tuple[tuple[float, float], tuple[float, float]], - internal_x: float, - internal_y: float, -) -> tuple[tuple[float, float], tuple[float, float]] | None: - x_limits, y_limits = limits - display_x = internal_x * DISPLAY_SCALE_LAMBDA - display_y = internal_y * DISPLAY_SCALE_LAMBDA - outside_x = display_x < x_limits[0] or display_x > x_limits[1] - outside_y = display_y < y_limits[0] or display_y > y_limits[1] - if not outside_x and not outside_y: - return None - x_values = np.array([x_limits[0], x_limits[1], display_x], dtype=float) - y_values = np.array([y_limits[0], y_limits[1], display_y], dtype=float) - minimum_span = max( - PHYSICAL_AXIS_MIN_SPAN_LAMBDA, - x_limits[1] - x_limits[0], - y_limits[1] - y_limits[0], - ) - return _square_axis_limits( - x_values, - y_values, - minimum_span=minimum_span, - padding=PHYSICAL_AXIS_PADDING_LAMBDA, - ) - - -def _element_touches_drag_bounds( - element: EditableElement, - bounds: tuple[float, float, float, float] | None, -) -> bool: - if bounds is None: - return False - min_x, max_x, min_y, max_y = bounds - tolerance = GRID_STEP * 0.5 - return ( - element.x <= min_x + tolerance - or element.x >= max_x - tolerance - or element.y <= min_y + tolerance - or element.y >= max_y - tolerance - ) - - -def _event_widget_is_text_input(event) -> bool: # noqa: ANN001 - widget = getattr(event, "widget", None) - if widget is None: - return False - try: - widget_class = widget.winfo_class() - except tk.TclError: - return False - return widget_class in { - "Entry", - "TEntry", - "Text", - "Combobox", - "TCombobox", - "Spinbox", - "TSpinbox", - } - - -def _axis_limits( - values: list[float] | np.ndarray, - minimum_span: float = 20.0, - padding: float = 6.0, -) -> tuple[float, float]: - value_array = np.asarray(values, dtype=float) - low = float(value_array.min()) - high = float(value_array.max()) - if high - low < minimum_span: - center = (low + high) / 2.0 - low = center - minimum_span / 2.0 - high = center + minimum_span / 2.0 - return low - padding, high + padding - - -def _axis_ticks_within(limits: tuple[float, float], step: float) -> np.ndarray: - low, high = limits - start = np.ceil(low / step) * step - stop = np.floor(high / step) * step - return np.arange(start, stop + step / 2.0, step) - - -def _apply_dbf_angle_ticks(ax) -> None: # noqa: ANN001 - ax.set_xticks(DBF_MAJOR_ANGLE_TICKS) - ax.set_xticks(DBF_MINOR_ANGLE_TICKS, minor=True) - - -def _apply_dbf_value_ticks(ax, display_mode: str) -> None: # noqa: ANN001 - if display_mode == DBF_DISPLAY_MAGNITUDE: - ax.set_yticks(DBF_MAGNITUDE_Y_TICKS) - else: - ax.set_yticks(DBF_DB_Y_TICKS) - - -def _square_axis_limits( - x_values: list[float] | np.ndarray, - y_values: list[float] | np.ndarray, - minimum_span: float, - padding: float, -) -> tuple[tuple[float, float], tuple[float, float]]: - x_low, x_high = _axis_limits(x_values, minimum_span=minimum_span, padding=padding) - y_low, y_high = _axis_limits(y_values, minimum_span=minimum_span, padding=padding) - x_span = x_high - x_low - y_span = y_high - y_low - target_span = max(x_span, y_span) - - if x_span < target_span: - x_center = (x_low + x_high) / 2.0 - x_low = x_center - target_span / 2.0 - x_high = x_center + target_span / 2.0 - if y_span < target_span: - y_center = (y_low + y_high) / 2.0 - y_low = y_center - target_span / 2.0 - y_high = y_center + target_span / 2.0 - return (x_low, x_high), (y_low, y_high) - - -def _fixed_box_equal_limits( - x_values: list[float] | np.ndarray, - y_values: list[float] | np.ndarray, - fig_width_in: float, - fig_height_in: float, - x_padding: float = 6.0, - y_padding: float = 6.0, - minimum_span: float = 20.0, -) -> tuple[tuple[float, float], tuple[float, float]]: - """Compute equal-aspect axis limits given a standalone Figure size.""" - x_low, x_high = _axis_limits(x_values, minimum_span=minimum_span, padding=x_padding) - y_low, y_high = _axis_limits(y_values, minimum_span=minimum_span, padding=y_padding) - x_span = x_high - x_low - y_span = y_high - y_low - box_ratio = fig_width_in / fig_height_in - data_ratio = x_span / y_span if y_span else box_ratio - - if data_ratio < box_ratio: - target_x_span = y_span * box_ratio - center = (x_low + x_high) / 2.0 - x_low = center - target_x_span / 2.0 - x_high = center + target_x_span / 2.0 - elif data_ratio > box_ratio: - target_y_span = x_span / box_ratio - center = (y_low + y_high) / 2.0 - y_low = center - target_y_span / 2.0 - y_high = center + target_y_span / 2.0 - - return (x_low, x_high), (y_low, y_high) - - -def _azimuth_status_label(metrics: ArrayMetrics) -> str: - labels = { - "Good": "方位良好", - "Acceptable": "方位可用", - "Risky": "方位风险", - "Bad": "方位较差", - } - return labels.get(metrics.front_radar_status, f"方位{metrics.front_radar_status}") - - -def _ambiguity_level_label(value: str) -> str: - labels = {"High": "高", "Medium": "中", "Low": "低"} - return labels.get(value, value) - - -def _angle_cut_reason_summary( - metrics: DbfAngleMetrics | None, - language: str = LANGUAGE_ZH, -) -> str: - if metrics is None: - return "N/A" - reason_keys = { - "竞争峰模糊": "cut_reason_peak_blurred", - "到达数据边界": "cut_reason_data_boundary", - "边界受限": "cut_reason_boundary_limited", - "误差跳变": "cut_reason_error_jump", - "谱不可靠": "cut_reason_unreliable", - "正常": "cut_reason_normal", - } - negative_key = reason_keys.get(metrics.negative_cut_reason) - positive_key = reason_keys.get(metrics.positive_cut_reason) - negative = ( - _text_for_language(negative_key, language) - if negative_key is not None - else metrics.negative_cut_reason - ) or "N/A" - positive = ( - _text_for_language(positive_key, language) - if positive_key is not None - else metrics.positive_cut_reason - ) or "N/A" - if negative == positive: - return negative - return _text_for_language( - "cut_reason_pair", - language, - negative=negative, - positive=positive, - ) - - -def _legacy_note_key(note: str) -> str: - note_lower = note.lower() - if "duplicate" in note_lower or "重复" in note: - return "duplicate" - if "windowing" in note_lower or "加窗" in note or "旁瓣" in note: - return "windowing" - if "ambiguity high" in note_lower or "模糊风险高" in note: - return "ambiguity high" - if "ambiguity medium" in note_lower or "模糊风险中" in note: - return "ambiguity medium" - if "不可用" in note or "未覆盖" in note: - return "ambiguity high" - return "none" - - -def _note_display(note: str) -> tuple[str, str]: - key = _legacy_note_key(note) - icon, color = NOTE_STYLES[key] - return f"{icon} {note}", color - - -def _dbf_mode_label(mode: str | None, language: str = LANGUAGE_ZH) -> str: - if mode == "elevation": - return _text_for_language("el", language) - return _text_for_language("az", language) - - -def _dbf_short_label(mode: str | None, language: str = LANGUAGE_ZH) -> str: - if mode == "elevation": - return _text_for_language("el_short", language) - return _text_for_language("az_short", language) - - -def _dbf_dictionary_mode_label(mode: str, language: str = LANGUAGE_ZH) -> str: - labels = { - DBF_DICT_IDEAL: "dbf_dict_ideal", - DBF_DICT_IDEAL_REVERSED: "dbf_dict_reversed", - DBF_DICT_CHANNEL_PATTERN: "dbf_dict_channel", - DBF_DICT_CHANNEL_PATTERN_ZERO_REF: "dbf_dict_channel", - DBF_DICT_CUSTOM: "dbf_dict_custom", - } - return _text_for_language(labels.get(mode, "dbf_dict_ideal"), language) - - -def _dbf_dictionary_chip_label(mode: str, language: str = LANGUAGE_ZH) -> str: - labels = { - DBF_DICT_IDEAL: "chip_dict_ideal", - DBF_DICT_IDEAL_REVERSED: "chip_dict_reversed", - DBF_DICT_CHANNEL_PATTERN: "chip_dict_channel", - DBF_DICT_CHANNEL_PATTERN_ZERO_REF: "chip_dict_channel", - DBF_DICT_CUSTOM: "chip_dict_custom", - } - return _text_for_language(labels.get(mode, "chip_dict_ideal"), language) - - -def _format_dbf_angle_label(angle: float, language: str = LANGUAGE_ZH) -> str: - if abs(angle) < 0.05: - return "0°" if language != LANGUAGE_EN else "0 deg" - return f"{angle:+.0f}°" if language != LANGUAGE_EN else f"{angle:+.0f} deg" - - -def _series_table_label(series, language: str = LANGUAGE_ZH) -> str: # noqa: ANN001 - if series is None: - return _text_for_language("ideal", language) - return series.short_label() - - -def _pattern_slot_label(kind: str, plane: str, language: str = LANGUAGE_ZH) -> str: - kind_label = _text_for_language( - "amp" if kind == PATTERN_KIND_AMPLITUDE else "phase", language - ) - plane_label = _text_for_language( - "el_short" if plane == PATTERN_PLANE_ELEVATION else "az_short", - language, - ) - return f"{plane_label}{kind_label}" if language != LANGUAGE_EN else f"{plane_label} {kind_label}" - - -def _dbf_frame_index_for_angle(angle: float) -> int: - frame = int(round((angle - DBF_SCAN_FOV[0]) / DBF_SCAN_STEP_DEG)) - return max(0, min(DBF_SCAN_GRID_SIZE - 1, frame)) - - -def _dbf_peak_index( - scan_angles: np.ndarray, - spectrum_db: np.ndarray, - true_angle: float, - tolerance_db: float = 1e-6, -) -> int: - return analysis_dbf_peak_index( - scan_angles, - spectrum_db, - true_angle, - tolerance_db=tolerance_db, - ) - - -# ═══════════════════════════════════════════════════════════════════════ -# Main GUI class -# ═══════════════════════════════════════════════════════════════════════ -class VirtualArrayGui: - """Controller for the native three-page PySide6 workspace.""" - - def _t(self, key: str, **kwargs) -> str: - return _text_for_language(key, getattr(self, "language", LANGUAGE_ZH), **kwargs) - - def __init__(self, window: QtWidgets.QMainWindow | tk.Tk) -> None: - if isinstance(window, tk.Tk): - root = window - else: - existing_root = getattr(window, "_tk_owner", None) - root = existing_root if isinstance(existing_root, tk.Tk) else tk.Tk(window) - self.root = root - apply_native_theme(root._app) - self.language = LANGUAGE_ZH - self.language_var = tk.StringVar(value=LANGUAGE_LABELS[self.language]) - self.root.title(self._t("app_title", version=APP_VERSION)) - self.root.configure(bg=THEME["bg"]) - - # Data state - self.elements = self._build_elements() - self.dragging: EditableElement | None = None - self.drag_bounds: tuple[float, float, float, float] | None = None - self.drag_axis_limits: tuple[tuple[float, float], tuple[float, float]] | None = None - self.drag_start_snapshot: LayoutSnapshot | None = None - self.drag_grab_offset: tuple[float, float] | None = None - self._physical_drag_after_id: str | None = None - self.selected_element: EditableElement | None = None - self.delete_mode = False - self.undo_stack: deque[LayoutSnapshot] = deque(maxlen=MAX_HISTORY_STATES) - self.redo_stack: deque[LayoutSnapshot] = deque(maxlen=MAX_HISTORY_STATES) - - # Hover state - self.physical_hover_annotation = None - self.physical_hover_marker = None - self.virtual_hover_annotation = None - self.virtual_hover_marker = None - self.virtual_hover_xy = np.empty((0, 2), dtype=float) - self.virtual_hover_counts = np.empty(0, dtype=int) - self.virtual_hover_text: list[str] = [] - self.physical_buttons: list[MplButton] = [] - self.physical_button_callbacks: list[int] = [] - self.physical_action_buttons: dict[str, ttk.Button] = {} - self.dbf_scan_active = False - self.dbf_scan_paused = False - self.dbf_scan_mode: str | None = None - self.dbf_scan_after_id: str | None = None - self.dbf_true_angles = np.empty(0, dtype=float) - self.dbf_scan_angles = np.empty(0, dtype=float) - self.dbf_spectra_db = np.empty((0, 0), dtype=float) - self.dbf_scan_frame = 0 - self.dbf_drag_mode: str | None = None - self.dbf2d_az_frame = _dbf_frame_index_for_angle(0.0) - self.dbf2d_el_frame = _dbf_frame_index_for_angle(0.0) - self.dbf2d_az_playing = False - self.dbf2d_el_playing = False - self.dbf2d_after_id: str | None = None - self.dbf2d_progress_updating = False - self.dbf2d_dragging = False - self.dbf2d_az_var: tk.DoubleVar | None = None - self.dbf2d_el_var: tk.DoubleVar | None = None - self.dbf2d_az_button: ttk.Button | None = None - self.dbf2d_el_button: ttk.Button | None = None - self.dbf2d_stop_button: ttk.Button | None = None - self.dbf2d_controls_widget: ttk.Frame | None = None - self.dbf2d_status_label: ttk.Label | None = None - self.dbf2d_fig: Figure | None = None - self.dbf2d_ax = None - self.dbf2d_cbar_ax = None - self.dbf2d_canvas: FigureCanvasTkAgg | None = None - self.dbf2d_empty_overlay: _EmptyStateOverlay | None = None - self.dbf2d_hover_annotation = None - self.dbf2d_hover_marker = None - self.dbf2d_hover_azimuths = np.empty(0, dtype=float) - self.dbf2d_hover_elevations = np.empty(0, dtype=float) - self.dbf2d_hover_db = np.empty((0, 0), dtype=float) - self.current_metrics: ArrayMetrics | None = None - self.main_notebook: ttk.Notebook | None = None - self.main_tab_buttons: dict[int, ttk.Button] = {} - self.main_tab_label_keys = { - 0: "main_tab_physical_virtual", - 1: "main_tab_1d", - 2: "main_tab_2d", - } - self.config_menu_button: ttk.Menubutton | None = None - self.language_menu_button: ttk.Menubutton | None = None - self.edit_menu_button: ttk.Menubutton | None = None - self.help_menu_button: ttk.Menubutton | None = None - self.app_logo_image: tk.PhotoImage | None = None - self.app_brand_label: ttk.Label | None = None - self.config_menu: tk.Menu | None = None - self.language_menu: tk.Menu | None = None - self.edit_menu: tk.Menu | None = None - self.help_menu: tk.Menu | None = None - self.native_menu_bar: QtWidgets.QMenuBar | None = None - self._native_brand_label: QtWidgets.QLabel | None = None - self.native_menus: dict[str, QtWidgets.QMenu] = {} - self.native_actions: dict[str, QtGui.QAction] = {} - self.native_language_actions: dict[str, QtGui.QAction] = {} - self.native_manual_menu: QtWidgets.QMenu | None = None - self.native_manual_chapter_actions: dict[str, QtGui.QAction] = {} - self.native_status_bar: QtWidgets.QStatusBar | None = None - self._manual_dialog: QtWidgets.QDialog | None = None - self._manual_select_chapter = None - self.workspace_splitter: QtWidgets.QSplitter | None = None - self._performance_report_thread: QtCore.QThread | None = None - self._performance_report_worker: _PerformanceReportWorker | None = None - self._performance_report_bridge: _PerformanceReportUiBridge | None = None - self._performance_report_progress: QtWidgets.QProgressDialog | None = None - self._performance_report_dialog: QtWidgets.QDialog | None = None - self._performance_export_parent: QtWidgets.QWidget | None = None - self._performance_export_kind = "report" - - self.element_pattern: ElementPattern | None = None - self.channel_patterns = ChannelPatternSet() - self.dbf_dictionary = DbfDictionaryConfig() - self.auto_tx_count = tk.StringVar(value="1") - self.auto_rx_count = tk.StringVar(value="1") - self.last_valid_frequency_ghz = DEFAULT_FREQUENCY_GHZ - self.frequency_ghz = tk.StringVar( - value=_format_frequency_ghz(DEFAULT_FREQUENCY_GHZ) - ) - self.frequency_entry: ttk.Entry | None = None - self.dbf_display_mode = tk.StringVar(value=DBF_DISPLAY_DB) - self.dbf_display_label: ttk.Label | None = None - self.dbf_display_db_radio: ttk.Radiobutton | None = None - self.dbf_display_mag_radio: ttk.Radiobutton | None = None - self.pattern_status = tk.StringVar(value=self._t("pattern_ideal")) - self.pattern_canvas: tk.Canvas | None = None - self.pattern_dot: int | None = None - self.status = tk.StringVar( - value=self._t("status_initial") - ) - self.header_frequency_text = tk.StringVar() - self.header_dictionary_text = tk.StringVar() - self.header_pattern_text = tk.StringVar() - self.header_kpi_texts: dict[str, tk.StringVar] = { - "chip_virtual_channels": tk.StringVar(value="N/A"), - "chip_az_resolution": tk.StringVar(value="N/A"), - "chip_el_resolution": tk.StringVar(value="N/A"), - } - self.header_title_label: ttk.Label | None = None - self.header_subtitle_label: ttk.Label | None = None - self.header_title_group: ttk.Frame | None = None - self.header_chip_labels: dict[str, ttk.Label] = {} - self.header_chip_value_labels: dict[str, ttk.Label] = {} - self.last_layout_dir = Path("outputs").resolve() - self.last_report_dir = Path("outputs").resolve() - self.last_report_error_limit_deg = 1.0 - self.last_pattern_dir = Path.home() - self.last_valid_margin_db = DBF_AMBIGUITY_MARGIN_DB - self.margin_db = tk.StringVar(value=_format_margin_db(DBF_AMBIGUITY_MARGIN_DB)) - self.margin_entry: ttk.Entry | None = None - self._restored_active_tab = 0 - self._restored_splitter_sizes: list[int] | None = None - self._load_local_state() - self._sync_auto_count_inputs() - - # ── Build the grid layout ───────────────────────────────── - root.grid_rowconfigure(0, weight=0) # Codex-style menu - root.grid_rowconfigure(1, weight=0) # Workspace header - root.grid_rowconfigure(2, weight=1, minsize=400) - root.grid_rowconfigure(3, weight=0) # Controls - root.grid_columnconfigure(0, weight=1, minsize=PLOT_COLUMN_MIN_WIDTH * 2) - root.grid_columnconfigure(1, weight=0) - root.grid_columnconfigure(2, weight=0) - style = ttk.Style(self.root) - style.theme_use("clam") - - # ── Refined ttk styles ───────────────────────────────────── - _f = THEME["font_family"] - _fm = THEME["font_family_mono"] - root.option_add("*Font", f"{{{_f}}} {THEME['font_size_base']}") - root.option_add("*Menu.Font", f"{{{_f}}} {THEME['font_size_base']}") - root.option_add("*Menu.background", THEME["card_bg"]) - root.option_add("*Menu.foreground", THEME["text_primary"]) - root.option_add("*Menu.activeBackground", THEME["menu_hover"]) - root.option_add("*Menu.activeForeground", THEME["text_primary"]) - root.option_add("*Menu.disabledForeground", THEME["text_muted"]) - root.option_add("*Menu.selectColor", THEME["focus"]) - root.option_add("*Menu.borderWidth", 1) - root.option_add("*Menu.activeBorderWidth", 0) - root.option_add("*Menu.relief", "solid") - root.option_add("*selectBackground", THEME["selection_fill"]) - root.option_add("*selectForeground", THEME["text_primary"]) - - style.configure("TFrame", background=THEME["bg"]) - style.configure("Panel.TFrame", background=THEME["panel_bg"], borderwidth=0) - style.configure( - "PlotPanel.TFrame", - background=THEME["card_bg"], - bordercolor=THEME["card_bg"], - lightcolor="#ffffff", - darkcolor=THEME["card_bg"], - relief="flat", - borderwidth=0, - ) - style.configure("ChartPane.TFrame", background=THEME["card_bg"], borderwidth=0) - style.configure("Card.TFrame", background=THEME["card_bg"]) - style.configure("Dialog.TFrame", background=THEME["bg"]) - style.configure( - "DialogRail.TLabelframe", - background=THEME["panel_bg"], - foreground=THEME["text_primary"], - font=(_f, THEME["font_size_base"], "bold"), - relief="flat", - borderwidth=0, - ) - style.configure( - "DialogContent.TLabelframe", - background=THEME["card_bg"], - foreground=THEME["text_primary"], - font=(_f, THEME["font_size_base"], "bold"), - relief="flat", - borderwidth=0, - ) - style.configure("Toolbar.TFrame", background=THEME["status_bar_bg"]) - style.configure("AppMenu.TFrame", background=THEME["app_menu_bg"]) - style.configure("Header.TFrame", background=THEME["header_bg"]) - style.configure("Workspace.TPanedwindow", background=THEME["bg"]) - style.configure( - "HeaderChip.TFrame", - background=THEME["header_bg"], - bordercolor=THEME["header_bg"], - lightcolor="#ffffff", - darkcolor=THEME["header_bg"], - relief="flat", - borderwidth=0, - ) - style.configure( - "ToolbarGroup.TFrame", - background=THEME["status_bar_bg"], - borderwidth=0, - ) - style.configure("PreviewToolbar.TFrame", background=THEME["card_bg"], borderwidth=0) - style.configure("ChartFooter.TFrame", background=THEME["panel_alt_bg"]) - style.configure("Status.TFrame", background=THEME["status_bar_bg"]) - style.configure("StatusInner.TFrame", background=THEME["status_bar_bg"]) - - style.configure( - "TLabel", - background=THEME["bg"], - foreground=THEME["text_primary"], - font=(_f, THEME["font_size_base"]), - ) - style.configure( - "Toolbar.TLabel", - background=THEME["status_bar_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"], "bold"), - ) - style.configure( - "DialogSectionTitle.TLabel", - background="transparent", - foreground=THEME["text_primary"], - font=(_f, THEME["font_size_base"], "bold"), - ) - style.configure( - "DialogSummary.TLabel", - background="transparent", - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"]), - ) - style.configure( - "Status.TLabel", - background=THEME["status_bar_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"]), - ) - style.configure( - "HeaderTitle.TLabel", - background=THEME["header_bg"], - foreground=THEME["text_primary"], - font=(_f, 13, "bold"), - ) - style.configure( - "HeaderSubtitle.TLabel", - background=THEME["header_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"]), - ) - style.configure( - "HeaderChipName.TLabel", - background=THEME["header_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"], "bold"), - ) - style.configure( - "HeaderChipValue.TLabel", - background=THEME["header_bg"], - foreground=THEME["accent"], - font=(_fm, THEME["font_size_sm"], "bold"), - ) - style.configure( - "HeaderChipPatternValue.TLabel", - background=THEME["header_bg"], - foreground=THEME["accent"], - font=(_f, THEME["font_size_sm"], "bold"), - ) - style.configure( - "HeaderLogo.TLabel", - background=THEME["header_bg"], - padding=(0, 0), - ) - style.configure( - "AppLogo.TLabel", - background=THEME["app_menu_bg"], - foreground=THEME["accent"], - font=(_f, 13, "bold"), - padding=(0, 0), - ) - style.configure( - "AppBrand.TLabel", - background=THEME["app_menu_bg"], - foreground=THEME["text_primary"], - font=(_f, 13, "bold"), - ) - style.configure( - "AppSeparator.TLabel", - background=THEME["app_menu_bg"], - foreground=THEME["card_border"], - font=(_f, THEME["font_size_lg"]), - ) - style.configure( - "Muted.TLabel", - background="transparent", - foreground=THEME["text_muted"], - font=(_f, THEME["font_size_sm"]), - ) - style.configure( - "ChartFooter.TLabel", - background=THEME["panel_alt_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"]), - ) - style.configure( - "Card.TLabel", - background=THEME["card_bg"], - foreground=THEME["text_primary"], - font=(_f, THEME["font_size_base"]), - ) - style.configure( - "CardMono.TLabel", - background=THEME["card_bg"], - foreground=THEME["text_primary"], - font=(_fm, THEME["font_size_base"]), - ) - style.configure( - "CardHeader.TLabel", - background=THEME["card_bg"], - foreground=THEME["text_primary"], - font=(_fm, THEME["font_size_base"], "bold"), - ) - style.configure( - "SectionTitle.TLabel", - background=THEME["card_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"], "bold"), - ) - style.configure( - "Badge.TLabel", - background=THEME["card_bg"], - foreground=THEME["text_primary"], - font=(_f, THEME["font_size_lg"], "bold"), - ) - style.configure( - "Metric.TFrame", - background=THEME["metric_bg"], - bordercolor=THEME["metric_bg"], - lightcolor="#ffffff", - darkcolor=THEME["metric_bg"], - relief="flat", - borderwidth=0, - ) - style.configure( - "MetricName.TLabel", - background=THEME["metric_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"]), - ) - style.configure( - "MetricSection.TLabel", - background=THEME["metric_bg"], - foreground=THEME["text_primary"], - font=(_f, THEME["font_size_base"], "bold"), - ) - style.configure( - "MetricValue.TLabel", - background=THEME["metric_bg"], - foreground=THEME["text_primary"], - font=(_fm, THEME["font_size_base"], "bold"), - ) - style.configure( - "MetricValueMuted.TLabel", - background=THEME["metric_bg"], - foreground=THEME["text_muted"], - font=(_fm, THEME["font_size_base"], "bold"), - ) - style.configure( - "MetricValueGood.TLabel", - background=THEME["metric_bg"], - foreground=THEME["success"], - font=(_fm, THEME["font_size_base"], "bold"), - ) - style.configure( - "MetricValueWarn.TLabel", - background=THEME["metric_bg"], - foreground=THEME["warning"], - font=(_fm, THEME["font_size_base"], "bold"), - ) - style.configure( - "MetricValueRisk.TLabel", - background=THEME["metric_bg"], - foreground=THEME["danger"], - font=(_fm, THEME["font_size_base"], "bold"), - ) - - button_base = { - "padding": (10, 5), - "relief": "flat", - "borderwidth": 1, - "focuscolor": THEME["focus"], - } - button_font = (_f, THEME["font_size_base"]) - style.configure( - "TButton", - **button_base, - font=button_font, - background=THEME["button_bg"], - foreground=THEME["text_primary"], - bordercolor=THEME["button_border"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["button_border"], - ) - style.map( - "TButton", - background=[ - ("disabled", THEME["disabled_bg"]), - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - foreground=[ - ("disabled", THEME["text_muted"]), - ("active", THEME["text_primary"]), - ], - bordercolor=[ - ("pressed", THEME["focus"]), - ("focus", THEME["focus"]), - ("active", THEME["focus_soft"]), - ], - lightcolor=[("pressed", THEME["button_pressed"]), ("active", THEME["button_hover"])], - darkcolor=[("pressed", THEME["button_pressed"]), ("active", THEME["button_hover"])], - ) - style.configure( - "Accent.TButton", - **button_base, - font=(_f, THEME["font_size_base"], "bold"), - background=THEME["primary_fill"], - foreground=THEME["text_inverse"], - bordercolor=THEME["primary_fill"], - lightcolor=THEME["primary_fill"], - darkcolor=THEME["primary_pressed"], - ) - style.map( - "Accent.TButton", - background=[ - ("disabled", "#9ca3af"), - ("pressed", THEME["primary_pressed"]), - ("active", THEME["primary_hover"]), - ], - foreground=[("disabled", "#f8fafc"), ("active", THEME["text_inverse"])], - bordercolor=[("focus", THEME["focus"]), ("active", THEME["primary_hover"])], - lightcolor=[("pressed", THEME["primary_pressed"]), ("active", THEME["primary_hover"])], - darkcolor=[("pressed", THEME["primary_pressed"]), ("active", THEME["primary_hover"])], - ) - large_button_map = { - "background": [ - ("disabled", THEME["disabled_bg"]), - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - "foreground": [ - ("disabled", THEME["text_muted"]), - ("active", THEME["text_primary"]), - ], - "bordercolor": [ - ("pressed", THEME["focus"]), - ("focus", THEME["focus"]), - ("active", THEME["focus_soft"]), - ], - "lightcolor": [ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - "darkcolor": [ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - } - style.configure( - "Large.TButton", - **{**button_base, "relief": "solid"}, - font=button_font, - background=THEME["button_bg"], - foreground=THEME["text_primary"], - bordercolor=THEME["button_border"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["button_border"], - ) - style.map("Large.TButton", **large_button_map) - compact_button_base = { - **button_base, - "padding": (8, 3), - } - style.configure( - "Compact.TButton", - **compact_button_base, - font=(_f, THEME["font_size_sm"], "bold"), - background=THEME["button_bg"], - foreground=THEME["text_primary"], - bordercolor=THEME["button_border"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["button_border"], - ) - style.map("Compact.TButton", **large_button_map) - style.configure( - "CompactPlay.TButton", - **compact_button_base, - font=(_f, THEME["font_size_sm"], "bold"), - background=THEME["button_bg"], - foreground=THEME["focus"], - bordercolor=THEME["focus_soft"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["focus_soft"], - ) - style.map( - "CompactPlay.TButton", - background=[ - ("disabled", THEME["disabled_bg"]), - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - foreground=[ - ("disabled", THEME["text_muted"]), - ("pressed", THEME["focus"]), - ("active", THEME["focus"]), - ], - bordercolor=[ - ("disabled", THEME["button_border"]), - ("focus", THEME["focus"]), - ("active", THEME["focus"]), - ], - lightcolor=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - darkcolor=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - ) - style.configure( - "CompactPlayActive.TButton", - **compact_button_base, - font=(_f, THEME["font_size_sm"], "bold"), - background=THEME["button_bg"], - foreground=THEME["focus"], - bordercolor=THEME["focus"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["focus"], - ) - style.map( - "CompactPlayActive.TButton", - background=[ - ("disabled", THEME["disabled_bg"]), - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - foreground=[ - ("disabled", THEME["text_muted"]), - ("active", THEME["focus"]), - ], - bordercolor=[ - ("disabled", THEME["button_border"]), - ("focus", THEME["focus"]), - ("active", THEME["focus"]), - ], - lightcolor=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - darkcolor=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - ) - style.configure( - "CompactStop.TButton", - **compact_button_base, - font=(_f, THEME["font_size_sm"], "bold"), - background=THEME["button_bg"], - foreground=THEME["danger"], - bordercolor=THEME["danger_border"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["danger_border"], - ) - style.map( - "CompactStop.TButton", - background=[ - ("disabled", THEME["disabled_bg"]), - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - foreground=[ - ("disabled", THEME["text_muted"]), - ("pressed", THEME["danger_pressed"]), - ("active", THEME["danger_pressed"]), - ], - bordercolor=[ - ("disabled", THEME["button_border"]), - ("focus", THEME["danger"]), - ("active", THEME["danger"]), - ], - lightcolor=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - darkcolor=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - ) - style.configure( - "CompactAccent.TButton", - **compact_button_base, - font=(_f, THEME["font_size_sm"], "bold"), - background=THEME["button_bg"], - foreground=THEME["text_primary"], - bordercolor=THEME["button_border"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["button_border"], - ) - style.map( - "CompactAccent.TButton", - background=[ - ("disabled", THEME["disabled_bg"]), - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - foreground=[("disabled", THEME["text_muted"]), ("active", THEME["text_primary"])], - bordercolor=[("focus", THEME["focus"]), ("active", THEME["focus_soft"])], - lightcolor=[("pressed", THEME["button_pressed"]), ("active", THEME["button_hover"])], - darkcolor=[("pressed", THEME["button_pressed"]), ("active", THEME["button_hover"])], - ) - style.configure( - "ToolbarPrimary.TButton", - **{**compact_button_base, "padding": (14, 4)}, - font=(_f, THEME["font_size_sm"], "bold"), - background=THEME["primary_fill"], - foreground=THEME["text_inverse"], - bordercolor=THEME["primary_fill"], - lightcolor=THEME["primary_fill"], - darkcolor=THEME["primary_pressed"], - ) - style.map( - "ToolbarPrimary.TButton", - background=[ - ("disabled", "#9ca3af"), - ("pressed", THEME["primary_pressed"]), - ("active", THEME["primary_hover"]), - ], - foreground=[("disabled", "#f8fafc"), ("active", THEME["text_inverse"])], - bordercolor=[ - ("disabled", THEME["button_border"]), - ("focus", THEME["focus"]), - ("active", THEME["primary_hover"]), - ], - lightcolor=[("pressed", THEME["primary_pressed"]), ("active", THEME["primary_hover"])], - darkcolor=[("pressed", THEME["primary_pressed"]), ("active", THEME["primary_hover"])], - ) - style.configure( - "CompactDanger.TButton", - **compact_button_base, - font=(_f, THEME["font_size_sm"], "bold"), - background=THEME["button_bg"], - foreground=THEME["danger"], - bordercolor=THEME["danger"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["danger_border"], - ) - style.map( - "CompactDanger.TButton", - background=[("pressed", THEME["button_pressed"]), ("active", THEME["button_hover"])], - foreground=[("active", THEME["danger_pressed"])], - bordercolor=[("pressed", THEME["danger_pressed"]), ("active", THEME["danger"])], - lightcolor=[("pressed", THEME["button_pressed"]), ("active", THEME["button_hover"])], - darkcolor=[("pressed", THEME["button_pressed"]), ("active", THEME["button_hover"])], - ) - style.configure( - "Toolbar.TMenubutton", - **button_base, - font=(_f, THEME["font_size_base"], "bold"), - background=THEME["button_bg"], - foreground=THEME["text_primary"], - bordercolor=THEME["button_border"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["button_border"], - ) - style.map( - "Toolbar.TMenubutton", - background=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - foreground=[("active", THEME["text_primary"])], - bordercolor=[ - ("pressed", THEME["focus"]), - ("focus", THEME["focus"]), - ("active", THEME["focus_soft"]), - ], - lightcolor=[("pressed", THEME["button_pressed"]), ("active", THEME["button_hover"])], - darkcolor=[("pressed", THEME["button_pressed"]), ("active", THEME["button_hover"])], - ) - style.configure( - "TopMenu.TMenubutton", - padding=(14, 7), - relief="flat", - borderwidth=0, - font=(_f, THEME["font_size_base"], "bold"), - background=THEME["app_menu_bg"], - foreground=THEME["app_menu_text"], - bordercolor=THEME["app_menu_bg"], - lightcolor=THEME["app_menu_bg"], - darkcolor=THEME["app_menu_bg"], - arrowcolor=THEME["app_menu_text"], - ) - style.map( - "TopMenu.TMenubutton", - background=[ - ("pressed", THEME["app_menu_hover"]), - ("active", THEME["app_menu_hover"]), - ], - foreground=[ - ("pressed", THEME["app_menu_text_active"]), - ("active", THEME["app_menu_text_active"]), - ], - bordercolor=[ - ("pressed", THEME["app_menu_hover"]), - ("active", THEME["app_menu_hover"]), - ], - lightcolor=[ - ("pressed", THEME["app_menu_hover"]), - ("active", THEME["app_menu_hover"]), - ], - darkcolor=[ - ("pressed", THEME["app_menu_hover"]), - ("active", THEME["app_menu_hover"]), - ], - arrowcolor=[ - ("pressed", THEME["app_menu_text_active"]), - ("active", THEME["app_menu_text_active"]), - ], - ) - style.configure( - "AppMenuArrow.TLabel", - background=THEME["app_menu_bg"], - foreground=THEME["app_menu_text"], - font=(_f, THEME["font_size_base"], "bold"), - ) - style.configure( - "Danger.TButton", - **{**button_base, "relief": "solid"}, - font=button_font, - background=THEME["danger_light"], - foreground=THEME["danger"], - bordercolor=THEME["danger"], - lightcolor=THEME["danger_light"], - darkcolor=THEME["danger_border"], - ) - style.map( - "Danger.TButton", - background=[ - ("disabled", THEME["disabled_bg"]), - ("pressed", "#fee2e2"), - ("active", THEME["danger_light"]), - ], - foreground=[ - ("disabled", THEME["text_muted"]), - ("pressed", THEME["danger_pressed"]), - ("active", THEME["danger_pressed"]), - ], - bordercolor=[ - ("disabled", THEME["button_border"]), - ("focus", THEME["danger"]), - ("active", THEME["danger"]), - ], - lightcolor=[("pressed", "#fee2e2"), ("active", THEME["danger_light"])], - darkcolor=[("pressed", "#fee2e2"), ("active", THEME["danger_light"])], - ) - dialog_button_base = { - **button_base, - "padding": (12, 7), - "relief": "solid", - } - dialog_button_map = { - "background": [ - ("disabled", THEME["disabled_bg"]), - ("pressed", THEME["dialog_button_pressed"]), - ("active", THEME["dialog_button_hover"]), - ], - "foreground": [ - ("disabled", THEME["text_muted"]), - ("active", THEME["text_primary"]), - ], - "bordercolor": [ - ("disabled", THEME["button_border"]), - ("focus", THEME["button_border"]), - ("active", THEME["button_border"]), - ], - "lightcolor": [ - ("pressed", THEME["dialog_button_pressed"]), - ("active", THEME["dialog_button_hover"]), - ], - "darkcolor": [ - ("pressed", THEME["dialog_button_pressed"]), - ("active", THEME["dialog_button_hover"]), - ], - } - style.configure( - "DialogButton.TButton", - **dialog_button_base, - font=button_font, - background=THEME["button_bg"], - foreground=THEME["text_primary"], - bordercolor=THEME["button_border"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["button_border"], - ) - style.map("DialogButton.TButton", **dialog_button_map) - style.configure( - "DialogDanger.TButton", - **dialog_button_base, - font=button_font, - background=THEME["button_bg"], - foreground=THEME["danger"], - bordercolor=THEME["button_border"], - lightcolor=THEME["button_bg"], - darkcolor=THEME["button_border"], - ) - danger_dialog_map = { - **dialog_button_map, - "foreground": [ - ("disabled", THEME["text_muted"]), - ("pressed", THEME["danger_pressed"]), - ("active", THEME["danger_pressed"]), - ], - } - style.map("DialogDanger.TButton", **danger_dialog_map) - - style.configure( - "TLabelframe", - background=THEME["card_bg"], - foreground=THEME["text_secondary"], - bordercolor=THEME["card_border"], - lightcolor=THEME["card_bg"], - darkcolor=THEME["card_border"], - relief="solid", - borderwidth=1, - font=(_f, THEME["font_size_sm"], "bold"), - ) - style.configure( - "TLabelframe.Label", - background=THEME["card_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"], "bold"), - ) - - style.configure( - "TEntry", - font=(_f, THEME["font_size_base"]), - padding=(6, 4), - fieldbackground=THEME["input_bg"], - background=THEME["input_bg"], - foreground=THEME["text_primary"], - bordercolor=THEME["button_border"], - lightcolor=THEME["input_bg"], - darkcolor=THEME["button_border"], - insertcolor=THEME["text_primary"], - selectbackground=THEME["selection_fill"], - selectforeground=THEME["text_primary"], - ) - style.map( - "TEntry", - bordercolor=[ - ("focus", THEME["focus"]), - ("active", THEME["focus_soft"]), - ], - fieldbackground=[ - ("disabled", THEME["disabled_bg"]), - ("focus", THEME["input_bg"]), - ], - ) - style.configure( - "TCombobox", - font=(_f, THEME["font_size_base"]), - fieldbackground=THEME["input_bg"], - background=THEME["button_bg"], - foreground=THEME["text_primary"], - bordercolor=THEME["button_border"], - arrowcolor=THEME["text_secondary"], - selectbackground=THEME["selection_fill"], - selectforeground=THEME["text_primary"], - ) - style.map( - "TCombobox", - bordercolor=[ - ("focus", THEME["focus"]), - ("active", THEME["focus_soft"]), - ], - fieldbackground=[ - ("readonly", THEME["input_bg"]), - ("disabled", THEME["disabled_bg"]), - ], - arrowcolor=[("active", THEME["focus"]), ("disabled", THEME["text_muted"])], - ) - for selector_style in ("TRadiobutton", "TCheckbutton"): - style.configure( - selector_style, - # Leave the base background unset so Qt paints the native - # indicator while the control inherits its parent surface. - background=None, - foreground=THEME["text_primary"], - font=(_f, THEME["font_size_base"]), - focuscolor=THEME["focus_soft"], - indicatorbackground=THEME["input_bg"], - indicatorforeground=THEME["focus"], - indicatorcolor=THEME["selection_fill"], - bordercolor=THEME["button_border"], - lightcolor=THEME["input_bg"], - darkcolor=THEME["button_border"], - ) - style.map( - selector_style, - background=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - indicatorbackground=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["hover_fill"]), - ("selected", THEME["selection_fill"]), - ], - indicatorcolor=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["hover_fill"]), - ("selected", THEME["selection_fill"]), - ], - foreground=[ - ("disabled", THEME["text_muted"]), - ("active", THEME["text_primary"]), - ("selected", THEME["text_primary"]), - ], - ) - style.configure( - "Toolbar.TRadiobutton", - background=THEME["status_bar_bg"], - ) - style.configure( - "Horizontal.TScale", - background=THEME["panel_alt_bg"], - troughcolor="#e2e6ec", - bordercolor=THEME["panel_alt_bg"], - lightcolor=THEME["accent"], - darkcolor=THEME["accent"], - ) - style.configure( - "Vertical.TScale", - background=THEME["panel_alt_bg"], - troughcolor="#e2e6ec", - bordercolor=THEME["panel_alt_bg"], - lightcolor=THEME["accent"], - darkcolor=THEME["accent"], - ) - style.configure( - "Treeview", - background=THEME["card_bg"], - fieldbackground=THEME["card_bg"], - foreground=THEME["text_primary"], - rowheight=32, - bordercolor=THEME["card_border"], - borderwidth=0, - font=(_f, THEME["font_size_base"]), - ) - style.map( - "Treeview", - background=[("selected", THEME["selection_fill"])], - foreground=[("selected", THEME["text_primary"])], - ) - style.configure( - "Treeview.Heading", - background=THEME["panel_alt_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"], "bold"), - relief="flat", - padding=(6, 5), - ) - style.map( - "Treeview.Heading", - background=[("active", THEME["button_hover"])], - foreground=[("active", THEME["text_primary"])], - ) - style.configure( - "Eval.TNotebook", - background=THEME["panel_bg"], - borderwidth=0, - tabmargins=(4, 0, 4, 0), - ) - style.configure( - "Workspace.TNotebook", - background=THEME["panel_bg"], - borderwidth=0, - tabmargins=(0, 0, 0, 8), - ) - style.configure( - "Workspace.TNotebook.Tab", - background=THEME["panel_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_base"], "bold"), - padding=(18, 8), - bordercolor=THEME["panel_bg"], - lightcolor=THEME["panel_bg"], - darkcolor=THEME["panel_bg"], - ) - style.map( - "Workspace.TNotebook.Tab", - background=[ - ("selected", THEME["card_bg"]), - ("active", THEME["button_hover"]), - ], - foreground=[ - ("selected", THEME["text_primary"]), - ("active", THEME["text_primary"]), - ], - bordercolor=[ - ("selected", THEME["card_border"]), - ("active", THEME["card_border"]), - ], - ) - style.configure( - "Eval.TNotebook.Tab", - background=THEME["panel_bg"], - foreground=THEME["text_secondary"], - font=(_f, THEME["font_size_sm"], "bold"), - padding=(14, 8), - bordercolor=THEME["panel_bg"], - lightcolor=THEME["panel_bg"], - darkcolor=THEME["panel_bg"], - ) - style.map( - "Eval.TNotebook.Tab", - background=[ - ("selected", THEME["card_bg"]), - ("active", THEME["button_hover"]), - ], - foreground=[ - ("selected", THEME["text_primary"]), - ("active", THEME["text_primary"]), - ], - bordercolor=[ - ("selected", THEME["card_border"]), - ("active", THEME["card_border"]), - ], - ) - style.configure( - "WorkspaceTab.TButton", - padding=(18, 8), - relief="flat", - borderwidth=0, - font=(_f, THEME["font_size_base"], "bold"), - background=THEME["panel_bg"], - foreground=THEME["text_secondary"], - bordercolor=THEME["panel_bg"], - lightcolor=THEME["panel_bg"], - darkcolor=THEME["panel_bg"], - ) - style.map( - "WorkspaceTab.TButton", - background=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["button_hover"]), - ], - foreground=[("active", THEME["text_primary"])], - ) - style.configure( - "WorkspaceTabSelected.TButton", - padding=(18, 8), - relief="flat", - borderwidth=1, - font=(_f, THEME["font_size_base"], "bold"), - background=THEME["card_bg"], - foreground=THEME["text_primary"], - bordercolor=THEME["card_border"], - lightcolor=THEME["card_bg"], - darkcolor=THEME["card_border"], - ) - style.map( - "WorkspaceTabSelected.TButton", - background=[ - ("pressed", THEME["button_pressed"]), - ("active", THEME["card_bg"]), - ], - foreground=[("active", THEME["text_primary"])], - ) - - self._build_app_menu(root) - self._build_workspace_header(root) - - # ── Row 2: Main notebook with 3 sub-pages ────────────────── - # ── Row 2: notebook (left) + overview panel (right) 4:1 ── - main_panel = ttk.Frame(root, style="Panel.TFrame", padding=(16, 8, 16, 8)) - main_panel.grid(row=2, column=0, columnspan=3, sticky="nsew") - main_panel.grid_columnconfigure(0, weight=1) - main_panel.grid_rowconfigure(0, weight=1) - - workspace_pane = ttk.PanedWindow( - main_panel, - orient=tk.HORIZONTAL, - style="Workspace.TPanedwindow", - ) - workspace_pane.grid(row=0, column=0, sticky="nsew") - self.workspace_splitter = workspace_pane._qt - self.workspace_splitter.setChildrenCollapsible(False) - self.workspace_splitter.setHandleWidth(8) - - workspace_content = ttk.Frame(workspace_pane, style="Panel.TFrame") - workspace_content.grid_rowconfigure(0, weight=1) - workspace_content.grid_columnconfigure(0, weight=1) - - self.main_notebook = ttk.Notebook(workspace_content, style="Workspace.TNotebook") - self.main_notebook.grid(row=0, column=0, sticky="nsew") - self.main_notebook.bind("<>", self._on_main_tab_changed, add="+") - self.main_notebook._qt.tabBar().setAccessibleName( - self._t("accessibility_workspace_pages") - ) - - overview_panel = ttk.Frame( - workspace_pane, - style="Panel.TFrame", - padding=(0, 0, 0, 0), - width=304, - ) - overview_panel.grid_rowconfigure(0, weight=1) - overview_panel.grid_columnconfigure(0, weight=1) - overview_panel._qt.setMinimumWidth(288) - overview_panel._qt.setMaximumWidth(360) - workspace_content._qt.setMinimumWidth(696) - workspace_pane.add(workspace_content, weight=4) - workspace_pane.add(overview_panel, weight=1) - self._build_evaluation_panel(overview_panel) - self.root.after_idle(self._restore_workspace_splitter) - - # ── Tab 1: Physical Array + Virtual Array (1:1) ────────── - tab1 = ttk.Frame(self.main_notebook, style="Card.TFrame") - self.main_notebook.add(tab1, text=self._t("main_tab_physical_virtual")) - tab1.grid_columnconfigure(0, weight=1) - tab1.grid_columnconfigure(1, weight=0, minsize=1) - tab1.grid_columnconfigure(2, weight=1) - tab1.grid_rowconfigure(0, weight=1) - - phys_frame = ttk.Frame(tab1, style="ChartPane.TFrame", padding=(12, 8, 12, 8)) - phys_frame.grid(row=0, column=0, sticky="nsew") - phys_frame.grid_rowconfigure(0, weight=0) - phys_frame.grid_rowconfigure(1, weight=1) - phys_frame.grid_columnconfigure(0, weight=1) - self._build_physical_toolbar(phys_frame) - - ttk.Separator(tab1, orient=tk.VERTICAL).grid(row=0, column=1, sticky="ns") - virt_frame = ttk.Frame(tab1, style="ChartPane.TFrame", padding=(12, 8, 12, 8)) - virt_frame.grid(row=0, column=2, sticky="nsew") - virt_frame.grid_rowconfigure(0, weight=1) - virt_frame.grid_columnconfigure(0, weight=1) - - # ── Tab 2: 1D DBF (Azimuth + Elevation) ────────────────── - tab2 = ttk.Frame(self.main_notebook, style="Panel.TFrame") - self.main_notebook.add(tab2, text=self._t("main_tab_1d")) - tab2.grid_columnconfigure(0, weight=1, uniform="dbf_col") - tab2.grid_columnconfigure(1, weight=1, uniform="dbf_col") - tab2.grid_rowconfigure(0, weight=1) - - self.az_chart = self._build_response_chart( - tab2, row=0, col=0, padding=(8, 6, 2, 6), mode="azimuth" - ) - self.el_chart = self._build_response_chart( - tab2, row=0, col=1, padding=(2, 6, 8, 6), mode="elevation" - ) - - # ── Tab 3: 2D DBF ───────────────────────────────────────── - tab3 = ttk.Frame(self.main_notebook, style="Panel.TFrame") - self.main_notebook.add(tab3, text=self._t("main_tab_2d")) - dbf2d_frame = self._build_dbf2d_widget(tab3) - dbf2d_frame.pack(fill=tk.BOTH, expand=True) - self._select_main_tab(self._restored_active_tab) - - # Physical Array figure - self.phys_fig = Figure(figsize=(PHYS_FIG_W, PHYS_FIG_H), dpi=FIG_DPI) - self.phys_fig.set_facecolor(THEME["card_bg"]) - self.physical_ax = self.phys_fig.add_subplot(111) - self.physical_ax.set_facecolor(THEME["plot_bg"]) - self.phys_fig.subplots_adjust(top=0.87, left=0.10, right=0.97, bottom=0.17) - self.phys_canvas = FigureCanvasTkAgg(self.phys_fig, master=phys_frame) - phys_widget = self.phys_canvas.get_tk_widget() - _style_canvas_widget(phys_widget) - phys_widget.grid(row=1, column=0, sticky="nsew") - - # Virtual Array figure - self.virt_fig = Figure(figsize=(VIRT_FIG_W, VIRT_FIG_H), dpi=FIG_DPI) - self.virt_fig.set_facecolor(THEME["card_bg"]) - self.virtual_ax = self.virt_fig.add_subplot(111) - self.virtual_ax.set_facecolor(THEME["plot_bg"]) - self.virt_canvas = FigureCanvasTkAgg(self.virt_fig, master=virt_frame) - virt_widget = self.virt_canvas.get_tk_widget() - _style_canvas_widget(virt_widget) - virt_widget.grid(row=0, column=0, sticky="nsew") - - # ── Row 2: Controls ─────────────────────────────────────── - controls_outer = ttk.Frame(root, style="Status.TFrame") - controls_outer.grid(row=3, column=0, columnspan=3, sticky="ew") - controls = ttk.Frame(controls_outer, style="Status.TFrame", padding=(16, 6, 16, 6)) - controls.pack(fill=tk.X) - - controls.grid_rowconfigure(0, minsize=32) - controls.grid_columnconfigure(4, weight=1) - - def toolbar_group( - column: int, - *, - sticky: str = "nsew", - padx: tuple[int, int] = (0, 12), - ) -> ttk.Frame: - group = ttk.Frame( - controls, - style="ToolbarGroup.TFrame", - padding=(TOOLBAR_GROUP_PAD_X, TOOLBAR_GROUP_PAD_Y), - ) - group.grid(row=0, column=column, sticky=sticky, padx=padx) - return group - - freq_group = toolbar_group(0) - self.freq_toolbar_label = ttk.Label( - freq_group, text=self._t("freq_label"), style="Toolbar.TLabel" - ) - self.freq_toolbar_label.pack(side=tk.LEFT, padx=(0, 4)) - freq_entry = ttk.Entry( - freq_group, - textvariable=self.frequency_ghz, - width=TOOLBAR_ENTRY_WIDTH, - justify="right", - ) - self.frequency_entry = freq_entry - freq_entry.pack(side=tk.LEFT) - freq_entry.bind("", self.on_frequency_changed) - freq_entry.bind("", self.on_frequency_changed) - - margin_group = toolbar_group(1) - self.margin_toolbar_label = ttk.Label( - margin_group, text=self._t("margin_label"), style="Toolbar.TLabel" - ) - self.margin_toolbar_label.pack(side=tk.LEFT, padx=(0, 4)) - margin_entry = ttk.Entry( - margin_group, - textvariable=self.margin_db, - width=TOOLBAR_ENTRY_WIDTH, - justify="right", - ) - self.margin_entry = margin_entry - margin_entry.pack(side=tk.LEFT) - margin_entry.bind("", self.on_margin_changed) - margin_entry.bind("", self.on_margin_changed) - - auto_group = toolbar_group(2) - self.auto_toolbar_label = ttk.Label( - auto_group, text=self._t("auto_label"), style="Toolbar.TLabel" - ) - self.auto_toolbar_label.pack(side=tk.LEFT, padx=(0, 4)) - auto_tx_entry = ttk.Entry( - auto_group, - textvariable=self.auto_tx_count, - width=TOOLBAR_ENTRY_WIDTH, - justify="right", - ) - auto_tx_entry.pack(side=tk.LEFT) - auto_tx_entry.bind("", self.apply_auto_array_layout) - ttk.Label( - auto_group, text="T", style="Toolbar.TLabel" - ).pack(side=tk.LEFT, padx=(2, 4)) - auto_rx_entry = ttk.Entry( - auto_group, - textvariable=self.auto_rx_count, - width=TOOLBAR_ENTRY_WIDTH, - justify="right", - ) - auto_rx_entry.pack(side=tk.LEFT) - auto_rx_entry.bind("", self.apply_auto_array_layout) - ttk.Label( - auto_group, text="R", style="Toolbar.TLabel" - ).pack(side=tk.LEFT, padx=(2, 6)) - self.auto_apply_button = ttk.Button( - auto_group, - text=self._t("auto_apply"), - command=self.apply_auto_array_layout, - style="ToolbarPrimary.TButton", - width=10, - ) - self.auto_apply_button.pack(side=tk.LEFT) - mark_primary(self.auto_apply_button._qt) - self.auto_apply_button._qt.setIcon( - QtGui.QIcon() - ) - self.auto_apply_button._qt.setMinimumWidth(116) - self.auto_apply_button._qt.setMaximumWidth(168) - self.auto_apply_button._qt.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Preferred, - QtWidgets.QSizePolicy.Policy.Fixed, - ) - self.auto_apply_button._qt.setDefault(True) - self.auto_apply_button._qt.setAutoDefault(True) - self.auto_apply_button._qt.setAccessibleName(self._t("auto_apply")) - - display_group = toolbar_group(3) - self.dbf_display_label = ttk.Label( - display_group, text=self._t("dbf_display_label"), style="Toolbar.TLabel" - ) - self.dbf_display_label.pack(side=tk.LEFT, padx=(0, 4)) - self.dbf_display_db_radio = ttk.Radiobutton( - display_group, - text=self._t("dbf_display_db"), - variable=self.dbf_display_mode, - value=DBF_DISPLAY_DB, - command=self.on_dbf_display_mode_changed, - style="Toolbar.TRadiobutton", - ) - self.dbf_display_db_radio.pack(side=tk.LEFT, padx=(0, 4)) - self.dbf_display_mag_radio = ttk.Radiobutton( - display_group, - text=self._t("dbf_display_magnitude"), - variable=self.dbf_display_mode, - value=DBF_DISPLAY_MAGNITUDE, - command=self.on_dbf_display_mode_changed, - style="Toolbar.TRadiobutton", - ) - self.dbf_display_mag_radio.pack(side=tk.LEFT) - - # ── Event bindings ──────────────────────────────────────── - # Physical array: press, motion, release (drag + hover) - self.phys_canvas.mpl_connect("button_press_event", self.on_press) - self.phys_canvas.mpl_connect("motion_notify_event", self.on_motion) - self.phys_canvas.mpl_connect("button_release_event", self.on_release) - self.phys_canvas.mpl_connect( - "pointer_cancel_event", self.on_physical_pointer_cancel - ) - # Virtual array: hover only - self.virt_canvas.mpl_connect("motion_notify_event", self.on_motion) - # Az/El response: hover only - for mode, chart in ( - ("azimuth", self.az_chart), - ("elevation", self.el_chart), - ): - chart.canvas.mpl_connect( - "button_press_event", - lambda event, chart_mode=mode: self.on_dbf_true_line_press( - event, chart_mode - ), - ) - chart.canvas.mpl_connect("motion_notify_event", self.on_motion) - chart.canvas.mpl_connect( - "button_release_event", - lambda event, chart_mode=mode: self.on_dbf_true_line_release( - event, chart_mode - ), - ) - chart.canvas.mpl_connect( - "pointer_cancel_event", - lambda _event, chart_mode=mode: self.on_dbf_true_line_cancel( - chart_mode - ), - ) - chart.canvas.mpl_connect( - "figure_leave_event", - lambda _event, response_chart=chart: self._on_response_figure_leave( - response_chart - ), - ) - if self.dbf2d_canvas is not None: - self.dbf2d_canvas.mpl_connect("button_press_event", self.on_dbf2d_crosshair_press) - self.dbf2d_canvas.mpl_connect("motion_notify_event", self.on_dbf2d_crosshair_motion) - self.dbf2d_canvas.mpl_connect("button_release_event", self.on_dbf2d_crosshair_release) - self.dbf2d_canvas.mpl_connect( - "pointer_cancel_event", self.on_dbf2d_pointer_cancel - ) - self.dbf2d_canvas.mpl_connect("figure_leave_event", self.on_dbf2d_figure_leave) - - self.root.bind("", self.on_arrow_key) - self.root.bind("", self.on_arrow_key) - self.root.bind("", self.on_arrow_key) - self.root.bind("", self.on_arrow_key) - self.root.bind("", self.on_delete_key) - self._bind_keyboard_shortcuts() - - self._refresh_language_texts() - self.generate_virtual_array() - self._resize_filter = _DebouncedResizeFilter( - self.root._window, - self._sync_plot_layout_after_window_change, - ) - self.root._window.installEventFilter(self._resize_filter) - - # ── Response chart helpers ────────────────────────────────────────── - - def _load_logo_image(self, path: Path) -> tk.PhotoImage | None: - try: - return tk.PhotoImage(file=str(path)) - except tk.TclError: - LOGGER.warning("Failed to load logo image: %s", path, exc_info=True) - return None - - def _build_app_menu(self, parent: tk.Widget) -> None: - window = getattr(parent, "_window", None) - if not isinstance(window, QtWidgets.QMainWindow): - raise TypeError("The Fluent workspace requires a native QMainWindow") - - menu_bar = QtWidgets.QMenuBar(window) - menu_bar.setObjectName("fluentAppMenu") - menu_bar.setNativeMenuBar(False) - menu_bar.setMinimumHeight(34) - window.setMenuBar(menu_bar) - self.native_menu_bar = menu_bar - - for key in ("menu_file", "menu_edit", "menu_view", "menu_help"): - self.native_menus[key] = menu_bar.addMenu(self._t(key)) - - style = window.style() - - def add_action( - menu_key: str, - text_key: str, - callback, - *, - icon: QtWidgets.QStyle.StandardPixmap | None = None, - shortcut: QtGui.QKeySequence | QtGui.QKeySequence.StandardKey | None = None, - target_menu: QtWidgets.QMenu | None = None, - ) -> QtGui.QAction: - action = QtGui.QAction(self._t(text_key), window) - if icon is not None: - action.setIcon(style.standardIcon(icon)) - if shortcut is not None: - action.setShortcut(shortcut) - action.triggered.connect(lambda _checked=False, cb=callback: cb()) - menu = target_menu if target_menu is not None else self.native_menus[menu_key] - menu.addAction(action) - self.native_actions[text_key] = action - return action - - add_action( - "menu_file", - "menu_import_layout", - self.import_layout_config, - icon=QtWidgets.QStyle.StandardPixmap.SP_DialogOpenButton, - shortcut=QtGui.QKeySequence.StandardKey.Open, - ) - add_action( - "menu_file", - "menu_export_layout", - self.export_layout_config, - icon=QtWidgets.QStyle.StandardPixmap.SP_DialogSaveButton, - shortcut=QtGui.QKeySequence.StandardKey.Save, - ) - self.native_menus["menu_file"].addSeparator() - add_action( - "menu_file", - "menu_export_report", - self.open_performance_report_dialog, - icon=QtWidgets.QStyle.StandardPixmap.SP_FileDialogInfoView, - ) - add_action( - "menu_edit", - "menu_undo", - self.undo_layout_change, - icon=QtWidgets.QStyle.StandardPixmap.SP_ArrowBack, - shortcut=QtGui.QKeySequence.StandardKey.Undo, - ) - add_action( - "menu_edit", - "menu_redo", - self.redo_layout_change, - icon=QtWidgets.QStyle.StandardPixmap.SP_ArrowForward, - shortcut=QtGui.QKeySequence.StandardKey.Redo, - ) - self.native_menus["menu_edit"].addSeparator() - add_action( - "menu_edit", - "menu_channel_patterns", - self.open_channel_patterns_dialog, - icon=QtWidgets.QStyle.StandardPixmap.SP_FileDialogDetailedView, - ) - add_action( - "menu_edit", - "menu_dbf_dictionary", - self.open_dbf_dictionary_dialog, - icon=QtWidgets.QStyle.StandardPixmap.SP_FileDialogContentsView, - ) - - language_group = QtGui.QActionGroup(window) - language_group.setExclusive(True) - for language, label_key in ( - (LANGUAGE_ZH, "language_zh"), - (LANGUAGE_EN, "language_en"), - (LANGUAGE_JA, "language_ja"), - ): - action = QtGui.QAction(self._t(label_key), window) - action.setCheckable(True) - action.setChecked(language == self.language) - action.triggered.connect( - lambda _checked=False, lang=language: self.set_language(lang) - ) - language_group.addAction(action) - self.native_menus["menu_view"].addAction(action) - self.native_language_actions[language] = action - self.native_actions[label_key] = action - - self.native_manual_menu = self.native_menus["menu_help"].addMenu( - style.standardIcon(QtWidgets.QStyle.StandardPixmap.SP_MessageBoxQuestion), - self._t("menu_user_manual"), - ) - open_manual_action = QtGui.QAction( - self._t("menu_user_manual_open"), window - ) - open_manual_action.setShortcut(QtGui.QKeySequence.StandardKey.HelpContents) - open_manual_action.triggered.connect( - lambda _checked=False: self._show_user_manual_dialog() - ) - self.native_manual_menu.addAction(open_manual_action) - self.native_actions["menu_user_manual_open"] = open_manual_action - self.native_manual_menu.addSeparator() - for chapter in manual_chapters(self.language): - action = QtGui.QAction(chapter.title, window) - action.triggered.connect( - lambda _checked=False, key=chapter.key: self._show_user_manual_dialog(key) - ) - self.native_manual_menu.addAction(action) - self.native_manual_chapter_actions[chapter.key] = action - self.native_menus["menu_help"].addSeparator() - add_action( - "menu_help", - "menu_about", - self._show_about_dialog, - icon=QtWidgets.QStyle.StandardPixmap.SP_MessageBoxInformation, - ) - - status_bar = QtWidgets.QStatusBar(window) - status_bar.setObjectName("fluentStatusBar") - status_bar.setAccessibleName(self._t("accessibility_status_bar")) - status_bar.setSizeGripEnabled(True) - window.setStatusBar(status_bar) - self.native_status_bar = status_bar - self.status._connect(lambda value: status_bar.showMessage(str(value))) - self._refresh_app_menus() - - def _refresh_app_menus(self) -> None: - if self.native_menu_bar is not None: - if self._native_brand_label is not None: - self._native_brand_label.setText(self._t("app_name")) - for key, menu in self.native_menus.items(): - menu.setTitle(self._t(key)) - for key, action in self.native_actions.items(): - action.setText(self._t(key)) - if self.native_manual_menu is not None: - self.native_manual_menu.setTitle(self._t("menu_user_manual")) - chapters_by_key = { - chapter.key: chapter for chapter in manual_chapters(self.language) - } - for key, action in self.native_manual_chapter_actions.items(): - chapter = chapters_by_key.get(key) - if chapter is not None: - action.setText(chapter.title) - for language, action in self.native_language_actions.items(): - action.setChecked(language == self.language) - return - if self.app_brand_label is not None: - self.app_brand_label.configure(text=self._t("app_name")) - if self.config_menu_button is not None: - self.config_menu_button.configure(text=self._t("menu_file")) - if self.edit_menu_button is not None: - self.edit_menu_button.configure(text=self._t("menu_edit")) - if self.language_menu_button is not None: - self.language_menu_button.configure(text=self._t("menu_view")) - if self.help_menu_button is not None: - self.help_menu_button.configure(text=self._t("menu_help")) - - if self.config_menu is not None: - self.config_menu.delete(0, tk.END) - self.config_menu.add_command( - label=self._t("menu_import_layout"), - command=self.import_layout_config, - ) - self.config_menu.add_command( - label=self._t("menu_export_layout"), - command=self.export_layout_config, - ) - self.config_menu.add_separator() - self.config_menu.add_command( - label=self._t("menu_export_report"), - command=self.open_performance_report_dialog, - ) - _style_popup_menu(self.config_menu) - - if self.edit_menu is not None: - self.edit_menu.delete(0, tk.END) - self.edit_menu.add_command( - label=self._t("menu_undo"), - command=self.undo_layout_change, - ) - self.edit_menu.add_command( - label=self._t("menu_redo"), - command=self.redo_layout_change, - ) - self.edit_menu.add_separator() - self.edit_menu.add_command( - label=self._t("menu_channel_patterns"), - command=self.open_channel_patterns_dialog, - ) - self.edit_menu.add_command( - label=self._t("menu_dbf_dictionary"), - command=self.open_dbf_dictionary_dialog, - ) - _style_popup_menu(self.edit_menu) - - if self.language_menu is not None: - self.language_menu.delete(0, tk.END) - for language, label_key in ( - (LANGUAGE_ZH, "language_zh"), - (LANGUAGE_EN, "language_en"), - (LANGUAGE_JA, "language_ja"), - ): - prefix = "✓ " if language == self.language else "" - self.language_menu.add_command( - label=f"{prefix}{self._t(label_key)}", - command=lambda lang=language: self.set_language(lang), - ) - _style_popup_menu(self.language_menu) - - if self.help_menu is not None: - self.help_menu.delete(0, tk.END) - self.help_menu.add_command( - label=self._t("menu_user_manual"), - command=self._show_user_manual_dialog, - ) - self.help_menu.add_separator() - self.help_menu.add_command( - label=self._t("menu_about"), - command=self._show_about_dialog, - ) - _style_popup_menu(self.help_menu) - - def _show_user_manual_dialog(self, chapter_key: str | None = None) -> None: - if self._manual_dialog is not None: - try: - if chapter_key and callable(self._manual_select_chapter): - self._manual_select_chapter(chapter_key) - self._manual_dialog.showNormal() - self._manual_dialog.raise_() - self._manual_dialog.activateWindow() - return - except RuntimeError: - self._manual_dialog = None - self._manual_select_chapter = None - - chapters = manual_chapters(self.language) - dialog = QtWidgets.QDialog(self.root._window) - dialog.setAttribute(QtCore.Qt.WidgetAttribute.WA_DeleteOnClose, True) - dialog.setObjectName("userManualDialog") - mark_workbench_role(dialog, "dialog-shell") - dialog.setWindowTitle(self._t("manual_title")) - layout = QtWidgets.QVBoxLayout(dialog) - layout.setContentsMargins(18, 16, 18, 14) - layout.setSpacing(12) - - header = QtWidgets.QWidget(dialog) - header.setObjectName("manualHeader") - mark_workbench_role(header, "dialog-header") - header_layout = QtWidgets.QHBoxLayout(header) - header_layout.setContentsMargins(12, 8, 12, 8) - header_layout.setSpacing(12) - title = QtWidgets.QLabel(self._t("manual_title"), header) - title_font = title.font() - title_font.setPointSize(14) - title_font.setBold(True) - title.setFont(title_font) - header_layout.addWidget(title, 1) - - result_count = QtWidgets.QLabel(header) - result_count.setObjectName("manualSearchResultCount") - result_count.setProperty("fluentRole", "caption") - result_count.setAccessibleName(self._t("manual_search_result_count", count=0)) - header_layout.addWidget(result_count) - - search = QtWidgets.QLineEdit(header) - search.setObjectName("manualSearch") - search.setPlaceholderText(self._t("manual_search_placeholder")) - search.setClearButtonEnabled(True) - search.setMaximumWidth(300) - search.setAccessibleName(self._t("manual_search_placeholder")) - header_layout.addWidget(search) - - previous_result = QtWidgets.QToolButton(header) - previous_result.setObjectName("manualPreviousResult") - previous_result.setIcon( - dialog.style().standardIcon(QtWidgets.QStyle.StandardPixmap.SP_ArrowBack) - ) - previous_result.setToolTip(self._t("manual_previous_result")) - previous_result.setAccessibleName(self._t("manual_previous_result")) - header_layout.addWidget(previous_result) - - next_result = QtWidgets.QToolButton(header) - next_result.setObjectName("manualNextResult") - next_result.setIcon( - dialog.style().standardIcon(QtWidgets.QStyle.StandardPixmap.SP_ArrowForward) - ) - next_result.setToolTip(self._t("manual_next_result")) - next_result.setAccessibleName(self._t("manual_next_result")) - header_layout.addWidget(next_result) - - result_position = QtWidgets.QLabel(header) - result_position.setObjectName("manualSearchPosition") - result_position.setProperty("fluentRole", "caption") - result_position.setMinimumWidth(42) - result_position.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - header_layout.addWidget(result_position) - layout.addWidget(header) - - content_splitter = QtWidgets.QSplitter( - QtCore.Qt.Orientation.Horizontal, dialog - ) - content_splitter.setObjectName("manualContentSplitter") - content_splitter.setChildrenCollapsible(False) - content_splitter.setHandleWidth(6) - - contents_group = QtWidgets.QGroupBox(self._t("manual_contents"), content_splitter) - contents_group.setObjectName("manualContentsPanel") - mark_workbench_role(contents_group, "dialog-rail") - contents_layout = QtWidgets.QVBoxLayout(contents_group) - contents_layout.setContentsMargins(8, 10, 8, 8) - chapter_list = QtWidgets.QListWidget(contents_group) - chapter_list.setObjectName("manualChapterList") - chapter_list.setProperty("pointingHandItems", True) - chapter_list.setAccessibleName(self._t("manual_contents_accessible")) - chapter_list.setUniformItemSizes(True) - chapter_list.setHorizontalScrollBarPolicy( - QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff - ) - for chapter in chapters: - item = QtWidgets.QListWidgetItem(chapter.title) - item.setData(QtCore.Qt.ItemDataRole.UserRole, chapter.key) - item.setToolTip(f"{chapter.title}\n{chapter.summary}") - chapter_list.addItem(item) - contents_layout.addWidget(chapter_list) - content_splitter.addWidget(contents_group) - - browser = QtWidgets.QTextBrowser(dialog) - browser.setObjectName("manualBrowser") - mark_workbench_role(browser, "dialog-content") - browser.setOpenExternalLinks(False) - browser.setAccessibleName(self._t("manual_body_accessible")) - content_splitter.addWidget(browser) - content_splitter.setStretchFactor(0, 0) - content_splitter.setStretchFactor(1, 1) - content_splitter.setSizes([230, 730]) - layout.addWidget(content_splitter, 1) - - search_documents = [ - manual_chapter_search_text(chapter).casefold() for chapter in chapters - ] - matching_rows = list(range(len(chapters))) - match_position = 0 - - def show_chapter(row: int) -> None: - if not 0 <= row < len(chapters): - return - browser.setHtml(manual_chapter_html(chapters[row])) - browser.moveCursor(QtGui.QTextCursor.MoveOperation.Start) - browser.verticalScrollBar().setValue(0) - query = search.text().strip() - if query: - browser.find(query) - - def select_chapter(key: str) -> None: - if search.text(): - search.clear() - for row in range(chapter_list.count()): - item = chapter_list.item(row) - if item.data(QtCore.Qt.ItemDataRole.UserRole) == key: - item.setHidden(False) - chapter_list.setCurrentRow(row) - chapter_list.scrollToItem(item) - return - - def update_result_labels() -> None: - count = len(matching_rows) - result_count.setText( - self._t("manual_search_result_count", count=count) - if search.text().strip() - else "" - ) - result_count.setAccessibleName( - self._t("manual_search_result_count", count=count) - ) - result_position.setText( - self._t( - "manual_search_position", - current=match_position + 1, - total=count, - ) - if search.text().strip() and count - else "" - ) - enabled = bool(search.text().strip() and count) - previous_result.setEnabled(enabled) - next_result.setEnabled(enabled) - - def go_to_result(delta: int) -> None: - nonlocal match_position - if not matching_rows: - return - match_position = (match_position + delta) % len(matching_rows) - chapter_list.setCurrentRow(matching_rows[match_position]) - update_result_labels() - - def update_search(query: str) -> None: - nonlocal matching_rows, match_position - normalized = query.strip().casefold() - matching_rows = [ - row - for row, document in enumerate(search_documents) - if not normalized or normalized in document - ] - for row in range(chapter_list.count()): - chapter_list.item(row).setHidden( - bool(normalized) and row not in matching_rows - ) - match_position = 0 - if matching_rows: - chapter_list.setCurrentRow(matching_rows[0]) - else: - chapter_list.setCurrentRow(-1) - browser.setPlainText( - f"{self._t('manual_search_no_results')}\n\n" - f"{self._t('manual_search_no_results_detail')}" - ) - update_result_labels() - - class _SearchKeyFilter(QtCore.QObject): - def eventFilter(self, watched, event) -> bool: # noqa: ANN001, N802 - if ( - watched is search - and event.type() == QtCore.QEvent.Type.KeyPress - and event.key() - in {QtCore.Qt.Key.Key_Return, QtCore.Qt.Key.Key_Enter} - ): - direction = ( - -1 - if event.modifiers() & QtCore.Qt.KeyboardModifier.ShiftModifier - else 1 - ) - go_to_result(direction) - return True - return super().eventFilter(watched, event) - - chapter_list.currentRowChanged.connect(show_chapter) - search.textChanged.connect(update_search) - previous_result.clicked.connect(lambda: go_to_result(-1)) - next_result.clicked.connect(lambda: go_to_result(1)) - search_key_filter = _SearchKeyFilter(dialog) - search.installEventFilter(search_key_filter) - - find_shortcut = QtGui.QShortcut( - QtGui.QKeySequence.StandardKey.Find, dialog - ) - find_shortcut.activated.connect( - lambda: (search.setFocus(), search.selectAll()) - ) - find_next_shortcut = QtGui.QShortcut( - QtGui.QKeySequence.StandardKey.FindNext, dialog - ) - find_next_shortcut.activated.connect(lambda: go_to_result(1)) - find_previous_shortcut = QtGui.QShortcut( - QtGui.QKeySequence.StandardKey.FindPrevious, dialog - ) - find_previous_shortcut.activated.connect(lambda: go_to_result(-1)) - - buttons = QtWidgets.QDialogButtonBox( - QtWidgets.QDialogButtonBox.StandardButton.Close, - parent=dialog, - ) - buttons.rejected.connect(dialog.close) - close_button = buttons.button(QtWidgets.QDialogButtonBox.StandardButton.Close) - close_button.setText(self._t("done")) - close_button.setAutoDefault(False) - close_button.setDefault(False) - mark_primary(close_button) - mark_workbench_role(buttons, "dialog-footer") - layout.addWidget(buttons) - fit_dialog_to_parent( - dialog, - self.root._window, - preferred_size=(1120, 720), - minimum_size=(760, 520), - ) - self._manual_dialog = dialog - self._manual_select_chapter = select_chapter - - def clear_manual_dialog() -> None: - self._manual_dialog = None - self._manual_select_chapter = None - - dialog.destroyed.connect(clear_manual_dialog) - initial_key = chapter_key or chapters[0].key - select_chapter(initial_key) - QtWidgets.QWidget.setTabOrder(search, chapter_list) - QtWidgets.QWidget.setTabOrder(chapter_list, browser) - QtWidgets.QWidget.setTabOrder(browser, close_button) - dialog.show() - search.setFocus() - - def _show_about_dialog(self) -> None: - log_path = current_log_path() - QtWidgets.QMessageBox.information( - self.root._window, - self._t("about_title"), - self._t( - "about_message", - version=APP_VERSION, - log_path=str(log_path) if log_path is not None else "N/A", - ), - ) - - def _build_main_tab_strip( - self, - parent: ttk.Frame, - tabs: tuple[tuple[int, str], ...], - ) -> None: - self.main_tab_buttons.clear() - for column, (index, label_key) in enumerate(tabs): - button = ttk.Button( - parent, - text=self._t(label_key), - style="WorkspaceTabSelected.TButton" if index == 0 else "WorkspaceTab.TButton", - command=lambda tab_index=index: self._select_main_tab(tab_index), - width=18, - ) - button.grid(row=0, column=column, sticky="ew", padx=(0 if column == 0 else 4, 0)) - parent.grid_columnconfigure(column, weight=0) - self.main_tab_buttons[index] = button - - def _select_main_tab(self, index: int) -> None: - if self.main_notebook is None: - return - try: - self.main_notebook.select(index) - except tk.TclError: - return - self._sync_main_tab_styles(index) - - def _on_main_tab_changed(self, _event: tk.Event | None = None) -> None: - if self.main_notebook is None: - return - try: - selected = self.main_notebook.index(self.main_notebook.select()) - except tk.TclError: - return - self._sync_main_tab_styles(selected) - - def _sync_main_tab_styles(self, selected: int) -> None: - for index, button in self.main_tab_buttons.items(): - button.configure( - style="WorkspaceTabSelected.TButton" - if index == selected - else "WorkspaceTab.TButton" - ) - - def _build_workspace_header(self, parent: tk.Widget) -> None: - header = ttk.Frame(parent, style="Header.TFrame", padding=(16, 9, 16, 9)) - header.grid(row=1, column=0, columnspan=3, sticky="ew") - header.grid_columnconfigure(0, weight=0) - header.grid_columnconfigure(1, weight=0) - header.grid_columnconfigure(2, weight=1) - - self.app_logo_image = self._load_logo_image(APP_LOGO_PNG_PATH) - logo_label = ttk.Label( - header, - image=self.app_logo_image, - style="HeaderLogo.TLabel", - ) - logo_label.grid(row=0, column=0, sticky="w", padx=(0, 10)) - logo_label._qt.setFixedSize(38, 38) - logo_label._qt.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - logo_label._qt.setAccessibleName("MAV") - if self.app_logo_image is not None and not self.app_logo_image.pixmap.isNull(): - pixel_ratio = max(1.0, logo_label._qt.devicePixelRatioF()) - physical_size = max(32, round(32 * pixel_ratio)) - logo_pixmap = self.app_logo_image.pixmap.scaled( - physical_size, - physical_size, - QtCore.Qt.AspectRatioMode.KeepAspectRatio, - QtCore.Qt.TransformationMode.SmoothTransformation, - ) - logo_pixmap.setDevicePixelRatio(pixel_ratio) - logo_label._qt.setPixmap(logo_pixmap) - - title_group = ttk.Frame(header, style="Header.TFrame") - self.header_title_group = title_group - title_group.grid(row=0, column=1, sticky="w", padx=(0, 18)) - title_group.grid_columnconfigure(0, weight=1) - self._update_header_title_group_width() - self.header_title_label = ttk.Label( - title_group, - text="", - style="HeaderTitle.TLabel", - anchor="w", - ) - self.header_title_label.grid(row=0, column=0, sticky="ew") - self.header_subtitle_label = ttk.Label( - title_group, - text="", - style="HeaderSubtitle.TLabel", - anchor="w", - ) - self.header_subtitle_label.grid(row=1, column=0, sticky="ew", pady=(2, 0)) - self.header_subtitle_label._qt.setMinimumWidth(0) - self.header_subtitle_label._qt.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Ignored, - QtWidgets.QSizePolicy.Policy.Preferred, - ) - self._set_header_title_text() - self._set_header_subtitle_text() - - chip_row = ttk.Frame(header, style="Header.TFrame") - chip_row._qt.setObjectName("workspaceHeaderChipRow") - chip_row.grid(row=0, column=2, sticky="e") - chip_specs = ( - ("chip_frequency", self.header_frequency_text, 90, 96), - ("chip_dictionary", self.header_dictionary_text, 128, None), - ("chip_pattern", self.header_pattern_text, 170, None), - ) - for column, (label_key, value_var, min_width, value_width) in enumerate( - chip_specs - ): - self._build_header_chip( - chip_row, - column, - label_key, - value_var, - min_width=min_width, - value_width=value_width, - compact=True, - ) - - def _build_header_chip( - self, - parent: ttk.Frame, - column: int, - label_key: str, - value_var: tk.StringVar, - *, - min_width: int = 160, - value_width: int | None = None, - compact: bool = False, - ) -> None: - parent.grid_columnconfigure(column, minsize=min_width) - chip = ttk.Frame( - parent, - style="HeaderChip.TFrame", - padding=(8, 4) if compact else (10, 6), - ) - chip._qt.setObjectName(f"headerChip_{label_key}") - chip.grid(row=0, column=column, sticky="ew", padx=(0 if column == 0 else 6, 0)) - chip.grid_columnconfigure(1, weight=1) - label = ttk.Label( - chip, - text=self._t(label_key), - style="HeaderChipName.TLabel", - anchor="w", - ) - label._qt.setObjectName(f"headerChipName_{label_key}") - label.grid(row=0, column=0, sticky="w") - value_style = ( - "HeaderChipPatternValue.TLabel" - if label_key == "chip_pattern" - else "HeaderChipValue.TLabel" - ) - value_label = ttk.Label( - chip, - textvariable=value_var, - style=value_style, - anchor="w", - ) - value_label._qt.setObjectName(f"headerChipValue_{label_key}") - value_label.grid(row=0, column=1, sticky="ew", padx=(7, 0)) - value_label._qt.setWordWrap(False) - if value_width is not None: - value_label._qt.setFixedWidth(value_width) - - def sync_tooltip(value: object) -> None: - full_text = str(value) - value_label._qt.setToolTip(full_text) - if value_width is None: - label_width = label._qt.sizeHint().width() - available = max(44, min_width - label_width - 31) - else: - available = value_width - value_label._qt.setText( - value_label._qt.fontMetrics().elidedText( - full_text, - QtCore.Qt.TextElideMode.ElideRight, - available, - ) - ) - - value_var._connect(sync_tooltip) - self.header_chip_labels[label_key] = label - self.header_chip_value_labels[label_key] = value_label - - def _restore_workspace_splitter(self) -> None: - splitter = self.workspace_splitter - if splitter is None: - return - sizes = self._restored_splitter_sizes - if sizes is not None and len(sizes) == 2 and all(size > 0 for size in sizes): - splitter.setSizes(sizes) - return - total = max(splitter.width(), WINDOW_WIDTH - 32) - splitter.setSizes([max(720, total - 304), 304]) - - def _refresh_workspace_header(self) -> None: - self._update_header_title_group_width() - if self.header_title_label is not None: - self._set_header_title_text() - if self.header_subtitle_label is not None: - self._set_header_subtitle_text() - for key, label in self.header_chip_labels.items(): - label.configure(text=self._t(key)) - - self.header_frequency_text.set( - f"{_format_frequency_ghz(self.current_frequency_ghz())} GHz" - ) - self.header_dictionary_text.set( - _dbf_dictionary_chip_label(self.dbf_dictionary.mode, self.language) - ) - physical_names = self._physical_channel_names() - virtual_names = self._virtual_channel_names() - amplitude = self._t( - self._channel_pattern_state_key( - physical_names, - virtual_names, - PATTERN_KIND_AMPLITUDE, - ) - ) - phase = self._t( - self._channel_pattern_state_key( - physical_names, - virtual_names, - PATTERN_KIND_PHASE, - ) - ) - if self.language == LANGUAGE_EN: - amplitude = amplitude.title() - phase = phase.title() - self.header_pattern_text.set( - amplitude if amplitude == phase else f"{amplitude} / {phase}" - ) - - def _header_title_width(self) -> int: - return { - LANGUAGE_EN: 340, - LANGUAGE_JA: 330, - }.get(self.language, 300) - - def _update_header_title_group_width(self) -> None: - if self.header_title_group is None: - return - width = self._header_title_width() - self.header_title_group._qt.setMinimumWidth(width) - self.header_title_group._qt.setMaximumWidth(width) - - def _set_header_title_text(self) -> None: - if self.header_title_label is None: - return - full_text = self._t("app_name") - label = self.header_title_label._qt - label.setToolTip(full_text) - label.setText( - label.fontMetrics().elidedText( - full_text, - QtCore.Qt.TextElideMode.ElideRight, - self._header_title_width() - 4, - ) - ) - - def _set_header_subtitle_text(self) -> None: - if self.header_subtitle_label is None: - return - full_text = self._t("app_subtitle") - label = self.header_subtitle_label._qt - label.setToolTip(full_text) - label.setText( - label.fontMetrics().elidedText( - full_text, - QtCore.Qt.TextElideMode.ElideRight, - self._header_title_width() - 4, - ) - ) - - def _set_default_workspace_sash(self) -> None: - return - - def _stabilize_default_workspace_sash(self) -> None: - return - - def _bind_keyboard_shortcuts(self) -> None: - self.root.bind("", self.on_refresh_shortcut) - self.root.bind("", self.on_refresh_shortcut) - self.root.bind("", self.on_refresh_shortcut) - self.root.bind("", self.on_refresh_shortcut) - self.root.bind("", self.on_focus_frequency_shortcut) - self.root.bind("", self.on_focus_frequency_shortcut) - for index in range(3): - self.root.bind( - f"", - lambda _event=None, tab_index=index: self._select_main_tab(tab_index), - ) - self.root.bind("", self.on_escape_key) - - def set_language(self, language: str) -> None: - if language not in SUPPORTED_LANGUAGES: - return - self.language = language - self.language_var.set(LANGUAGE_LABELS[language]) - self._refresh_language_texts() - if hasattr(self, "phys_canvas"): - self.generate_virtual_array() - - def _refresh_language_texts(self) -> None: - self.root.title(self._t("app_title", version=APP_VERSION)) - self._refresh_app_menus() - for index, label_key in self.main_tab_label_keys.items(): - button = self.main_tab_buttons.get(index) - if button is not None: - button.configure(text=self._t(label_key)) - if self.main_notebook is not None: - for index, page in enumerate(self.main_notebook.tabs()): - label_key = self.main_tab_label_keys.get(index) - if label_key is not None: - self.main_notebook.tab(page, text=self._t(label_key)) - if getattr(self, "freq_toolbar_label", None) is not None: - self.freq_toolbar_label.configure(text=self._t("freq_label")) - if getattr(self, "margin_toolbar_label", None) is not None: - self.margin_toolbar_label.configure(text=self._t("margin_label")) - if getattr(self, "auto_toolbar_label", None) is not None: - self.auto_toolbar_label.configure(text=self._t("auto_label")) - if getattr(self, "auto_apply_button", None) is not None: - self.auto_apply_button.configure(text=self._t("auto_apply")) - self.auto_apply_button._qt.setAccessibleName(self._t("auto_apply")) - if getattr(self, "dbf_display_label", None) is not None: - self.dbf_display_label.configure(text=self._t("dbf_display_label")) - if getattr(self, "dbf_display_db_radio", None) is not None: - self.dbf_display_db_radio.configure(text=self._t("dbf_display_db")) - if getattr(self, "dbf_display_mag_radio", None) is not None: - self.dbf_display_mag_radio.configure(text=self._t("dbf_display_magnitude")) - for key, button in self.physical_action_buttons.items(): - button.configure(text=self._t(key)) - button._qt.setAccessibleName(self._t(key)) - self._update_delete_button_state() - for button, key in zip( - self.physical_buttons, - ( - "physical_add_tx", - "physical_add_rx", - "physical_delete", - "physical_clear", - ), - ): - button.label.set_text(self._t(key)) - if getattr(self, "eval_frame", None) is not None: - self.overview_frame.configure(text=self._t("overview_title")) - self.angle_eval_frame.configure(text=self._t("angle_eval_title")) - for key, label in self.primary_name_labels.items(): - label.configure(text=self._t(key)) - for key, label in self.secondary_name_labels.items(): - label_key = getattr(self, "secondary_name_label_keys", {}).get(key, key) - label.configure(text=self._t(label_key)) - if self.main_notebook is not None: - self.main_notebook._qt.tabBar().setAccessibleName( - self._t("accessibility_workspace_pages") - ) - if self.native_status_bar is not None: - self.native_status_bar.setAccessibleName( - self._t("accessibility_status_bar") - ) - for chart in (getattr(self, "az_chart", None), getattr(self, "el_chart", None)): - if chart is None: - continue - chart.play_button._qt.setAccessibleName(self._t("dbf_play_compact")) - chart.stop_button._qt.setAccessibleName(self._t("dbf_stop_compact")) - self._update_dbf_scan_controls() - self._update_dbf2d_controls() - self._update_channel_pattern_status() - self._refresh_workspace_header() - - def _build_response_chart( - self, - parent: tk.Widget, - row: int, - col: int, - padding: tuple[int, int, int, int], - mode: str, - ) -> ResponseChart: - """Create a response chart (Az or El) and embed it in the grid.""" - frame = ttk.Frame(parent, style="PlotPanel.TFrame", padding=padding) - frame.grid( - row=row, - column=col, - sticky="nsew", - pady=(2, 0), - ) - frame.grid_rowconfigure(0, weight=1) - frame.grid_rowconfigure(1, weight=0) - frame.grid_columnconfigure(0, weight=1) - - fig = Figure(figsize=(RESPONSE_FIG_W, RESPONSE_FIG_H), dpi=FIG_DPI) - fig.set_facecolor(THEME["card_bg"]) - ax = fig.add_subplot(111) - ax.set_facecolor(THEME["plot_bg"]) - fig.subplots_adjust(top=0.82, left=0.13, right=0.97, bottom=0.18) - canvas = FigureCanvasTkAgg(fig, master=frame) - canvas_widget = canvas.get_tk_widget() - _style_canvas_widget(canvas_widget) - canvas_widget.grid(row=0, column=0, sticky="nsew") - - progress_frame = ttk.Frame(frame, style="ChartFooter.TFrame", padding=(6, 5)) - progress_frame.grid(row=1, column=0, sticky="ew", pady=(4, 0)) - progress_frame.grid_columnconfigure(0, weight=1) - - control_row = ttk.Frame(progress_frame, style="ChartFooter.TFrame") - control_row.grid(row=0, column=0, sticky="ew") - control_row.grid_columnconfigure(0, weight=1) - progress_label = ttk.Label( - control_row, - text=f"{_dbf_short_label(mode, self.language)} {_format_dbf_angle_label(0.0, self.language)}", - style="ChartFooter.TLabel", - anchor="w", - ) - progress_label.grid(row=0, column=0, sticky="ew") - play_button = ttk.Button( - control_row, - text=self._t("dbf_play_compact"), - command=( - self.toggle_az_dbf_animation - if mode == "azimuth" - else self.toggle_el_dbf_animation - ), - style="CompactPlay.TButton", - width=6, - ) - play_button.grid(row=0, column=1, sticky="e", padx=(8, 5)) - stop_button = ttk.Button( - control_row, - text=self._t("dbf_stop_compact"), - command=self.stop_dbf_scan_animation, - style="CompactStop.TButton", - width=6, - ) - stop_button.grid(row=0, column=2, sticky="e") - stop_button.configure(state=tk.DISABLED) - native_style = self.root._window.style() - play_button._qt.setIcon( - native_style.standardIcon(QtWidgets.QStyle.StandardPixmap.SP_MediaPlay) - ) - play_button._qt.setCheckable(True) - stop_button._qt.setIcon( - native_style.standardIcon(QtWidgets.QStyle.StandardPixmap.SP_MediaStop) - ) - play_button._qt.setAccessibleName(self._t("dbf_play_compact")) - stop_button._qt.setAccessibleName(self._t("dbf_stop_compact")) - chart = ResponseChart( - fig=fig, - ax=ax, - canvas=canvas, - progress_label=progress_label, - play_button=play_button, - stop_button=stop_button, - footer_widget=progress_frame, - ) - chart.empty_overlay = _EmptyStateOverlay(canvas) - return chart - - def _build_physical_toolbar(self, parent: ttk.Frame) -> None: - toolbar = ttk.Frame(parent, style="Card.TFrame", padding=(0, 0, 0, 6)) - toolbar.grid(row=0, column=0, sticky="ew") - toolbar.grid_columnconfigure(4, weight=1) - - button_specs = ( - ("physical_add_tx", self.add_tx_element, "Compact.TButton"), - ("physical_add_rx", self.add_rx_element, "Compact.TButton"), - ("physical_delete", self.toggle_delete_mode, "Compact.TButton"), - ("physical_clear", self.clear_array_layout, "CompactStop.TButton"), - ) - for column, (key, command, style_name) in enumerate(button_specs): - button = ttk.Button( - toolbar, - text=self._t(key), - command=command, - style=style_name, - width=8, - ) - button.grid(row=0, column=column, sticky="w", padx=(0 if column == 0 else 6, 0)) - self.physical_action_buttons[key] = button - delete_button = self.physical_action_buttons["physical_delete"]._qt - delete_button.setCheckable(True) - delete_button.setIcon( - self.root._window.style().standardIcon( - QtWidgets.QStyle.StandardPixmap.SP_TrashIcon - ) - ) - self.physical_action_buttons["physical_clear"]._qt.setIcon( - self.root._window.style().standardIcon( - QtWidgets.QStyle.StandardPixmap.SP_DialogResetButton - ) - ) - - def _update_delete_button_state(self) -> None: - button = self.physical_action_buttons.get("physical_delete") - if button is None: - return - button.configure( - style="CompactDanger.TButton" if self.delete_mode else "Compact.TButton" - ) - button._qt.setChecked(self.delete_mode) - - def _build_figure_buttons( - self, - fig: Figure, - button_specs: tuple[tuple[str, list[float], callable], ...], - buttons_list: list[MplButton], - callbacks_list: list[int], - ) -> None: - """Add MplButton widgets to *fig* from *button_specs*.""" - for label, rect, callback in button_specs: - button_ax = fig.add_axes(rect) - button_ax.set_facecolor(THEME["mpl_btn_bg"]) - for spine in button_ax.spines.values(): - spine.set_edgecolor(THEME["mpl_btn_border"]) - spine.set_linewidth(0.8) - button = MplButton( - button_ax, label, - color=THEME["mpl_btn_bg"], - hovercolor=THEME["mpl_btn_hover"], - ) - button.label.set_fontsize(9) - button.label.set_color(THEME["mpl_btn_text"]) - button.label.set_fontweight("bold") - button.label.set_horizontalalignment("center") - button.label.set_verticalalignment("center") - cid = button.on_clicked(lambda _event, action=callback: action()) - buttons_list.append(button) - callbacks_list.append(cid) - - # ── Qt-compatible Evaluation Panel ──────────────────────────────── - - def _build_primary_metric_tile( - self, - parent: ttk.Frame, - key: str, - row: int, - ) -> None: - tile = ttk.Frame(parent, style="Metric.TFrame", padding=(9, 3)) - tile.grid( - row=row, - column=0, - sticky="nsew", - pady=(0, 2), - ) - tile.grid_columnconfigure(0, weight=1) - tile.grid_columnconfigure(1, weight=0) - name_label = ttk.Label( - tile, - text=self._t(key), - style="MetricName.TLabel", - anchor="w", - justify=tk.LEFT, - wraplength=150, - ) - name_label.grid(row=0, column=0, sticky="w", padx=(0, 2)) - value_label = ttk.Label( - tile, - text="", - style="MetricValue.TLabel", - anchor="e", - justify=tk.RIGHT, - wraplength=90, - ) - value_label.grid(row=0, column=1, sticky="e") - self.primary_name_labels[key] = name_label - self.primary_value_labels[key] = value_label - - def _build_angle_metric_group( - self, - parent: ttk.Frame, - axis_key: str, - metric_specs: tuple[tuple[str, str], ...], - row: int, - ) -> None: - group = ttk.Frame(parent, style="Metric.TFrame", padding=(9, 4)) - group.grid( - row=row, - column=0, - sticky="nsew", - pady=(0, 2), - ) - group.grid_columnconfigure(0, weight=0, minsize=82) - group.grid_columnconfigure(1, weight=1, minsize=140) - title = ttk.Label( - group, - text=self._t(axis_key), - style="MetricSection.TLabel", - anchor="w", - ) - title.grid(row=0, column=0, columnspan=2, sticky="ew", pady=(0, 1)) - self.secondary_name_labels[f"{axis_key}_section"] = title - self.secondary_name_label_keys[f"{axis_key}_section"] = axis_key - - for row, (metric_key, label_key) in enumerate(metric_specs, start=1): - name_label = ttk.Label( - group, - text=self._t(label_key), - style="MetricName.TLabel", - anchor="w", - justify=tk.LEFT, - wraplength=108, - ) - name_label._qt.setWordWrap(True) - name_label.grid(row=row, column=0, sticky="w", padx=(0, 2)) - value_label = ttk.Label( - group, - text="", - style="MetricValue.TLabel", - anchor="e", - justify=tk.RIGHT, - wraplength=260, - ) - value_label.grid(row=row, column=1, sticky="e") - self.secondary_name_labels[metric_key] = name_label - self.secondary_name_label_keys[metric_key] = label_key - self.secondary_value_labels[metric_key] = value_label - - def _build_evaluation_panel(self, parent: ttk.Frame) -> None: - """Build the Array Evaluation card using Qt-compatible widgets.""" - self.eval_frame = ttk.Frame(parent, style="Card.TFrame", padding=(6, 4)) - self.eval_frame.grid(row=0, column=0, sticky="nsew") - self.eval_frame.grid_rowconfigure(0, weight=0) - self.eval_frame.grid_rowconfigure(1, weight=0) - self.eval_frame.grid_rowconfigure(2, weight=1) - self.eval_frame.grid_columnconfigure(0, weight=1) - - self.primary_name_labels: dict[str, ttk.Label] = {} - self.secondary_name_labels: dict[str, ttk.Label] = {} - self.secondary_name_label_keys: dict[str, str] = {} - self.primary_value_labels: dict[str, ttk.Label] = {} - self.secondary_value_labels: dict[str, ttk.Label] = {} - - # PRIMARY section - self.overview_frame = ttk.LabelFrame( - self.eval_frame, - text=self._t("overview_title"), - padding=(6, 2), - style="TLabelframe", - ) - self.overview_frame.grid(row=0, column=0, sticky="ew", pady=(0, 2)) - self.overview_frame.grid_columnconfigure(0, weight=1) - - for i, key in enumerate(PRIMARY_EVAL_ROWS): - self._build_primary_metric_tile(self.overview_frame, key, i) - - # SECONDARY section - self.angle_eval_frame = ttk.LabelFrame( - self.eval_frame, - text=self._t("angle_eval_title"), - padding=(6, 2), - style="TLabelframe", - ) - self.angle_eval_frame.grid(row=1, column=0, sticky="ew") - self.angle_eval_frame.grid_columnconfigure(0, weight=1) - - for i, (axis_key, metric_specs) in enumerate(ANGLE_EVAL_GROUPS): - self._build_angle_metric_group( - self.angle_eval_frame, - axis_key, - metric_specs, - i, - ) - - def _build_dbf2d_widget(self, parent: tk.Widget) -> ttk.Frame: - dbf2d_frame = ttk.Frame( - parent, - style="PlotPanel.TFrame", - padding=(2, 6, 8, 6), - ) - dbf2d_frame.grid_columnconfigure(0, weight=1) - dbf2d_frame.grid_rowconfigure(0, weight=1) - self.dbf2d_frame = dbf2d_frame - - self.dbf2d_fig = Figure(figsize=(DBF2D_FIG_SIZE, DBF2D_FIG_SIZE), dpi=FIG_DPI) - self.dbf2d_fig.set_facecolor(THEME["card_bg"]) - self.dbf2d_ax = self.dbf2d_fig.add_axes([0.11, 0.12, 0.70, 0.78]) - self.dbf2d_cbar_ax = self.dbf2d_fig.add_axes([0.87, 0.18, 0.035, 0.64]) - self.dbf2d_ax.set_facecolor(THEME["plot_bg"]) - self.dbf2d_canvas = FigureCanvasTkAgg(self.dbf2d_fig, master=self.dbf2d_frame) - dbf2d_widget = self.dbf2d_canvas.get_tk_widget() - _style_canvas_widget(dbf2d_widget) - dbf2d_widget.grid(row=0, column=0, sticky="nsew") - self.dbf2d_empty_overlay = _EmptyStateOverlay(dbf2d_widget) - - button_row = ttk.Frame(self.dbf2d_frame, style="Card.TFrame") - self.dbf2d_controls_widget = button_row - button_row.grid(row=1, column=0, sticky="ew", pady=(5, 0)) - for col in range(3): - button_row.grid_columnconfigure(col, weight=1, uniform="dbf2d_buttons") - self.dbf2d_az_button = ttk.Button( - button_row, - text=self._t("dbf2d_play_az"), - command=lambda: self.toggle_dbf2d_animation("azimuth"), - style="CompactPlay.TButton", - width=8, - ) - self.dbf2d_az_button.grid(row=0, column=0, sticky="ew", padx=(0, 4)) - self.dbf2d_el_button = ttk.Button( - button_row, - text=self._t("dbf2d_play_el"), - command=lambda: self.toggle_dbf2d_animation("elevation"), - style="CompactPlay.TButton", - width=8, - ) - self.dbf2d_el_button.grid(row=0, column=1, sticky="ew", padx=4) - self.dbf2d_stop_button = ttk.Button( - button_row, - text=self._t("dbf2d_stop"), - command=self.stop_dbf2d_animation, - style="CompactStop.TButton", - width=7, - ) - self.dbf2d_stop_button.grid(row=0, column=2, sticky="ew", padx=(4, 0)) - self.dbf2d_stop_button.configure(state=tk.DISABLED) - native_style = self.root._window.style() - for button in (self.dbf2d_az_button, self.dbf2d_el_button): - button._qt.setIcon( - native_style.standardIcon(QtWidgets.QStyle.StandardPixmap.SP_MediaPlay) - ) - button._qt.setCheckable(True) - self.dbf2d_stop_button._qt.setIcon( - native_style.standardIcon(QtWidgets.QStyle.StandardPixmap.SP_MediaStop) - ) - - self.dbf2d_status_label = ttk.Label( - self.dbf2d_frame, - text="", - style="Card.TLabel", - font=(THEME["font_family_mono"], THEME["font_size_sm"]), - anchor="center", - ) - self.dbf2d_status_label.grid(row=2, column=0, sticky="ew", pady=(4, 0)) - - return dbf2d_frame - - def _build_dbf2d_panel(self, parent=None) -> None: # noqa: ANN001 - if parent is None: - parent = getattr(self, "eval_notebook", None) - if parent is None: - return - is_notebook = isinstance(parent, ttk.Notebook) - is_pane = isinstance(parent, ttk.PanedWindow) - dbf2d_frame = self._build_dbf2d_widget(parent) - dbf2d_frame.configure( - style="Card.TFrame" if is_notebook else "PlotPanel.TFrame", - padding=(2, 6, 8, 6), - ) - if is_notebook: - parent.add(dbf2d_frame, text=self._t("eval_tab_dbf2d")) - elif is_pane: - parent.add(dbf2d_frame, weight=1) - - def _metric_value_style(self, key: str, value: str) -> str: - unavailable_values = { - self._t("metric_value_unavailable"), - "N/A", - } - if value in unavailable_values: - return "MetricValueMuted.TLabel" - if value == "N/A": - return "MetricValueMuted.TLabel" - if key == "row_virtual_channels": - return "MetricValueGood.TLabel" if "(100%)" in value else "MetricValueWarn.TLabel" - if key.endswith("_margin"): - if value == self._t("metric_value_no_competitor"): - return "MetricValueGood.TLabel" - match = re.match(r"^\s*(-?\d+(?:\.\d+)?)", value) - if match is not None: - margin = float(match.group(1)) - return ( - "MetricValueGood.TLabel" - if margin >= max(self.current_margin_db(), 0.5) - else "MetricValueWarn.TLabel" - ) - if key.endswith("_cut"): - if value in { - self._t("cut_reason_normal"), - self._t("cut_reason_data_boundary"), - }: - return "MetricValueGood.TLabel" - if any( - marker in value - for marker in ( - self._t("cut_reason_unreliable"), - self._t("cut_reason_peak_blurred"), - self._t("metric_value_unavailable"), - ) - ): - return "MetricValueRisk.TLabel" - return "MetricValueWarn.TLabel" - return "MetricValue.TLabel" - - def _update_evaluation_panel(self, metrics: ArrayMetrics) -> None: - """Update the Qt-compatible evaluation panel with current metrics.""" - utilization = ( - metrics.unique_count / metrics.virtual_count if metrics.virtual_count else 0.0 - ) - az_dbf_metrics = self._dbf_angle_metrics_for_mode("azimuth") - el_dbf_metrics = self._dbf_angle_metrics_for_mode("elevation") - - # PRIMARY values - values = { - "row_channel_count": f"{metrics.tx_count}T × {metrics.rx_count}R", - "row_virtual_channels": f"{metrics.unique_count}/{metrics.virtual_count} ({utilization:.0%})", - "row_az_aperture": _format_mm(self.aperture_mm(metrics.x_aperture)), - "row_el_aperture": _format_mm(self.aperture_mm(metrics.y_aperture)), - "row_az_resolution": _format_float(metrics.azimuth_resolution, "°"), - "row_el_resolution": _format_float(metrics.elevation_resolution, "°"), - } - for key, val in values.items(): - if key in self.primary_value_labels: - self.primary_value_labels[key].configure( - text=val, - style=self._metric_value_style(key, val), - ) - - # SECONDARY values - sec_values = { - "row_az_no_fold": _format_angle_range(az_dbf_metrics), - "row_az_no_fold_error": _format_axis_angle_metrics( - az_dbf_metrics, - "no_fold_error", - self.language, - ), - "row_az_margin": _format_axis_angle_metrics( - az_dbf_metrics, - "margin", - self.language, - ), - "row_az_cut": _angle_cut_reason_summary(az_dbf_metrics, self.language), - "row_el_no_fold": _format_angle_range(el_dbf_metrics), - "row_el_no_fold_error": _format_axis_angle_metrics( - el_dbf_metrics, - "no_fold_error", - self.language, - ), - "row_el_margin": _format_axis_angle_metrics( - el_dbf_metrics, - "margin", - self.language, - ), - "row_el_cut": _angle_cut_reason_summary(el_dbf_metrics, self.language), - } - for key, val in sec_values.items(): - if key in self.secondary_value_labels: - self.secondary_value_labels[key].configure( - text=val, - style=self._metric_value_style(key, val), - ) - - self.header_kpi_texts["chip_virtual_channels"].set(values["row_virtual_channels"]) - self.header_kpi_texts["chip_az_resolution"].set(values["row_az_resolution"]) - self.header_kpi_texts["chip_el_resolution"].set(values["row_el_resolution"]) - - # ── Array data ──────────────────────────────────────────────────── - - def _set_frequency_ghz(self, frequency: float) -> None: - self.last_valid_frequency_ghz = frequency - self.frequency_ghz.set(_format_frequency_ghz(frequency)) - - def _normalize_frequency_input(self) -> tuple[float, bool]: - frequency = _parse_frequency_ghz(self.frequency_ghz.get()) - if frequency is None: - fallback = self.last_valid_frequency_ghz - self.frequency_ghz.set(_format_frequency_ghz(fallback)) - return fallback, False - self._set_frequency_ghz(frequency) - return frequency, True - - def current_frequency_ghz(self) -> float: - frequency = _parse_frequency_ghz(self.frequency_ghz.get()) - return frequency if frequency is not None else self.last_valid_frequency_ghz - - def _set_margin_db(self, margin: float) -> None: - self.last_valid_margin_db = margin - self.margin_db.set(_format_margin_db(margin)) - - def _normalize_margin_input(self) -> tuple[float, bool]: - margin = _parse_margin_db(self.margin_db.get()) - if margin is None: - fallback = self.last_valid_margin_db - self.margin_db.set(_format_margin_db(fallback)) - return fallback, False - self._set_margin_db(margin) - return margin, True - - def current_margin_db(self) -> float: - margin = _parse_margin_db(self.margin_db.get()) - return margin if margin is not None else self.last_valid_margin_db - - def _current_dbf_display_mode(self) -> str: - mode = DBF_DISPLAY_DB - mode_var = getattr(self, "dbf_display_mode", None) - if mode_var is not None: - try: - mode = str(mode_var.get()) - except Exception: - mode = DBF_DISPLAY_DB - if mode not in SUPPORTED_DBF_DISPLAY_MODES: - mode = DBF_DISPLAY_DB - if mode_var is not None: - try: - mode_var.set(mode) - except Exception: - pass - return mode - - def _dbf_display_values(self, spectrum_db: np.ndarray) -> np.ndarray: - db_values = np.asarray(spectrum_db, dtype=float) - if self._current_dbf_display_mode() == DBF_DISPLAY_MAGNITUDE: - magnitude = np.power(10.0, np.minimum(db_values, 0.0) / 20.0) - return np.clip( - np.nan_to_num(magnitude, nan=0.0, posinf=1.0, neginf=0.0), - 0.0, - 1.0, - ) - return np.clip( - np.nan_to_num(db_values, nan=-40.0, posinf=0.0, neginf=-40.0), - -40.0, - 0.0, - ) - - def _dbf_display_value(self, value_db: float) -> float: - values = self._dbf_display_values(np.array([value_db], dtype=float)) - return float(values[0]) - - def _dbf_display_axis_label(self) -> str: - if self._current_dbf_display_mode() == DBF_DISPLAY_MAGNITUDE: - return self._t("dbf_axis_correlation_mag") - return self._t("dbf_axis_correlation_db") - - def _dbf_display_colorbar_label(self) -> str: - if self._current_dbf_display_mode() == DBF_DISPLAY_MAGNITUDE: - return self._t("dbf2d_colorbar_label_mag") - return self._t("dbf2d_colorbar_label") - - def _format_dbf_display_value(self, value_db: float) -> str: - if self._current_dbf_display_mode() == DBF_DISPLAY_MAGNITUDE: - return self._t( - "dbf_correlation_mag_value", value=self._dbf_display_value(value_db) - ) - return self._t("dbf_correlation_db_value", value=value_db) - - def wavelength_mm(self) -> float: - return LIGHT_SPEED_MM_PER_NS / self.current_frequency_ghz() - - def half_wavelength_mm(self) -> float: - return self.wavelength_mm() / 2.0 - - def aperture_mm(self, aperture_half_lambda: float) -> float: - return aperture_half_lambda * self.half_wavelength_mm() - - def _build_elements(self) -> list[EditableElement]: - return _starter_layout_elements() - - def current_array(self) -> AntennaArray: - tx = [ - ArrayPoint(name=element.name, x=element.x, y=element.y) - for element in self.elements - if element.kind == "tx" - ] - rx = [ - ArrayPoint(name=element.name, x=element.x, y=element.y) - for element in self.elements - if element.kind == "rx" - ] - return AntennaArray(tx=tx, rx=rx) - - def _elements_of_kind(self, kind: str) -> list[EditableElement]: - return [element for element in self.elements if element.kind == kind] - - def _sync_auto_count_inputs(self) -> None: - auto_tx_count = getattr(self, "auto_tx_count", None) - auto_rx_count = getattr(self, "auto_rx_count", None) - if auto_tx_count is not None: - auto_tx_count.set(str(len(self._elements_of_kind("tx")))) - if auto_rx_count is not None: - auto_rx_count.set(str(len(self._elements_of_kind("rx")))) - - def _renumber_elements(self) -> None: - selected = self.selected_element - renumbered: list[EditableElement] = [] - for kind in ("tx", "rx"): - prefix = _element_prefix(kind) - sorted_elements = sorted( - self._elements_of_kind(kind), - key=lambda element: (element.x, element.y, element.index), - ) - for index, element in enumerate(sorted_elements): - element.index = index - element.name = f"{prefix}{index + 1}" - renumbered.append(element) - self.elements = renumbered - if any(element is selected for element in self.elements): - self.selected_element = selected - else: - self.selected_element = None - - def _clear_interaction_state(self) -> None: - self.delete_mode = False - self.selected_element = None - self._reset_physical_drag_state() - self._sync_auto_count_inputs() - self._update_delete_button_state() - if hasattr(self, "phys_canvas"): - self._set_physical_cursor("") - - def _release_physical_pointer(self) -> None: - release_pointer = getattr( - getattr(self, "phys_canvas", None), "release_pointer", None - ) - if callable(release_pointer): - release_pointer() - - def _reset_physical_drag_state(self) -> None: - """Clear every physical-drag resource, including capture and timers.""" - - self._cancel_physical_drag_redraw() - self.dragging = None - self.drag_bounds = None - self.drag_axis_limits = None - self.drag_start_snapshot = None - self.drag_grab_offset = None - self._release_physical_pointer() - - def _schedule_physical_drag_redraw(self) -> None: - """Coalesce high-frequency pointer moves to roughly one frame.""" - - if self._physical_drag_after_id is not None: - return - self._physical_drag_after_id = self.root.after( - 16, self._flush_physical_drag_redraw - ) - - def _flush_physical_drag_redraw(self) -> None: - self._physical_drag_after_id = None - if self.dragging is None: - return - self._draw_physical_array() - self.phys_canvas.draw_idle() - - def _cancel_physical_drag_redraw(self) -> None: - after_id = getattr(self, "_physical_drag_after_id", None) - if after_id is None: - return - self._physical_drag_after_id = None - try: - self.root.after_cancel(after_id) - except (RuntimeError, tk.TclError): - pass - - def _layout_snapshot_for( - self, - elements: list[EditableElement], - selected_element: EditableElement | None, - ) -> LayoutSnapshot: - selected_key = ( - (selected_element.kind, selected_element.index, selected_element.name) - if selected_element is not None - else None - ) - return LayoutSnapshot( - elements=tuple( - ( - element.kind, - int(element.index), - element.name, - round(float(element.x), ROUND_DECIMALS), - round(float(element.y), ROUND_DECIMALS), - ) - for element in elements - ), - selected_key=selected_key, - ) - - def _capture_layout_snapshot(self) -> LayoutSnapshot: - return self._layout_snapshot_for(self.elements, self.selected_element) - - def _push_undo_snapshot(self, snapshot: LayoutSnapshot | None = None) -> None: - snapshot = snapshot if snapshot is not None else self._capture_layout_snapshot() - if not self.undo_stack or self.undo_stack[-1] != snapshot: - self.undo_stack.append(snapshot) - self.redo_stack.clear() - - def _restore_layout_snapshot(self, snapshot: LayoutSnapshot) -> None: - self.elements = [ - EditableElement(kind=kind, index=index, name=name, x=x, y=y) - for kind, index, name, x, y in snapshot.elements - ] - self.selected_element = None - if snapshot.selected_key is not None: - for element in self.elements: - key = (element.kind, element.index, element.name) - if key == snapshot.selected_key: - self.selected_element = element - break - self._reset_physical_drag_state() - - def _cancel_physical_drag(self) -> bool: - """Restore the press-time layout and release all drag resources.""" - - snapshot = self.drag_start_snapshot - had_drag = self.dragging is not None or snapshot is not None - if snapshot is not None: - self._restore_layout_snapshot(snapshot) - else: - self._reset_physical_drag_state() - if had_drag: - self.generate_virtual_array() - return had_drag - - def undo_layout_change(self, event=None) -> str | None: # noqa: ANN001 - if event is not None and _event_widget_is_text_input(event): - return None - - current_snapshot = self._capture_layout_snapshot() - while self.undo_stack and self.undo_stack[-1] == current_snapshot: - self.undo_stack.pop() - if not self.undo_stack: - self.status.set(self._t("undo_empty")) - return "break" - - previous_snapshot = self.undo_stack.pop() - self.redo_stack.append(current_snapshot) - self._restore_layout_snapshot(previous_snapshot) - self.generate_virtual_array() - self.status.set(self._t("undo_done")) - return "break" - - def redo_layout_change(self, event=None) -> str | None: # noqa: ANN001 - if event is not None and _event_widget_is_text_input(event): - return None - - current_snapshot = self._capture_layout_snapshot() - while self.redo_stack and self.redo_stack[-1] == current_snapshot: - self.redo_stack.pop() - if not self.redo_stack: - self.status.set(self._t("redo_empty")) - return "break" - - next_snapshot = self.redo_stack.pop() - if not self.undo_stack or self.undo_stack[-1] != current_snapshot: - self.undo_stack.append(current_snapshot) - self._restore_layout_snapshot(next_snapshot) - self.generate_virtual_array() - self.status.set(self._t("redo_done")) - return "break" - - def _next_element_position(self, kind: str) -> tuple[float, float]: - same_kind = self._elements_of_kind(kind) - if not same_kind: - return (0.0, 0.0 if kind == "tx" else -10.0) - - anchor = ( - self.selected_element - if self.selected_element is not None and self.selected_element.kind == kind - else max(same_kind, key=lambda element: (element.x, element.y)) - ) - occupied = {(element.x, element.y) for element in self.elements} - x = snap_to_grid(anchor.x + 2 * GRID_STEP) - y = snap_to_grid(anchor.y) - while (x, y) in occupied: - x = snap_to_grid(x + 2 * GRID_STEP) - return x, y - - def add_tx_element(self) -> None: - self._add_element("tx") - - def add_rx_element(self) -> None: - self._add_element("rx") - - def _add_element(self, kind: str) -> None: - current_count = len(self._elements_of_kind(kind)) - max_count = _max_elements_for_kind(kind) - prefix = _element_prefix(kind) - if current_count >= max_count: - self.status.set(self._t("limit_reached", prefix=prefix, max_count=max_count)) - messagebox.showinfo( - self._t("antenna_limit_title"), - self._t("count_limit_detail", prefix=prefix, max_count=max_count), - ) - return - - self._push_undo_snapshot() - x, y = self._next_element_position(kind) - element = EditableElement( - kind=kind, - index=current_count, - name=f"{prefix}{current_count + 1}", - x=x, - y=y, - ) - self.elements.append(element) - self.selected_element = element - self._renumber_elements() - self.delete_mode = False - self._reset_physical_drag_state() - self._sync_auto_count_inputs() - self._update_delete_button_state() - self.generate_virtual_array() - self.status.set( - self._t( - "added_element", - element=element.name, - x=element.x * DISPLAY_SCALE_LAMBDA, - y=element.y * DISPLAY_SCALE_LAMBDA, - ) - ) - - def _build_physical_figure_controls(self) -> None: - self._build_figure_buttons( - self.phys_fig, - ( - (self._t("physical_add_tx"), [0.55, 0.91, 0.07, 0.055], self.add_tx_element), - (self._t("physical_add_rx"), [0.625, 0.91, 0.07, 0.055], self.add_rx_element), - (self._t("physical_delete"), [0.70, 0.91, 0.105, 0.055], self.toggle_delete_mode), - (self._t("physical_clear"), [0.81, 0.91, 0.105, 0.055], self.clear_array_layout), - ), - self.physical_buttons, - self.physical_button_callbacks, - ) - - def toggle_delete_mode(self, _event=None) -> None: # noqa: ANN001 - self.delete_mode = not self.delete_mode - self._reset_physical_drag_state() - if self.delete_mode: - self.status.set(self._t("delete_mode_on")) - else: - self.status.set(self._t("delete_mode_off")) - self._update_delete_button_state() - self._set_physical_cursor("crosshair" if self.delete_mode else "") - - def clear_array_layout(self, _event=None) -> None: # noqa: ANN001 - new_elements = _starter_layout_elements() - if self._layout_snapshot_for(new_elements, None) == self._capture_layout_snapshot(): - self.status.set(self._t("layout_already_clear")) - return - self._push_undo_snapshot() - self.elements = new_elements - self._clear_interaction_state() - self._sync_auto_count_inputs() - self.generate_virtual_array() - self.status.set(self._t("layout_cleared")) - - def apply_auto_array_layout(self, _event=None) -> str: # noqa: ANN001 - try: - tx_count = _validate_element_count(self.auto_tx_count.get(), "tx") - rx_count = _validate_element_count(self.auto_rx_count.get(), "rx") - except ValueError as exc: - self.status.set(str(exc)) - messagebox.showinfo(self._t("auto_layout_title"), str(exc)) - return "break" - - new_elements = _build_auto_layout_elements(tx_count, rx_count) - if self._layout_snapshot_for(new_elements, None) == self._capture_layout_snapshot(): - self.status.set(self._t("auto_layout_already", tx=tx_count, rx=rx_count)) - return "break" - - self._push_undo_snapshot() - self.elements = new_elements - self._clear_interaction_state() - self._sync_auto_count_inputs() - self.generate_virtual_array() - self.status.set(self._t("auto_layout_done", tx=tx_count, rx=rx_count)) - return "break" - - def delete_selected_element(self) -> None: - if self.selected_element is None: - self.toggle_delete_mode() - return - - self._delete_element(self.selected_element) - - def _delete_element(self, element: EditableElement) -> bool: - same_kind_count = len(self._elements_of_kind(element.kind)) - if same_kind_count <= 1: - prefix = _element_prefix(element.kind) - self.status.set(self._t("delete_last", prefix=prefix)) - messagebox.showinfo( - self._t("antenna_limit_title"), - self._t("delete_last_detail", prefix=prefix), - ) - return False - - deleted_name = element.name - self._push_undo_snapshot() - self.elements = [candidate for candidate in self.elements if candidate is not element] - self.selected_element = None - self._reset_physical_drag_state() - self._renumber_elements() - self._sync_auto_count_inputs() - self.generate_virtual_array() - mode_suffix = self._t("delete_mode_suffix") if self.delete_mode else "" - self.status.set(self._t("deleted_element", element=deleted_name, suffix=mode_suffix)) - return True - - # ── Button handlers ─────────────────────────────────────────────── - - def on_frequency_changed(self, _event=None) -> str: # noqa: ANN001 - frequency, is_valid = self._normalize_frequency_input() - self.generate_virtual_array() - if is_valid: - self.status.set( - self._t("frequency_set", frequency=_format_frequency_ghz(frequency)) - ) - else: - self.status.set( - self._t("frequency_invalid", frequency=_format_frequency_ghz(frequency)) - ) - return "break" - - def on_margin_changed(self, _event=None) -> str: # noqa: ANN001 - margin, is_valid = self._normalize_margin_input() - self.generate_virtual_array() - if is_valid: - self.status.set(self._t("margin_set", value=_format_margin_db(margin))) - else: - self.status.set(self._t("margin_invalid", value=_format_margin_db(margin))) - return "break" - - def on_dbf_display_mode_changed(self) -> str: - mode = self._current_dbf_display_mode() - if hasattr(self, "az_chart") and hasattr(self, "el_chart"): - if self.dbf_scan_active or self.dbf_scan_mode is not None: - self._draw_dbf_scan_frame() - else: - self._draw_dbf_reference_spectrum("azimuth") - self._draw_dbf_reference_spectrum("elevation") - if getattr(self, "dbf2d_canvas", None) is not None: - self._draw_dbf2d_heatmap() - label_key = ( - "dbf_display_magnitude" - if mode == DBF_DISPLAY_MAGNITUDE - else "dbf_display_db" - ) - self.status.set(self._t("dbf_display_changed", mode=self._t(label_key))) - return "break" - - def on_save_shortcut(self, _event=None) -> str: # noqa: ANN001 - self.export_layout_config() - return "break" - - def on_import_shortcut(self, _event=None) -> str: # noqa: ANN001 - self.import_layout_config() - return "break" - - def on_refresh_shortcut(self, _event=None) -> str: # noqa: ANN001 - _frequency, is_valid = self._normalize_frequency_input() - self.generate_virtual_array() - self.status.set(self._t("refreshed") if is_valid else self._t("refresh_invalid")) - return "break" - - def on_focus_frequency_shortcut(self, _event=None) -> str: # noqa: ANN001 - if self.frequency_entry is not None: - self.frequency_entry.focus_set() - self.frequency_entry.selection_range(0, tk.END) - return "break" - - def on_escape_key(self, _event=None) -> str: # noqa: ANN001 - dbf_mode = getattr(self, "dbf_drag_mode", None) - if dbf_mode is not None: - chart = self._chart_for_dbf_mode(dbf_mode) - chart.canvas.release_pointer() - self.on_dbf_true_line_cancel(dbf_mode) - self.status.set(self._t("drag_cancel")) - return "break" - - if getattr(self, "dbf2d_dragging", False): - if self.dbf2d_canvas is not None: - self.dbf2d_canvas.release_pointer() - self.on_dbf2d_pointer_cancel() - self.status.set(self._t("drag_cancel")) - return "break" - - if self.delete_mode: - self.delete_mode = False - self._reset_physical_drag_state() - self.status.set(self._t("delete_mode_off")) - self._update_delete_button_state() - self._set_physical_cursor("") - return "break" - - if self._cancel_physical_drag(): - self.status.set(self._t("drag_cancel")) - return "break" - - if self.selected_element is None: - self.status.set(self._t("no_selection")) - return "break" - self.selected_element = None - self._draw_physical_array() - self.phys_canvas.draw_idle() - self.status.set(self._t("selection_cleared")) - return "break" - - def on_physical_pointer_cancel(self, _event=None) -> None: # noqa: ANN001 - if self._cancel_physical_drag(): - self.status.set(self._t("drag_cancel")) - - def _event_dbf_angle(self, event, chart: ResponseChart) -> float | None: # noqa: ANN001 - if event.xdata is not None: - return float(event.xdata) - if event.x is None or event.y is None: - return None - try: - angle, _gain = chart.ax.transData.inverted().transform((event.x, event.y)) - except (TypeError, ValueError): - return None - return float(angle) - - def _set_chart_cursor(self, chart: ResponseChart, cursor: str) -> None: - if chart.canvas is None or not hasattr(chart.canvas, "get_tk_widget"): - return - try: - chart.canvas.get_tk_widget().configure(cursor=cursor) - except (tk.TclError, AttributeError): - return - - def _set_physical_cursor(self, cursor: str) -> None: - try: - self.phys_canvas.get_tk_widget().configure(cursor=cursor) - except (tk.TclError, AttributeError): - return - - def _update_physical_cursor(self, event) -> None: # noqa: ANN001 - if self.dragging is not None: - self._set_physical_cursor("closedhand") - return - if self.delete_mode: - self._set_physical_cursor("crosshair") - return - if ( - event.inaxes == self.physical_ax - and event.xdata is not None - and event.ydata is not None - ): - nearest = self._nearest_element( - _to_internal_half_lambda(float(event.xdata)), - _to_internal_half_lambda(float(event.ydata)), - ) - self._set_physical_cursor("openhand" if nearest is not None else "") - return - self._set_physical_cursor("") - - def _response_event_near_true_line(self, event, chart: ResponseChart) -> bool: # noqa: ANN001 - if event.inaxes != chart.ax or event.xdata is None or chart.true_angle is None: - return False - x_low, x_high = chart.ax.get_xlim() - tolerance = max(2.0, abs(x_high - x_low) * 0.015) - return abs(float(event.xdata) - float(chart.true_angle)) <= tolerance - - def _update_response_cursor(self, event, chart: ResponseChart) -> None: # noqa: ANN001 - self._set_chart_cursor( - chart, - "hand2" if self._response_event_near_true_line(event, chart) else "", - ) - - def _on_response_figure_leave(self, chart: ResponseChart) -> None: - self._hide_response_hover(chart) - self._set_chart_cursor(chart, "") - - def _set_dbf_scan_frame(self, mode: str, frame: int) -> None: - frame = max(0, min(DBF_SCAN_GRID_SIZE - 1, int(frame))) - - if self.dbf_scan_after_id is not None: - try: - self.root.after_cancel(self.dbf_scan_after_id) - except tk.TclError: - pass - self.dbf_scan_after_id = None - - if ( - self.dbf_scan_mode != mode - or self.dbf_true_angles.size == 0 - or self.dbf_scan_angles.size == 0 - or self.dbf_spectra_db.size == 0 - ): - self._normalize_frequency_input() - self._load_dbf_spectra(mode) - - self.dbf_scan_frame = min(frame, len(self.dbf_true_angles) - 1) - self.dbf_scan_active = True - self.dbf_scan_paused = True - self._draw_dbf_scan_frame() - self._update_dbf_scan_controls() - language = getattr(self, "language", LANGUAGE_ZH) - label = _dbf_mode_label(mode, language) - true_angle = self._current_dbf_true_angle() - self.status.set(self._t("dbf_pause_status", mode=label, angle=true_angle)) - - def _set_dbf_scan_angle(self, mode: str, angle: float) -> None: - self._set_dbf_scan_frame(mode, _dbf_frame_index_for_angle(angle)) - - def on_dbf_true_line_press(self, event, mode: str) -> None: # noqa: ANN001 - chart = self._chart_for_dbf_mode(mode) - if event.button != 1 or event.inaxes != chart.ax: - return - if not self._response_event_near_true_line(event, chart): - return - angle = self._event_dbf_angle(event, chart) - if angle is None: - return - self.dbf_drag_mode = mode - chart.canvas.grab_pointer(chart.ax) - self._set_chart_cursor(chart, "hand2") - self._hide_response_hover(chart) - self._set_dbf_scan_angle(mode, angle) - - def _drag_dbf_true_line(self, event) -> None: # noqa: ANN001 - mode = self.dbf_drag_mode - if mode is None: - return - chart = self._chart_for_dbf_mode(mode) - angle = self._event_dbf_angle(event, chart) - if angle is None: - return - self._set_dbf_scan_angle(mode, angle) - - def on_dbf_true_line_release(self, event, mode: str) -> None: # noqa: ANN001 - if self.dbf_drag_mode != mode: - return - self._drag_dbf_true_line(event) - self.dbf_drag_mode = None - chart = self._chart_for_dbf_mode(mode) - chart.canvas.release_pointer() - self._update_response_cursor(event, chart) - - def on_dbf_true_line_cancel(self, mode: str) -> None: - if self.dbf_drag_mode != mode: - return - self.dbf_drag_mode = None - self._set_chart_cursor(self._chart_for_dbf_mode(mode), "") - - def toggle_az_dbf_animation(self, _event=None) -> None: # noqa: ANN001 - self.toggle_dbf_scan_animation("azimuth") - - def toggle_el_dbf_animation(self, _event=None) -> None: # noqa: ANN001 - self.toggle_dbf_scan_animation("elevation") - - def toggle_dbf_scan_animation(self, mode: str = "azimuth") -> None: - if self.dbf_scan_active and self.dbf_scan_mode == mode: - if self.dbf_scan_paused: - self.resume_dbf_scan_animation() - else: - self.pause_dbf_scan_animation() - return - self.start_dbf_scan_animation(mode) - - def start_dbf_scan_animation(self, mode: str = "azimuth") -> None: - self.stop_dbf_scan_animation(restore_response=True) - _frequency, is_valid = self._normalize_frequency_input() - self._load_dbf_spectra(mode) - self.dbf_scan_frame = 0 - self.dbf_scan_active = True - self.dbf_scan_paused = False - self._update_dbf_scan_controls() - self._draw_dbf_scan_frame() - self._schedule_dbf_scan_frame() - language = getattr(self, "language", LANGUAGE_ZH) - label = _dbf_mode_label(mode, language) - self.status.set( - self._t("dbf_play_status", mode=label) - if is_valid - else self._t("dbf_play_status_invalid", mode=label) - ) - - def _dbf_spectrum_bank_for_mode(self, mode: str): - if mode == "azimuth": - return dbf_azimuth_spectrum_bank - if mode == "elevation": - return dbf_elevation_spectrum_bank - raise ValueError(f"Unknown DBF animation mode: {mode!r}") - - def _dbf_angle_metrics_for_mode(self, mode: str) -> DbfAngleMetrics | None: - try: - spectrum_bank = self._dbf_spectrum_bank_for_mode(mode) - true_angles, scan_angles, spectra_db = spectrum_bank( - self.current_array(), - tx_pattern=self.element_pattern, - rx_pattern=self.element_pattern, - channel_patterns=self.channel_patterns, - dbf_dictionary=self.dbf_dictionary, - ) - return dbf_angle_metrics_from_spectra( - true_angles, - scan_angles, - spectra_db, - ambiguity_margin_db=self.current_margin_db(), - ) - except Exception: - LOGGER.exception("Failed to calculate %s DBF angle metrics", mode) - return None - - def _load_dbf_spectra(self, mode: str) -> None: - spectrum_bank = self._dbf_spectrum_bank_for_mode(mode) - self.dbf_true_angles, self.dbf_scan_angles, self.dbf_spectra_db = ( - spectrum_bank( - self.current_array(), - tx_pattern=self.element_pattern, - rx_pattern=self.element_pattern, - channel_patterns=self.channel_patterns, - dbf_dictionary=self.dbf_dictionary, - ) - ) - self.dbf_scan_mode = mode - - def pause_dbf_scan_animation(self) -> None: - if not self.dbf_scan_active or self.dbf_scan_paused: - return - if self.dbf_scan_after_id is not None: - try: - self.root.after_cancel(self.dbf_scan_after_id) - except tk.TclError: - pass - self.dbf_scan_after_id = None - self.dbf_scan_paused = True - self._update_dbf_scan_controls() - language = getattr(self, "language", LANGUAGE_ZH) - label = _dbf_mode_label(self.dbf_scan_mode, language) - true_angle = self._current_dbf_true_angle() - self.status.set(self._t("dbf_pause_status", mode=label, angle=true_angle)) - - def resume_dbf_scan_animation(self) -> None: - if not self.dbf_scan_active or not self.dbf_scan_paused: - return - self.dbf_scan_paused = False - self._update_dbf_scan_controls() - self._schedule_dbf_scan_frame() - language = getattr(self, "language", LANGUAGE_ZH) - label = _dbf_mode_label(self.dbf_scan_mode, language) - self.status.set(self._t("dbf_resume_status", mode=label)) - - def stop_dbf_scan_animation(self, restore_response: bool = True) -> None: - had_animation = self.dbf_scan_active or self.dbf_scan_mode is not None - if self.dbf_scan_after_id is not None: - try: - self.root.after_cancel(self.dbf_scan_after_id) - except tk.TclError: - pass - self.dbf_scan_after_id = None - self.dbf_scan_active = False - self.dbf_scan_paused = False - self.dbf_scan_mode = None - self._update_dbf_scan_controls() - if restore_response and had_animation: - self.generate_virtual_array() - - def _schedule_dbf_scan_frame(self) -> None: - self.dbf_scan_after_id = self.root.after( - DBF_SCAN_INTERVAL_MS, - self._advance_dbf_scan_animation, - ) - - def _advance_dbf_scan_animation(self) -> None: - if not self.dbf_scan_active or self.dbf_scan_paused: - return - self.dbf_scan_frame += 1 - if self.dbf_scan_frame >= len(self.dbf_true_angles): - self.dbf_scan_after_id = None - self.dbf_scan_active = False - self.dbf_scan_paused = False - language = getattr(self, "language", LANGUAGE_ZH) - label = _dbf_mode_label(self.dbf_scan_mode, language) - self._update_dbf_scan_controls() - self.status.set(self._t("dbf_complete_status", mode=label)) - return - self._draw_dbf_scan_frame() - self._schedule_dbf_scan_frame() - - def _update_dbf_scan_controls(self) -> None: - for mode, chart in ( - ("azimuth", getattr(self, "az_chart", None)), - ("elevation", getattr(self, "el_chart", None)), - ): - if chart is None: - continue - is_active_mode = self.dbf_scan_active and self.dbf_scan_mode == mode - has_paused_mode = ( - self.dbf_scan_paused - and self.dbf_scan_mode == mode - and self.dbf_true_angles.size > 0 - ) - if chart.play_button is not None: - if is_active_mode: - text = ( - self._t("dbf_resume_compact") - if self.dbf_scan_paused - else self._t("dbf_pause_compact") - ) - elif has_paused_mode: - text = self._t("dbf_resume_compact") - else: - text = self._t("dbf_play_compact") - style_name = ( - "CompactPlayActive.TButton" - if is_active_mode or has_paused_mode - else "CompactPlay.TButton" - ) - chart.play_button.configure(text=text, style=style_name) - active_or_paused = is_active_mode or has_paused_mode - chart.play_button._qt.setChecked(active_or_paused) - icon_kind = ( - QtWidgets.QStyle.StandardPixmap.SP_MediaPause - if is_active_mode and not self.dbf_scan_paused - else QtWidgets.QStyle.StandardPixmap.SP_MediaPlay - ) - chart.play_button._qt.setIcon( - self.root._window.style().standardIcon(icon_kind) - ) - if chart.stop_button is not None: - chart.stop_button.configure(text=self._t("dbf_stop_compact")) - state = tk.NORMAL if self.dbf_scan_mode == mode else tk.DISABLED - chart.stop_button.configure(state=state) - - def _chart_for_dbf_mode(self, mode: str) -> ResponseChart: - return self.el_chart if mode == "elevation" else self.az_chart - - def _set_dbf_progress( - self, mode: str, frame_index: int, true_angle: float - ) -> None: - chart = self._chart_for_dbf_mode(mode) - if chart.progress_label is not None: - language = getattr(self, "language", LANGUAGE_ZH) - chart.progress_label.configure( - text=( - f"{_dbf_short_label(mode, language)} " - f"{_format_dbf_angle_label(true_angle, language)} " - f"({frame_index + 1}/{DBF_SCAN_GRID_SIZE})" - ) - ) - - def _current_dbf_true_angle(self) -> float: - if self.dbf_true_angles.size == 0: - return 0.0 - frame = min(self.dbf_scan_frame, len(self.dbf_true_angles) - 1) - return float(self.dbf_true_angles[frame]) - - def _draw_dbf_reference_spectrum(self, mode: str) -> None: - spectrum_bank = self._dbf_spectrum_bank_for_mode(mode) - _true_angles, scan_angles, spectra_db = spectrum_bank( - self.current_array(), - true_angles_deg=np.asarray([0.0], dtype=float), - tx_pattern=self.element_pattern, - rx_pattern=self.element_pattern, - channel_patterns=self.channel_patterns, - dbf_dictionary=self.dbf_dictionary, - ) - self._draw_dbf_spectrum( - mode=mode, - true_angle=0.0, - scan_angles=scan_angles, - spectrum_db=spectra_db[0], - frame_label=self._t("reference_frame"), - frame_index=_dbf_frame_index_for_angle(0.0), - ) - - def _draw_dbf_scan_frame(self) -> None: - if ( - self.dbf_true_angles.size == 0 - or self.dbf_scan_angles.size == 0 - or self.dbf_spectra_db.size == 0 - ): - return - - frame = min(self.dbf_scan_frame, len(self.dbf_true_angles) - 1) - true_angle = float(self.dbf_true_angles[frame]) - spectrum_db = self.dbf_spectra_db[frame] - self._draw_dbf_spectrum( - mode=self.dbf_scan_mode or "azimuth", - true_angle=true_angle, - scan_angles=self.dbf_scan_angles, - spectrum_db=spectrum_db, - frame_label=self._t( - "frame_label", frame=frame + 1, total=len(self.dbf_true_angles) - ), - frame_index=frame, - ) - - def _draw_dbf_spectrum( - self, - mode: str, - true_angle: float, - scan_angles: np.ndarray, - spectrum_db: np.ndarray, - frame_label: str, - frame_index: int | None = None, - ) -> None: - peak_index = _dbf_peak_index(scan_angles, spectrum_db, true_angle) - peak_angle = float(scan_angles[peak_index]) - peak_gain = float(spectrum_db[peak_index]) - true_index = int(np.argmin(np.abs(scan_angles - true_angle))) - true_gain = float(spectrum_db[true_index]) - language = getattr(self, "language", LANGUAGE_ZH) - mode_label = _dbf_mode_label(mode, language) - chart = self._chart_for_dbf_mode(mode) - chart.true_angle = float(true_angle) - ax = chart.ax - ax.clear() - _configure_axis_chrome(ax) - if frame_index is not None: - self._set_dbf_progress(mode, frame_index, true_angle) - - display_mode = self._current_dbf_display_mode() - display_spectrum = self._dbf_display_values(spectrum_db) - true_display_value = self._dbf_display_value(true_gain) - peak_display_value = self._dbf_display_value(peak_gain) - ax.plot( - scan_angles, - display_spectrum, - color=THEME["response_line"], - linewidth=5.0, - alpha=0.12, - solid_capstyle="round", - ) - ax.plot( - scan_angles, - display_spectrum, - color=THEME["response_line"], - linewidth=2.0, - solid_capstyle="round", - ) - ax.axvline( - true_angle, - color=THEME["sidelobe"], - linewidth=1.9, - linestyle="-", - zorder=4, - label=self._t("legend_true_angle"), - ) - ax.scatter( - [true_angle], - [true_display_value], - marker="o", - s=58, - color=THEME["sidelobe"], - edgecolors="#ffffff", - linewidths=0.9, - zorder=5, - ) - ax.scatter( - [peak_angle], - [peak_display_value], - marker="x", - s=70, - color=THEME["secondary_accent"], - linewidths=1.8, - zorder=6, - label=self._t("legend_peak"), - ) - ax.set_xlim(DBF_SCAN_FOV) - _apply_dbf_angle_ticks(ax) - if display_mode == DBF_DISPLAY_MAGNITUDE: - ax.set_ylim(-0.02, 1.04) - else: - ax.set_ylim(-40.0, 1.0) - _apply_dbf_value_ticks(ax, display_mode) - ax.set_title( - self._t("dbf_title", mode=mode_label), - pad=6, - y=1.02, - loc="left", - color=THEME["text_primary"], - fontweight="bold", - ) - axis_key = "axis_el_angle" if mode == "elevation" else "axis_az_angle" - ax.set_xlabel(self._t(axis_key), color=THEME["text_secondary"]) - ax.set_ylabel( - self._dbf_display_axis_label(), - labelpad=2, - color=THEME["text_secondary"], - ) - ax.grid(True, alpha=THEME["grid_alpha"], color=THEME["grid_color"], linewidth=0.55) - ax.text( - 0.02, - 0.08, - ( - self._t( - "dbf_info", - true=true_angle, - peak=peak_angle, - frame=frame_label, - ) - ), - transform=ax.transAxes, - ha="left", - va="bottom", - fontsize=9, - color=THEME["text_primary"], - bbox={ - "boxstyle": "round,pad=0.25", - "facecolor": THEME["card_bg"], - "edgecolor": THEME["card_border"], - "alpha": 0.93, - "linewidth": 0.7, - }, - ) - _style_legend(ax.legend(loc="lower right", fontsize=9, framealpha=0.92)) - - chart.hover_db = spectrum_db - chart.hover_angles = scan_angles - chart.hover_annotation = _new_response_hover_annotation(ax) - chart.hover_marker = ax.scatter( - [], - [], - marker="o", - s=44, - facecolors=THEME["hover_fill"], - edgecolors=THEME["focus"], - linewidths=1.0, - zorder=8, - ) - chart.hover_marker.set_visible(False) - chart.canvas.draw_idle() - - def toggle_dbf2d_animation(self, axis: str) -> None: - if axis == "azimuth": - self.dbf2d_az_playing = not self.dbf2d_az_playing - elif axis == "elevation": - self.dbf2d_el_playing = not self.dbf2d_el_playing - else: - raise ValueError(f"Unknown 2D DBF axis: {axis!r}") - self._update_dbf2d_controls() - if self.dbf2d_az_playing or self.dbf2d_el_playing: - self._schedule_dbf2d_frame() - axes = [] - if self.dbf2d_az_playing: - axes.append(_dbf_mode_label("azimuth", self.language)) - if self.dbf2d_el_playing: - axes.append(_dbf_mode_label("elevation", self.language)) - self.status.set(self._t("dbf2d_running", axes=" + ".join(axes))) - else: - self._cancel_dbf2d_timer() - - def stop_dbf2d_animation(self, update_status: bool = True) -> None: - self._cancel_dbf2d_timer() - self.dbf2d_az_playing = False - self.dbf2d_el_playing = False - self._update_dbf2d_controls() - if update_status: - self.status.set(self._t("dbf2d_stopped")) - - def _cancel_dbf2d_timer(self) -> None: - if self.dbf2d_after_id is not None: - try: - self.root.after_cancel(self.dbf2d_after_id) - except tk.TclError: - pass - self.dbf2d_after_id = None - - def _schedule_dbf2d_frame(self) -> None: - if self.dbf2d_after_id is None and ( - self.dbf2d_az_playing or self.dbf2d_el_playing - ): - self.dbf2d_after_id = self.root.after( - DBF_SCAN_INTERVAL_MS, - self._advance_dbf2d_animation, - ) - - def _advance_dbf2d_animation(self) -> None: - self.dbf2d_after_id = None - if self.dbf2d_az_playing: - self.dbf2d_az_frame = (self.dbf2d_az_frame + 1) % DBF_SCAN_GRID_SIZE - if self.dbf2d_el_playing: - self.dbf2d_el_frame = (self.dbf2d_el_frame + 1) % DBF_SCAN_GRID_SIZE - if self.dbf2d_az_playing or self.dbf2d_el_playing: - self._draw_dbf2d_heatmap() - self._schedule_dbf2d_frame() - else: - self._update_dbf2d_controls() - - def on_dbf2d_progress_changed(self, axis: str, raw_value: str) -> None: - if self.dbf2d_progress_updating: - return - try: - frame = int(round(float(raw_value))) - except (TypeError, ValueError): - return - frame = max(0, min(DBF_SCAN_GRID_SIZE - 1, frame)) - if axis == "azimuth": - self.dbf2d_az_frame = frame - self.dbf2d_az_playing = False - elif axis == "elevation": - self.dbf2d_el_frame = frame - self.dbf2d_el_playing = False - else: - return - if not self.dbf2d_az_playing and not self.dbf2d_el_playing: - self._cancel_dbf2d_timer() - self._draw_dbf2d_heatmap() - self._update_dbf2d_controls() - self.status.set( - self._t("dbf2d_paused_axis", axis=_dbf_mode_label(axis, self.language)) - ) - - def _event_dbf2d_angles(self, event) -> tuple[float, float] | None: # noqa: ANN001 - if self.dbf2d_ax is None: - return None - if event.xdata is not None and event.ydata is not None: - return float(event.xdata), float(event.ydata) - if event.x is None or event.y is None: - return None - try: - azimuth, elevation = self.dbf2d_ax.transData.inverted().transform( - (event.x, event.y) - ) - except (TypeError, ValueError): - return None - return float(azimuth), float(elevation) - - def _set_dbf2d_cursor(self, cursor: str) -> None: - if self.dbf2d_canvas is None: - return - try: - self.dbf2d_canvas.get_tk_widget().configure(cursor=cursor) - except (tk.TclError, AttributeError): - return - - def _dbf2d_event_near_crosshair(self, event) -> bool: # noqa: ANN001 - if event.inaxes != self.dbf2d_ax or event.xdata is None or event.ydata is None: - return False - azimuth, elevation = self._current_dbf2d_angles() - x_low, x_high = self.dbf2d_ax.get_xlim() - y_low, y_high = self.dbf2d_ax.get_ylim() - x_tolerance = max(2.0, abs(x_high - x_low) * 0.015) - y_tolerance = max(2.0, abs(y_high - y_low) * 0.015) - return ( - abs(float(event.xdata) - azimuth) <= x_tolerance - or abs(float(event.ydata) - elevation) <= y_tolerance - ) - - def _update_dbf2d_cursor(self, event) -> None: # noqa: ANN001 - self._set_dbf2d_cursor( - "hand2" if self._dbf2d_event_near_crosshair(event) else "" - ) - - def _set_dbf2d_angles(self, azimuth: float, elevation: float) -> None: - self.dbf2d_az_frame = _dbf_frame_index_for_angle(azimuth) - self.dbf2d_el_frame = _dbf_frame_index_for_angle(elevation) - self.dbf2d_az_playing = False - self.dbf2d_el_playing = False - self._cancel_dbf2d_timer() - self._draw_dbf2d_heatmap() - self._update_dbf2d_controls() - current_azimuth, current_elevation = self._current_dbf2d_angles() - self.status.set( - self._t( - "dbf2d_dragged", - az=current_azimuth, - el=current_elevation, - ) - ) - - def on_dbf2d_crosshair_press(self, event) -> None: # noqa: ANN001 - if event.button != 1 or event.inaxes != self.dbf2d_ax: - return - if not self._dbf2d_event_near_crosshair(event): - return - angles = self._event_dbf2d_angles(event) - if angles is None: - return - self.dbf2d_dragging = True - if self.dbf2d_canvas is not None: - self.dbf2d_canvas.grab_pointer(self.dbf2d_ax) - self._set_dbf2d_cursor("hand2") - self._hide_dbf2d_hover() - self._set_dbf2d_angles(*angles) - - def on_dbf2d_crosshair_motion(self, event) -> None: # noqa: ANN001 - if not self.dbf2d_dragging: - self._update_dbf2d_cursor(event) - self._update_dbf2d_hover(event) - return - angles = self._event_dbf2d_angles(event) - if angles is None: - return - self._set_dbf2d_cursor("hand2") - self._set_dbf2d_angles(*angles) - - def on_dbf2d_crosshair_release(self, event) -> None: # noqa: ANN001 - if not self.dbf2d_dragging: - return - angles = self._event_dbf2d_angles(event) - if angles is not None: - self._set_dbf2d_angles(*angles) - self.dbf2d_dragging = False - if self.dbf2d_canvas is not None: - self.dbf2d_canvas.release_pointer() - self._update_dbf2d_cursor(event) - - def on_dbf2d_pointer_cancel(self, _event=None) -> None: # noqa: ANN001 - if not self.dbf2d_dragging: - return - self.dbf2d_dragging = False - self._set_dbf2d_cursor("") - - def on_dbf2d_figure_leave(self, _event) -> None: # noqa: ANN001 - if not self.dbf2d_dragging: - self._set_dbf2d_cursor("") - self._hide_dbf2d_hover() - - def _current_dbf2d_angles(self) -> tuple[float, float]: - azimuth = DBF_SCAN_FOV[0] + self.dbf2d_az_frame * DBF_SCAN_STEP_DEG - elevation = DBF_SCAN_FOV[0] + self.dbf2d_el_frame * DBF_SCAN_STEP_DEG - return float(azimuth), float(elevation) - - def _set_dbf2d_progress(self) -> None: - self.dbf2d_progress_updating = True - try: - if self.dbf2d_az_var is not None: - self.dbf2d_az_var.set(float(self.dbf2d_az_frame)) - if self.dbf2d_el_var is not None: - self.dbf2d_el_var.set(float(self.dbf2d_el_frame)) - finally: - self.dbf2d_progress_updating = False - - if self.dbf2d_status_label is not None: - azimuth, elevation = self._current_dbf2d_angles() - frame_index = self.dbf2d_el_frame * DBF_SCAN_GRID_SIZE + self.dbf2d_az_frame + 1 - total = DBF_SCAN_GRID_SIZE * DBF_SCAN_GRID_SIZE - self.dbf2d_status_label.configure( - text=self._t( - "dbf2d_status", - az=azimuth, - el=elevation, - frame=frame_index, - total=total, - ) - ) - - def _update_dbf2d_controls(self) -> None: - if self.dbf2d_az_button is not None: - self.dbf2d_az_button.configure( - text=self._t("dbf2d_pause_az") - if self.dbf2d_az_playing - else self._t("dbf2d_play_az"), - style=( - "CompactPlayActive.TButton" - if self.dbf2d_az_playing - else "CompactPlay.TButton" - ), - ) - self.dbf2d_az_button._qt.setChecked(self.dbf2d_az_playing) - self.dbf2d_az_button._qt.setIcon( - self.root._window.style().standardIcon( - QtWidgets.QStyle.StandardPixmap.SP_MediaPause - if self.dbf2d_az_playing - else QtWidgets.QStyle.StandardPixmap.SP_MediaPlay - ) - ) - if self.dbf2d_el_button is not None: - self.dbf2d_el_button.configure( - text=self._t("dbf2d_pause_el") - if self.dbf2d_el_playing - else self._t("dbf2d_play_el"), - style=( - "CompactPlayActive.TButton" - if self.dbf2d_el_playing - else "CompactPlay.TButton" - ), - ) - self.dbf2d_el_button._qt.setChecked(self.dbf2d_el_playing) - self.dbf2d_el_button._qt.setIcon( - self.root._window.style().standardIcon( - QtWidgets.QStyle.StandardPixmap.SP_MediaPause - if self.dbf2d_el_playing - else QtWidgets.QStyle.StandardPixmap.SP_MediaPlay - ) - ) - if self.dbf2d_stop_button is not None: - state = tk.NORMAL if self.dbf2d_az_playing or self.dbf2d_el_playing else tk.DISABLED - self.dbf2d_stop_button.configure(text=self._t("dbf2d_stop"), state=state) - self._set_dbf2d_progress() - - def _draw_dbf2d_heatmap(self) -> None: - if self.dbf2d_ax is None or self.dbf2d_canvas is None: - return - metrics = self.current_metrics - if metrics is not None and ( - metrics.azimuth_resolution is None - or metrics.elevation_resolution is None - ): - self.dbf2d_hover_azimuths = np.empty(0, dtype=float) - self.dbf2d_hover_elevations = np.empty(0, dtype=float) - self.dbf2d_hover_db = np.empty((0, 0), dtype=float) - self.dbf2d_ax.clear() - if self.dbf2d_cbar_ax is not None: - self.dbf2d_cbar_ax.clear() - self.dbf2d_canvas.draw_idle() - return - azimuth, elevation = self._current_dbf2d_angles() - scan_azimuths, scan_elevations, spectrum_db = dbf_2d_spectrum( - self.current_array(), - true_azimuth_deg=azimuth, - true_elevation_deg=elevation, - tx_pattern=self.element_pattern, - rx_pattern=self.element_pattern, - channel_patterns=self.channel_patterns, - dbf_dictionary=self.dbf_dictionary, - ) - self.dbf2d_hover_azimuths = scan_azimuths - self.dbf2d_hover_elevations = scan_elevations - self.dbf2d_hover_db = spectrum_db - peak_el_index, peak_az_index = np.unravel_index( - int(np.argmax(spectrum_db)), spectrum_db.shape - ) - peak_az = float(scan_azimuths[peak_az_index]) - peak_el = float(scan_elevations[peak_el_index]) - peak_az_error = peak_az - azimuth - peak_el_error = peak_el - elevation - - ax = self.dbf2d_ax - ax.clear() - _configure_axis_chrome(ax) - display_mode = self._current_dbf_display_mode() - display_spectrum = self._dbf_display_values(spectrum_db) - color_min, color_max = ( - (0.0, 1.0) - if display_mode == DBF_DISPLAY_MAGNITUDE - else (-40.0, 0.0) - ) - image = ax.imshow( - display_spectrum, - origin="lower", - extent=( - float(scan_azimuths[0]), - float(scan_azimuths[-1]), - float(scan_elevations[0]), - float(scan_elevations[-1]), - ), - aspect="auto", - cmap="magma", - vmin=color_min, - vmax=color_max, - interpolation="nearest", - ) - if self.dbf2d_cbar_ax is not None and self.dbf2d_fig is not None: - self.dbf2d_cbar_ax.clear() - colorbar = self.dbf2d_fig.colorbar(image, cax=self.dbf2d_cbar_ax) - if display_mode == DBF_DISPLAY_MAGNITUDE: - colorbar.set_ticks(np.linspace(0.0, 1.0, 6)) - colorbar.set_label( - self._dbf_display_colorbar_label(), - color=THEME["text_secondary"], - fontsize=9, - ) - colorbar.ax.tick_params( - labelsize=9, - colors=THEME["text_secondary"], - length=2.5, - width=0.6, - ) - colorbar.outline.set_edgecolor(THEME["axis_spine"]) - colorbar.outline.set_linewidth(0.6) - self.dbf2d_cbar_ax.set_facecolor(THEME["card_bg"]) - ax.set_aspect("auto") - ax.set_xlim(DBF_SCAN_FOV) - ax.set_ylim(DBF_SCAN_FOV) - _apply_dbf_angle_ticks(ax) - ax.axvline(azimuth, color="#ffffff", linewidth=1.0, alpha=0.82) - ax.axhline(elevation, color="#ffffff", linewidth=1.0, alpha=0.82) - ax.scatter( - [peak_az], - [peak_el], - marker="x", - s=48, - color=THEME["secondary_light"], - linewidths=1.5, - zorder=5, - ) - ax.set_title( - self._t("dbf2d_plot_title"), - loc="left", - pad=5, - color=THEME["text_primary"], - fontweight="bold", - ) - ax.set_xlabel("") - ax.set_ylabel("") - ax.text( - 0.99, - 0.02, - f"{self._t('az_short')}(°)", - transform=ax.transAxes, - ha="right", - va="bottom", - fontsize=9, - color=THEME["text_secondary"], - bbox={ - "boxstyle": "round,pad=0.18", - "facecolor": THEME["plot_bg"], - "edgecolor": THEME["axis_spine"], - "alpha": 0.78, - "linewidth": 0.4, - }, - ) - ax.text( - 0.02, - 0.52, - f"{self._t('el_short')}(°)", - transform=ax.transAxes, - ha="left", - va="center", - rotation=90, - fontsize=9, - color=THEME["text_secondary"], - bbox={ - "boxstyle": "round,pad=0.18", - "facecolor": THEME["plot_bg"], - "edgecolor": THEME["axis_spine"], - "alpha": 0.78, - "linewidth": 0.4, - }, - ) - ax.text( - 0.02, - 0.96, - self._t( - "dbf2d_heatmap_info", - az=azimuth, - el=elevation, - peak_az=peak_az, - peak_el=peak_el, - ), - transform=ax.transAxes, - ha="left", - va="top", - fontsize=9, - color=THEME["text_primary"], - bbox={ - "boxstyle": "round,pad=0.25", - "facecolor": THEME["panel_alt_bg"], - "edgecolor": THEME["card_border"], - "alpha": 0.96, - "linewidth": 0.8, - }, - ) - ax.text( - 0.98, - 0.96, - self._t( - "dbf2d_peak_delta", - az=peak_az_error, - el=peak_el_error, - ), - transform=ax.transAxes, - ha="right", - va="top", - fontsize=9, - color=THEME["accent_pressed"], - bbox={ - "boxstyle": "round,pad=0.25", - "facecolor": THEME["accent_light"], - "edgecolor": THEME["focus_soft"], - "alpha": 0.96, - "linewidth": 0.8, - }, - ) - self.dbf2d_hover_annotation = _new_response_hover_annotation(ax) - self.dbf2d_hover_marker = ax.scatter( - [], - [], - marker="o", - s=46, - facecolors=THEME["hover_fill"], - edgecolors=THEME["focus"], - linewidths=1.0, - zorder=8, - ) - self.dbf2d_hover_marker.set_visible(False) - self._set_dbf2d_progress() - self.dbf2d_canvas.draw_idle() - - def open_dbf_dictionary_dialog(self) -> None: - dialog = tk.Toplevel(self.root) - _style_toplevel(dialog) - dialog._qt.setObjectName("dbfDictionaryDialog") - mark_workbench_role(dialog._qt, "dialog-shell") - dialog.title(self._t("dbf_dictionary_title")) - dialog.transient(self.root) - fit_dialog_to_parent( - dialog._qt, - self.root._window, - preferred_size=(1240, 720), - minimum_size=(820, 540), - ) - - root_frame = ttk.Frame(dialog, style="Dialog.TFrame", padding=16) - root_frame.pack(fill=tk.BOTH, expand=True) - mode_column_width = 320 if self.language == LANGUAGE_EN else 304 - root_frame.grid_columnconfigure(0, weight=0, minsize=mode_column_width) - root_frame.grid_columnconfigure(1, weight=1) - root_frame.grid_rowconfigure(0, weight=1) - - initial_mode = self.dbf_dictionary.mode - if initial_mode == DBF_DICT_CHANNEL_PATTERN_ZERO_REF: - initial_mode = DBF_DICT_CHANNEL_PATTERN - mode_var = tk.StringVar(value=initial_mode) - axis_var = tk.StringVar(value="azimuth") - dictionary_target_var = tk.StringVar(value=CHANNEL_PATTERN_TARGET_VIRTUAL) - phase_reverse_var = tk.BooleanVar(value=self.dbf_dictionary.custom_phase_reversed) - zero_calibrate_var = tk.BooleanVar( - value=self.dbf_dictionary.custom_zero_phase_calibrated - ) - custom_holder: dict[str, DbfDictionaryTable | None] = { - "azimuth": self.dbf_dictionary.custom_azimuth_table, - "elevation": self.dbf_dictionary.custom_elevation_table, - } - az_file_var = tk.StringVar() - el_file_var = tk.StringVar() - - mode_frame = ttk.Frame( - root_frame, - style="Panel.TFrame", - padding=(8, 8), - ) - mode_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 16)) - mode_frame._qt.setObjectName("dbfModePanel") - mode_frame.configure(style="Panel.TFrame") - mark_workbench_role(mode_frame._qt, "dialog-rail") - for column in range(2): - mode_frame.grid_columnconfigure( - column, weight=1, uniform="dbf_dictionary_buttons" - ) - ttk.Label( - mode_frame, - text=self._t("dbf_dict_source_title"), - style="DialogSectionTitle.TLabel", - ).grid(row=0, column=0, columnspan=2, sticky="w", pady=(0, 10)) - mode_row = 1 - for mode in ( - DBF_DICT_IDEAL, - DBF_DICT_IDEAL_REVERSED, - DBF_DICT_CHANNEL_PATTERN, - DBF_DICT_CUSTOM, - ): - mode_button = ttk.Radiobutton( - mode_frame, - text=_dbf_dictionary_mode_label(mode, self.language), - variable=mode_var, - value=mode, - command=lambda: sync_dialog_state(), - ) - mode_button.grid( - row=mode_row, - column=0, - columnspan=2, - sticky="w", - pady=(0, 7), - ) - mode_button._qt.setObjectName(f"dbfMode_{mode}") - mode_row += 1 - - custom_import_scroll = QtWidgets.QScrollArea(mode_frame._qt) - custom_import_scroll.setObjectName("dbfCustomImportScroll") - custom_import_scroll.setWidgetResizable(True) - custom_import_scroll.setFrameShape(QtWidgets.QFrame.Shape.NoFrame) - custom_import_scroll.setHorizontalScrollBarPolicy( - QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff - ) - custom_import_scroll.setVerticalScrollBarPolicy( - QtCore.Qt.ScrollBarPolicy.ScrollBarAsNeeded - ) - custom_import_scroll.viewport().setAutoFillBackground(True) - scroll_palette = custom_import_scroll.viewport().palette() - scroll_palette.setColor( - QtGui.QPalette.ColorRole.Window, - QtGui.QColor(THEME["panel_bg"]), - ) - custom_import_scroll.viewport().setPalette(scroll_palette) - mode_frame._ensure_grid_layout().addWidget( - custom_import_scroll, - mode_row, - 0, - 1, - 2, - ) - mode_frame.grid_rowconfigure(mode_row, weight=1) - - custom_import_frame = ttk.Frame(mode_frame, style="Panel.TFrame") - custom_import_frame._qt.setObjectName("dbfCustomImportPanel") - custom_import_frame.configure(style="Panel.TFrame") - mark_workbench_role(custom_import_frame._qt, "dialog-rail") - custom_import_scroll.setWidget(custom_import_frame._qt) - custom_import_frame.grid_columnconfigure(0, weight=1) - custom_import_frame.grid_columnconfigure(1, weight=1) - custom_row = 0 - - ttk.Label( - custom_import_frame, - text=self._t("dbf_dict_import_title"), - style="DialogSectionTitle.TLabel", - ).grid(row=custom_row, column=0, columnspan=2, sticky="w", pady=(0, 8)) - custom_row += 1 - ttk.Label( - custom_import_frame, - text=self._t("summary_target_label"), - style="Muted.TLabel", - ).grid(row=custom_row, column=0, columnspan=2, sticky="w") - custom_row += 1 - ttk.Radiobutton( - custom_import_frame, - text=self._t("summary_target_physical"), - variable=dictionary_target_var, - value=CHANNEL_PATTERN_TARGET_PHYSICAL, - ).grid(row=custom_row, column=0, sticky="w", pady=(4, 0)) - ttk.Radiobutton( - custom_import_frame, - text=self._t("summary_target_virtual"), - variable=dictionary_target_var, - value=CHANNEL_PATTERN_TARGET_VIRTUAL, - ).grid(row=custom_row, column=1, sticky="w", pady=(4, 0)) - custom_row += 1 - - ttk.Separator(custom_import_frame).grid( - row=custom_row, column=0, columnspan=2, sticky="ew", pady=8 - ) - custom_row += 1 - az_file_label = ttk.Label( - custom_import_frame, - textvariable=az_file_var, - style="Muted.TLabel", - ) - az_file_label.grid( - row=custom_row, column=0, columnspan=2, sticky="ew", pady=(0, 3) - ) - custom_row += 1 - az_load_button = ttk.Button( - custom_import_frame, - text=self._t("dbf_dict_load_az"), - command=lambda: load_custom_dictionary("azimuth"), - style="DialogButton.TButton", - ) - az_load_button._qt.setObjectName("dbfLoadAzButton") - az_load_button.grid(row=custom_row, column=0, sticky="ew", pady=(0, 4)) - az_clear_button = ttk.Button( - custom_import_frame, - text=self._t("dbf_dict_clear_az"), - command=lambda: clear_custom_dictionary("azimuth"), - style="DialogButton.TButton", - ) - az_clear_button._qt.setObjectName("dbfClearAzButton") - az_clear_button.grid( - row=custom_row, column=1, sticky="ew", padx=(6, 0), pady=(0, 4) - ) - custom_row += 1 - el_file_label = ttk.Label( - custom_import_frame, - textvariable=el_file_var, - style="Muted.TLabel", - ) - el_file_label.grid( - row=custom_row, column=0, columnspan=2, sticky="ew", pady=(3, 3) - ) - custom_row += 1 - el_load_button = ttk.Button( - custom_import_frame, - text=self._t("dbf_dict_load_el"), - command=lambda: load_custom_dictionary("elevation"), - style="DialogButton.TButton", - ) - el_load_button._qt.setObjectName("dbfLoadElButton") - el_load_button.grid(row=custom_row, column=0, sticky="ew") - el_clear_button = ttk.Button( - custom_import_frame, - text=self._t("dbf_dict_clear_el"), - command=lambda: clear_custom_dictionary("elevation"), - style="DialogButton.TButton", - ) - el_clear_button._qt.setObjectName("dbfClearElButton") - el_clear_button.grid(row=custom_row, column=1, sticky="ew", padx=(6, 0)) - custom_row += 1 - - calibration_separator = ttk.Separator(custom_import_frame) - calibration_separator._qt.setObjectName("dbfCalibrationSeparator") - calibration_separator.grid( - row=custom_row, column=0, columnspan=2, sticky="ew", pady=8 - ) - custom_row += 1 - ttk.Label( - custom_import_frame, - text=self._t("dbf_dict_calibration_title"), - style="DialogSectionTitle.TLabel", - ).grid(row=custom_row, column=0, columnspan=2, sticky="w") - custom_row += 1 - phase_reverse_toggle = ttk.Checkbutton( - custom_import_frame, - text=self._t("dbf_dict_phase_reverse"), - variable=phase_reverse_var, - command=lambda: redraw_preview(), - ) - phase_reverse_toggle._qt.setObjectName("dbfPhaseReverseToggle") - phase_reverse_toggle.grid( - row=custom_row, column=0, columnspan=2, sticky="w", pady=(4, 0) - ) - custom_row += 1 - zero_calibrate_toggle = ttk.Checkbutton( - custom_import_frame, - text=self._t("dbf_dict_zero_calibrate"), - variable=zero_calibrate_var, - command=lambda: redraw_preview(), - ) - zero_calibrate_toggle._qt.setObjectName("dbfZeroCalibrateToggle") - zero_calibrate_toggle.grid( - row=custom_row, column=0, columnspan=2, sticky="w", pady=(2, 0) - ) - - preview_frame = ttk.Frame( - root_frame, - style="Card.TFrame", - ) - preview_frame._qt.setObjectName("dbfPreviewPanel") - preview_frame.configure(style="Card.TFrame") - mark_workbench_role(preview_frame._qt, "dialog-content") - preview_frame.grid(row=0, column=1, sticky="nsew") - preview_frame.grid_rowconfigure(2, weight=1) - preview_frame.grid_columnconfigure(0, weight=1) - - preview_header = ttk.Frame( - preview_frame, style="Card.TFrame", padding=(12, 8, 12, 6) - ) - preview_header._qt.setObjectName("dbfPreviewHeader") - preview_header.configure(style="Card.TFrame") - mark_workbench_role(preview_header._qt, "dialog-header") - preview_header.grid(row=0, column=0, sticky="ew") - preview_header.grid_columnconfigure(1, weight=1) - ttk.Label( - preview_header, - text=self._t("dbf_dictionary_preview_title").strip(), - style="DialogSectionTitle.TLabel", - ).grid(row=0, column=0, sticky="w") - - preview_status = ttk.Label( - preview_header, - text="", - style="DialogSummary.TLabel", - anchor="e", - ) - preview_status.grid(row=0, column=1, sticky="ew", padx=(12, 0)) - preview_status._qt.setMinimumWidth(0) - preview_status._qt.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Ignored, - QtWidgets.QSizePolicy.Policy.Preferred, - ) - - preview_toolbar = ttk.Frame( - preview_frame, style="PreviewToolbar.TFrame", padding=(12, 4, 12, 8) - ) - preview_toolbar.grid(row=1, column=0, sticky="ew") - preview_toolbar._qt.setObjectName("dbfPreviewToolbar") - - az_axis_button = ttk.Button( - preview_toolbar, - text=self._t("az_short"), - command=lambda: select_preview_axis("azimuth"), - style="DialogButton.TButton", - width=8, - ) - az_axis_button.pack(side=tk.LEFT) - az_axis_button._qt.setObjectName("dbfPreviewAzButton") - az_axis_button._qt.setCheckable(True) - az_axis_button._qt.setFixedWidth(92) - el_axis_button = ttk.Button( - preview_toolbar, - text=self._t("el_short"), - command=lambda: select_preview_axis("elevation"), - style="DialogButton.TButton", - width=8, - ) - el_axis_button.pack(side=tk.LEFT, padx=(0, 12)) - el_axis_button._qt.setObjectName("dbfPreviewElButton") - el_axis_button._qt.setCheckable(True) - el_axis_button._qt.setFixedWidth(92) - axis_button_group = QtWidgets.QButtonGroup(dialog._qt) - axis_button_group.setExclusive(True) - axis_button_group.addButton(az_axis_button._qt) - axis_button_group.addButton(el_axis_button._qt) - - angle_locator_var = tk.StringVar() - angle_locator = ttk.Entry( - preview_toolbar, - textvariable=angle_locator_var, - width=16, - justify="right", - ) - angle_locator.pack(side=tk.LEFT) - angle_locator._qt.setPlaceholderText(self._t("dbf_dict_locate_angle")) - angle_locator._qt.setAccessibleName(self._t("dbf_dict_locate_angle")) - angle_locator._qt.setMinimumWidth(180) - angle_locator._qt.setMaximumWidth(260) - angle_locator.bind("", lambda _event=None: locate_preview_angle()) - fit_columns_button = ttk.Button( - preview_toolbar, - text=self._t("dbf_dict_fit_columns"), - command=lambda: fit_preview_columns(), - style="DialogButton.TButton", - ) - fit_columns_button.pack(side=tk.RIGHT) - fit_columns_button._qt.setObjectName("dbfFitColumnsButton") - fit_columns_button._qt.setToolTip(self._t("dbf_dict_fit_columns_tooltip")) - fit_columns_button._qt.setAccessibleName(self._t("dbf_dict_fit_columns")) - fit_columns_button._qt.setAccessibleDescription( - self._t("dbf_dict_fit_columns_tooltip") - ) - fit_columns_button._qt.setFixedWidth(112) - - matrix_area = ttk.Frame(preview_frame, style="Card.TFrame") - matrix_area.grid(row=2, column=0, sticky="nsew") - matrix_area.grid_rowconfigure(0, weight=1) - matrix_area.grid_columnconfigure(0, weight=1) - matrix_tree = ttk.Treeview(matrix_area, show="headings", height=10) - matrix_tree.grid(row=0, column=0, sticky="nsew") - matrix_tree._qt.setObjectName("dbfPreviewTable") - matrix_tree._qt.setSortingEnabled(False) - matrix_tree._qt.setSelectionMode( - QtWidgets.QAbstractItemView.SelectionMode.NoSelection - ) - matrix_y_scroll = ttk.Scrollbar( - matrix_area, orient=tk.VERTICAL, command=matrix_tree.yview - ) - matrix_y_scroll.grid(row=0, column=1, sticky="ns") - matrix_x_scroll = ttk.Scrollbar( - matrix_area, orient=tk.HORIZONTAL, command=matrix_tree.xview - ) - matrix_x_scroll.grid(row=1, column=0, sticky="ew") - matrix_tree.configure( - yscrollcommand=matrix_y_scroll.set, - xscrollcommand=matrix_x_scroll.set, - ) - - def set_preview_status_text(text: str) -> None: - label = preview_status._qt - label.setToolTip(text) - available_width = max( - 240, - dialog._qt.width() - mode_column_width - 110, - ) - label.setText( - label.fontMetrics().elidedText( - text, - QtCore.Qt.TextElideMode.ElideMiddle, - available_width, - ) - ) - - file_state_label = ttk.Label( - preview_frame, - text="", - style="DialogSummary.TLabel", - anchor="w", - ) - file_state_label.grid(row=3, column=0, sticky="ew", padx=12, pady=(6, 0)) - file_state_label._qt.setObjectName("dbfFileState") - - quality_status = ttk.Label( - preview_frame, - text="", - style="Card.TLabel", - wraplength=720, - ) - quality_status.grid(row=4, column=0, sticky="ew", padx=12, pady=(6, 10)) - quality_status._qt.setObjectName("dbfQualityCallout") - quality_status._qt.setWordWrap(True) - quality_status._qt.setMinimumHeight(48) - - button_row = ttk.Frame(root_frame, style="Card.TFrame") - button_row.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(10, 0)) - button_row._qt.setObjectName("dbfDictionaryActionBar") - mark_workbench_role(button_row._qt, "dialog-footer") - button_row.grid_columnconfigure(0, weight=1) - - pending_label = ttk.Label( - button_row, - text="", - style="DialogSummary.TLabel", - anchor="w", - ) - pending_label.grid(row=0, column=0, sticky="ew") - - def select_preview_axis(axis: str) -> None: - axis_var.set(axis) - az_axis_button._qt.setChecked(axis == "azimuth") - el_axis_button._qt.setChecked(axis == "elevation") - redraw_preview() - - def fit_preview_columns() -> None: - table = matrix_tree._qt - header = table.horizontalHeader() - for section in range(table.model().columnCount()): - header.setSectionResizeMode( - section, QtWidgets.QHeaderView.ResizeMode.Interactive - ) - table.resizeColumnsToContents() - if table.model().columnCount() > 0: - table.setColumnWidth(0, max(68, min(86, table.columnWidth(0)))) - for section in range(1, table.model().columnCount()): - table.setColumnWidth(section, max(64, min(96, table.columnWidth(section)))) - - def locate_preview_angle() -> None: - text = angle_locator_var.get().strip().replace("\N{DEGREE SIGN}", "") - if not text: - return - try: - requested = float(text) - except ValueError: - angle_locator._qt.selectAll() - return - row_count = matrix_tree._qt.model().rowCount() - if row_count <= 0: - return - bounded = min(max(requested, DBF_SCAN_FOV[0]), DBF_SCAN_FOV[1]) - span = DBF_SCAN_FOV[1] - DBF_SCAN_FOV[0] - row = round((bounded - DBF_SCAN_FOV[0]) / span * (row_count - 1)) - index = matrix_tree._qt.model().index(row, 0) - matrix_tree._qt.selectRow(row) - matrix_tree._qt.scrollTo( - index, - QtWidgets.QAbstractItemView.ScrollHint.PositionAtCenter, - ) - angle_locator_var.set(f"{bounded:+.0f}\N{DEGREE SIGN}") - - def refresh_file_labels() -> None: - def table_label(table: DbfDictionaryTable | None) -> str: - if table is None: - return self._t("dbf_dict_no_file") - target_key = ( - "summary_target_virtual" - if table.channel_mode == CHANNEL_MODE_VIRTUAL - else "summary_target_physical" - ) - return f"{table.display_name} ({self._t(target_key)})" - - az_file = table_label(custom_holder["azimuth"]) - el_file = table_label(custom_holder["elevation"]) - az_text = self._t( - "dbf_dict_file_status", - axis=_dbf_short_label("azimuth", self.language), - file=az_file, - ) - el_text = self._t( - "dbf_dict_file_status", - axis=_dbf_short_label("elevation", self.language), - file=el_file, - ) - for variable, label, full_text in ( - (az_file_var, az_file_label, az_text), - (el_file_var, el_file_label, el_text), - ): - variable.set(full_text) - label._qt.setToolTip(full_text) - label._qt.setText( - label._qt.fontMetrics().elidedText( - full_text, - QtCore.Qt.TextElideMode.ElideMiddle, - 285, - ) - ) - az_clear_button._qt.setEnabled(custom_holder["azimuth"] is not None) - el_clear_button._qt.setEnabled(custom_holder["elevation"] is not None) - - if mode_var.get() == DBF_DICT_CUSTOM: - file_state_text = self._t( - "dbf_dict_custom_file_state", - az=az_file, - el=el_file, - ) - else: - file_state_text = self._t( - "dbf_dict_builtin_file_state", - rows=DBF_SCAN_GRID_SIZE, - cols=max(1, len(self.current_array().virtual_points())), - ) - file_state_label.configure(text=file_state_text) - file_state_label._qt.setToolTip(file_state_text) - file_state_label._qt.setContentsMargins(12, 0, 12, 0) - - def current_config(require_complete: bool = False) -> DbfDictionaryConfig: - mode = mode_var.get() - if mode == DBF_DICT_CUSTOM: - if require_complete and ( - custom_holder["azimuth"] is None - and custom_holder["elevation"] is None - ): - raise ValueError(self._t("dbf_dict_need_axis_files")) - return DbfDictionaryConfig( - mode=mode, - custom_azimuth_table=custom_holder["azimuth"], - custom_elevation_table=custom_holder["elevation"], - custom_phase_reversed=phase_reverse_var.get(), - custom_zero_phase_calibrated=zero_calibrate_var.get(), - ) - - def show_matrix_message(message: str) -> None: - matrix_tree.configure(columns=("message",), displaycolumns=("message",)) - matrix_tree.heading("message", text=self._t("dbf_dictionary_preview_title").strip()) - matrix_tree.column("message", width=520, anchor="center", stretch=True) - matrix_tree.set_rows([(message,)]) - set_preview_status_text(message) - quality_status.configure( - text=self._t("dbf_dict_quality_unavailable"), - foreground=THEME["text_secondary"], - ) - mark_callout(quality_status._qt, "neutral") - - def update_quality_status(report: DbfDictionaryQualityReport) -> None: - capability_limited = ( - report.channel_count <= 1 - or mode_var.get() - in { - DBF_DICT_IDEAL, - DBF_DICT_IDEAL_REVERSED, - DBF_DICT_CHANNEL_PATTERN, - } - ) - if ( - report.severity == DBF_DICTIONARY_QUALITY_DANGER - and not capability_limited - ): - text_key = "dbf_dict_quality_danger" - color = THEME["danger"] - callout_role = "danger" - elif report.severity in { - DBF_DICTIONARY_QUALITY_WARNING, - DBF_DICTIONARY_QUALITY_DANGER, - }: - text_key = "dbf_dict_quality_warning" - color = THEME["warning"] - callout_role = "warning" - else: - text_key = "dbf_dict_quality_ok" - color = THEME["success"] - callout_role = "success" - quality_status.configure( - text=self._t( - text_key, - rows=report.row_count, - cols=report.channel_count, - rank=report.non_neighbor_effective_rank, - rank_rows=report.non_neighbor_rank_rows, - ambiguous_rows=report.competitor_ambiguous_rows, - zeros=report.zero_norm_rows, - ), - foreground=color, - ) - mark_callout(quality_status._qt, callout_role) - - def redraw_preview() -> None: - try: - config = current_config() - angles = np.linspace(DBF_SCAN_FOV[0], DBF_SCAN_FOV[1], DBF_SCAN_GRID_SIZE) - matrix = config.scan_matrix( - self.current_array(), - angles, - axis=axis_var.get(), - channel_patterns=self.channel_patterns, - ) - update_quality_status(dictionary_quality_report(matrix, angles)) - phase = dictionary_phase_preview(matrix) - columns = ("angle",) + tuple( - f"CH{index + 1}" for index in range(phase.shape[1]) - ) - matrix_tree.configure(columns=columns, displaycolumns=columns) - matrix_tree.heading("angle", text="Angle") - matrix_tree.column("angle", width=74, anchor="e", stretch=False) - for column in columns[1:]: - matrix_tree.heading(column, text=column) - matrix_tree.column(column, width=72, anchor="e", stretch=False) - header = matrix_tree._qt.horizontalHeader() - header.setSectionResizeMode( - 0, QtWidgets.QHeaderView.ResizeMode.ResizeToContents - ) - for section in range(1, len(columns)): - header.setSectionResizeMode( - section, - ( - QtWidgets.QHeaderView.ResizeMode.Stretch - if len(columns) <= 5 - else QtWidgets.QHeaderView.ResizeMode.Interactive - ), - ) - matrix_tree.set_rows( - [ - ( - f"{angle:+.0f}", - *[f"{value:+.1f}" for value in row_values], - ) - for angle, row_values in zip(angles, phase) - ] - ) - axis_label = _dbf_short_label(axis_var.get(), self.language) - set_preview_status_text( - f"{axis_label} \N{MIDDLE DOT} " - f"{_dbf_dictionary_mode_label(config.mode, self.language)} " - f"\N{MIDDLE DOT} {matrix.shape[0]} " - f"\N{MULTIPLICATION SIGN} {matrix.shape[1]}" - ) - if config.mode != DBF_DICT_CUSTOM: - file_state_text = self._t( - "dbf_dict_builtin_file_state", - rows=matrix.shape[0], - cols=matrix.shape[1], - ) - file_state_label.configure(text=file_state_text) - file_state_label._qt.setToolTip(file_state_text) - except Exception as exc: - show_matrix_message(str(exc)) - - def load_custom_dictionary(axis: str) -> None: - filename = filedialog.askopenfilename( - title=( - self._t("dbf_dict_load_el") - if axis == "elevation" - else self._t("dbf_dict_load_az") - ), - initialdir=str(self.last_pattern_dir), - filetypes=[ - ("DBF Dictionary", "*.csv *.tsv *.xlsx *.xlsm"), - (self._t("csv_type"), "*.csv"), - ("Excel", "*.xlsx *.xlsm"), - (self._t("all_files_type"), "*.*"), - ], - ) - if not filename: - return - try: - table = load_dbf_dictionary_table( - filename, - self.current_array(), - channel_mode=( - CHANNEL_MODE_PHYSICAL - if dictionary_target_var.get() - == CHANNEL_PATTERN_TARGET_PHYSICAL - else CHANNEL_MODE_VIRTUAL - ), - ) - except Exception as exc: - LOGGER.exception("Failed to load DBF dictionary from %s", filename) - messagebox.showerror(self._t("dbf_dict_custom_failed"), str(exc)) - return - self.last_pattern_dir = Path(filename).parent - custom_holder[axis] = table - mode_var.set(DBF_DICT_CUSTOM) - axis_var.set(axis) - self.status.set( - self._t( - "dbf_dict_custom_loaded", - axis=_dbf_short_label(axis, self.language), - file=Path(filename).name, - ) - ) - sync_dialog_state() - - def clear_custom_dictionary(axis: str) -> None: - custom_holder[axis] = None - sync_dialog_state() - - def apply_dictionary() -> None: - try: - config = current_config(require_complete=True) - except Exception as exc: - messagebox.showinfo(self._t("dbf_dictionary_title"), str(exc)) - return - self.dbf_dictionary = config - self.generate_virtual_array() - self.status.set( - self._t( - "dbf_dict_applied", - mode=_dbf_dictionary_mode_label(config.mode, self.language), - ) - ) - dialog.destroy() - - button_box = QtWidgets.QDialogButtonBox( - QtWidgets.QDialogButtonBox.StandardButton.Apply - | QtWidgets.QDialogButtonBox.StandardButton.Cancel, - parent=button_row._qt, - ) - button_row._qt.layout().addWidget( - button_box, - 0, - 1, - 1, - 2, - QtCore.Qt.AlignmentFlag.AlignRight, - ) - apply_button = button_box.button( - QtWidgets.QDialogButtonBox.StandardButton.Apply - ) - cancel_button = button_box.button( - QtWidgets.QDialogButtonBox.StandardButton.Cancel - ) - apply_button.setText(self._t("dbf_dict_apply")) - cancel_button.setText(self._t("dbf_dict_cancel")) - apply_button.clicked.connect(apply_dictionary) - cancel_button.clicked.connect(dialog.destroy) - mark_primary(apply_button) - apply_button.setIcon(QtGui.QIcon()) - apply_button.setDefault(True) - apply_button.setAutoDefault(True) - apply_button.setAccessibleName(self._t("dbf_dict_apply")) - cancel_button.setAccessibleName(self._t("dbf_dict_cancel")) - - def sync_dialog_state() -> None: - is_custom = mode_var.get() == DBF_DICT_CUSTOM - custom_import_scroll.setVisible(is_custom) - az_axis_button._qt.setChecked(axis_var.get() == "azimuth") - el_axis_button._qt.setChecked(axis_var.get() == "elevation") - apply_button.setEnabled( - not is_custom - or custom_holder["azimuth"] is not None - or custom_holder["elevation"] is not None - ) - pending_label.configure( - text=self._t( - "dbf_dict_pending", - mode=_dbf_dictionary_mode_label(mode_var.get(), self.language), - ) - ) - refresh_file_labels() - redraw_preview() - - custom_layout = custom_import_frame._qt.layout() - if custom_layout is not None: - custom_layout.activate() - custom_import_frame._qt.setMinimumHeight( - custom_import_frame._qt.minimumSizeHint().height() - ) - sync_dialog_state() - dialog_layout = dialog._qt.layout() - if dialog_layout is not None: - dialog_layout.activate() - fit_dialog_to_parent( - dialog._qt, - self.root._window, - preferred_size=(1240, max(720, dialog._qt.sizeHint().height())), - minimum_size=(820, 540), - ) - - def open_channel_patterns_dialog(self) -> None: - dialog = tk.Toplevel(self.root) - _style_toplevel(dialog) - dialog._qt.setObjectName("channelPatternsDialog") - mark_workbench_role(dialog._qt, "dialog-shell") - dialog.title(self._t("channel_dialog_title")) - dialog.transient(self.root) - fit_dialog_to_parent( - dialog._qt, - self.root._window, - preferred_size=(1180, 650), - minimum_size=(820, 520), - ) - compact_channel_actions = dialog._qt.width() < 920 - - root_frame = ttk.Frame(dialog, style="Dialog.TFrame", padding=16) - root_frame.pack(fill=tk.BOTH, expand=True) - rail_width = 320 if self.language == LANGUAGE_EN else 304 - root_frame.grid_columnconfigure(0, weight=0, minsize=rail_width) - root_frame.grid_columnconfigure(1, weight=1) - root_frame.grid_rowconfigure(0, weight=1) - - summary_frame = ttk.LabelFrame( - root_frame, - text=self._t("summary_csv_title"), - padding=(8, 6), - style="DialogRail.TLabelframe", - ) - summary_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 16)) - summary_frame._qt.setObjectName("channelPatternSourcePanel") - summary_frame.configure(style="DialogRail.TLabelframe") - mark_workbench_role(summary_frame._qt, "dialog-rail") - summary_frame._qt.setMaximumWidth(rail_width) - for column in range(2): - summary_frame.grid_columnconfigure(column, weight=1, uniform="summary_buttons") - summary_target_var = tk.StringVar(value=CHANNEL_PATTERN_TARGET_PHYSICAL) - summary_target_label = ttk.Label( - summary_frame, - text=self._t("summary_target_label"), - style="TLabel", - ) - physical_target_button = ttk.Radiobutton( - summary_frame, - text=self._t("summary_target_physical"), - variable=summary_target_var, - value=CHANNEL_PATTERN_TARGET_PHYSICAL, - command=lambda: refresh_tree(), - ) - virtual_target_button = ttk.Radiobutton( - summary_frame, - text=self._t("summary_target_virtual"), - variable=summary_target_var, - value=CHANNEL_PATTERN_TARGET_VIRTUAL, - command=lambda: refresh_tree(), - ) - summary_target_label.grid( - row=0, column=0, columnspan=2, sticky="w", pady=(0, 4) - ) - physical_target_button.grid( - row=1, column=0, sticky="w", padx=(0, 8), pady=(0, 6) - ) - virtual_target_button.grid( - row=1, column=1, sticky="w", pady=(0, 6) - ) - - summary_specs = ( - (_pattern_slot_label(PATTERN_KIND_AMPLITUDE, PATTERN_PLANE_HORIZONTAL, self.language), PATTERN_KIND_AMPLITUDE, PATTERN_PLANE_HORIZONTAL), - (_pattern_slot_label(PATTERN_KIND_AMPLITUDE, PATTERN_PLANE_ELEVATION, self.language), PATTERN_KIND_AMPLITUDE, PATTERN_PLANE_ELEVATION), - (_pattern_slot_label(PATTERN_KIND_PHASE, PATTERN_PLANE_HORIZONTAL, self.language), PATTERN_KIND_PHASE, PATTERN_PLANE_HORIZONTAL), - (_pattern_slot_label(PATTERN_KIND_PHASE, PATTERN_PLANE_ELEVATION, self.language), PATTERN_KIND_PHASE, PATTERN_PLANE_ELEVATION), - ) - for index, (label, kind, plane) in enumerate(summary_specs): - action_row = 2 + index // 2 - action_column = index % 2 - ttk.Button( - summary_frame, - text=self._t("load_summary", label=label), - command=lambda k=kind, p=plane: self._load_summary_channel_pattern( - k, p, summary_target_var.get(), dialog, refresh_tree - ), - style="Compact.TButton", - ).grid( - row=action_row, - column=action_column, - sticky="ew", - padx=(0 if action_column == 0 else 6, 0), - pady=(0, 5), - ) - - clear_all_button = ttk.Button( - summary_frame, - text=self._t("clear_all"), - command=lambda: clear_all_patterns(), - style="CompactDanger.TButton", - ) - clear_all_button.grid( - row=4, column=0, columnspan=2, sticky="ew", pady=(0, 1) - ) - - table_frame = ttk.LabelFrame( - root_frame, - text=self._t("physical_channels_title"), - padding=(8, 6), - style="DialogContent.TLabelframe", - ) - table_frame.grid(row=0, column=1, sticky="nsew") - table_frame._qt.setObjectName("channelPatternTablePanel") - table_frame.configure(style="DialogContent.TLabelframe") - mark_workbench_role(table_frame._qt, "dialog-content") - table_frame.grid_rowconfigure(0, weight=1) - table_frame.grid_columnconfigure(0, weight=1) - - columns = ("channel", "amp_h", "amp_e", "phase_h", "phase_e") - tree = ttk.Treeview(table_frame, columns=columns, show="headings", height=8) - tree._qt.setProperty("pointingHandItems", True) - tree.tag_configure("odd", background=THEME["panel_alt_bg"]) - tree.tag_configure("even", background=THEME["card_bg"]) - headings = { - "channel": self._t("column_channel"), - "amp_h": summary_specs[0][0], - "amp_e": summary_specs[1][0], - "phase_h": summary_specs[2][0], - "phase_e": summary_specs[3][0], - } - widths = { - "channel": 90, - "amp_h": 170, - "amp_e": 170, - "phase_h": 170, - "phase_e": 170, - } - for column in columns: - tree.heading(column, text=headings[column], anchor="center") - tree.column(column, width=widths[column], minwidth=70, anchor="center") - header = tree._qt.horizontalHeader() - header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeMode.ResizeToContents) - for section in range(1, len(columns)): - header.setSectionResizeMode(section, QtWidgets.QHeaderView.ResizeMode.Stretch) - tree.grid(row=0, column=0, sticky="nsew") - - scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=tree.yview) - scrollbar.grid(row=0, column=1, sticky="ns") - tree.configure(yscrollcommand=scrollbar.set) - - button_row = ttk.Frame(root_frame, style="Dialog.TFrame") - button_row.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(10, 0)) - button_row._qt.setObjectName("channelPatternActionBar") - button_row.configure(style="Dialog.TFrame") - mark_workbench_role(button_row._qt, "dialog-footer") - bottom_column_count = 2 if compact_channel_actions else 6 - for column in range(bottom_column_count): - button_row.grid_columnconfigure(column, weight=1, uniform="channel_buttons") - for index, (label, kind, plane) in enumerate(summary_specs): - action_row = index // 2 if compact_channel_actions else 0 - action_column = index % 2 if compact_channel_actions else index - ttk.Button( - button_row, - text=self._t("set_pattern", label=label), - command=lambda k=kind, p=plane: self._load_single_channel_pattern( - tree, k, p, dialog, refresh_tree - ), - style="Compact.TButton", - ).grid( - row=action_row, - column=action_column, - sticky="ew", - padx=(0 if action_column == 0 else 6, 0), - pady=(0, 5) if compact_channel_actions else 0, - ) - clear_channel_button = ttk.Button( - button_row, - text=self._t("clear_channel"), - command=lambda: clear_selected_channel(), - style="CompactDanger.TButton", - ) - if compact_channel_actions: - clear_channel_button.grid(row=2, column=0, sticky="ew") - else: - clear_channel_button.grid(row=0, column=4, sticky="ew", padx=(6, 0)) - close_box = QtWidgets.QDialogButtonBox( - QtWidgets.QDialogButtonBox.StandardButton.Close, - parent=button_row._qt, - ) - close_button = close_box.button( - QtWidgets.QDialogButtonBox.StandardButton.Close - ) - close_button.setText(self._t("done")) - close_button.clicked.connect(dialog.destroy) - mark_primary(close_button) - if compact_channel_actions: - button_row._qt.layout().addWidget(close_box, 2, 1) - else: - button_row._qt.layout().addWidget(close_box, 0, 5) - - def refresh_tree() -> None: - selected = tree.selection() - selected_channel = selected[0] if selected else None - for item in tree.get_children(): - tree.delete(item) - for row_index, channel_name in enumerate( - self._pattern_channel_names(summary_target_var.get()) - ): - pattern = self.channel_patterns.pattern_for(channel_name) - tree.insert( - "", - tk.END, - iid=channel_name, - tags=("odd" if row_index % 2 else "even",), - values=( - channel_name, - _series_table_label(pattern.amplitude_horizontal, self.language), - _series_table_label(pattern.amplitude_elevation, self.language), - _series_table_label(pattern.phase_horizontal, self.language), - _series_table_label(pattern.phase_elevation, self.language), - ), - ) - if selected_channel in tree.get_children(): - tree.selection_set(selected_channel) - tree.focus(selected_channel) - - def clear_selected_channel() -> None: - channel_name = self._selected_pattern_channel(tree) - if channel_name is None: - return - self.channel_patterns.clear_channel(channel_name) - self._after_channel_patterns_changed( - self._t("channel_cleared", channel=channel_name) - ) - refresh_tree() - - def clear_all_patterns() -> None: - if self.channel_patterns.is_empty() and self.element_pattern is None: - self.status.set(self._t("channel_already_ideal")) - return - self.channel_patterns.clear() - self.element_pattern = None - self._after_channel_patterns_changed(self._t("channel_all_cleared")) - refresh_tree() - - refresh_tree() - if tree.get_children(): - first = tree.get_children()[0] - tree.selection_set(first) - tree.focus(first) - fit_dialog_to_parent( - dialog._qt, - self.root._window, - preferred_size=(1180, 650), - minimum_size=(820 if compact_channel_actions else 920, 520), - ) - - def _physical_channel_names(self) -> list[str]: - array = self.current_array() - return [point.name for point in array.tx] + [point.name for point in array.rx] - - def _virtual_channel_names(self) -> list[str]: - array = self.current_array() - return virtual_channel_names( - [point.name for point in array.tx], - [point.name for point in array.rx], - ) - - def _all_pattern_channel_names(self) -> list[str]: - return [*self._physical_channel_names(), *self._virtual_channel_names()] - - def _pattern_channel_names(self, target: str) -> list[str]: - if target == CHANNEL_PATTERN_TARGET_VIRTUAL: - return self._virtual_channel_names() - return self._physical_channel_names() - - def _selected_pattern_channel(self, tree: ttk.Treeview) -> str | None: - selected = tree.selection() - if not selected: - messagebox.showinfo( - self._t("channel_patterns_title"), - self._t("select_channel_first"), - ) - return None - return str(selected[0]) - - def _load_summary_channel_pattern( - self, - kind: str, - plane: str, - target: str, - parent: tk.Toplevel, - refresh_callback: callable, - ) -> None: - filename = self._ask_channel_pattern_file( - title=self._t( - "load_summary_title", - label=_pattern_slot_label(kind, plane, self.language), - ), - parent=parent, - ) - if not filename: - return - channel_names = self._pattern_channel_names(target) - try: - series_by_channel = load_hfss_summary_pattern( - filename, - channel_names, - value_kind=kind, - ) - except Exception as exc: - LOGGER.exception("Load channel pattern summary failed: %s", filename) - messagebox.showerror(self._t("load_summary_failed"), str(exc)) - return - - self.channel_patterns.update_many(series_by_channel, kind, plane) - self._after_channel_patterns_changed( - self._t( - "summary_loaded", - label=_pattern_slot_label(kind, plane, self.language), - file=Path(filename).name, - ) - ) - refresh_callback() - - def _load_single_channel_pattern( - self, - tree: ttk.Treeview, - kind: str, - plane: str, - parent: tk.Toplevel, - refresh_callback: callable, - ) -> None: - channel_name = self._selected_pattern_channel(tree) - if channel_name is None: - return - filename = self._ask_channel_pattern_file( - title=self._t( - "load_channel_title", - label=_pattern_slot_label(kind, plane, self.language), - channel=channel_name, - ), - parent=parent, - ) - if not filename: - return - try: - series = load_hfss_pattern_series(filename, value_kind=kind) - except Exception as exc: - LOGGER.exception("Load channel pattern failed: %s", filename) - messagebox.showerror(self._t("load_channel_failed"), str(exc)) - return - - self.channel_patterns.set_series(channel_name, kind, plane, series) - self._after_channel_patterns_changed( - self._t( - "channel_loaded", - label=_pattern_slot_label(kind, plane, self.language), - channel=channel_name, - file=Path(filename).name, - ) - ) - refresh_callback() - - def _ask_channel_pattern_file( - self, - title: str, - parent: tk.Toplevel, - ) -> str: - filename = filedialog.askopenfilename( - parent=parent, - title=title, - initialdir=str(self.last_pattern_dir), - filetypes=[ - (self._t("hfss_csv_type"), "*.csv *.tsv *.xlsx *.xlsm"), - (self._t("csv_type"), "*.csv"), - (self._t("tsv_type"), "*.tsv"), - ("Excel", "*.xlsx *.xlsm"), - (self._t("all_files_type"), "*.*"), - ], - ) - if filename: - self.last_pattern_dir = Path(filename).parent - return filename - - def _after_channel_patterns_changed(self, message: str) -> None: - self._update_channel_pattern_status() - self.generate_virtual_array() - self.status.set(message) - - def _update_channel_pattern_status(self) -> None: - physical_names = self._physical_channel_names() - virtual_names = self._virtual_channel_names() - amplitude_key = self._channel_pattern_state_key( - physical_names, - virtual_names, - PATTERN_KIND_AMPLITUDE, - ) - phase_key = self._channel_pattern_state_key( - physical_names, - virtual_names, - PATTERN_KIND_PHASE, - ) - self.pattern_status.set( - self._t( - "pattern_amp_phase_status", - amplitude=self._t(amplitude_key), - phase=self._t(phase_key), - ) - ) - if amplitude_key == "pattern_state_ideal" and phase_key == "pattern_state_ideal": - self._set_pattern_indicator(THEME["text_muted"]) - else: - self._set_pattern_indicator(THEME["secondary_accent"]) - self._refresh_workspace_header() - - def _channel_pattern_state_key( - self, - physical_names: list[str], - virtual_names: list[str], - kind: str, - ) -> str: - physical_count = self._configured_pattern_count(physical_names, kind) - virtual_count = self._configured_pattern_count(virtual_names, kind) - if physical_count == 0 and virtual_count == 0: - if kind == PATTERN_KIND_AMPLITUDE and self.element_pattern is not None: - return "pattern_state_imported" - return "pattern_state_ideal" - - physical_full = bool(physical_names) and physical_count == len(physical_names) - virtual_full = bool(virtual_names) and virtual_count == len(virtual_names) - physical_whole = physical_count in (0, len(physical_names)) - virtual_whole = virtual_count in (0, len(virtual_names)) - if (physical_full or virtual_full) and physical_whole and virtual_whole: - return "pattern_state_imported" - return "pattern_state_mixed" - - def _configured_pattern_count(self, channel_names: list[str], kind: str) -> int: - return sum( - self._pattern_has_kind(self.channel_patterns.pattern_for(channel_name), kind) - for channel_name in channel_names - ) - - @staticmethod - def _pattern_has_kind(pattern, kind: str) -> bool: # noqa: ANN001 - if kind == PATTERN_KIND_AMPLITUDE: - return ( - pattern.amplitude_horizontal is not None - or pattern.amplitude_elevation is not None - ) - return pattern.phase_horizontal is not None or pattern.phase_elevation is not None - - def _set_pattern_indicator(self, color: str) -> None: - if self.pattern_canvas is None or self.pattern_dot is None: - return - self.pattern_canvas.itemconfig(self.pattern_dot, fill=color) - - def import_element_pattern(self) -> None: - filename = filedialog.askopenfilename( - title=self._t("element_pattern_import_title"), - initialdir=str(self.last_pattern_dir), - filetypes=[ - (self._t("element_pattern_file_type"), "*.csv *.tsv"), - (self._t("csv_type"), "*.csv"), - (self._t("tsv_type"), "*.tsv"), - (self._t("all_files_type"), "*.*"), - ], - ) - if not filename: - return - self.last_pattern_dir = Path(filename).parent - - try: - pattern = load_element_pattern(filename) - except Exception as exc: - LOGGER.exception("Import element pattern failed: %s", filename) - messagebox.showerror(self._t("element_pattern_import_failed"), str(exc)) - return - - confirmed_pattern = self._confirm_element_pattern_import(pattern) - if confirmed_pattern is None: - self.status.set(self._t("element_pattern_import_canceled")) - return - - pattern = confirmed_pattern - self.element_pattern = pattern - self._update_channel_pattern_status() - LOGGER.info("Imported element pattern from %s", filename) - self.generate_virtual_array() - self.status.set(self._t("element_pattern_loaded", name=pattern.name)) - - def clear_element_pattern(self) -> None: - if self.element_pattern is None: - self.status.set(self._t("element_pattern_already_isotropic")) - return - LOGGER.info("Cleared element pattern: %s", self.element_pattern.source_path) - self.element_pattern = None - self._update_channel_pattern_status() - self.generate_virtual_array() - self.status.set(self._t("element_pattern_cleared")) - - def _confirm_element_pattern_import( - self, pattern: ElementPattern - ) -> ElementPattern | None: - dialog = tk.Toplevel(self.root) - _style_toplevel(dialog) - dialog._qt.setObjectName("elementPatternConfirmationDialog") - mark_workbench_role(dialog._qt, "dialog-shell") - dialog.title(self._t("element_pattern_confirm_title")) - dialog.transient(self.root) - dialog.grab_set() - fit_dialog_to_parent( - dialog._qt, - self.root._window, - preferred_size=(920, 680), - minimum_size=(720, 520), - ) - - title = ttk.Label( - dialog, - text=f"{pattern.name}", - font=(THEME["font_family"], 10, "bold"), - foreground=THEME["text_primary"], - background=THEME["bg"], - ) - title.pack(fill=tk.X, padx=10, pady=(8, 2)) - subtitle = ttk.Label( - dialog, - text="", - font=(THEME["font_family"], 9), - foreground=THEME["text_secondary"], - background=THEME["bg"], - ) - subtitle.pack(fill=tk.X, padx=10, pady=(0, 6)) - metrics_frame = ttk.Frame( - dialog, - style="Metric.TFrame", - padding=(10, 7), - ) - metrics_frame.pack(fill=tk.X, padx=10, pady=(0, 8)) - horizontal_metrics_label = ttk.Label( - metrics_frame, - text="", - style="MetricValue.TLabel", - font=(THEME["font_family_mono"], 9), - foreground=THEME["response_line"], - ) - horizontal_metrics_label.pack(anchor="w") - elevation_metrics_label = ttk.Label( - metrics_frame, - text="", - style="MetricValue.TLabel", - font=(THEME["font_family_mono"], 9), - foreground=THEME["secondary_accent"], - ) - elevation_metrics_label.pack(anchor="w") - - fig = Figure(figsize=(7.8, 5.0), dpi=FIG_DPI) - fig.set_facecolor(THEME["card_bg"]) - horizontal_ax = fig.add_subplot(211) - elevation_ax = fig.add_subplot(212) - - canvas = FigureCanvasTkAgg(fig, master=dialog) - canvas_widget = canvas.get_tk_widget() - _style_canvas_widget(canvas_widget) - canvas_widget.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 8)) - - state: dict[str, ElementPattern | None] = {"pattern": pattern, "confirmed": None} - - def redraw_preview() -> None: - current = state["pattern"] - if current is None: - return - elevation_column = ( - self._t( - "element_pattern_preview_elevation_column", - column=current.elevation_column, - ) - if current.elevation_column - else "" - ) - subtitle.configure( - text=self._t( - "element_pattern_preview_columns", - angle=current.angle_column, - horizontal=current.horizontal_column, - elevation=elevation_column, - ) - ) - - horizontal_ax.clear() - elevation_ax.clear() - horizontal_ax.plot( - current.angles_deg, - current.horizontal_gain_db, - color=THEME["response_line"], - linewidth=1.8, - ) - horizontal_metrics = format_pattern_cut_metrics( - pattern_cut_metrics(current.angles_deg, current.horizontal_gain_db) - ) - horizontal_metrics_label.configure( - text=self._t( - "element_pattern_horizontal_metrics", - metrics=horizontal_metrics, - ) - ) - horizontal_ax.set_title( - self._t("element_pattern_horizontal_title"), - loc="left", - ) - horizontal_ax.set_ylabel(self._t("element_pattern_axis_gain")) - _configure_pattern_preview_axis(horizontal_ax, current.angles_deg) - horizontal_ax.grid(True, alpha=0.3, color=THEME["grid_major_color"], linewidth=0.55) - - if current.elevation_gain_db is not None: - elevation_ax.plot( - current.angles_deg, - current.elevation_gain_db, - color=THEME["secondary_accent"], - linewidth=1.8, - ) - elevation_metrics = format_pattern_cut_metrics( - pattern_cut_metrics(current.angles_deg, current.elevation_gain_db) - ) - elevation_metrics_label.configure( - text=self._t( - "element_pattern_elevation_metrics", - metrics=elevation_metrics, - ) - ) - else: - elevation_ax.text( - 0.5, - 0.5, - self._t("element_pattern_no_elevation"), - transform=elevation_ax.transAxes, - ha="center", - va="center", - fontsize=10, - ) - elevation_metrics_label.configure( - text=self._t("element_pattern_elevation_reuse") - ) - elevation_ax.set_title( - self._t("element_pattern_elevation_title"), - loc="left", - ) - elevation_ax.set_xlabel(self._t("element_pattern_axis_angle")) - elevation_ax.set_ylabel(self._t("element_pattern_axis_gain")) - _configure_pattern_preview_axis(elevation_ax, current.angles_deg) - elevation_ax.grid(True, alpha=0.3, color=THEME["grid_major_color"], linewidth=0.55) - fig.tight_layout() - canvas.draw_idle() - - redraw_preview() - - def confirm() -> None: - state["confirmed"] = state["pattern"] - dialog.destroy() - - def cancel() -> None: - state["confirmed"] = None - dialog.destroy() - - def swap_axes() -> None: - current = state["pattern"] - if current is None: - return - state["pattern"] = current.swapped_axes() - redraw_preview() - - button_row = ttk.Frame(dialog) - button_row._qt.setObjectName("elementPatternActionBar") - mark_workbench_role(button_row._qt, "dialog-footer") - button_row.pack(fill=tk.X, padx=10, pady=(0, 10)) - button_layout = QtWidgets.QHBoxLayout(button_row._qt) - button_layout.setContentsMargins(0, 0, 0, 0) - button_box = QtWidgets.QDialogButtonBox( - QtWidgets.QDialogButtonBox.StandardButton.Ok - | QtWidgets.QDialogButtonBox.StandardButton.Cancel, - parent=button_row._qt, - ) - import_button = button_box.button( - QtWidgets.QDialogButtonBox.StandardButton.Ok - ) - cancel_button = button_box.button( - QtWidgets.QDialogButtonBox.StandardButton.Cancel - ) - import_button.setText(self._t("element_pattern_import_button")) - cancel_button.setText(self._t("element_pattern_cancel_button")) - import_button.clicked.connect(confirm) - cancel_button.clicked.connect(cancel) - mark_primary(import_button) - swap_button = button_box.addButton( - self._t("element_pattern_swap_button"), - QtWidgets.QDialogButtonBox.ButtonRole.ActionRole, - ) - swap_button.clicked.connect(swap_axes) - button_layout.addWidget(button_box) - if pattern.elevation_gain_db is None: - swap_button.setEnabled(False) - dialog.protocol("WM_DELETE_WINDOW", cancel) - fit_dialog_to_parent( - dialog._qt, - self.root._window, - preferred_size=(920, 680), - minimum_size=(720, 520), - ) - dialog.wait_window() - return state["confirmed"] - - def open_performance_report_dialog(self) -> None: - """Open the reusable report form for one or more sequential exports.""" - from .performance_report_dialog import PerformanceReportDialog - - current_dialog = self._performance_report_dialog - if current_dialog is not None and current_dialog.isVisible(): - current_dialog.raise_() - current_dialog.activateWindow() - return - - metrics = self.current_metrics or self._metrics_for_export() - azimuth_available = ( - metrics.x_aperture > 0.0 and metrics.azimuth_resolution is not None - ) - elevation_available = ( - metrics.y_aperture > 0.0 and metrics.elevation_resolution is not None - ) - dialog = PerformanceReportDialog( - self.root._window, - language=self.language, - initial_directory=self.last_report_dir, - azimuth_available=azimuth_available, - elevation_available=elevation_available, - initial_error_limit_deg=self.last_report_error_limit_deg, - ) - dialog.ensurePolished() - if dialog.layout() is not None: - dialog.layout().activate() - fit_dialog_to_parent( - dialog, - self.root._window, - preferred_size=(920, 600), - minimum_size=(820, 540), - margin=12, - ) - dialog.export_requested.connect( - lambda export_kind, current=dialog: ( - self._export_from_performance_report_dialog(current, export_kind) - ) - ) - dialog.finished.connect( - lambda _result, current=dialog: self._clear_performance_report_dialog( - current - ) - ) - self._performance_report_dialog = dialog - dialog.open() - - def _clear_performance_report_dialog(self, dialog) -> None: # noqa: ANN001 - if self._performance_report_dialog is dialog: - self._performance_report_dialog = None - delete_later = getattr(dialog, "deleteLater", None) - if callable(delete_later): - delete_later() - - def _export_from_performance_report_dialog( - self, - dialog, - export_kind: str, - ) -> None: # noqa: ANN001 - """Start one export without closing or resetting the settings dialog.""" - from .performance_report import ( - AngleErrorImageOptions, - generate_angle_error_image, - generate_performance_report, - ) - - if ( - self._performance_report_thread is not None - and self._performance_report_thread.isRunning() - ): - return - - self.last_report_error_limit_deg = dialog.error_limit_spin.value() - if export_kind == "angle_image": - inherited_options = dialog.angle_error_image_options() - output_path = inherited_options.output_path.resolve() - options = AngleErrorImageOptions( - output_path=output_path, - error_limit_deg=inherited_options.error_limit_deg, - language=inherited_options.language, - ) - generator = generate_angle_error_image - export_kind = "angle_image" - overwrite_title = self._t("angle_image_overwrite_title") - overwrite_question = self._t( - "angle_image_overwrite_question", file=output_path - ) - else: - options = dialog.options() - output_path = options.output_path.resolve() - generator = generate_performance_report - export_kind = "report" - overwrite_title = self._t("report_overwrite_title") - overwrite_question = self._t( - "report_overwrite_question", file=output_path - ) - if output_path.exists(): - answer = QtWidgets.QMessageBox.question( - dialog, - overwrite_title, - overwrite_question, - QtWidgets.QMessageBox.StandardButton.Yes - | QtWidgets.QMessageBox.StandardButton.No, - QtWidgets.QMessageBox.StandardButton.No, - ) - if answer != QtWidgets.QMessageBox.StandardButton.Yes: - return - - self.last_report_dir = output_path.parent - dialog.set_export_busy(True) - self._performance_export_parent = dialog - try: - self._start_performance_report_export( - generator, - self._performance_report_snapshot(), - options, - export_kind=export_kind, - ) - except Exception: - self._performance_export_parent = None - dialog.set_export_busy(False) - raise - - def _performance_report_snapshot(self): # noqa: ANN202 - from .performance_report import PerformanceReportSnapshot - - return PerformanceReportSnapshot( - array=self.current_array(), - frequency_ghz=self.current_frequency_ghz(), - ambiguity_margin_db=self.current_margin_db(), - dbf_dictionary=deepcopy(self.dbf_dictionary), - element_pattern=deepcopy(self.element_pattern), - channel_patterns=deepcopy(self.channel_patterns), - current_config=deepcopy(self._layout_config()), - app_version=APP_VERSION, - created_at=datetime.now().astimezone(), - ) - - def _start_performance_report_export( - self, - generator, - snapshot, - options, - *, - export_kind: str = "report", - ) -> None: # noqa: ANN001 - if ( - self._performance_report_thread is not None - and self._performance_report_thread.isRunning() - ): - return - - self._performance_export_kind = ( - "angle_image" if export_kind == "angle_image" else "report" - ) - exporting_key = ( - "angle_image_exporting_status" - if self._performance_export_kind == "angle_image" - else "report_exporting_status" - ) - progress_title_key = ( - "angle_image_progress_title" - if self._performance_export_kind == "angle_image" - else "report_progress_title" - ) - export_parent = self._performance_export_parent or self.root._window - - progress = QtWidgets.QProgressDialog( - self._t(exporting_key), - self._t("report_cancel_button"), - 0, - 100, - export_parent, - ) - progress.setObjectName("performanceReportProgress") - progress.setWindowTitle(self._t(progress_title_key)) - progress.setWindowModality(QtCore.Qt.WindowModality.WindowModal) - progress.setMinimumDuration(0) - progress.setAutoClose(False) - progress.setAutoReset(False) - mark_workbench_role(progress, "progress-dialog") - progress.setMinimumSize(480, 160) - progress.setValue(0) - progress_label = progress.findChild(QtWidgets.QLabel) - if progress_label is not None: - progress_label.setObjectName("performanceReportProgressLabel") - mark_workbench_role(progress_label, "progress-status") - progress_label.setWordWrap(True) - progress_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter) - progress_label.setMinimumHeight(32) - progress.setLabelText(f"{self._t(exporting_key)} · 0%") - progress_bar = progress.findChild(QtWidgets.QProgressBar) - if progress_bar is not None: - progress_bar.setObjectName("performanceReportProgressBar") - mark_workbench_role(progress_bar, "report-progress") - progress_bar.setTextVisible(False) - progress_bar.setAccessibleName(self._t(progress_title_key)) - cancel_button = progress.findChild(QtWidgets.QPushButton) - if cancel_button is not None: - cancel_button.setObjectName("performanceReportCancelButton") - - thread = QtCore.QThread() - worker = _PerformanceReportWorker(generator, snapshot, options) - bridge = _PerformanceReportUiBridge(self, thread, self.root._window) - worker.moveToThread(thread) - thread.started.connect(worker.run) - queued = QtCore.Qt.ConnectionType.QueuedConnection - worker.progress.connect(bridge.on_progress, queued) - worker.succeeded.connect(bridge.on_succeeded, queued) - worker.failed.connect(bridge.on_failed, queued) - worker.cancelled.connect(bridge.on_cancelled, queued) - worker.finished.connect(thread.quit) - worker.finished.connect(worker.deleteLater) - thread.finished.connect(bridge.on_thread_finished) - thread.finished.connect(thread.deleteLater) - progress.canceled.connect(bridge.on_cancel_requested) - - self._performance_report_thread = thread - self._performance_report_worker = worker - self._performance_report_bridge = bridge - self._performance_report_progress = progress - self.status.set(self._t(exporting_key)) - progress.show() - thread.start() - - @QtCore.Slot(int, str) - def _on_performance_report_progress(self, percent: int, message: str) -> None: - progress = self._performance_report_progress - if progress is not None: - # QProgressDialog treats its maximum as a terminal/reset state. The - # worker's terminal signal owns closure, so progress stays at 99 here. - visible_percent = max(0, min(99, int(percent))) - progress.setLabelText(f"{message} · {visible_percent}%") - progress.setValue(visible_percent) - self.status.set(message) - - @QtCore.Slot() - def _cancel_performance_report_export(self) -> None: - thread = self._performance_report_thread - if thread is None or not thread.isRunning(): - return - thread.requestInterruption() - canceling_key = ( - "angle_image_canceling_status" - if self._performance_export_kind == "angle_image" - else "report_canceling_status" - ) - progress = self._performance_report_progress - if progress is not None: - progress.setLabelText(self._t(canceling_key)) - cancel_button = progress.findChild( - QtWidgets.QPushButton, "performanceReportCancelButton" - ) - if cancel_button is not None: - cancel_button.setEnabled(False) - self.status.set(self._t(canceling_key)) - - @QtCore.Slot(object) - def _on_performance_report_succeeded(self, artifacts) -> None: # noqa: ANN001 - self._close_performance_report_progress() - message_parent = self._performance_export_parent or self.root._window - if self._performance_export_kind == "angle_image": - self.status.set( - self._t("angle_image_exported_status", file=artifacts.png_path) - ) - QtWidgets.QMessageBox.information( - message_parent, - self._t("angle_image_exported_title"), - self._t("angle_image_exported_message", file=artifacts.png_path), - ) - return - data_note = "" - if artifacts.data_directory is not None: - data_note = self._t( - "report_exported_data_note", - directory=artifacts.data_directory, - ) - self.status.set( - self._t("report_exported_status", file=artifacts.pdf_path) - ) - QtWidgets.QMessageBox.information( - message_parent, - self._t("report_exported_title"), - self._t( - "report_exported_message", - file=artifacts.pdf_path, - data_note=data_note, - ), - ) - - @QtCore.Slot(str) - def _on_performance_report_failed(self, message: str) -> None: - self._close_performance_report_progress() - message_parent = self._performance_export_parent or self.root._window - title_key = ( - "angle_image_export_failed_title" - if self._performance_export_kind == "angle_image" - else "report_export_failed_title" - ) - self.status.set(self._t(title_key)) - QtWidgets.QMessageBox.critical( - message_parent, - self._t(title_key), - message, - ) - - @QtCore.Slot() - def _on_performance_report_cancelled(self) -> None: - self._close_performance_report_progress() - canceled_key = ( - "angle_image_canceled_status" - if self._performance_export_kind == "angle_image" - else "report_canceled_status" - ) - self.status.set(self._t(canceled_key)) - - def _close_performance_report_progress(self) -> None: - progress = self._performance_report_progress - if progress is None: - return - self._performance_report_progress = None - signals_were_blocked = progress.blockSignals(True) - try: - progress.hide() - progress.close() - finally: - progress.blockSignals(signals_were_blocked) - progress.deleteLater() - - def _clear_performance_report_thread( - self, - thread: QtCore.QThread, - bridge: _PerformanceReportUiBridge, - ) -> None: - owns_thread = self._performance_report_thread is thread - if owns_thread: - self._performance_report_thread = None - self._performance_report_worker = None - if self._performance_report_bridge is bridge: - self._performance_report_bridge = None - bridge.deleteLater() - if owns_thread: - export_parent = self._performance_export_parent - self._performance_export_parent = None - set_export_busy = getattr(export_parent, "set_export_busy", None) - if callable(set_export_busy): - set_export_busy(False) - self._performance_export_kind = "report" - - def export_layout_config(self) -> None: - default_path = Path("outputs") / "antenna_layout.json" - default_path.parent.mkdir(exist_ok=True) - filename = filedialog.asksaveasfilename( - title=self._t("export_layout_title"), - initialdir=str(self.last_layout_dir), - initialfile=default_path.name, - defaultextension=".json", - filetypes=[(self._t("layout_json_type"), "*.json")], - ) - if not filename: - return - self.last_layout_dir = Path(filename).parent - config = self._layout_config() - with open(filename, "w", encoding="utf-8") as file: - file.write(_layout_config_to_json(config)) - LOGGER.info("Exported layout config to %s", filename) - self.status.set(self._t("exported_layout", file=filename)) - - def import_layout_config(self) -> None: - filename = filedialog.askopenfilename( - title=self._t("import_layout_title"), - initialdir=str(self.last_layout_dir), - filetypes=[ - (self._t("layout_json_type"), "*.json"), - (self._t("all_files_type"), "*.*"), - ], - ) - if not filename: - return - self.last_layout_dir = Path(filename).parent - previous_snapshot = self._capture_layout_snapshot() - try: - with open(filename, "r", encoding="utf-8") as file: - config = json.load(file) - imported_elements = self._elements_from_layout_config(config) - except Exception as exc: - LOGGER.exception("Import layout failed: %s", filename) - messagebox.showerror(self._t("import_layout_failed"), str(exc)) - return - - imported_snapshot = self._layout_snapshot_for(imported_elements, None) - if imported_snapshot != previous_snapshot: - self._push_undo_snapshot(previous_snapshot) - self.elements = imported_elements - self.dragging = None - self.drag_bounds = None - self.drag_axis_limits = None - self.drag_start_snapshot = None - self.selected_element = None - self._sync_auto_count_inputs() - self.generate_virtual_array() - tx = [element for element in self.elements if element.kind == "tx"] - rx = [element for element in self.elements if element.kind == "rx"] - x_values = [element.x * DISPLAY_SCALE_LAMBDA for element in self.elements] - y_values = [element.y * DISPLAY_SCALE_LAMBDA for element in self.elements] - self.status.set( - self._t( - "imported_layout", - file=Path(filename).name, - tx=tx[0].name, - tx_x=tx[0].x * DISPLAY_SCALE_LAMBDA, - tx_y=tx[0].y * DISPLAY_SCALE_LAMBDA, - rx=rx[0].name, - rx_x=rx[0].x * DISPLAY_SCALE_LAMBDA, - rx_y=rx[0].y * DISPLAY_SCALE_LAMBDA, - x_min=min(x_values), - x_max=max(x_values), - y_min=min(y_values), - y_max=max(y_values), - ) - ) - LOGGER.info("Imported layout config from %s", filename) - - # ── Layout config I/O ───────────────────────────────────────────── - - def _layout_config(self) -> dict[str, object]: - config = self._layout_coordinates_config() - metrics = self._metrics_for_export() - config["evaluation"] = self._layout_evaluation(metrics) - return config - - def _layout_coordinates_config(self) -> dict[str, object]: - tx = [element for element in self.elements if element.kind == "tx"] - rx = [element for element in self.elements if element.kind == "rx"] - return { - "version": LAYOUT_CONFIG_VERSION, - "unit": LAYOUT_UNIT, - "tx": [ - { - "name": element.name, - "x": _json_number(element.x * DISPLAY_SCALE_LAMBDA, digits=9), - "y": _json_number(element.y * DISPLAY_SCALE_LAMBDA, digits=9), - } - for element in tx - ], - "rx": [ - { - "name": element.name, - "x": _json_number(element.x * DISPLAY_SCALE_LAMBDA, digits=9), - "y": _json_number(element.y * DISPLAY_SCALE_LAMBDA, digits=9), - } - for element in rx - ], - } - - def _elements_from_layout_config(self, config: object) -> list[EditableElement]: - if not isinstance(config, dict): - raise ValueError("Layout config must be a JSON object.") - if config.get("version") != LAYOUT_CONFIG_VERSION: - raise ValueError(f"Unsupported layout version: {config.get('version')!r}.") - unit = config.get("unit") - if unit not in LAYOUT_UNITS_LAMBDA | LEGACY_LAYOUT_UNITS_HALF_LAMBDA: - raise ValueError("Layout unit must be 'lambda'.") - coordinates_are_lambda = unit in LAYOUT_UNITS_LAMBDA - - elements: list[EditableElement] = [] - for kind in ("tx", "rx"): - raw_points = config.get(kind) - if not isinstance(raw_points, list) or not raw_points: - raise ValueError(f"Layout field '{kind}' must be a non-empty list.") - max_count = _max_elements_for_kind(kind) - if len(raw_points) > max_count: - prefix = _element_prefix(kind) - raise ValueError(f"Layout has {len(raw_points)} {prefix} elements; maximum is {max_count}.") - for index, raw_point in enumerate(raw_points): - if not isinstance(raw_point, dict): - raise ValueError(f"{kind}[{index}] must be an object.") - try: - name = f"{_element_prefix(kind)}{index + 1}" - raw_x = float(raw_point["x"]) - raw_y = float(raw_point["y"]) - if coordinates_are_lambda: - raw_x = _to_internal_half_lambda(raw_x) - raw_y = _to_internal_half_lambda(raw_y) - x = snap_to_grid(raw_x) - y = snap_to_grid(raw_y) - except KeyError as exc: - raise ValueError(f"{kind}[{index}] is missing coordinate {exc}.") from exc - except (TypeError, ValueError) as exc: - raise ValueError(f"{kind}[{index}] has invalid coordinates.") from exc - elements.append(EditableElement(kind=kind, index=index, name=name, x=x, y=y)) - return elements - - def _metrics_for_export(self) -> ArrayMetrics: - array = self.current_array() - unique, counts = array.unique_virtual_xy(decimals=ROUND_DECIMALS) - _af_db, _azimuths, _elevations, metrics = calculate_metrics_and_psf( - array, - unique, - counts, - tx_pattern=self.element_pattern, - rx_pattern=self.element_pattern, - channel_patterns=self.channel_patterns, - ) - return metrics - - def _layout_evaluation(self, metrics: ArrayMetrics) -> dict[str, object]: - utilization = metrics.unique_count / metrics.virtual_count if metrics.virtual_count else 0.0 - return { - "frequency_ghz": _format_frequency_ghz(self.current_frequency_ghz()), - "ambiguity_margin_db": _json_number(self.current_margin_db(), digits=3), - "dbf_dictionary": { - "mode": self.dbf_dictionary.mode, - "custom_sources": { - "azimuth": ( - self.dbf_dictionary.custom_azimuth_table.source_path - if self.dbf_dictionary.custom_azimuth_table is not None - else None - ), - "elevation": ( - self.dbf_dictionary.custom_elevation_table.source_path - if self.dbf_dictionary.custom_elevation_table is not None - else None - ), - }, - "custom_phase_reversed": self.dbf_dictionary.custom_phase_reversed, - "custom_zero_phase_calibrated": ( - self.dbf_dictionary.custom_zero_phase_calibrated - ), - }, - "virtual_utilization": { - "unique_points": metrics.unique_count, - "virtual_channels": metrics.virtual_count, - "ratio": _json_number(utilization, digits=6), - "duplicate_points": metrics.duplicate_excess, - }, - "az_aperture_mm": _json_number(self.aperture_mm(metrics.x_aperture), digits=3), - "az_aperture_lambda": _json_number(metrics.x_aperture * DISPLAY_SCALE_LAMBDA, digits=9), - "az_resolution_deg": _json_number(metrics.azimuth_resolution, digits=3), - "az_3db_bw_deg": _json_number(metrics.azimuth_3db_beamwidth, digits=3), - "az_psl_db": _json_number(metrics.azimuth_psl_db, digits=3), - "first_sidelobe": { - "level_db": _json_number(metrics.azimuth_first_sidelobe_db, digits=3), - "az_deg": _json_number(metrics.azimuth_first_sidelobe_angle, digits=3), - }, - "az_grating_lobe": { - "level_db": _json_number(metrics.azimuth_grating_lobe_db, digits=3), - "az_deg": _json_number(metrics.azimuth_grating_lobe_angle, digits=3), - }, - "az_islr_db": _json_number(metrics.azimuth_islr_db, digits=3), - "el_3db_bw_deg": _json_number(metrics.elevation_3db_beamwidth, digits=3), - "el_psl_db": _json_number(metrics.elevation_psl_db, digits=3), - "psl_2d_worst_db": _json_number(metrics.psl_db, digits=3), - "psl_2d_location_deg": { - "az": _json_number(metrics.sidelobe_azimuth, digits=3), - "el": _json_number(metrics.sidelobe_elevation, digits=3), - }, - "element_pattern": self._element_pattern_export_info(), - "channel_patterns": self._channel_pattern_export_info(), - "notes": self._notes_parts(metrics), - } - - # ── Main generation pipeline ────────────────────────────────────── - - def generate_virtual_array(self) -> None: - self.stop_dbf_scan_animation(restore_response=False) - self.stop_dbf2d_animation(update_status=False) - array = self.current_array() - unique, counts = array.unique_virtual_xy(decimals=ROUND_DECIMALS) - pair_map = self._build_virtual_pair_map(array) - af_db, azimuths, elevations, metrics = calculate_metrics_and_psf( - array, - unique, - counts, - tx_pattern=self.element_pattern, - rx_pattern=self.element_pattern, - channel_patterns=self.channel_patterns, - ) - self.current_metrics = metrics - - self._draw_physical_array() - self._draw_virtual_array(unique, counts, pair_map, metrics) - self._update_evaluation_panel(metrics) - self._update_channel_pattern_status() - self._draw_dbf_reference_spectrum("azimuth") - self._draw_dbf_reference_spectrum("elevation") - self._draw_dbf2d_heatmap() - self._update_capability_empty_states(metrics) - - self.status.set(self._t("status_ready")) - self._refresh_workspace_header() - self.phys_canvas.draw_idle() - self.virt_canvas.draw_idle() - self.az_chart.canvas.draw_idle() - self.el_chart.canvas.draw_idle() - - def _update_capability_empty_states(self, metrics: ArrayMetrics) -> None: - az_available = metrics.azimuth_resolution is not None and metrics.x_aperture > 0 - el_available = metrics.elevation_resolution is not None and metrics.y_aperture > 0 - - for chart, available, title_key in ( - (self.az_chart, az_available, "empty_azimuth_title"), - (self.el_chart, el_available, "empty_elevation_title"), - ): - if chart.empty_overlay is not None: - chart.empty_overlay.setAccessibleName( - self._t("accessibility_plot_capability") - ) - chart.empty_overlay.set_content( - self._t(title_key), - self._t("empty_array_body"), - ) - chart.empty_overlay.set_action( - self._t("empty_action_edit_array"), - lambda: self._select_main_tab(0), - ) - chart.empty_overlay.show_overlay(not available) - if chart.footer_widget is not None: - chart.footer_widget._qt.setVisible(available) - if chart.play_button is not None: - chart.play_button.configure(state=tk.NORMAL if available else tk.DISABLED) - if not available and chart.stop_button is not None: - chart.stop_button.configure(state=tk.DISABLED) - - has_2d = az_available and el_available - if self.dbf2d_empty_overlay is not None: - self.dbf2d_empty_overlay.setAccessibleName( - self._t("accessibility_plot_capability") - ) - self.dbf2d_empty_overlay.set_content( - self._t("empty_2d_title"), - self._t("empty_2d_body"), - ) - target_index = 1 if az_available or el_available else 0 - action_key = ( - "empty_action_view_1d" - if target_index == 1 - else "empty_action_edit_array" - ) - self.dbf2d_empty_overlay.set_action( - self._t(action_key), - lambda index=target_index: self._select_main_tab(index), - ) - self.dbf2d_empty_overlay.show_overlay(not has_2d) - if self.dbf2d_controls_widget is not None: - self.dbf2d_controls_widget._qt.setVisible(has_2d) - if self.dbf2d_status_label is not None: - self.dbf2d_status_label._qt.setVisible(has_2d) - for button in (self.dbf2d_az_button, self.dbf2d_el_button): - if button is not None: - button.configure(state=tk.NORMAL if has_2d else tk.DISABLED) - if not has_2d and self.dbf2d_stop_button is not None: - self.dbf2d_stop_button.configure(state=tk.DISABLED) - - def _build_virtual_pair_map( - self, array: AntennaArray - ) -> dict[tuple[float, float], list[str]]: - pair_map: dict[tuple[float, float], list[str]] = defaultdict(list) - for point in array.virtual_points(): - key = (round(point.x, ROUND_DECIMALS), round(point.y, ROUND_DECIMALS)) - pair_map[key].append(f"{point.tx_name}-{point.rx_name}") - return pair_map - - # ── Plot drawing ────────────────────────────────────────────────── - - def _draw_physical_array(self) -> None: - self.physical_ax.clear() - _configure_axis_chrome(self.physical_ax) - tx = [element for element in self.elements if element.kind == "tx"] - rx = [element for element in self.elements if element.kind == "rx"] - - self.physical_ax.scatter( - _to_display_lambda([element.x for element in tx]), - _to_display_lambda([element.y for element in tx]), - marker="D", - s=62, - facecolors="none", - edgecolors=THEME["tx_color"], - linewidths=1.8, - label="Tx", - ) - self.physical_ax.scatter( - _to_display_lambda([element.x for element in rx]), - _to_display_lambda([element.y for element in rx]), - marker="*", - s=112, - color=THEME["rx_color"], - edgecolors=THEME["rx_edge"], - linewidths=0.55, - label="Rx", - ) - self.physical_hover_marker = self.physical_ax.scatter( - [], - [], - marker="o", - s=260, - facecolors=THEME["hover_fill"], - edgecolors=THEME["focus"], - linewidths=1.6, - alpha=0.45, - zorder=45, - label="_nolegend_", - ) - self.physical_hover_marker.set_visible(False) - if self.selected_element is not None: - self.physical_ax.scatter( - _to_display_lambda([self.selected_element.x]), - _to_display_lambda([self.selected_element.y]), - marker="o", - s=292, - facecolors="none", - edgecolors=THEME["selection"], - linewidths=2.6, - zorder=5, - label="_nolegend_", - ) - for element in self.elements: - if self.selected_element is element: - self.physical_ax.annotate( - element.name, - xy=( - element.x * DISPLAY_SCALE_LAMBDA, - element.y * DISPLAY_SCALE_LAMBDA, - ), - xytext=(7, 16), - textcoords="offset points", - fontsize=9, - ha="left", - va="bottom", - color=THEME["text_primary"], - bbox={ - "boxstyle": "round,pad=0.18", - "facecolor": THEME["selection_fill"], - "edgecolor": THEME["focus"], - "alpha": 0.95, - "linewidth": 0.6, - }, - ) - else: - dy = 1.0 if element.kind == "tx" else -1.15 - self.physical_ax.text( - element.x * DISPLAY_SCALE_LAMBDA, - element.y * DISPLAY_SCALE_LAMBDA + dy, - element.name, - fontsize=9, - ha="center", - va="center", - color=THEME["text_secondary"], - ) - - self.physical_ax.set_title( - self._t("physical_title"), fontsize=TITLE_SIZE, pad=6, y=1.02, loc="left", - color=THEME["text_primary"], fontweight="bold", - ) - self.physical_ax.set_xlabel("x (λ)", color=THEME["text_secondary"]) - self.physical_ax.set_ylabel("y (λ)", color=THEME["text_secondary"]) - if self.drag_axis_limits is not None: - x_limits, y_limits = self.drag_axis_limits - else: - physical_x = _to_display_lambda([element.x for element in self.elements]) - physical_y = _to_display_lambda([element.y for element in self.elements]) - x_limits, y_limits = _square_axis_limits( - physical_x, - physical_y, - minimum_span=PHYSICAL_AXIS_MIN_SPAN_LAMBDA, - padding=PHYSICAL_AXIS_PADDING_LAMBDA, - ) - self.physical_ax.set_xlim(*x_limits) - self.physical_ax.set_ylim(*y_limits) - self.physical_ax.set_xticks( - _axis_ticks_within(x_limits, PHYSICAL_MAJOR_GRID_STEP_LAMBDA) - ) - self.physical_ax.set_yticks( - _axis_ticks_within(y_limits, PHYSICAL_MAJOR_GRID_STEP_LAMBDA) - ) - self.physical_ax.set_xticks( - _axis_ticks_within(x_limits, DISPLAY_GRID_STEP_LAMBDA), - minor=True, - ) - self.physical_ax.set_yticks( - _axis_ticks_within(y_limits, DISPLAY_GRID_STEP_LAMBDA), - minor=True, - ) - self.physical_ax.grid( - True, which="major", color=THEME["grid_major_color"], linewidth=0.95, alpha=0.66 - ) - self.physical_ax.grid( - True, which="minor", color=THEME["grid_minor_color"], linewidth=0.42, alpha=0.24 - ) - if self.dragging is not None: - self._set_physical_cursor("closedhand") - snap_x = self.dragging.x * DISPLAY_SCALE_LAMBDA - snap_y = self.dragging.y * DISPLAY_SCALE_LAMBDA - self.physical_ax.axvline( - snap_x, - color=THEME["selection"], - linestyle="--", - linewidth=1.35, - alpha=0.86, - zorder=3, - ) - self.physical_ax.axhline( - snap_y, - color=THEME["selection"], - linestyle="--", - linewidth=1.35, - alpha=0.86, - zorder=3, - ) - self.physical_ax.scatter( - [snap_x], - [snap_y], - marker="o", - s=430, - facecolors="none", - edgecolors=THEME["selection"], - linewidths=2.8, - zorder=6, - label="_nolegend_", - ) - _style_legend( - self.physical_ax.legend( - loc="upper right", - fontsize=9, - frameon=False, - markerscale=0.72, - borderpad=0.15, - labelspacing=0.25, - handlelength=1.0, - handletextpad=0.35, - ) - ) - self.physical_ax.set_aspect("equal", adjustable="box", anchor="C") - self.physical_hover_annotation = self.physical_ax.annotate( - "", - xy=(0, 0), - xytext=(12, 12), - textcoords="offset points", - bbox={ - "boxstyle": "round,pad=0.35", - "facecolor": THEME["card_bg"], - "edgecolor": THEME["focus_soft"], - "alpha": 0.95, - "linewidth": 0.8, - }, - arrowprops={"arrowstyle": "->", "color": THEME["focus"], "linewidth": 0.8}, - fontsize=9, - color=THEME["text_primary"], - annotation_clip=False, - zorder=60, - ) - self.physical_hover_annotation.set_clip_on(False) - self.physical_hover_annotation.set_visible(False) - - def _draw_virtual_array( - self, - unique: np.ndarray, - counts: np.ndarray, - pair_map: dict[tuple[float, float], list[str]], - metrics: ArrayMetrics, - ) -> None: - self.virtual_ax.clear() - _configure_axis_chrome(self.virtual_ax) - unique_display = _to_display_lambda(unique) - x_min, x_max = float(unique_display[:, 0].min()), float(unique_display[:, 0].max()) - y_min, y_max = float(unique_display[:, 1].min()), float(unique_display[:, 1].max()) - self.virtual_ax.add_patch( - Rectangle( - (x_min, y_min), - x_max - x_min, - y_max - y_min, - fill=False, - linestyle="--", - linewidth=1.2, - edgecolor=THEME["text_secondary"], - alpha=0.5, - ) - ) - sizes = 80 + 54 * np.clip(counts - 2, 0, 6) - single_mask = counts == 1 - duplicate_mask = counts > 1 - if np.any(single_mask): - self.virtual_ax.scatter( - unique_display[single_mask, 0], - unique_display[single_mask, 1], - s=34, - marker="o", - color=THEME["rx_color"], - edgecolors=THEME["rx_edge"], - linewidths=0.55, - label=self._t("unique_point"), - ) - if np.any(duplicate_mask): - self.virtual_ax.scatter( - unique_display[duplicate_mask, 0], - unique_display[duplicate_mask, 1], - s=sizes[duplicate_mask], - color=THEME["warning"], - marker="o", - edgecolors="#92400e", - linewidths=1.35, - label=self._t("duplicate_point"), - ) - self.virtual_hover_marker = self.virtual_ax.scatter( - [], - [], - marker="o", - s=210, - facecolors=THEME["hover_fill"], - edgecolors=THEME["focus"], - linewidths=1.5, - alpha=0.5, - zorder=7, - label="_nolegend_", - ) - self.virtual_hover_marker.set_visible(False) - for (x, y), count in zip(unique_display, counts): - if count > 1: - self.virtual_ax.annotate( - f"×{int(count)}", - xy=(x, y), - xytext=(5, 5), - textcoords="offset points", - fontsize=12, - color=THEME["danger"], - weight="bold", - ) - - # Store hover data - self.virtual_hover_xy = unique_display - self.virtual_hover_counts = counts.astype(int, copy=True) - self.virtual_hover_text = [] - for x, y in unique: - key = (round(float(x), ROUND_DECIMALS), round(float(y), ROUND_DECIMALS)) - pairs = pair_map.get(key, []) - pair_text = ", ".join(pairs[:10]) - if len(pairs) > 10: - pair_text += self._t("virtual_pairs_more", count=len(pairs)) - self.virtual_hover_text.append( - self._t( - "virtual_hover", - x=x * DISPLAY_SCALE_LAMBDA, - y=y * DISPLAY_SCALE_LAMBDA, - count=len(pairs), - pairs=pair_text, - ) - ) - - self.virtual_hover_annotation = self.virtual_ax.annotate( - "", - xy=(0, 0), - xytext=(12, 12), - textcoords="offset points", - bbox={ - "boxstyle": "round,pad=0.35", - "facecolor": THEME["card_bg"], - "edgecolor": THEME["focus_soft"], - "alpha": 0.95, - "linewidth": 0.8, - }, - arrowprops={"arrowstyle": "->", "color": THEME["focus"], "linewidth": 0.8}, - fontsize=9, - color=THEME["text_primary"], - annotation_clip=False, - zorder=60, - ) - self.virtual_hover_annotation.set_clip_on(False) - self.virtual_hover_annotation.set_visible(False) - - self.virtual_ax.set_title(self._t("virtual_title"), fontsize=TITLE_SIZE, pad=8, loc="left", - color=THEME["text_primary"], fontweight="bold") - self.virtual_ax.set_xlabel("x (λ)", color=THEME["text_secondary"]) - self.virtual_ax.set_ylabel("y (λ)", color=THEME["text_secondary"]) - self.virtual_ax.grid(True, alpha=THEME["grid_alpha"], color=THEME["grid_color"], linewidth=0.55) - - # Simple padded limits — let set_aspect("equal") handle the rest - x_limits = _axis_limits(unique_display[:, 0], minimum_span=6.0, padding=2.0) - y_limits = _axis_limits(unique_display[:, 1], minimum_span=6.0, padding=2.0) - self.virtual_ax.set_xlim(*x_limits) - self.virtual_ax.set_ylim(*y_limits) - self.virtual_ax.set_xticks( - np.arange( - np.floor(x_limits[0] / 5) * 5, - np.ceil(x_limits[1] / 5) * 5 + 1, - 5, - ) - ) - self.virtual_ax.set_yticks( - np.arange( - np.floor(y_limits[0] / 5) * 5, - np.ceil(y_limits[1] / 5) * 5 + 1, - 5, - ) - ) - self.virtual_ax.set_xticks( - np.arange( - np.floor(x_limits[0] / DISPLAY_GRID_STEP_LAMBDA) * DISPLAY_GRID_STEP_LAMBDA, - x_limits[1] + DISPLAY_GRID_STEP_LAMBDA, - DISPLAY_GRID_STEP_LAMBDA, - ), - minor=True, - ) - self.virtual_ax.set_yticks( - np.arange( - np.floor(y_limits[0] / DISPLAY_GRID_STEP_LAMBDA) * DISPLAY_GRID_STEP_LAMBDA, - y_limits[1] + DISPLAY_GRID_STEP_LAMBDA, - DISPLAY_GRID_STEP_LAMBDA, - ), - minor=True, - ) - self.virtual_ax.set_aspect("equal", adjustable="box") - - self.virtual_ax.text( - 0.98, - 0.97, - self._t( - "virtual_info", - unique=metrics.unique_count, - total=metrics.virtual_count, - duplicate=metrics.duplicate_excess, - x=_format_mm(self.aperture_mm(metrics.x_aperture)), - y=_format_mm(self.aperture_mm(metrics.y_aperture)), - ), - transform=self.virtual_ax.transAxes, - ha="right", - va="top", - fontsize=9, - color=THEME["text_primary"], - bbox={ - "boxstyle": "round,pad=0.18", - "facecolor": THEME["card_bg"], - "edgecolor": THEME["card_border"], - "alpha": 0.92, - "linewidth": 0.5, - }, - ) - if counts.max() > 1: - _style_legend(self.virtual_ax.legend(loc="lower left", fontsize=9)) - - def _draw_response_common( - self, - ax, - response_cut: ResponseCut, - metrics: ArrayMetrics, - ) -> None: - """Shared drawing logic for both Az and El response figures.""" - ax.clear() - _configure_axis_chrome(ax) - response_db = response_cut.gains_db - response_angles = response_cut.angles - sidelobe_index, sidelobe_is_peak = _response_sidelobe_marker( - response_angles, response_db, response_cut.mainlobe_guard - ) - sidelobe_angle = float(response_angles[sidelobe_index]) - sidelobe_gain = float(response_db[sidelobe_index]) - sidelobe_label = ( - self._t("max_sidelobe") if sidelobe_is_peak else self._t("guard_edge_max") - ) - response_ylim = (-40.0, 0.0) - - ax.plot( - response_angles, - response_db, - color=THEME["response_line"], - linewidth=5.0, - alpha=0.12, - solid_capstyle="round", - ) - ax.plot( - response_angles, - response_db, - color=THEME["response_line"], - linewidth=2.0, - solid_capstyle="round", - ) - show_legend = False - if self.element_pattern is not None: - if response_cut.mode == RESPONSE_MODE_ELEVATION: - element_pattern_cut = self.element_pattern.normalized_elevation_gain_db_at( - response_angles - ) - else: - element_pattern_cut = self.element_pattern.normalized_horizontal_gain_db_at( - response_angles - ) - pattern_cut = np.clip( - element_pattern_cut, - response_ylim[0], - response_ylim[1], - ) - ax.plot( - response_angles, - pattern_cut, - color=THEME["response_secondary_line"], - linestyle="--", - linewidth=1.3, - alpha=0.72, - label=response_cut.pattern_label, - ) - show_legend = True - ax.set_xlim(response_cut.fov) - ax.set_ylim(response_ylim) - ax.set_xticks(_axis_ticks_within(response_cut.fov, 20.0)) - ax.set_xticks(_axis_ticks_within(response_cut.fov, 10.0), minor=True) - ax.set_yticks(_axis_ticks_within(response_ylim, 10.0)) - ax.axvspan( - -response_cut.mainlobe_guard, - response_cut.mainlobe_guard, - color=THEME["accent_light"], - alpha=0.7, - ) - ax.scatter( - [0.0], - [0.0], - marker="+", - s=80, - color=THEME["text_primary"], - linewidths=2.0, - zorder=4, - ) - # Max sidelobe marker - ax.scatter( - [sidelobe_angle], - [sidelobe_gain], - marker="x", - s=70, - color=THEME["sidelobe"], - linewidths=2.0, - zorder=5, - clip_on=True, - label=sidelobe_label, - ) - - x_low, x_high = response_cut.fov - y_low, y_high = response_ylim - annotation_boxes: list[tuple[float, float, float, float]] = [] - - def annotation_position(angle: float, gain: float) -> tuple[float, float, str]: - angle_axes = (angle - x_low) / (x_high - x_low) - gain_axes = (gain - y_low) / (y_high - y_low) - box_width = 0.18 - box_height = 0.15 - if angle >= 0: - base_x = min(angle_axes + 0.08, 0.76) - ha = "left" - else: - base_x = max(angle_axes - 0.08, 0.24) - ha = "right" - - candidates = (0.12, -0.12, 0.25, -0.25, 0.38, -0.34, 0.0) - for offset in candidates: - y = float(np.clip(gain_axes + offset, 0.18, 0.82)) - if ha == "left": - box = (base_x, y - box_height / 2, base_x + box_width, y + box_height / 2) - else: - box = (base_x - box_width, y - box_height / 2, base_x, y + box_height / 2) - if not any(_axes_boxes_overlap(box, existing) for existing in annotation_boxes): - annotation_boxes.append(box) - return base_x, y, ha - - fallback_y = float(np.clip(gain_axes, 0.18, 0.82)) - if ha == "left": - annotation_boxes.append( - (base_x, fallback_y - box_height / 2, base_x + box_width, fallback_y + box_height / 2) - ) - else: - annotation_boxes.append( - (base_x - box_width, fallback_y - box_height / 2, base_x, fallback_y + box_height / 2) - ) - return base_x, fallback_y, ha - - annotation_x, annotation_y, annotation_ha = annotation_position( - sidelobe_angle, sidelobe_gain - ) - ax.annotate( - ( - f"{sidelobe_label}\n{response_cut.label} = {sidelobe_angle:.1f}°\n" - f"{self._t('gain_value', value=sidelobe_gain)}" - ), - xy=(sidelobe_angle, sidelobe_gain), - xytext=(annotation_x, annotation_y), - textcoords=ax.transAxes, - ha=annotation_ha, - va="center", - fontsize=9, - color="#7c2d12", - bbox={ - "boxstyle": "round,pad=0.25", - "facecolor": "#fff7ed", - "edgecolor": "#fed7aa", - "alpha": 0.92, - "linewidth": 0.7, - }, - arrowprops={"arrowstyle": "->", "color": THEME["sidelobe"], "linewidth": 0.7}, - annotation_clip=True, - ) - - # Grating lobe marker (Az only) - if ( - response_cut.mode == RESPONSE_MODE_AZIMUTH - and metrics.azimuth_grating_lobe_angle is not None - and metrics.azimuth_grating_lobe_db is not None - ): - grating_angle = metrics.azimuth_grating_lobe_angle - grating_gain = metrics.azimuth_grating_lobe_db - grating_same_as_max = ( - abs(grating_angle - sidelobe_angle) - <= float(np.diff(response_angles).mean()) / 2.0 - and abs(grating_gain - sidelobe_gain) <= 0.05 - ) - ax.scatter( - [grating_angle], - [grating_gain], - marker="^", - s=82, - facecolors="none", - edgecolors=THEME["secondary_accent"], - linewidths=1.8, - zorder=6, - clip_on=True, - label=( - self._t("grating_lobe_max") - if grating_same_as_max - else self._t("grating_lobe") - ), - ) - show_legend = True - if not grating_same_as_max: - grating_x, grating_y, grating_ha = annotation_position( - grating_angle, grating_gain - ) - ax.annotate( - ( - f"{self._t('grating_lobe')}\n" - f"{_dbf_short_label('azimuth', self.language)} = {grating_angle:.1f}°\n" - f"{self._t('gain_value', value=grating_gain)}" - ), - xy=(grating_angle, grating_gain), - xytext=(grating_x, grating_y), - textcoords=ax.transAxes, - ha=grating_ha, - va="center", - fontsize=9, - color="#134e4a", - bbox={ - "boxstyle": "round,pad=0.25", - "facecolor": THEME["secondary_light"], - "edgecolor": "#5eead4", - "alpha": 0.92, - "linewidth": 0.7, - }, - arrowprops={"arrowstyle": "->", "color": THEME["secondary_accent"], "linewidth": 0.7}, - annotation_clip=True, - ) - else: - _style_legend(ax.legend(loc="lower right", fontsize=9, framealpha=0.92)) - show_legend = False - - ax.set_title(self._t("response_title", mode=response_cut.label), pad=6, y=1.02, loc="left", - color=THEME["text_primary"], fontweight="bold") - ax.set_xlabel(response_cut.x_label, color=THEME["text_secondary"]) - ax.set_ylabel(self._t("axis_gain"), labelpad=2, color=THEME["text_secondary"]) - ax.grid(True, alpha=THEME["grid_alpha"], color=THEME["grid_color"], linewidth=0.55) - if show_legend: - _style_legend(ax.legend(loc="lower right", fontsize=9, framealpha=0.92)) - - response_psl_db = ( - metrics.elevation_psl_db - if response_cut.mode == RESPONSE_MODE_ELEVATION - else metrics.azimuth_psl_db - ) - # PSL badge in lower-left corner - ax.text( - 0.02, - 0.08, - self._t("psl_label", mode=response_cut.label, value=response_psl_db), - transform=ax.transAxes, - ha="left", - va="bottom", - fontsize=9, - color=THEME["text_primary"], - bbox={ - "boxstyle": "round,pad=0.25", - "facecolor": THEME["card_bg"], - "edgecolor": THEME["card_border"], - "alpha": 0.93, - "linewidth": 0.7, - }, - ) - - return response_db, response_angles - - def _draw_response( - self, - mode: str, - chart: ResponseChart, - af_db: np.ndarray, - azimuths: np.ndarray, - elevations: np.ndarray, - metrics: ArrayMetrics, - ) -> None: - """Draw a response chart (Az or El) and set up hover data.""" - response_cut = _response_cut_for_mode( - af_db, azimuths, elevations, mode, self.language - ) - response_db, response_angles = self._draw_response_common(chart.ax, response_cut, metrics) - - chart.hover_db = response_db - chart.hover_angles = response_angles - chart.hover_annotation = _new_response_hover_annotation(chart.ax) - chart.hover_marker = chart.ax.scatter( - [], - [], - marker="o", - s=42, - facecolors=THEME["selection_fill"], - edgecolors=THEME["focus"], - linewidths=1.2, - zorder=8, - clip_on=True, - ) - chart.hover_marker.set_visible(False) - - # ── Notes helpers ───────────────────────────────────────────────── - - def _notes_parts(self, metrics: ArrayMetrics) -> list[str]: - notes = [] - if metrics.duplicate_excess > 0: - notes.append("存在重复虚拟通道") - if metrics.azimuth_psl_db > -10.0: - notes.append("建议加窗降低旁瓣") - if metrics.elevation_ambiguity_level == "High": - notes.append("俯仰模糊风险高") - elif metrics.elevation_ambiguity_level == "Medium": - notes.append("俯仰模糊风险中") - return notes - - def _element_pattern_export_info(self) -> dict[str, object]: - if self.element_pattern is None: - return {"mode": "isotropic"} - return { - "mode": "loaded", - "source": self.element_pattern.source_path, - "angle_column": self.element_pattern.angle_column, - "horizontal_column": self.element_pattern.horizontal_column, - "elevation_column": self.element_pattern.elevation_column, - } - - def _channel_pattern_export_info(self) -> dict[str, object]: - current_channels = self._all_pattern_channel_names() - configured = [] - for channel_name in current_channels: - pattern = self.channel_patterns.pattern_for(channel_name) - if pattern.is_empty(): - continue - configured.append( - { - "channel": channel_name, - "amplitude_h": _series_table_label(pattern.amplitude_horizontal), - "amplitude_e": _series_table_label(pattern.amplitude_elevation), - "phase_h": _series_table_label(pattern.phase_horizontal), - "phase_e": _series_table_label(pattern.phase_elevation), - } - ) - return { - "mode": "ideal" if not configured else "channel_patterns", - "configured_channels": len(configured), - "configured_series": sum( - self.channel_patterns.pattern_for(channel).series_count() - for channel in current_channels - ), - "channels": configured, - } - - def _load_local_state(self) -> None: - try: - state = load_state() - if not state: - return - if state.get("version") != LOCAL_STATE_VERSION: - LOGGER.info("Ignoring unsupported local state version: %r", state.get("version")) - return - - language = state.get("language") - if language in SUPPORTED_LANGUAGES: - self.language = str(language) - self.language_var.set(LANGUAGE_LABELS[self.language]) - - layout_dir = state.get("last_layout_dir") - if isinstance(layout_dir, str) and layout_dir: - self.last_layout_dir = Path(layout_dir) - - report_dir = state.get("last_report_dir") - if isinstance(report_dir, str) and report_dir: - self.last_report_dir = Path(report_dir) - - report_error_limit = state.get("last_report_error_limit_deg") - try: - parsed_report_error_limit = float(report_error_limit) - except (TypeError, ValueError): - parsed_report_error_limit = float("nan") - if math.isfinite(parsed_report_error_limit) and 0.0 < parsed_report_error_limit <= 30.0: - self.last_report_error_limit_deg = parsed_report_error_limit - - pattern_dir = state.get("last_pattern_dir") - if isinstance(pattern_dir, str) and pattern_dir: - self.last_pattern_dir = Path(pattern_dir) - - frequency = state.get("frequency_ghz") - parsed_frequency = _parse_frequency_ghz(frequency) - if parsed_frequency is not None: - self._set_frequency_ghz(parsed_frequency) - - margin = state.get("ambiguity_margin_db") - parsed_margin = _parse_margin_db(margin) - if parsed_margin is not None: - self._set_margin_db(parsed_margin) - - dbf_display_mode = state.get("dbf_display_mode") - if dbf_display_mode in SUPPORTED_DBF_DISPLAY_MODES: - self.dbf_display_mode.set(str(dbf_display_mode)) - - window = state.get("window") - if isinstance(window, dict): - geometry = _validated_window_geometry(window.get("geometry")) - if geometry is not None: - self.root.geometry(geometry) - active_tab = window.get("active_tab") - if isinstance(active_tab, int) and 0 <= active_tab <= 2: - self._restored_active_tab = active_tab - splitter_sizes = window.get("splitter_sizes") - if ( - isinstance(splitter_sizes, list) - and len(splitter_sizes) == 2 - and all(isinstance(size, int) and size > 0 for size in splitter_sizes) - ): - self._restored_splitter_sizes = list(splitter_sizes) - window_state = window.get("state") - if window_state == "zoomed": - self.root.after( - 0, - lambda: self._restore_window_state("zoomed"), - ) - - layout = state.get("layout") - if layout is not None: - self.elements = self._elements_from_layout_config(layout) - - dictionary_state = state.get("dbf_dictionary") - if isinstance(dictionary_state, dict): - mode = str(dictionary_state.get("mode", DBF_DICT_IDEAL)) - if mode == DBF_DICT_CHANNEL_PATTERN_ZERO_REF: - mode = DBF_DICT_CHANNEL_PATTERN - elif mode not in { - DBF_DICT_IDEAL, - DBF_DICT_IDEAL_REVERSED, - DBF_DICT_CHANNEL_PATTERN, - DBF_DICT_CUSTOM, - }: - mode = DBF_DICT_IDEAL - custom_phase_reversed = bool( - dictionary_state.get("custom_phase_reversed", False) - ) - custom_zero_phase_calibrated = bool( - dictionary_state.get("custom_zero_phase_calibrated", False) - ) - custom_azimuth_table = None - custom_elevation_table = None - legacy_custom_path = dictionary_state.get("custom_path") - custom_azimuth_path = dictionary_state.get("custom_azimuth_path") - custom_elevation_path = dictionary_state.get("custom_elevation_path") - if not isinstance(custom_azimuth_path, str) or not custom_azimuth_path: - custom_azimuth_path = legacy_custom_path - if not isinstance(custom_elevation_path, str) or not custom_elevation_path: - custom_elevation_path = legacy_custom_path - custom_channel_modes = { - "azimuth": dictionary_state.get("custom_azimuth_channel_mode"), - "elevation": dictionary_state.get("custom_elevation_channel_mode"), - } - if mode == DBF_DICT_CUSTOM: - for axis_name, custom_path in ( - ("azimuth", custom_azimuth_path), - ("elevation", custom_elevation_path), - ): - if not isinstance(custom_path, str) or not custom_path: - continue - try: - table = load_dbf_dictionary_table( - custom_path, - self.current_array(), - channel_mode=custom_channel_modes.get(axis_name), - ) - except Exception: - LOGGER.warning( - "Failed to restore %s DBF dictionary from %s", - axis_name, - custom_path, - ) - mode = DBF_DICT_IDEAL - continue - if axis_name == "azimuth": - custom_azimuth_table = table - else: - custom_elevation_table = table - if ( - custom_azimuth_table is None - and custom_elevation_table is None - ): - mode = DBF_DICT_IDEAL - self.dbf_dictionary = DbfDictionaryConfig( - mode=mode, - custom_azimuth_table=custom_azimuth_table, - custom_elevation_table=custom_elevation_table, - custom_phase_reversed=custom_phase_reversed, - custom_zero_phase_calibrated=custom_zero_phase_calibrated, - ) - - pattern_path = state.get("element_pattern_path") - if isinstance(pattern_path, str) and pattern_path: - try: - pattern = load_element_pattern(pattern_path) - self.element_pattern = pattern - self._update_channel_pattern_status() - LOGGER.info("Restored element pattern from %s", pattern_path) - except Exception: - LOGGER.warning("Failed to restore element pattern from %s", pattern_path) - - LOGGER.info("Loaded local state from %s", state_path()) - except Exception: - LOGGER.exception("Failed to load local state from %s", state_path()) - - def _restore_window_state(self, window_state: str) -> None: - try: - self.root.state(window_state) - except tk.TclError: - LOGGER.warning("Failed to restore window state: %s", window_state) - self._schedule_layout_sync() - - def _schedule_layout_sync(self) -> None: - for delay_ms in (0, 120, 350): - try: - self.root.after(delay_ms, self._sync_plot_layout_after_window_change) - except tk.TclError: - return - - def _sync_plot_layout_after_window_change(self) -> None: - try: - self.root.update_idletasks() - except tk.TclError: - return - - adjust_root_rows = getattr(self.root, "_adjust_root_overflow_rows", None) - if callable(adjust_root_rows): - try: - adjust_root_rows() - except Exception: - LOGGER.debug("Failed to adjust root rows after window change", exc_info=True) - - try: - self._stabilize_default_workspace_sash() - except Exception: - LOGGER.debug("Failed to stabilize workspace sash after window change", exc_info=True) - - canvases = ( - getattr(self, "phys_canvas", None), - getattr(self, "virt_canvas", None), - getattr(getattr(self, "az_chart", None), "canvas", None), - getattr(getattr(self, "el_chart", None), "canvas", None), - getattr(self, "dbf2d_canvas", None), - ) - for canvas in canvases: - if canvas is None: - continue - try: - canvas.figure.sync_equal_axis_layout( - canvas.winfo_width(), - canvas.winfo_height(), - ) - canvas.draw_idle() - except Exception: - LOGGER.debug("Failed to sync plot canvas after window change", exc_info=True) - - def _window_state_config(self) -> dict[str, object]: - self.root.update_idletasks() - window_state = self.root.state() - if window_state == "iconic": - window_state = "normal" - config: dict[str, object] = { - "geometry": self.root.winfo_geometry(), - "state": window_state, - } - if self.main_notebook is not None: - try: - config["active_tab"] = self.main_notebook.index( - self.main_notebook.select() - ) - except tk.TclError: - config["active_tab"] = 0 - if self.workspace_splitter is not None: - config["splitter_sizes"] = [int(size) for size in self.workspace_splitter.sizes()] - return config - - def _save_local_state(self) -> None: - state = { - "version": LOCAL_STATE_VERSION, - "language": self.language, - "last_layout_dir": str(self.last_layout_dir), - "last_report_dir": str(self.last_report_dir), - "last_report_error_limit_deg": self.last_report_error_limit_deg, - "last_pattern_dir": str(self.last_pattern_dir), - "frequency_ghz": _format_frequency_ghz(self.current_frequency_ghz()), - "ambiguity_margin_db": _format_margin_db(self.current_margin_db()), - "dbf_display_mode": self._current_dbf_display_mode(), - "dbf_dictionary": { - "mode": self.dbf_dictionary.mode, - "custom_azimuth_path": ( - self.dbf_dictionary.custom_azimuth_table.source_path - if self.dbf_dictionary.custom_azimuth_table is not None - else "" - ), - "custom_azimuth_channel_mode": ( - self.dbf_dictionary.custom_azimuth_table.channel_mode - if self.dbf_dictionary.custom_azimuth_table is not None - else "" - ), - "custom_elevation_path": ( - self.dbf_dictionary.custom_elevation_table.source_path - if self.dbf_dictionary.custom_elevation_table is not None - else "" - ), - "custom_elevation_channel_mode": ( - self.dbf_dictionary.custom_elevation_table.channel_mode - if self.dbf_dictionary.custom_elevation_table is not None - else "" - ), - "custom_phase_reversed": self.dbf_dictionary.custom_phase_reversed, - "custom_zero_phase_calibrated": ( - self.dbf_dictionary.custom_zero_phase_calibrated - ), - }, - "layout": self._layout_coordinates_config(), - "window": self._window_state_config(), - } - if self.element_pattern is not None and self.element_pattern.source_path: - state["element_pattern_path"] = str(self.element_pattern.source_path) - save_state(state) - LOGGER.info("Saved local state to %s", state_path()) - - def on_close(self) -> None: - try: - report_thread = self._performance_report_thread - if report_thread is not None and report_thread.isRunning(): - report_thread.requestInterruption() - report_thread.quit() - report_thread.wait(30_000) - self.stop_dbf_scan_animation(restore_response=False) - self.stop_dbf2d_animation(update_status=False) - self._save_local_state() - except Exception: - LOGGER.exception("Failed to save local state") - self.root.destroy() - - # ── Event handlers ──────────────────────────────────────────────── - - def on_press(self, event) -> None: # noqa: ANN001 - if event.inaxes != self.physical_ax or event.xdata is None or event.ydata is None: - return - internal_x = _to_internal_half_lambda(event.xdata) - internal_y = _to_internal_half_lambda(event.ydata) - - if self.delete_mode: - element = self._nearest_element(internal_x, internal_y) - if element is None: - self.status.set(self._t("delete_click_element")) - return - self._delete_element(element) - return - - self.dragging = self._nearest_element(internal_x, internal_y) - if self.dragging is not None: - self.drag_start_snapshot = self._capture_layout_snapshot() - self.drag_grab_offset = ( - self.dragging.x - internal_x, - self.dragging.y - internal_y, - ) - x_limits = tuple(float(value) for value in self.physical_ax.get_xlim()) - y_limits = tuple(float(value) for value in self.physical_ax.get_ylim()) - self.drag_axis_limits = (x_limits, y_limits) - self.drag_bounds = _drag_axis_bounds_from_limits(self.drag_axis_limits) - self.selected_element = self.dragging - self.phys_canvas.grab_pointer(self.physical_ax) - self.status.set( - self._t( - "selected_element", - element=self.dragging.name, - x=self.dragging.x * DISPLAY_SCALE_LAMBDA, - y=self.dragging.y * DISPLAY_SCALE_LAMBDA, - ) - ) - self._draw_physical_array() - self.phys_canvas.draw_idle() - elif self.selected_element is not None: - self.drag_start_snapshot = None - self.selected_element = None - self.status.set(self._t("select_element_hint")) - self._draw_physical_array() - self.phys_canvas.draw_idle() - else: - self.drag_start_snapshot = None - - def on_motion(self, event) -> None: # noqa: ANN001 - if self.dbf_drag_mode is not None: - self._set_chart_cursor( - self._chart_for_dbf_mode(self.dbf_drag_mode), "hand2" - ) - self._drag_dbf_true_line(event) - return - - if self.dragging is not None: - if event.x is None or event.y is None: - return - display_x, display_y = self.physical_ax.transData.inverted().transform( - (event.x, event.y) - ) - pointer_x = _to_internal_half_lambda(float(display_x)) - pointer_y = _to_internal_half_lambda(float(display_y)) - internal_x, internal_y = _drag_position_with_offset( - pointer_x, - pointer_y, - self.drag_grab_offset, - None, - ) - if self.drag_bounds is not None: - if self.drag_axis_limits is not None: - expanded_limits = _expanded_physical_drag_limits( - self.drag_axis_limits, - internal_x, - internal_y, - ) - if expanded_limits is not None: - self.drag_axis_limits = expanded_limits - self.drag_bounds = _drag_axis_bounds_from_limits(expanded_limits) - internal_x, internal_y = _drag_position_with_offset( - pointer_x, - pointer_y, - self.drag_grab_offset, - self.drag_bounds, - ) - self.dragging.x = internal_x - self.dragging.y = internal_y - self.status.set( - self._t( - "moving_element", - element=self.dragging.name, - x=self.dragging.x * DISPLAY_SCALE_LAMBDA, - y=self.dragging.y * DISPLAY_SCALE_LAMBDA, - ) - ) - self._schedule_physical_drag_redraw() - return - - self._update_physical_hover(event) - self._update_physical_cursor(event) - self._update_virtual_hover(event) - self._update_response_cursor(event, self.az_chart) - self._update_response_cursor(event, self.el_chart) - self._update_response_hover( - event, self.az_chart, _dbf_short_label("azimuth", self.language) - ) - self._update_response_hover( - event, self.el_chart, _dbf_short_label("elevation", self.language) - ) - - def on_release(self, event) -> None: # noqa: ANN001 - if self.dragging is not None: - self._cancel_physical_drag_redraw() - if self.drag_bounds is not None: - min_x, max_x, min_y, max_y = self.drag_bounds - self.dragging.x = _snap_to_grid_inside( - self.dragging.x, min_x, max_x - ) - self.dragging.y = _snap_to_grid_inside( - self.dragging.y, min_y, max_y - ) - else: - self.dragging.x = snap_to_grid(self.dragging.x) - self.dragging.y = snap_to_grid(self.dragging.y) - self.status.set( - self._t( - "placed_element", - element=self.dragging.name, - x=self.dragging.x * DISPLAY_SCALE_LAMBDA, - y=self.dragging.y * DISPLAY_SCALE_LAMBDA, - ) - ) - current_snapshot = self._capture_layout_snapshot() - if ( - self.drag_start_snapshot is not None - and self.drag_start_snapshot != current_snapshot - ): - self._push_undo_snapshot(self.drag_start_snapshot) - released_axis_limits = ( - None - if _element_touches_drag_bounds(self.dragging, self.drag_bounds) - else self.drag_axis_limits - ) - self.dragging = None - self.drag_bounds = None - self.drag_start_snapshot = None - self.drag_grab_offset = None - try: - self.drag_axis_limits = released_axis_limits - self.generate_virtual_array() - finally: - self.drag_axis_limits = None - self._release_physical_pointer() - self._set_physical_cursor("openhand") - - def on_arrow_key(self, event) -> str | None: - if _event_widget_is_text_input(event): - return None - if self.selected_element is None: - return "break" - - dx = 0.0 - dy = 0.0 - if event.keysym == "Left": - dx = -GRID_STEP - elif event.keysym == "Right": - dx = GRID_STEP - elif event.keysym == "Up": - dy = GRID_STEP - elif event.keysym == "Down": - dy = -GRID_STEP - else: - return "break" - - new_x = snap_to_grid(self.selected_element.x + dx) - new_y = snap_to_grid(self.selected_element.y + dy) - if new_x == self.selected_element.x and new_y == self.selected_element.y: - return "break" - - self._push_undo_snapshot() - self.selected_element.x = new_x - self.selected_element.y = new_y - self.generate_virtual_array() - self.status.set( - self._t( - "selected_element", - element=self.selected_element.name, - x=self.selected_element.x * DISPLAY_SCALE_LAMBDA, - y=self.selected_element.y * DISPLAY_SCALE_LAMBDA, - ) - ) - return "break" - - def on_delete_key(self, event) -> str | None: # noqa: ANN001 - if _event_widget_is_text_input(event): - return None - self.delete_selected_element() - return "break" - - # ── Hover logic ─────────────────────────────────────────────────── - - def _update_virtual_hover(self, event) -> None: # noqa: ANN001 - if self.virtual_hover_annotation is None: - return - if ( - event.inaxes != self.virtual_ax - or event.xdata is None - or event.ydata is None - or len(self.virtual_hover_xy) == 0 - ): - needs_redraw = False - if self.virtual_hover_annotation.get_visible(): - self.virtual_hover_annotation.set_visible(False) - needs_redraw = True - if self.virtual_hover_marker is not None and self.virtual_hover_marker.get_visible(): - self.virtual_hover_marker.set_visible(False) - needs_redraw = True - if needs_redraw: - self.virt_canvas.draw_idle() - return - - x_span = max(abs(np.diff(self.virtual_ax.get_xlim())[0]), 1.0) - y_span = max(abs(np.diff(self.virtual_ax.get_ylim())[0]), 1.0) - normalized_distance = np.hypot( - (self.virtual_hover_xy[:, 0] - event.xdata) / x_span, - (self.virtual_hover_xy[:, 1] - event.ydata) / y_span, - ) - index = int(np.argmin(normalized_distance)) - if normalized_distance[index] > 0.018: - needs_redraw = False - if self.virtual_hover_annotation.get_visible(): - self.virtual_hover_annotation.set_visible(False) - needs_redraw = True - if self.virtual_hover_marker is not None and self.virtual_hover_marker.get_visible(): - self.virtual_hover_marker.set_visible(False) - needs_redraw = True - if needs_redraw: - self.virt_canvas.draw_idle() - return - - xy = self.virtual_hover_xy[index] - if self.virtual_hover_marker is not None: - count = ( - int(self.virtual_hover_counts[index]) - if self.virtual_hover_counts.size > index - else 1 - ) - self.virtual_hover_marker.set_offsets([xy]) - self.virtual_hover_marker.set_sizes([210 + min(max(count - 1, 0), 6) * 36]) - self.virtual_hover_marker.set_visible(True) - self.virtual_hover_annotation.xy = (xy[0], xy[1]) - self.virtual_hover_annotation.set_text(self.virtual_hover_text[index]) - self.virtual_hover_annotation.set_visible(True) - self.virt_canvas.draw_idle() - - def _update_physical_hover(self, event) -> None: # noqa: ANN001 - if self.physical_hover_annotation is None: - return - if event.inaxes != self.physical_ax or event.xdata is None or event.ydata is None: - needs_redraw = False - if self.physical_hover_annotation.get_visible(): - self.physical_hover_annotation.set_visible(False) - needs_redraw = True - if self.physical_hover_marker is not None and self.physical_hover_marker.get_visible(): - self.physical_hover_marker.set_visible(False) - needs_redraw = True - if needs_redraw: - self.phys_canvas.draw_idle() - return - if not self.elements: - needs_redraw = False - if self.physical_hover_annotation.get_visible(): - self.physical_hover_annotation.set_visible(False) - needs_redraw = True - if self.physical_hover_marker is not None and self.physical_hover_marker.get_visible(): - self.physical_hover_marker.set_visible(False) - needs_redraw = True - if needs_redraw: - self.phys_canvas.draw_idle() - return - - internal_x = _to_internal_half_lambda(event.xdata) - internal_y = _to_internal_half_lambda(event.ydata) - distances = np.array( - [ - (element.x - internal_x) ** 2 + (element.y - internal_y) ** 2 - for element in self.elements - ], - dtype=float, - ) - index = int(np.argmin(distances)) - if distances[index] > 2.0: - needs_redraw = False - if self.physical_hover_annotation.get_visible(): - self.physical_hover_annotation.set_visible(False) - needs_redraw = True - if self.physical_hover_marker is not None and self.physical_hover_marker.get_visible(): - self.physical_hover_marker.set_visible(False) - needs_redraw = True - if needs_redraw: - self.phys_canvas.draw_idle() - return - - element = self.elements[index] - display_x = element.x * DISPLAY_SCALE_LAMBDA - display_y = element.y * DISPLAY_SCALE_LAMBDA - if self.physical_hover_marker is not None: - self.physical_hover_marker.set_offsets([[display_x, display_y]]) - self.physical_hover_marker.set_visible(True) - self.physical_hover_annotation.xy = (display_x, display_y) - self.physical_hover_annotation.set_text( - f"{element.name}\nx = {display_x:g} λ\ny = {display_y:g} λ" - ) - self.physical_hover_annotation.set_visible(True) - self.phys_canvas.draw_idle() - - def _hide_dbf2d_hover(self) -> None: - if self.dbf2d_hover_annotation is None: - return - needs_redraw = False - if self.dbf2d_hover_annotation.get_visible(): - self.dbf2d_hover_annotation.set_visible(False) - needs_redraw = True - if ( - self.dbf2d_hover_marker is not None - and self.dbf2d_hover_marker.get_visible() - ): - self.dbf2d_hover_marker.set_visible(False) - needs_redraw = True - if needs_redraw and self.dbf2d_canvas is not None: - self.dbf2d_canvas.draw_idle() - - def _update_dbf2d_hover(self, event) -> None: # noqa: ANN001 - if self.dbf2d_hover_annotation is None: - return - if ( - event.inaxes != self.dbf2d_ax - or event.xdata is None - or event.ydata is None - or self.dbf2d_hover_azimuths.size == 0 - or self.dbf2d_hover_elevations.size == 0 - or self.dbf2d_hover_db.size == 0 - ): - self._hide_dbf2d_hover() - return - - az_index = int(np.argmin(np.abs(self.dbf2d_hover_azimuths - event.xdata))) - el_index = int(np.argmin(np.abs(self.dbf2d_hover_elevations - event.ydata))) - if ( - el_index >= self.dbf2d_hover_db.shape[0] - or az_index >= self.dbf2d_hover_db.shape[1] - ): - self._hide_dbf2d_hover() - return - - azimuth = float(self.dbf2d_hover_azimuths[az_index]) - elevation = float(self.dbf2d_hover_elevations[el_index]) - gain_db = float(self.dbf2d_hover_db[el_index, az_index]) - if self.dbf2d_hover_marker is not None: - self.dbf2d_hover_marker.set_offsets([[azimuth, elevation]]) - self.dbf2d_hover_marker.set_visible(True) - - self.dbf2d_hover_annotation.xy = (float(event.xdata), float(event.ydata)) - x_low, x_high = self.dbf2d_ax.get_xlim() - y_low, y_high = self.dbf2d_ax.get_ylim() - x_frac = (float(event.xdata) - x_low) / (x_high - x_low) if x_high != x_low else 0.5 - y_frac = (float(event.ydata) - y_low) / (y_high - y_low) if y_high != y_low else 0.5 - x_offset = -12 if x_frac > 0.70 else 12 - y_offset = -30 if y_frac > 0.62 else 14 - self.dbf2d_hover_annotation.set_position((x_offset, y_offset)) - self.dbf2d_hover_annotation.set_ha("right" if x_offset < 0 else "left") - self.dbf2d_hover_annotation.set_va("top" if y_offset < 0 else "bottom") - self.dbf2d_hover_annotation.set_text( - self._t( - "dbf2d_hover", - az=azimuth, - el=elevation, - value=self._format_dbf_display_value(gain_db), - ) - ) - self.dbf2d_hover_annotation.set_visible(True) - if self.dbf2d_canvas is not None: - self.dbf2d_canvas.draw_idle() - - def _update_response_hover( - self, event, chart: ResponseChart, label: str # noqa: ANN001 - ) -> None: - """Update hover tooltip for a response chart (Az or El).""" - if chart.hover_annotation is None: - return - if ( - event.inaxes != chart.ax - or event.xdata is None - or event.ydata is None - or chart.hover_db.size == 0 - ): - needs_redraw = False - if chart.hover_annotation.get_visible(): - chart.hover_annotation.set_visible(False) - needs_redraw = True - if chart.hover_marker is not None and chart.hover_marker.get_visible(): - chart.hover_marker.set_visible(False) - needs_redraw = True - if needs_redraw: - chart.canvas.draw_idle() - return - - angle_index = int(np.argmin(np.abs(chart.hover_angles - event.xdata))) - angle = float(chart.hover_angles[angle_index]) - gain_db = float(chart.hover_db[angle_index]) - display_value = self._dbf_display_value(gain_db) - if chart.hover_marker is not None: - chart.hover_marker.set_offsets([[angle, display_value]]) - chart.hover_marker.set_visible(True) - chart.hover_annotation.xy = (float(event.xdata), float(event.ydata)) - x_low, x_high = chart.ax.get_xlim() - y_low, y_high = chart.ax.get_ylim() - x_frac = (float(event.xdata) - x_low) / (x_high - x_low) if x_high != x_low else 0.5 - y_frac = (float(event.ydata) - y_low) / (y_high - y_low) if y_high != y_low else 0.5 - x_offset = -12 if x_frac > 0.72 else 12 - y_offset = -28 if y_frac > 0.60 else 14 - chart.hover_annotation.set_position((x_offset, y_offset)) - chart.hover_annotation.set_ha("right" if x_offset < 0 else "left") - chart.hover_annotation.set_va("top" if y_offset < 0 else "bottom") - chart.hover_annotation.set_text( - f"{label} = {angle:.1f}°\n{self._format_dbf_display_value(gain_db)}" - ) - chart.hover_annotation.set_visible(True) - chart.canvas.draw_idle() - - def _hide_response_hover(self, chart: ResponseChart) -> None: - if chart.hover_annotation is None: - return - needs_redraw = False - if chart.hover_annotation.get_visible(): - chart.hover_annotation.set_visible(False) - needs_redraw = True - if chart.hover_marker is not None and chart.hover_marker.get_visible(): - chart.hover_marker.set_visible(False) - needs_redraw = True - if needs_redraw: - chart.canvas.draw_idle() - - def _nearest_element(self, x: float, y: float) -> EditableElement | None: - if not self.elements: - return None - distances = [ - ((element.x - x) ** 2 + (element.y - y) ** 2, element) - for element in self.elements - ] - distance, element = min(distances, key=lambda item: item[0]) - return element if distance <= 4.0 else None - - -# ═══════════════════════════════════════════════════════════════════════ -# Entry point -# ═══════════════════════════════════════════════════════════════════════ -def main() -> None: - log_path = configure_logging() - install_excepthook() - LOGGER.info("Starting MIMO Array Visualizer") - _qt_app = QtWidgets.QApplication.instance() or QtWidgets.QApplication(sys.argv) - window = QtWidgets.QMainWindow() - root = tk.Tk(window) - apply_native_theme(root._app) - _set_window_icon(root) - root.report_callback_exception = _show_unhandled_tk_exception - root.geometry(f"{WINDOW_WIDTH}x{WINDOW_HEIGHT}") - root.minsize(WINDOW_MIN_WIDTH, WINDOW_MIN_HEIGHT) - LOGGER.info("Log file: %s", log_path) - app = VirtualArrayGui(window) - root.resizable(True, True) - root.protocol("WM_DELETE_WINDOW", app.on_close) - app._schedule_layout_sync() - try: - root.mainloop() - finally: - LOGGER.info("MIMO Array Visualizer exited") - - -if __name__ == "__main__": - main() diff --git a/src/virtual_array/gui_mod.py b/src/virtual_array/gui_mod.py deleted file mode 100644 index 5316bda..0000000 --- a/src/virtual_array/gui_mod.py +++ /dev/null @@ -1,16 +0,0 @@ -"""Compatibility alias for the canonical :mod:`virtual_array.gui` module. - -The former experimental entrypoint is intentionally kept importable while all -implementation and launch paths live in ``virtual_array.gui``. -""" - -from __future__ import annotations - -from . import gui as _implementation - - -for _name in dir(_implementation): - if not _name.startswith("__"): - globals()[_name] = getattr(_implementation, _name) -if __name__ == "__main__": - main() diff --git a/src/virtual_array/native_theme.py b/src/virtual_array/native_theme.py deleted file mode 100644 index 2db141a..0000000 --- a/src/virtual_array/native_theme.py +++ /dev/null @@ -1,833 +0,0 @@ -"""Carbon-led application-wide tokens and native Qt styling. - -The compatibility widgets in :mod:`virtual_array.qt_tk` still generate local -styles, so this module deliberately owns the shared colour, geometry and -interaction vocabulary. Carbon supplies the dense engineering-workbench -structure; Apple principles are retained for immediate, interruptible feedback -and predictable direct manipulation. New native Qt surfaces should use these -tokens and dynamic roles instead of adding one-off stylesheets. -""" - -from __future__ import annotations - -import sys -from dataclasses import dataclass - -from PySide6 import QtCore, QtGui, QtWidgets - - -@dataclass(frozen=True) -class WorkbenchTokens: - """Light tokens for a dense, neutral engineering workstation. - - The names intentionally remain generic because they are consumed by both - the native Qt shell and the Tk-compatible adapter. Values are centralized - here so visual changes remain reliable and inexpensive to maintain. - """ - - canvas: str = "#f4f4f4" - surface: str = "#ffffff" - surface_subtle: str = "#f4f4f4" - surface_muted: str = "#e8e8e8" - surface_hover: str = "#e8e8e8" - surface_pressed: str = "#c6c6c6" - surface_selected: str = "#d0e2ff" - chrome_surface: str = "#ffffff" - border: str = "#e0e0e0" - border_strong: str = "#c6c6c6" - control_border: str = "#8d8d8d" - text: str = "#161616" - text_secondary: str = "#525252" - text_tertiary: str = "#6f6f6f" - accent: str = "#0f62fe" - accent_hover: str = "#0353e9" - accent_pressed: str = "#002d9c" - accent_tint: str = "#d0e2ff" - focus: str = "#0f62fe" - primary_fill: str = "#0f62fe" - primary_hover: str = "#0353e9" - primary_pressed: str = "#002d9c" - success: str = "#198038" - success_fill: str = "#defbe6" - warning: str = "#8e6a00" - warning_fill: str = "#fff8e1" - danger: str = "#da1e28" - danger_fill: str = "#fff1f1" - disabled: str = "#e0e0e0" - radius: int = 4 - card_radius: int = 4 - base_font_pt: int = 10 - caption_font_pt: int = 9 - - -TOKENS = WorkbenchTokens() - -# Compatibility for integrations that imported the old class names directly. -AppleTokens = WorkbenchTokens -FluentTokens = WorkbenchTokens - - -def application_font() -> QtGui.QFont: - """Return the platform system font with reliable CJK fallbacks.""" - - if sys.platform.startswith("win"): - families = [ - "Microsoft YaHei UI", - "Segoe UI Variable Text", - "Segoe UI", - "Microsoft YaHei", - "Noto Sans CJK SC", - ] - elif sys.platform == "darwin": - families = [ - "SF Pro Text", - ".AppleSystemUIFont", - "PingFang SC", - "Heiti SC", - ] - else: - families = [ - "Noto Sans CJK SC", - "Noto Sans", - "DejaVu Sans", - ] - font = QtGui.QFont(families[0]) - if hasattr(font, "setFamilies"): - font.setFamilies(families) - font.setPointSize(TOKENS.base_font_pt) - return font - - -def application_palette() -> QtGui.QPalette: - """Build a complete light palette for controls not covered by QSS.""" - - t = TOKENS - palette = QtGui.QPalette() - palette.setColor(QtGui.QPalette.ColorRole.Window, QtGui.QColor(t.canvas)) - palette.setColor(QtGui.QPalette.ColorRole.WindowText, QtGui.QColor(t.text)) - palette.setColor(QtGui.QPalette.ColorRole.Base, QtGui.QColor(t.surface)) - palette.setColor(QtGui.QPalette.ColorRole.AlternateBase, QtGui.QColor(t.surface_subtle)) - palette.setColor(QtGui.QPalette.ColorRole.ToolTipBase, QtGui.QColor(t.text)) - palette.setColor(QtGui.QPalette.ColorRole.ToolTipText, QtGui.QColor("#ffffff")) - palette.setColor(QtGui.QPalette.ColorRole.Text, QtGui.QColor(t.text)) - palette.setColor(QtGui.QPalette.ColorRole.Button, QtGui.QColor(t.surface)) - palette.setColor(QtGui.QPalette.ColorRole.ButtonText, QtGui.QColor(t.text)) - palette.setColor(QtGui.QPalette.ColorRole.Highlight, QtGui.QColor(t.accent_tint)) - palette.setColor(QtGui.QPalette.ColorRole.HighlightedText, QtGui.QColor(t.text)) - palette.setColor( - QtGui.QPalette.ColorGroup.Disabled, - QtGui.QPalette.ColorRole.Text, - QtGui.QColor(t.text_tertiary), - ) - palette.setColor( - QtGui.QPalette.ColorGroup.Disabled, - QtGui.QPalette.ColorRole.ButtonText, - QtGui.QColor(t.text_tertiary), - ) - return palette - - -def application_stylesheet() -> str: - t = TOKENS - return f""" - QMainWindow {{ - background: {t.canvas}; - color: {t.text}; - }} - QDialog, QMessageBox, QProgressDialog {{ - background: {t.surface}; - color: {t.text}; - }} - QWidget {{ - color: {t.text}; - selection-background-color: {t.surface_selected}; - selection-color: {t.text}; - }} - QFrame[surfaceRole="card"] {{ - background: {t.surface}; - border: 1px solid {t.border}; - border-radius: {t.card_radius}px; - }} - QLabel[fluentRole="caption"] {{ - color: {t.text_secondary}; - font-size: {t.caption_font_pt}pt; - }} - QLabel[fluentRole="muted"] {{ color: {t.text_secondary}; }} - QLabel[fluentRole="success"] {{ color: {t.success}; }} - QLabel[fluentRole="warning"] {{ color: {t.warning}; }} - QLabel[fluentRole="danger"] {{ color: {t.danger}; }} - QLabel[fluentRole="callout-neutral"] {{ - background: {t.surface_subtle}; - color: {t.text_secondary}; - border: 1px solid {t.border}; - border-radius: {t.radius}px; - padding: 8px 10px; - }} - QLabel[fluentRole="callout-success"] {{ - background: {t.success_fill}; - color: {t.success}; - border: 1px solid #9ac5a2; - border-radius: {t.radius}px; - padding: 8px 10px; - }} - QLabel[fluentRole="callout-warning"] {{ - background: {t.warning_fill}; - color: {t.warning}; - border: 1px solid #d6b766; - border-radius: {t.radius}px; - padding: 8px 10px; - }} - QLabel[fluentRole="callout-danger"] {{ - background: {t.danger_fill}; - color: {t.danger}; - border: 1px solid #e5a1aa; - border-radius: {t.radius}px; - padding: 8px 10px; - }} - - QMenuBar {{ - background: {t.chrome_surface}; - border-bottom: 1px solid {t.border}; - min-height: 28px; - padding: 1px 14px; - spacing: 4px; - }} - QMenuBar::item {{ - background: transparent; - border-radius: 2px; - padding: 4px 10px; - }} - QMenuBar::item:selected {{ - background: {t.surface_hover}; - color: {t.accent_pressed}; - }} - QMenuBar::item:pressed {{ background: {t.surface_pressed}; }} - QMenu {{ - background: {t.surface}; - border: 1px solid {t.border_strong}; - border-radius: {t.radius}px; - padding: 4px; - }} - QMenu::item {{ - border-radius: 2px; - padding: 7px 34px 7px 11px; - }} - QMenu::item:selected {{ - background: {t.surface_selected}; - color: {t.accent_pressed}; - }} - QMenu::separator {{ - height: 1px; - background: {t.border}; - margin: 5px 8px; - }} - - QPushButton, QToolButton {{ - min-height: 32px; - background: {t.surface}; - border: 1px solid {t.control_border}; - border-radius: {t.radius}px; - padding: 1px 13px; - }} - QPushButton:hover, QToolButton:hover {{ - background: {t.surface_hover}; - border-color: {t.control_border}; - }} - QPushButton:pressed, QToolButton:pressed {{ - background: {t.surface_pressed}; - border-color: {t.accent_pressed}; - }} - QPushButton:checked, QToolButton:checked, - QPushButton[fluentState="active"], QToolButton[fluentState="active"] {{ - background: {t.accent_tint}; - border-color: {t.accent}; - color: {t.accent_pressed}; - font-weight: 600; - }} - QPushButton:focus, QToolButton:focus, - QLineEdit:focus, QComboBox:focus, QSpinBox:focus, QDoubleSpinBox:focus, - QAbstractItemView:focus {{ - border: 2px solid {t.focus}; - }} - QPushButton:disabled, QToolButton:disabled {{ - background: {t.disabled}; - border-color: {t.border}; - color: {t.text_tertiary}; - }} - QPushButton[fluentRole="primary"], QToolButton[fluentRole="primary"] {{ - min-height: 32px; - background: {t.primary_fill}; - border-color: {t.primary_fill}; - color: white; - font-weight: 600; - }} - QPushButton[fluentRole="primary"]:hover, - QToolButton[fluentRole="primary"]:hover {{ - background: {t.primary_hover}; - border-color: {t.primary_hover}; - }} - QPushButton[fluentRole="primary"]:pressed, - QToolButton[fluentRole="primary"]:pressed {{ - background: {t.primary_pressed}; - border-color: {t.primary_pressed}; - }} - QPushButton[fluentRole="danger"] {{ - color: {t.danger}; - border-color: #e5a1aa; - }} - QPushButton[fluentRole="danger"]:hover {{ background: {t.danger_fill}; }} - QPushButton[fluentRole="quiet"], QToolButton[fluentRole="quiet"] {{ - background: transparent; - border-color: transparent; - color: {t.text_secondary}; - }} - QPushButton[fluentRole="quiet"]:hover, QToolButton[fluentRole="quiet"]:hover {{ - background: {t.surface_hover}; - color: {t.text}; - }} - - QLineEdit, QComboBox, QSpinBox, QDoubleSpinBox {{ - min-height: 32px; - background: {t.surface}; - border: 1px solid {t.control_border}; - border-radius: 2px; - padding: 1px 9px; - }} - QLineEdit:hover, QComboBox:hover, QSpinBox:hover, QDoubleSpinBox:hover {{ - border-color: {t.accent}; - }} - QLineEdit:disabled, QComboBox:disabled, QSpinBox:disabled, QDoubleSpinBox:disabled {{ - background: {t.disabled}; - border-color: {t.border}; - color: {t.text_tertiary}; - }} - QComboBox::drop-down {{ border: 0; width: 28px; }} - QComboBox QAbstractItemView {{ - background: {t.surface}; - border: 1px solid {t.control_border}; - selection-background-color: {t.surface_selected}; - outline: 0; - }} - QCheckBox, QRadioButton {{ spacing: 7px; }} - QCheckBox:hover, QRadioButton:hover {{ color: {t.accent_pressed}; }} - - QGroupBox {{ - background: {t.surface}; - border: 1px solid {t.border}; - border-radius: {t.card_radius}px; - margin-top: 15px; - padding: 13px 11px 11px 11px; - font-weight: 600; - }} - QGroupBox::title {{ - subcontrol-origin: margin; - left: 12px; - padding: 0 5px; - color: {t.text_secondary}; - }} - - QDialog[workbenchRole="dialog-shell"] {{ - background: {t.canvas}; - }} - QWidget[workbenchRole="dialog-rail"] {{ - background: {t.canvas}; - border: 0; - border-radius: 0; - }} - QGroupBox[workbenchRole="dialog-rail"] {{ - background: {t.canvas}; - border: 0; - border-radius: 0; - margin-top: 18px; - padding: 12px 8px 8px 8px; - }} - QWidget[workbenchRole="dialog-header"] {{ - background: {t.surface}; - border: 0; - border-bottom: 1px solid {t.border}; - border-radius: 0; - }} - QWidget[workbenchRole="dialog-content"] {{ - background: {t.surface}; - border: 0; - border-radius: 0; - }} - QGroupBox[workbenchRole="dialog-section"] {{ - background: {t.surface}; - border: 0; - border-top: 1px solid {t.border}; - border-radius: 0; - margin-top: 19px; - padding: 14px 12px 10px 12px; - }} - QGroupBox[workbenchRole="dialog-section"]::title, - QGroupBox[workbenchRole="dialog-rail"]::title {{ - subcontrol-origin: margin; - left: 8px; - padding: 0 4px; - color: {t.text}; - background: transparent; - font-weight: 600; - }} - QWidget[workbenchRole="dialog-footer"] {{ - background: {t.canvas}; - border: 0; - border-top: 1px solid {t.border}; - border-radius: 0; - }} - QTextBrowser[workbenchRole="dialog-content"], - QListView[workbenchRole="dialog-content"], - QTableView[workbenchRole="dialog-content"] {{ - background: {t.surface}; - border: 0; - border-radius: 0; - }} - QTabWidget::pane {{ - background: {t.surface}; - border: 1px solid {t.border}; - border-radius: 0; - }} - QTabBar::tab {{ - min-height: 32px; - min-width: 104px; - background: transparent; - color: {t.text_secondary}; - border: 1px solid transparent; - border-radius: 0; - padding: 0 14px; - margin: 2px; - font-weight: 600; - }} - QTabBar::tab:selected {{ - background: {t.surface}; - color: {t.text}; - border-color: {t.border}; - }} - QTabBar::tab:hover:!selected {{ - background: {t.surface_hover}; - color: {t.text}; - }} - - QTableView, QTreeView, QListView, QTextBrowser, QPlainTextEdit, QTextEdit {{ - background: {t.surface}; - alternate-background-color: {t.surface_subtle}; - border: 1px solid {t.control_border}; - border-radius: 0; - gridline-color: {t.border}; - outline: 0; - }} - QTableView::item, QTreeView::item, QListView::item {{ - min-height: 32px; - padding: 2px 7px; - border-bottom: 1px solid {t.border}; - }} - QTableView::item:hover, QTreeView::item:hover, QListView::item:hover {{ - background: {t.surface_hover}; - }} - QTableView::item:selected, QTreeView::item:selected, QListView::item:selected {{ - background: {t.surface_selected}; - color: {t.accent_pressed}; - border-bottom: 1px solid {t.accent}; - font-weight: 600; - }} - QHeaderView::section {{ - min-height: 32px; - background: {t.surface_muted}; - color: {t.text_secondary}; - border: 0; - border-right: 1px solid {t.border}; - border-bottom: 1px solid {t.border_strong}; - padding: 2px 8px; - font-weight: 600; - }} - QTextBrowser, QPlainTextEdit, QTextEdit {{ padding: 8px; }} - - QScrollBar:vertical {{ - background: transparent; - width: 9px; - margin: 2px; - }} - QScrollBar::handle:vertical {{ - background: {t.border_strong}; - min-height: 28px; - border-radius: 4px; - }} - QScrollBar::handle:vertical:hover {{ background: {t.control_border}; }} - QScrollBar:horizontal {{ - background: transparent; - height: 9px; - margin: 2px; - }} - QScrollBar::handle:horizontal {{ - background: {t.border_strong}; - min-width: 28px; - border-radius: 4px; - }} - QScrollBar::handle:horizontal:hover {{ background: {t.control_border}; }} - QScrollBar::add-line, QScrollBar::sub-line {{ width: 0; height: 0; }} - QScrollBar::add-page, QScrollBar::sub-page {{ background: transparent; }} - - QStatusBar {{ - background: {t.chrome_surface}; - border-top: 1px solid {t.border}; - color: {t.text_secondary}; - min-height: 24px; - max-height: 24px; - padding-left: 8px; - }} - QStatusBar::item {{ border: 0; }} - QSplitter::handle {{ background: transparent; }} - QSplitter::handle:horizontal {{ width: 8px; }} - QSplitter::handle:vertical {{ height: 8px; }} - QSplitter::handle:hover {{ - background: {t.surface_selected}; - border-radius: 4px; - }} - QProgressBar {{ - min-height: 8px; - max-height: 8px; - background: {t.surface_muted}; - border: 0; - border-radius: 4px; - text-align: center; - }} - QProgressBar::chunk {{ - background: {t.accent}; - border-radius: 4px; - }} - QProgressBar[workbenchRole="report-progress"] {{ - min-height: 12px; - max-height: 12px; - background: {t.surface_muted}; - border: 1px solid {t.border_strong}; - border-radius: 6px; - text-align: center; - }} - QProgressBar[workbenchRole="report-progress"]::chunk {{ - background: {t.accent}; - border: 0; - border-radius: 5px; - }} - QLabel[workbenchRole="progress-status"] {{ - color: {t.text}; - font-size: {t.base_font_pt}pt; - font-weight: 500; - padding: 0 4px; - }} - QToolTip {{ - background: {t.text}; - color: white; - border: 0; - border-radius: 8px; - padding: 7px 10px; - }} - """ - - -class _InteractiveCursorPolicy(QtCore.QObject): - """Keep click affordances consistent for current and future Qt widgets.""" - - _SYNC_EVENTS = { - QtCore.QEvent.Type.EnabledChange, - QtCore.QEvent.Type.Enter, - QtCore.QEvent.Type.MouseMove, - QtCore.QEvent.Type.Polish, - QtCore.QEvent.Type.Show, - } - - @staticmethod - def _set_shape(widget: QtWidgets.QWidget, pointing: bool) -> None: - shape = ( - QtCore.Qt.CursorShape.PointingHandCursor - if pointing - else QtCore.Qt.CursorShape.ArrowCursor - ) - if widget.cursor().shape() != shape: - widget.setCursor(QtGui.QCursor(shape)) - - @staticmethod - def _event_position( - widget: QtWidgets.QWidget, event: QtCore.QEvent | None - ) -> QtCore.QPoint: - if isinstance(event, QtGui.QMouseEvent): - return event.position().toPoint() - return widget.mapFromGlobal(QtGui.QCursor.pos()) - - @classmethod - def _sync_tab_bar( - cls, tab_bar: QtWidgets.QTabBar, event: QtCore.QEvent | None - ) -> None: - tab_bar.setMouseTracking(True) - index = tab_bar.tabAt(cls._event_position(tab_bar, event)) - cls._set_shape( - tab_bar, - tab_bar.isEnabled() - and index >= 0 - and tab_bar.isTabEnabled(index), - ) - - @classmethod - def _sync_menu( - cls, - menu: QtWidgets.QMenu | QtWidgets.QMenuBar, - event: QtCore.QEvent | None, - ) -> None: - menu.setMouseTracking(True) - action = menu.actionAt(cls._event_position(menu, event)) - cls._set_shape( - menu, - menu.isEnabled() - and action is not None - and action.isEnabled() - and not action.isSeparator(), - ) - - @classmethod - def _sync_spin_box( - cls, spin: QtWidgets.QAbstractSpinBox, event: QtCore.QEvent | None - ) -> None: - spin.setMouseTracking(True) - option = QtWidgets.QStyleOptionSpinBox() - spin.initStyleOption(option) - sub_control = spin.style().hitTestComplexControl( - QtWidgets.QStyle.ComplexControl.CC_SpinBox, - option, - cls._event_position(spin, event), - spin, - ) - pointing = ( - spin.isEnabled() - and not spin.isReadOnly() - and sub_control - in { - QtWidgets.QStyle.SubControl.SC_SpinBoxUp, - QtWidgets.QStyle.SubControl.SC_SpinBoxDown, - } - ) - cls._set_shape(spin, pointing) - - @classmethod - def _sync_item_viewport( - cls, viewport: QtWidgets.QWidget, event: QtCore.QEvent | None - ) -> bool: - view = viewport.parentWidget() - if not isinstance(view, QtWidgets.QAbstractItemView): - return False - if not bool(view.property("pointingHandItems")) or viewport is not view.viewport(): - return False - viewport.setMouseTracking(True) - index = view.indexAt(cls._event_position(viewport, event)) - flags = index.flags() if index.isValid() else QtCore.Qt.ItemFlag.NoItemFlags - pointing = ( - view.isEnabled() - and index.isValid() - and bool(flags & QtCore.Qt.ItemFlag.ItemIsEnabled) - and bool(flags & QtCore.Qt.ItemFlag.ItemIsSelectable) - and not bool(flags & QtCore.Qt.ItemFlag.ItemIsEditable) - ) - cls._set_shape(viewport, pointing) - return True - - @classmethod - def sync_widget( - cls, widget: QtWidgets.QWidget, event: QtCore.QEvent | None = None - ) -> None: - if bool(widget.property("preserveCursor")): - return - if isinstance(widget, QtWidgets.QTabBar): - cls._sync_tab_bar(widget, event) - elif isinstance(widget, (QtWidgets.QMenu, QtWidgets.QMenuBar)): - cls._sync_menu(widget, event) - elif isinstance(widget, QtWidgets.QAbstractSpinBox): - cls._sync_spin_box(widget, event) - elif cls._sync_item_viewport(widget, event): - return - elif isinstance( - widget, - ( - QtWidgets.QAbstractButton, - QtWidgets.QComboBox, - QtWidgets.QSlider, - ), - ): - cls._set_shape(widget, widget.isEnabled()) - - def eventFilter( - self, watched: QtCore.QObject, event: QtCore.QEvent - ) -> bool: # noqa: N802 - if ( - isinstance(watched, QtWidgets.QWidget) - and event.type() in self._SYNC_EVENTS - ): - self.sync_widget(watched, event) - return False - - -def install_interactive_cursor_policy(app: QtWidgets.QApplication) -> None: - """Install one state-aware pointer policy across native and wrapped Qt UI.""" - - policy = getattr(app, "_workbench_interactive_cursor_policy", None) - if not isinstance(policy, _InteractiveCursorPolicy): - policy = _InteractiveCursorPolicy(app) - app.installEventFilter(policy) - app._workbench_interactive_cursor_policy = policy # type: ignore[attr-defined] - for widget in app.allWidgets(): - policy.sync_widget(widget) - - -def apply_native_theme(app: QtWidgets.QApplication) -> None: - """Apply one deterministic Carbon-led light theme application-wide.""" - - if "Fusion" in QtWidgets.QStyleFactory.keys(): - app.setStyle("Fusion") - app.setFont(application_font()) - app.setPalette(application_palette()) - app.setStyleSheet(application_stylesheet()) - install_interactive_cursor_policy(app) - - -def _repolish(widget: QtWidgets.QWidget) -> None: - widget.style().unpolish(widget) - widget.style().polish(widget) - widget.update() - - -def mark_primary(widget: QtWidgets.QWidget) -> None: - """Give a button the single primary-action treatment. - - A local rule is retained for compatibility buttons whose generated widget - stylesheet would otherwise outrank the application property selector. - """ - - widget.setProperty("fluentRole", "primary") - if not widget.objectName(): - widget.setObjectName(f"fluentPrimary_{id(widget)}") - selector = f"#{widget.objectName()}" - local_rules = f""" - {selector} {{ - min-height: 32px; - background: {TOKENS.primary_fill}; - border: 1px solid {TOKENS.primary_fill}; - border-radius: {TOKENS.radius}px; - color: white; - font-weight: 600; - }} - {selector}:hover {{ - background: {TOKENS.primary_hover}; - border-color: {TOKENS.primary_hover}; - }} - {selector}:pressed {{ - background: {TOKENS.primary_pressed}; - border-color: {TOKENS.primary_pressed}; - }} - {selector}:disabled {{ - background: {TOKENS.disabled}; - border-color: {TOKENS.border}; - color: {TOKENS.text_tertiary}; - }} - {selector}:focus {{ border: 2px solid {TOKENS.focus}; }} - """ - widget.setStyleSheet(f"{widget.styleSheet()}\n{local_rules}") - _repolish(widget) - - -def mark_danger(widget: QtWidgets.QWidget) -> None: - widget.setProperty("fluentRole", "danger") - _repolish(widget) - - -def mark_quiet(widget: QtWidgets.QWidget) -> None: - widget.setProperty("fluentRole", "quiet") - _repolish(widget) - - -def mark_workbench_role(widget: QtWidgets.QWidget, role: str) -> None: - """Apply one shared region role used by every custom workbench dialog.""" - - normalized = role if role in { - "dialog-shell", - "dialog-rail", - "dialog-header", - "dialog-content", - "dialog-section", - "dialog-footer", - "progress-dialog", - "progress-status", - "report-progress", - } else "dialog-content" - widget.setProperty("workbenchRole", normalized) - _repolish(widget) - - -def mark_callout(widget: QtWidgets.QWidget, role: str) -> None: - """Apply a semantic, non-blocking callout treatment to a label.""" - - normalized = role if role in {"neutral", "success", "warning", "danger"} else "neutral" - widget.setProperty("fluentRole", f"callout-{normalized}") - palette = { - "neutral": (TOKENS.surface_subtle, TOKENS.text_secondary, TOKENS.border), - "success": (TOKENS.success_fill, TOKENS.success, "#9ac5a2"), - "warning": (TOKENS.warning_fill, TOKENS.warning, "#d6b766"), - "danger": (TOKENS.danger_fill, TOKENS.danger, "#e5a1aa"), - } - fill, color, border = palette[normalized] - if not widget.objectName(): - widget.setObjectName(f"fluentCallout_{id(widget)}") - base_stylesheet = widget.property("fluentCalloutBaseStyleSheet") - if base_stylesheet is None: - base_stylesheet = widget.styleSheet() - widget.setProperty("fluentCalloutBaseStyleSheet", base_stylesheet) - selector = f"#{widget.objectName()}" - widget.setStyleSheet( - f"{base_stylesheet}\n{selector} {{ background: {fill}; color: {color}; " - f"border: 1px solid {border}; border-radius: {TOKENS.radius}px; " - "padding: 8px 10px; }}" - ) - _repolish(widget) - - -def fit_dialog_to_parent( - dialog: QtWidgets.QDialog, - parent: QtWidgets.QWidget | None, - *, - preferred_size: tuple[int, int], - minimum_size: tuple[int, int] = (620, 440), - margin: int = 24, -) -> QtCore.QRect: - """Size and centre a dialog inside both its parent and working screen. - - This keeps configuration windows usable after DPI, monitor or remote - desktop changes. The requested minimum is itself clamped instead of - forcing the top-level window outside a small workspace. - """ - - screen = dialog.screen() or QtGui.QGuiApplication.primaryScreen() - if screen is None: - target = QtCore.QRect(0, 0, *preferred_size) - else: - available = screen.availableGeometry().adjusted(margin, margin, -margin, -margin) - bounds = QtCore.QRect(available) - if parent is not None and parent.isVisible(): - parent_bounds = parent.frameGeometry().adjusted( - margin, margin, -margin, -margin - ) - intersection = bounds.intersected(parent_bounds) - if intersection.width() >= 480 and intersection.height() >= 360: - bounds = intersection - - width = max(360, min(int(preferred_size[0]), bounds.width())) - height = max(300, min(int(preferred_size[1]), bounds.height())) - target = QtCore.QRect(0, 0, width, height) - target.moveCenter(bounds.center()) - if target.left() < bounds.left(): - target.moveLeft(bounds.left()) - if target.top() < bounds.top(): - target.moveTop(bounds.top()) - - dialog.setMinimumSize( - min(int(minimum_size[0]), target.width()), - min(int(minimum_size[1]), target.height()), - ) - dialog.resize(target.size()) - dialog.move(target.topLeft()) - return target diff --git a/src/virtual_array/performance_report_dialog.py b/src/virtual_array/performance_report_dialog.py deleted file mode 100644 index 914a7dd..0000000 --- a/src/virtual_array/performance_report_dialog.py +++ /dev/null @@ -1,900 +0,0 @@ -from __future__ import annotations - -from datetime import datetime -from pathlib import Path -from typing import TYPE_CHECKING, Any - -from PySide6 import QtCore, QtWidgets - -from .native_theme import TOKENS, mark_primary, mark_workbench_role -from .performance_report import MAX_HOLD_STRIDE_FRAMES, hold_curve_frame_count -from .qt_tk import AppleSwitch - -if TYPE_CHECKING: - from .performance_report import AngleErrorImageOptions, PerformanceReportOptions - - -_SUPPORTED_LANGUAGES = {"zh", "en", "ja"} - -_TEXT = { - "dialog_title": { - "zh": "输出当前配置性能报告", - "en": "Export Current Configuration Performance Report", - "ja": "現在構成の性能レポートを出力", - }, - "output_group": {"zh": "报告文件", "en": "Report file", "ja": "レポートファイル"}, - "output_path": {"zh": "PDF 路径", "en": "PDF path", "ja": "PDF パス"}, - "browse": {"zh": "浏览…", "en": "Browse…", "ja": "参照…"}, - "pdf_filter": { - "zh": "PDF 报告 (*.pdf);;所有文件 (*)", - "en": "PDF report (*.pdf);;All files (*)", - "ja": "PDF レポート (*.pdf);;すべてのファイル (*)", - }, - "browse_title": { - "zh": "选择性能报告保存位置", - "en": "Choose performance report location", - "ja": "性能レポートの保存先を選択", - }, - "report_title": {"zh": "报告标题", "en": "Report title", "ja": "レポートタイトル"}, - "default_report_title": { - "zh": "当前配置测角性能报告", - "en": "Current Configuration Angle Performance Report", - "ja": "現在構成の測角性能レポート", - }, - "axis_group": { - "zh": "{axis}测角范围{availability}", - "en": "{axis} angle ranges{availability}", - "ja": "{axis}測角範囲{availability}", - }, - "unavailable_suffix": { - "zh": "(当前配置不可用)", - "en": " (unavailable for this configuration)", - "ja": "(現在の構成では利用不可)", - }, - "azimuth": {"zh": "方位", "en": "Azimuth", "ja": "方位"}, - "elevation": {"zh": "俯仰", "en": "Elevation", "ja": "仰角"}, - "focus_range": { - "zh": "性能关注真角范围", - "en": "Performance focus", - "ja": "性能評価する真角度範囲", - }, - "hold_range": { - "zh": "角谱 Hold 真角范围", - "en": "Spectrum Hold frames", - "ja": "角度スペクトル Hold 真角度範囲", - }, - "to": {"zh": "至", "en": "to", "ja": "~"}, - "follow_focus": { - "zh": "Hold 跟随关注范围", - "en": "Match focus range", - "ja": "評価範囲に連動", - }, - "hold_curve_stride": { - "zh": "Hold 曲线间隔", - "en": "Curve interval", - "ja": "Hold 曲線間隔", - }, - "hold_curve_stride_tooltip": { - "zh": "当前真实角网格为 1°/帧。1° 表示全部帧;大于 1° 时按间隔绘制,并始终保留范围起止帧。", - "en": "The current true-angle grid is 1 deg per frame. Use 1 deg for every frame; larger intervals retain both range endpoints.", - "ja": "現在の真角度グリッドは1°/フレームです。1°は全フレームを描画し、それ以上では範囲両端を保持します。", - }, - "frame_count": { - "zh": "范围内 {range_count} 帧;每 {step}°({step} 帧)绘制 1 条,共 {curve_count} 条;起止角均保留。", - "en": "{range_count} frames in range; plot every {step} deg ({step} frames): {curve_count} curves; endpoints retained.", - "ja": "範囲内 {range_count} フレーム;{step}°({step} フレーム)ごとに描画し、計 {curve_count} 本;両端を保持。", - }, - "azimuth_plane_note": { - "zh": "方位 1D DBF 角谱使用主平面切面:俯仰真实角固定为 0°。", - "en": "Azimuth 1D DBF uses the principal-plane cut with true elevation fixed at 0 deg.", - "ja": "方位 1D DBF は主平面カットを使用し、真の仰角を 0° に固定します。", - }, - "elevation_plane_note": { - "zh": "俯仰 1D DBF 角谱使用主平面切面:方位真实角固定为 0°。", - "en": "Elevation 1D DBF uses the principal-plane cut with true azimuth fixed at 0 deg.", - "ja": "仰角 1D DBF は主平面カットを使用し、真の方位角を 0° に固定します。", - }, - "settings_group": { - "zh": "性能判据与数据", - "en": "Criteria and data", - "ja": "性能判定基準とデータ", - }, - "error_limit": { - "zh": "测角误差门限", - "en": "Angle-error limit", - "ja": "測角誤差しきい値", - }, - "spectrum_floor": { - "zh": "dB 图显示下限", - "en": "dB display floor", - "ja": "dB 角度スペクトル表示下限", - }, - "spectrum_vertical_scale": { - "zh": "角谱输出(可多选)", - "en": "Spectrum pages (select one or both)", - "ja": "角度スペクトル出力(複数選択可)", - }, - "spectrum_scale_tooltip": { - "zh": "可同时开启:报告将分别输出 dB 角谱页和归一化模值角谱页。", - "en": "Both may be enabled; the report then adds separate dB and normalized-magnitude spectrum pages.", - "ja": "両方を有効にすると、dB角度スペクトルと正規化振幅スペクトルを別ページで出力します。", - }, - "spectrum_db": { - "zh": "dB", - "en": "dB", - "ja": "dB", - }, - "spectrum_magnitude": { - "zh": "模值", - "en": "Magnitude", - "ja": "振幅値", - }, - "include_raw": { - "zh": "导出 CSV/JSON 数据", - "en": "CSV/JSON data", - "ja": "CSV/JSON データ", - }, - "criteria_note": { - "zh": "关注范围用于性能统计;Hold 范围与曲线间隔控制叠加图密度。Max-Hold 包络及 CSV/JSON 数据仍使用范围内全部帧。", - "en": "The focus range drives performance metrics; the Hold range and curve interval control overlay density. Max-hold and CSV/JSON data still use every in-range frame.", - "ja": "評価範囲は性能統計に使用し、Hold範囲と曲線間隔は重ね合わせ密度を制御します。Max-HoldとCSV/JSONは範囲内全フレームを使用します。", - }, - "save_angle_image": { - "zh": "仅输出测角误差 PNG", - "en": "Export Angle-error PNG Only", - "ja": "測角誤差 PNG のみ出力", - }, - "save_angle_image_tooltip": { - "zh": "使用当前误差门限,保存到 PDF 路径所在目录,文件名追加 _angle_error。", - "en": "Use the current error limit and save beside the PDF path with _angle_error appended.", - "ja": "現在の誤差しきい値を使用し、PDF パスと同じフォルダーへ _angle_error を付けて保存します。", - }, - "validation_path": { - "zh": "请选择 PDF 报告的输出路径。", - "en": "Choose an output path for the PDF report.", - "ja": "PDF レポートの出力先を選択してください。", - }, - "validation_range": { - "zh": "{axis}的{kind}起始角不能大于终止角。", - "en": "The {axis} {kind} start angle must not exceed its stop angle.", - "ja": "{axis}の{kind}開始角度は終了角度以下にしてください。", - }, - "focus_kind": {"zh": "关注范围", "en": "focus range", "ja": "評価範囲"}, - "hold_kind": {"zh": "Hold 范围", "en": "Hold range", "ja": "Hold 範囲"}, - "validation_no_axis": { - "zh": "当前配置不具备方位或俯仰测角能力,无法生成性能报告。", - "en": "This configuration has no azimuth or elevation angle capability.", - "ja": "現在の構成には方位・仰角の測角能力がないため、レポートを生成できません。", - }, - "validation_spectrum_scale": { - "zh": "角谱纵坐标至少选择一种:dB 或模值。", - "en": "Select at least one spectrum vertical scale: dB or magnitude.", - "ja": "角度スペクトルの縦軸を少なくとも 1 つ選択してください:dB または振幅値。", - }, - "save": {"zh": "输出报告", "en": "Export report", "ja": "レポートを出力"}, - "cancel": {"zh": "取消", "en": "Cancel", "ja": "キャンセル"}, -} - - -def _text(key: str, language: str, **values: Any) -> str: - translations = _TEXT[key] - template = translations.get(language, translations["zh"]) - return template.format(**values) - - -class PerformanceReportDialog(QtWidgets.QDialog): - """Collect performance-report settings without performing any file I/O.""" - - export_requested = QtCore.Signal(str) - - def __init__( - self, - parent: QtWidgets.QWidget | None, - *, - language: str, - initial_directory: Path, - azimuth_available: bool, - elevation_available: bool, - initial_error_limit_deg: float = 1.0, - ) -> None: - super().__init__(parent) - self.setObjectName("performanceReportDialog") - mark_workbench_role(self, "dialog-shell") - - self.language = language if language in _SUPPORTED_LANGUAGES else "zh" - self._azimuth_available = bool(azimuth_available) - self._elevation_available = bool(elevation_available) - self._initial_directory = Path(initial_directory).expanduser() - try: - parsed_error_limit = float(initial_error_limit_deg) - except (TypeError, ValueError): - parsed_error_limit = 1.0 - if not 0.1 <= parsed_error_limit <= 30.0: - parsed_error_limit = 1.0 - self._initial_error_limit_deg = parsed_error_limit - self._selected_export_kind = "report" - self._export_busy = False - - self.setWindowTitle(_text("dialog_title", self.language)) - self.setModal(True) - self.setMinimumWidth(820) - - self._build_ui() - self._connect_signals() - self._sync_hold_range("az") - self._sync_hold_range("el") - self._update_frame_count("az") - self._update_frame_count("el") - self._refresh_validation() - - def _build_ui(self) -> None: - layout = QtWidgets.QVBoxLayout(self) - layout.setContentsMargins(16, 16, 16, 12) - layout.setSpacing(10) - - workspace = QtWidgets.QWidget(self) - workspace.setObjectName("performanceReportWorkspace") - workspace_layout = QtWidgets.QGridLayout(workspace) - workspace_layout.setContentsMargins(0, 0, 0, 0) - workspace_layout.setHorizontalSpacing(16) - workspace_layout.setVerticalSpacing(0) - workspace_layout.setColumnStretch(1, 1) - - rail = QtWidgets.QScrollArea(workspace) - rail.setObjectName("performanceReportRail") - mark_workbench_role(rail, "dialog-rail") - rail.setFrameShape(QtWidgets.QFrame.Shape.NoFrame) - rail.setWidgetResizable(True) - rail.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - rail.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAsNeeded) - rail.viewport().setAutoFillBackground(False) - rail_width = 340 - rail.setMinimumWidth(rail_width) - rail.setMaximumWidth(360) - - rail_content = QtWidgets.QWidget(rail) - rail_content.setObjectName("performanceReportRailContent") - mark_workbench_role(rail_content, "dialog-rail") - rail_layout = QtWidgets.QVBoxLayout(rail_content) - rail_layout.setContentsMargins(0, 0, 0, 0) - rail_layout.setSpacing(8) - rail.setWidget(rail_content) - - content_panel = QtWidgets.QWidget(workspace) - content_panel.setObjectName("performanceReportContent") - mark_workbench_role(content_panel, "dialog-content") - content_layout = QtWidgets.QVBoxLayout(content_panel) - content_layout.setContentsMargins(12, 10, 12, 10) - content_layout.setSpacing(10) - - workspace_layout.addWidget(rail, 0, 0) - workspace_layout.addWidget(content_panel, 0, 1) - layout.addWidget(workspace, 1) - - output_group = QtWidgets.QGroupBox( - _text("output_group", self.language), rail_content - ) - output_group.setObjectName("reportOutputGroup") - mark_workbench_role(output_group, "dialog-rail") - output_layout = QtWidgets.QFormLayout(output_group) - output_layout.setFieldGrowthPolicy( - QtWidgets.QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow - ) - output_layout.setHorizontalSpacing(12) - output_layout.setVerticalSpacing(6) - output_layout.setRowWrapPolicy(QtWidgets.QFormLayout.RowWrapPolicy.WrapLongRows) - - output_row = QtWidgets.QWidget(output_group) - output_row_layout = QtWidgets.QHBoxLayout(output_row) - output_row_layout.setContentsMargins(0, 0, 0, 0) - output_row_layout.setSpacing(8) - self.output_path_edit = QtWidgets.QLineEdit( - str(self._initial_directory / self._default_filename()), output_row - ) - self.output_path_edit.setObjectName("reportOutputPath") - self.output_path_edit.setClearButtonEnabled(True) - self.output_path_edit.setCursorPosition(0) - self.browse_button = QtWidgets.QPushButton(_text("browse", self.language), output_row) - self.browse_button.setObjectName("reportBrowseButton") - output_row_layout.addWidget(self.output_path_edit, 1) - output_row_layout.addWidget(self.browse_button) - # Let the row shrink to its safe minimum before QFormLayout decides to - # wrap it. This preserves the compact side-by-side form at 340 px while - # long paths remain horizontally scrollable inside the line edit. - output_row.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Ignored, - QtWidgets.QSizePolicy.Policy.Preferred, - ) - - path_label = QtWidgets.QLabel(_text("output_path", self.language), output_group) - path_label.setBuddy(self.output_path_edit) - output_layout.addRow(path_label, output_row) - - self.title_edit = QtWidgets.QLineEdit( - _text("default_report_title", self.language), output_group - ) - self.title_edit.setObjectName("reportTitle") - self.title_edit.setMaxLength(100) - self.title_edit.setCursorPosition(0) - self.title_edit.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Expanding, - QtWidgets.QSizePolicy.Policy.Fixed, - ) - self.title_edit.setMinimumWidth(120) - title_label = QtWidgets.QLabel(_text("report_title", self.language), output_group) - title_label.setBuddy(self.title_edit) - output_layout.addRow(title_label, self.title_edit) - rail_layout.addWidget(output_group) - - self.azimuth_group = self._build_axis_group( - axis="az", - available=self._azimuth_available, - default_start=-70, - default_stop=70, - ) - self.elevation_group = self._build_axis_group( - axis="el", - available=self._elevation_available, - default_start=-15, - default_stop=15, - ) - self.axis_tabs = QtWidgets.QTabWidget(content_panel) - self.axis_tabs.setObjectName("reportAxisTabs") - mark_workbench_role(self.axis_tabs, "dialog-content") - self.axis_tabs.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Expanding, - QtWidgets.QSizePolicy.Policy.Expanding, - ) - self.axis_tabs.setStyleSheet( - "QTabWidget#reportAxisTabs::pane { border: 0; background: transparent; }" - ) - self.azimuth_page = self._axis_scroll_page("az", self.azimuth_group) - self.elevation_page = self._axis_scroll_page("el", self.elevation_group) - azimuth_index = self.axis_tabs.addTab( - self.azimuth_page, _text("azimuth", self.language) - ) - elevation_index = self.axis_tabs.addTab( - self.elevation_page, _text("elevation", self.language) - ) - self.axis_tabs.setTabEnabled(azimuth_index, self._azimuth_available) - self.axis_tabs.setTabEnabled(elevation_index, self._elevation_available) - if not self._azimuth_available and self._elevation_available: - self.axis_tabs.setCurrentIndex(elevation_index) - content_layout.addWidget(self.axis_tabs, 1) - - settings_group = QtWidgets.QGroupBox( - _text("settings_group", self.language), rail_content - ) - settings_group.setObjectName("reportPerformanceSettingsGroup") - mark_workbench_role(settings_group, "dialog-rail") - settings_layout = QtWidgets.QFormLayout(settings_group) - settings_layout.setHorizontalSpacing(12) - settings_layout.setVerticalSpacing(6) - settings_layout.setFieldGrowthPolicy( - QtWidgets.QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow - ) - settings_layout.setRowWrapPolicy( - QtWidgets.QFormLayout.RowWrapPolicy.WrapAllRows - ) - - self.error_limit_spin = QtWidgets.QDoubleSpinBox(settings_group) - self.error_limit_spin.setObjectName("reportErrorLimitDeg") - self.error_limit_spin.setRange(0.1, 30.0) - self.error_limit_spin.setDecimals(1) - self.error_limit_spin.setSingleStep(0.1) - self.error_limit_spin.setSuffix("°") - self.error_limit_spin.setValue(self._initial_error_limit_deg) - self.error_limit_spin.setMaximumWidth(132) - settings_layout.addRow(_text("error_limit", self.language), self.error_limit_spin) - - self.spectrum_floor_spin = QtWidgets.QDoubleSpinBox(settings_group) - self.spectrum_floor_spin.setObjectName("reportSpectrumFloorDb") - self.spectrum_floor_spin.setRange(-120.0, -10.0) - self.spectrum_floor_spin.setDecimals(1) - self.spectrum_floor_spin.setSingleStep(5.0) - self.spectrum_floor_spin.setSuffix(" dB") - self.spectrum_floor_spin.setValue(-40.0) - self.spectrum_floor_spin.setMaximumWidth(132) - settings_layout.addRow(_text("spectrum_floor", self.language), self.spectrum_floor_spin) - - spectrum_scale_row = QtWidgets.QWidget(settings_group) - spectrum_scale_layout = QtWidgets.QHBoxLayout(spectrum_scale_row) - spectrum_scale_layout.setContentsMargins(0, 0, 0, 0) - spectrum_scale_layout.setSpacing(16) - self.include_spectrum_db_checkbox = AppleSwitch( - _text("spectrum_db", self.language), spectrum_scale_row - ) - self.include_spectrum_db_checkbox.setObjectName("reportIncludeSpectrumDb") - self.include_spectrum_db_checkbox.setChecked(True) - self.include_spectrum_magnitude_checkbox = AppleSwitch( - _text("spectrum_magnitude", self.language), spectrum_scale_row - ) - self.include_spectrum_magnitude_checkbox.setObjectName( - "reportIncludeSpectrumMagnitude" - ) - self.include_spectrum_magnitude_checkbox.setChecked(False) - spectrum_scale_tooltip = _text("spectrum_scale_tooltip", self.language) - self.include_spectrum_db_checkbox.setToolTip(spectrum_scale_tooltip) - self.include_spectrum_magnitude_checkbox.setToolTip(spectrum_scale_tooltip) - spectrum_scale_row.setToolTip(spectrum_scale_tooltip) - spectrum_scale_layout.addWidget(self.include_spectrum_db_checkbox) - spectrum_scale_layout.addWidget(self.include_spectrum_magnitude_checkbox) - spectrum_scale_layout.addStretch(1) - spectrum_scale_label = QtWidgets.QLabel( - _text("spectrum_vertical_scale", self.language), settings_group - ) - spectrum_scale_label.setObjectName("reportSpectrumScaleLabel") - spectrum_scale_label.setWordWrap(True) - spectrum_scale_label.setToolTip(spectrum_scale_tooltip) - settings_layout.addRow(spectrum_scale_label, spectrum_scale_row) - - self.include_raw_checkbox = AppleSwitch( - _text("include_raw", self.language), settings_group - ) - self.include_raw_checkbox.setObjectName("reportIncludeRawData") - self.include_raw_checkbox.setChecked(True) - settings_layout.addRow(self.include_raw_checkbox) - - criteria_note = QtWidgets.QLabel(_text("criteria_note", self.language), settings_group) - criteria_note.setObjectName("reportCriteriaNote") - criteria_note.setWordWrap(True) - criteria_note.setMinimumWidth(0) - criteria_note.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Ignored, - QtWidgets.QSizePolicy.Policy.Preferred, - ) - criteria_note.setProperty("fluentRole", "caption") - settings_layout.addRow(criteria_note) - rail_layout.addWidget(settings_group) - - # Validation is a dialog-wide state, so keep it outside the scroll rail. - # This prevents long localized messages from being half-clipped at the - # bottom of compact windows while leaving the configuration rail usable. - self.validation_label = QtWidgets.QLabel(self) - self.validation_label.setObjectName("reportValidationError") - self.validation_label.setWordWrap(True) - self.validation_label.setStyleSheet(f"color: {TOKENS.danger};") - rail_layout.addStretch(1) - - self.button_box = QtWidgets.QDialogButtonBox( - QtWidgets.QDialogButtonBox.StandardButton.Save - | QtWidgets.QDialogButtonBox.StandardButton.Cancel, - parent=self, - ) - self.button_box.setObjectName("performanceReportButtonBox") - mark_workbench_role(self.button_box, "dialog-footer") - self.save_button = self.button_box.button( - QtWidgets.QDialogButtonBox.StandardButton.Save - ) - self.cancel_button = self.button_box.button( - QtWidgets.QDialogButtonBox.StandardButton.Cancel - ) - self.angle_image_button = self.button_box.addButton( - _text("save_angle_image", self.language), - QtWidgets.QDialogButtonBox.ButtonRole.ActionRole, - ) - self.save_button.setObjectName("reportSaveButton") - self.cancel_button.setObjectName("reportCancelButton") - self.angle_image_button.setObjectName("reportAngleErrorImageButton") - self.save_button.setText(_text("save", self.language)) - self.cancel_button.setText(_text("cancel", self.language)) - self.angle_image_button.setToolTip( - _text("save_angle_image_tooltip", self.language) - ) - mark_primary(self.save_button) - axis_available = self._azimuth_available or self._elevation_available - self.save_button.setEnabled(axis_available) - self.angle_image_button.setEnabled(axis_available) - layout.addWidget(self.validation_label) - layout.addWidget(self.button_box) - - def _build_axis_group( - self, - *, - axis: str, - available: bool, - default_start: int, - default_stop: int, - ) -> QtWidgets.QGroupBox: - long_name = _text("azimuth" if axis == "az" else "elevation", self.language) - availability = "" if available else _text("unavailable_suffix", self.language) - group = QtWidgets.QGroupBox( - _text( - "axis_group", - self.language, - axis=long_name, - availability=availability, - ), - self, - ) - group.setObjectName( - "azimuthReportGroup" if axis == "az" else "elevationReportGroup" - ) - mark_workbench_role(group, "dialog-section") - grid = QtWidgets.QGridLayout(group) - grid.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetMinimumSize) - grid.setHorizontalSpacing(10) - grid.setVerticalSpacing(8) - grid.setColumnStretch(3, 1) - grid.setRowStretch(7, 1) - - focus_start = self._angle_spin(f"{axis}FocusStart", default_start, group) - focus_stop = self._angle_spin(f"{axis}FocusStop", default_stop, group) - hold_start = self._angle_spin(f"{axis}HoldStart", default_start, group) - hold_stop = self._angle_spin(f"{axis}HoldStop", default_stop, group) - - focus_label = QtWidgets.QLabel(_text("focus_range", self.language), group) - focus_label.setBuddy(focus_start) - hold_label = QtWidgets.QLabel(_text("hold_range", self.language), group) - hold_label.setBuddy(hold_start) - grid.addWidget(focus_label, 0, 0, 1, 4) - grid.addWidget(focus_start, 1, 0) - grid.addWidget(QtWidgets.QLabel(_text("to", self.language), group), 1, 1) - grid.addWidget(focus_stop, 1, 2) - grid.addWidget(hold_label, 2, 0, 1, 4) - grid.addWidget(hold_start, 3, 0) - grid.addWidget(QtWidgets.QLabel(_text("to", self.language), group), 3, 1) - grid.addWidget(hold_stop, 3, 2) - - hold_controls = QtWidgets.QWidget(group) - hold_controls.setObjectName(f"{axis}HoldControls") - hold_controls_layout = QtWidgets.QVBoxLayout(hold_controls) - hold_controls_layout.setContentsMargins(0, 0, 0, 0) - hold_controls_layout.setSpacing(8) - - follow = AppleSwitch( - _text("follow_focus", self.language), hold_controls - ) - follow.setObjectName(f"{axis}HoldFollowsFocus") - follow.setChecked(True) - - curve_stride_row = QtWidgets.QWidget(hold_controls) - curve_stride_row_layout = QtWidgets.QHBoxLayout(curve_stride_row) - curve_stride_row_layout.setContentsMargins(0, 0, 0, 0) - curve_stride_row_layout.setSpacing(10) - - curve_stride = QtWidgets.QSpinBox(curve_stride_row) - curve_stride.setObjectName(f"{axis}HoldCurveStep") - curve_stride.setRange(1, MAX_HOLD_STRIDE_FRAMES) - curve_stride.setSingleStep(1) - curve_stride.setSuffix("°") - curve_stride.setValue(1) - curve_stride.setAlignment(QtCore.Qt.AlignmentFlag.AlignRight) - curve_stride.setMaximumWidth(120) - curve_stride.setToolTip( - _text("hold_curve_stride_tooltip", self.language) - ) - curve_stride_label = QtWidgets.QLabel( - _text("hold_curve_stride", self.language), curve_stride_row - ) - curve_stride_label.setBuddy(curve_stride) - hold_controls_layout.addWidget(follow) - curve_stride_row_layout.addWidget(curve_stride_label) - curve_stride_row_layout.addWidget(curve_stride) - curve_stride_row_layout.addStretch(1) - hold_controls_layout.addWidget(curve_stride_row) - grid.addWidget(hold_controls, 4, 0, 1, 4) - - frame_count = QtWidgets.QLabel(group) - frame_count.setObjectName(f"{axis}HoldFrameCount") - frame_count.setProperty("fluentRole", "caption") - frame_count.setWordWrap(True) - grid.addWidget(frame_count, 5, 0, 1, 4) - - note_key = "azimuth_plane_note" if axis == "az" else "elevation_plane_note" - plane_note = QtWidgets.QLabel(_text(note_key, self.language), group) - plane_note.setObjectName(f"{axis}OrthogonalPlaneNote") - plane_note.setWordWrap(True) - plane_note.setProperty("fluentRole", "caption") - grid.addWidget(plane_note, 6, 0, 1, 4) - - setattr(self, f"{axis}_focus_start", focus_start) - setattr(self, f"{axis}_focus_stop", focus_stop) - setattr(self, f"{axis}_hold_start", hold_start) - setattr(self, f"{axis}_hold_stop", hold_stop) - setattr(self, f"{axis}_hold_follows_focus", follow) - setattr(self, f"{axis}_hold_curve_step", curve_stride) - setattr(self, f"{axis}_hold_frame_count", frame_count) - - hold_start.setEnabled(False) - hold_stop.setEnabled(False) - group.setEnabled(available) - return group - - def _axis_scroll_page( - self, axis: str, group: QtWidgets.QGroupBox - ) -> QtWidgets.QScrollArea: - """Keep range controls intact when a short screen constrains the dialog.""" - - page = QtWidgets.QScrollArea(self) - page.setObjectName(f"{axis}ReportScrollArea") - mark_workbench_role(page, "dialog-content") - page.setFrameShape(QtWidgets.QFrame.Shape.NoFrame) - page.setWidgetResizable(True) - page.setHorizontalScrollBarPolicy( - QtCore.Qt.ScrollBarPolicy.ScrollBarAsNeeded - ) - page.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarPolicy.ScrollBarAsNeeded) - page.viewport().setAutoFillBackground(False) - page.setStyleSheet( - f"QScrollArea#{page.objectName()} {{ border: 0; background: transparent; }}" - ) - page.setWidget(group) - return page - - @staticmethod - def _angle_spin( - object_name: str, value: int, parent: QtWidgets.QWidget - ) -> QtWidgets.QSpinBox: - spin = QtWidgets.QSpinBox(parent) - spin.setObjectName(object_name) - spin.setRange(-90, 90) - spin.setSingleStep(1) - spin.setSuffix("°") - spin.setValue(value) - spin.setAlignment(QtCore.Qt.AlignmentFlag.AlignRight) - return spin - - def _connect_signals(self) -> None: - self.browse_button.clicked.connect(self._browse_output_path) - self.output_path_edit.textChanged.connect(self._refresh_validation) - self.include_spectrum_db_checkbox.toggled.connect(self._spectrum_db_toggled) - self.include_spectrum_magnitude_checkbox.toggled.connect( - self._refresh_validation - ) - self.button_box.accepted.connect(self._request_report_export) - self.button_box.rejected.connect(self.reject) - self.angle_image_button.clicked.connect(self._request_angle_image_export) - - for axis in ("az", "el"): - focus_start = getattr(self, f"{axis}_focus_start") - focus_stop = getattr(self, f"{axis}_focus_stop") - hold_start = getattr(self, f"{axis}_hold_start") - hold_stop = getattr(self, f"{axis}_hold_stop") - follow = getattr(self, f"{axis}_hold_follows_focus") - curve_stride = getattr(self, f"{axis}_hold_curve_step") - - focus_start.valueChanged.connect( - lambda _value, current_axis=axis: self._focus_range_changed(current_axis) - ) - focus_stop.valueChanged.connect( - lambda _value, current_axis=axis: self._focus_range_changed(current_axis) - ) - hold_start.valueChanged.connect( - lambda _value, current_axis=axis: self._hold_range_changed(current_axis) - ) - hold_stop.valueChanged.connect( - lambda _value, current_axis=axis: self._hold_range_changed(current_axis) - ) - follow.toggled.connect( - lambda _checked, current_axis=axis: self._follow_toggled(current_axis) - ) - curve_stride.valueChanged.connect( - lambda _value, current_axis=axis: self._update_frame_count(current_axis) - ) - - @staticmethod - def _default_filename() -> str: - timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") - return f"mimo_performance_report_{timestamp}.pdf" - - @staticmethod - def _ensure_pdf_suffix(path: Path) -> Path: - if path.suffix.lower() == ".pdf": - return path - return path.with_suffix(".pdf") - - def _browse_output_path(self) -> None: - selected, _selected_filter = QtWidgets.QFileDialog.getSaveFileName( - self, - _text("browse_title", self.language), - self.output_path_edit.text(), - _text("pdf_filter", self.language), - ) - if selected: - self.output_path_edit.setText(str(self._ensure_pdf_suffix(Path(selected)))) - - def _focus_range_changed(self, axis: str) -> None: - self._sync_hold_range(axis) - self._refresh_validation() - - def _hold_range_changed(self, axis: str) -> None: - self._update_frame_count(axis) - self._refresh_validation() - - def _follow_toggled(self, axis: str) -> None: - follows = getattr(self, f"{axis}_hold_follows_focus").isChecked() - available = ( - self._azimuth_available if axis == "az" else self._elevation_available - ) - getattr(self, f"{axis}_hold_start").setEnabled(available and not follows) - getattr(self, f"{axis}_hold_stop").setEnabled(available and not follows) - self._sync_hold_range(axis) - self._refresh_validation() - - def _spectrum_db_toggled(self, checked: bool) -> None: - self.spectrum_floor_spin.setEnabled(checked) - self._refresh_validation() - - def _sync_hold_range(self, axis: str) -> None: - if not getattr(self, f"{axis}_hold_follows_focus").isChecked(): - return - getattr(self, f"{axis}_hold_start").setValue( - getattr(self, f"{axis}_focus_start").value() - ) - getattr(self, f"{axis}_hold_stop").setValue( - getattr(self, f"{axis}_focus_stop").value() - ) - self._update_frame_count(axis) - - def _update_frame_count(self, axis: str) -> None: - start = getattr(self, f"{axis}_hold_start").value() - stop = getattr(self, f"{axis}_hold_stop").value() - range_count = max(0, stop - start + 1) - step = getattr(self, f"{axis}_hold_curve_step").value() - curve_count = hold_curve_frame_count(range_count, step) - getattr(self, f"{axis}_hold_frame_count").setText( - _text( - "frame_count", - self.language, - range_count=range_count, - step=step, - curve_count=curve_count, - ) - ) - - def _validation_error( - self, - export_kind: str = "report", - ) -> tuple[str, QtWidgets.QWidget | None]: - if not self.output_path_edit.text().strip(): - return _text("validation_path", self.language), self.output_path_edit - if not (self._azimuth_available or self._elevation_available): - return _text("validation_no_axis", self.language), None - if export_kind == "report" and not ( - self.include_spectrum_db_checkbox.isChecked() - or self.include_spectrum_magnitude_checkbox.isChecked() - ): - return ( - _text("validation_spectrum_scale", self.language), - self.include_spectrum_db_checkbox, - ) - - if export_kind == "report": - for axis, available in ( - ("az", self._azimuth_available), - ("el", self._elevation_available), - ): - if not available: - continue - axis_name = _text( - "azimuth" if axis == "az" else "elevation", self.language - ) - for kind in ("focus", "hold"): - start = getattr(self, f"{axis}_{kind}_start") - stop = getattr(self, f"{axis}_{kind}_stop") - if start.value() > stop.value(): - return ( - _text( - "validation_range", - self.language, - axis=axis_name, - kind=_text(f"{kind}_kind", self.language), - ), - start, - ) - return "", None - - def _set_validation_message(self, message: str) -> None: - self.validation_label.setText(message) - self.validation_label.setVisible(bool(message)) - - def _refresh_validation(self, *_args: Any) -> None: - report_message, _widget = self._validation_error("report") - image_message, _image_widget = self._validation_error("angle_image") - self._set_validation_message(report_message) - self.save_button.setEnabled(not self._export_busy and not report_message) - self.angle_image_button.setEnabled( - not self._export_busy and not image_message - ) - - def _request_report_export(self) -> None: - self._request_export("report") - - def _request_angle_image_export(self) -> None: - self._request_export("angle_image") - - def _request_export(self, export_kind: str) -> None: - if self._export_busy: - return - message, invalid_widget = self._validation_error(export_kind) - self._set_validation_message(message) - if message: - if invalid_widget is not None: - invalid_widget.setFocus(QtCore.Qt.FocusReason.OtherFocusReason) - return - - normalised_path = self._ensure_pdf_suffix( - Path(self.output_path_edit.text().strip()).expanduser() - ) - self.output_path_edit.setText(str(normalised_path)) - self._selected_export_kind = export_kind - self.export_requested.emit(export_kind) - - def set_export_busy(self, busy: bool) -> None: - """Disable output actions while one background export is active.""" - - self._export_busy = bool(busy) - self.cancel_button.setEnabled(not self._export_busy) - self._refresh_validation() - - def reject(self) -> None: - if self._export_busy: - return - super().reject() - - def closeEvent(self, event: Any) -> None: # noqa: N802 - if self._export_busy: - event.ignore() - return - super().closeEvent(event) - - @property - def export_kind(self) -> str: - """Return the output action that accepted the dialog.""" - - return self._selected_export_kind - - def angle_error_image_options(self) -> AngleErrorImageOptions: - """Return standalone-image settings inherited from this report form.""" - - from .performance_report import AngleErrorImageOptions - - report_path = self._ensure_pdf_suffix( - Path(self.output_path_edit.text().strip()).expanduser() - ) - image_path = report_path.with_name(f"{report_path.stem}_angle_error.png") - return AngleErrorImageOptions( - output_path=image_path, - error_limit_deg=self.error_limit_spin.value(), - language=self.language, - ) - - def options(self) -> PerformanceReportOptions: - """Return the selected report options; no directories or files are created.""" - - from .performance_report import AngleRange, PerformanceReportOptions - - def angle_range(axis: str, kind: str): - return AngleRange( - start_deg=getattr(self, f"{axis}_{kind}_start").value(), - stop_deg=getattr(self, f"{axis}_{kind}_stop").value(), - ) - - output_path = self._ensure_pdf_suffix( - Path(self.output_path_edit.text().strip()).expanduser() - ) - title = self.title_edit.text().strip() or _text( - "default_report_title", self.language - ) - return PerformanceReportOptions( - output_path=output_path, - title=title, - azimuth_focus=angle_range("az", "focus"), - elevation_focus=angle_range("el", "focus"), - azimuth_hold=angle_range("az", "hold"), - elevation_hold=angle_range("el", "hold"), - azimuth_hold_stride_frames=self.az_hold_curve_step.value(), - elevation_hold_stride_frames=self.el_hold_curve_step.value(), - error_limit_deg=self.error_limit_spin.value(), - spectrum_floor_db=self.spectrum_floor_spin.value(), - include_spectrum_db=self.include_spectrum_db_checkbox.isChecked(), - include_spectrum_magnitude=( - self.include_spectrum_magnitude_checkbox.isChecked() - ), - include_raw_data=self.include_raw_checkbox.isChecked(), - language=self.language, - ) - - -__all__ = ["PerformanceReportDialog"] diff --git a/src/virtual_array/phasor.py b/src/virtual_array/phasor.py new file mode 100644 index 0000000..f4afd76 --- /dev/null +++ b/src/virtual_array/phasor.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import numpy as np + + +def unit_phasor(phase_rad: np.ndarray) -> np.ndarray: + """Return ``exp(1j * phase)`` for a real phase array. + + Writing cos/sin into a preallocated complex array gives the same values as + ``np.exp(1j * phase)`` but avoids NumPy's slower complex ``exp`` path, which + dominates the 2D array-factor and 2D DBF dictionary computations. + """ + phase = np.asarray(phase_rad, dtype=float) + result = np.empty(phase.shape, dtype=complex) + np.cos(phase, out=result.real) + np.sin(phase, out=result.imag) + return result diff --git a/src/virtual_array/project.py b/src/virtual_array/project.py new file mode 100644 index 0000000..d55fb93 --- /dev/null +++ b/src/virtual_array/project.py @@ -0,0 +1,341 @@ +"""Project document: the complete, serializable state of one array study. + +A project is what the web client edits and what every compute request sends. +It is deliberately self-contained so the server can stay stateless per +request: imported files (element patterns, channel patterns, DBF dictionaries) +are referenced by content-addressed asset IDs instead of local paths. + +Coordinates are stored in wavelengths (λ), matching the layout JSON files of +the desktop tool. The computation core works in λ/2 units; conversion happens +only in :func:`project_array`. +""" + +from __future__ import annotations + +import math +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +from .dbf_dictionary import ( + CHANNEL_MODE_PHYSICAL, + CHANNEL_MODE_VIRTUAL, + DBF_DICT_CHANNEL_PATTERN, + DBF_DICT_CHANNEL_PATTERN_ZERO_REF, + DBF_DICT_CUSTOM, + DBF_DICT_IDEAL, + DBF_DICT_IDEAL_REVERSED, +) +from .element_pattern import virtual_channel_names +from .geometry import AntennaArray, ArrayPoint + +PROJECT_SCHEMA_VERSION = 2 +LAYOUT_V1_VERSION = 1 +MAX_TX_COUNT = 16 +MAX_RX_COUNT = 16 +# Grid pitch of the layout editor: λ/2, i.e. one core-grid step. +GRID_STEP_LAMBDA = 0.5 +HALF_LAMBDA_PER_LAMBDA = 2.0 +DEFAULT_FREQUENCY_GHZ = 77.0 +DEFAULT_AMBIGUITY_MARGIN_DB = 0.5 +AUTO_LAYOUT_SPACING_LAMBDA = 1.0 +AUTO_LAYOUT_TX_Y_LAMBDA = 2.0 +AUTO_LAYOUT_RX_Y_LAMBDA = -2.0 +COORDINATE_LIMIT_LAMBDA = 500.0 +LIGHT_SPEED_MM_PER_NS = 299.792458 + +LAYOUT_UNITS_LAMBDA = {"lambda", "λ"} +LEGACY_LAYOUT_UNITS_HALF_LAMBDA = {"lambda/2", "λ/2"} + +DictionaryMode = Literal["ideal", "ideal_reversed", "channel_pattern", "custom"] +ChannelMode = Literal["virtual", "physical"] +PatternKind = Literal["amplitude", "phase"] +PatternPlane = Literal["horizontal", "elevation"] + + +class _Model(BaseModel): + model_config = ConfigDict(extra="ignore") + + +class Point(_Model): + x: float + y: float + + @field_validator("x", "y") + @classmethod + def _finite(cls, value: float) -> float: + if not math.isfinite(value) or abs(value) > COORDINATE_LIMIT_LAMBDA: + raise ValueError( + f"Coordinates must be finite and within ±{COORDINATE_LIMIT_LAMBDA:g} λ." + ) + return float(value) + + +class Layout(_Model): + tx: list[Point] = Field(min_length=1, max_length=MAX_TX_COUNT) + rx: list[Point] = Field(min_length=1, max_length=MAX_RX_COUNT) + + +class DictionarySettings(_Model): + mode: DictionaryMode = "ideal" + azimuth_asset: str | None = None + elevation_asset: str | None = None + channel_mode: ChannelMode = "virtual" + phase_reversed: bool = False + zero_phase_calibrated: bool = False + + @field_validator("mode", mode="before") + @classmethod + def _legacy_mode(cls, value: Any) -> Any: + return DBF_DICT_CHANNEL_PATTERN if value == DBF_DICT_CHANNEL_PATTERN_ZERO_REF else value + + @model_validator(mode="after") + def _custom_needs_asset(self) -> DictionarySettings: + if ( + self.mode == DBF_DICT_CUSTOM + and self.azimuth_asset is None + and self.elevation_asset is None + ): + raise ValueError( + "An imported DBF dictionary needs at least one azimuth or elevation file." + ) + return self + + +class ElementPatternSettings(_Model): + asset: str + swap_axes: bool = False + + +class ChannelPatternBinding(_Model): + """One imported amplitude or phase cut assigned to one channel.""" + + channel: str + kind: PatternKind + plane: PatternPlane + asset: str + # Index of the data column after the angle column in the source file. + column_index: int = Field(ge=0) + column: str = "" + + +class Project(_Model): + version: int = PROJECT_SCHEMA_VERSION + name: str = Field(default="未命名阵列", max_length=120) + frequency_ghz: float = Field(default=DEFAULT_FREQUENCY_GHZ, gt=0.0, le=1000.0) + ambiguity_margin_db: float = Field(default=DEFAULT_AMBIGUITY_MARGIN_DB, ge=0.0, le=60.0) + layout: Layout + dbf_dictionary: DictionarySettings = Field(default_factory=DictionarySettings) + element_pattern: ElementPatternSettings | None = None + channel_patterns: list[ChannelPatternBinding] = Field(default_factory=list) + + @property + def tx_names(self) -> list[str]: + return [f"Tx{index}" for index in range(1, len(self.layout.tx) + 1)] + + @property + def rx_names(self) -> list[str]: + return [f"Rx{index}" for index in range(1, len(self.layout.rx) + 1)] + + @property + def physical_channel_names(self) -> list[str]: + return [*self.tx_names, *self.rx_names] + + @property + def virtual_channel_names(self) -> list[str]: + return virtual_channel_names(self.tx_names, self.rx_names) + + @property + def wavelength_mm(self) -> float: + return LIGHT_SPEED_MM_PER_NS / self.frequency_ghz + + def asset_ids(self) -> set[str]: + ids = {binding.asset for binding in self.channel_patterns} + if self.element_pattern is not None: + ids.add(self.element_pattern.asset) + for asset in (self.dbf_dictionary.azimuth_asset, self.dbf_dictionary.elevation_asset): + if asset is not None: + ids.add(asset) + return ids + + +def snap_lambda(value: float) -> float: + """Snap a λ coordinate to the λ/2 editor grid.""" + return round(value / GRID_STEP_LAMBDA) * GRID_STEP_LAMBDA + 0.0 + + +def project_array(project: Project) -> AntennaArray: + """Build the core array (λ/2 units) from a project.""" + tx = [ + ArrayPoint(name=name, x=point.x * HALF_LAMBDA_PER_LAMBDA, y=point.y * HALF_LAMBDA_PER_LAMBDA) + for name, point in zip(project.tx_names, project.layout.tx) + ] + rx = [ + ArrayPoint(name=name, x=point.x * HALF_LAMBDA_PER_LAMBDA, y=point.y * HALF_LAMBDA_PER_LAMBDA) + for name, point in zip(project.rx_names, project.layout.rx) + ] + return AntennaArray(tx=tx, rx=rx) + + +def centered_positions(count: int) -> list[float]: + offset = (count - 1) * AUTO_LAYOUT_SPACING_LAMBDA / 2.0 + return [snap_lambda(index * AUTO_LAYOUT_SPACING_LAMBDA - offset) for index in range(count)] + + +def auto_layout(tx_count: int, rx_count: int) -> Layout: + """Centered Tx and Rx rows: the desktop tool's "Apply Array" quick start.""" + if not 1 <= tx_count <= MAX_TX_COUNT: + raise ValueError(f"Tx count must be from 1 to {MAX_TX_COUNT}.") + if not 1 <= rx_count <= MAX_RX_COUNT: + raise ValueError(f"Rx count must be from 1 to {MAX_RX_COUNT}.") + return Layout( + tx=[Point(x=x, y=AUTO_LAYOUT_TX_Y_LAMBDA) for x in centered_positions(tx_count)], + rx=[Point(x=x, y=AUTO_LAYOUT_RX_Y_LAMBDA) for x in centered_positions(rx_count)], + ) + + +def default_project() -> Project: + """The reference 8T8R layout (examples/case4) used as the starting point.""" + from .examples.case4_5tx7rx_sel import RX_X, RX_Y, TX_X, TX_Y + + scale = 1.0 / HALF_LAMBDA_PER_LAMBDA + return Project( + name="Case4 8T8R", + layout=Layout( + tx=[Point(x=x * scale, y=y * scale) for x, y in zip(TX_X, TX_Y)], + rx=[Point(x=x * scale, y=y * scale) for x, y in zip(RX_X, RX_Y)], + ), + ) + + +def layout_from_v1(config: Any) -> Layout: + """Parse a desktop-tool layout JSON (version 1) into a layout. + + Element names in the file are ignored: channels are numbered by list + order, exactly as the desktop importer did. + """ + if not isinstance(config, dict): + raise ValueError("Layout config must be a JSON object.") + if config.get("version") != LAYOUT_V1_VERSION: + raise ValueError(f"Unsupported layout version: {config.get('version')!r}.") + unit = config.get("unit") + if unit not in LAYOUT_UNITS_LAMBDA | LEGACY_LAYOUT_UNITS_HALF_LAMBDA: + raise ValueError("Layout unit must be 'lambda'.") + scale = 1.0 if unit in LAYOUT_UNITS_LAMBDA else 1.0 / HALF_LAMBDA_PER_LAMBDA + + points: dict[str, list[Point]] = {} + for kind, limit in (("tx", MAX_TX_COUNT), ("rx", MAX_RX_COUNT)): + raw_points = config.get(kind) + if not isinstance(raw_points, list) or not raw_points: + raise ValueError(f"Layout field '{kind}' must be a non-empty list.") + if len(raw_points) > limit: + raise ValueError( + f"Layout has {len(raw_points)} {kind.capitalize()} elements; maximum is {limit}." + ) + parsed: list[Point] = [] + for index, raw_point in enumerate(raw_points): + if not isinstance(raw_point, dict): + raise ValueError(f"{kind}[{index}] must be an object.") + try: + x = snap_lambda(float(raw_point["x"]) * scale) + y = snap_lambda(float(raw_point["y"]) * scale) + parsed.append(Point(x=x, y=y)) + except KeyError as exc: + raise ValueError(f"{kind}[{index}] is missing coordinate {exc}.") from exc + except (TypeError, ValueError) as exc: + raise ValueError(f"{kind}[{index}] has invalid coordinates.") from exc + points[kind] = parsed + return Layout(tx=points["tx"], rx=points["rx"]) + + +def project_from_document(document: Any) -> Project: + """Accept either a v2 project document or a v1 layout file.""" + if not isinstance(document, dict): + raise ValueError("Project file must be a JSON object.") + if document.get("version") == LAYOUT_V1_VERSION: + layout = layout_from_v1(document) + project = Project(layout=layout) + evaluation = document.get("evaluation") + if isinstance(evaluation, dict): + frequency = _parse_number(evaluation.get("frequency_ghz") or evaluation.get("frequency_mode")) + margin = _parse_number(evaluation.get("ambiguity_margin_db")) + updates: dict[str, Any] = {} + if frequency is not None and frequency > 0: + updates["frequency_ghz"] = frequency + if margin is not None and margin >= 0: + updates["ambiguity_margin_db"] = margin + if updates: + project = project.model_copy(update=updates) + return project + if document.get("version") == PROJECT_SCHEMA_VERSION: + return Project.model_validate(document) + raise ValueError(f"Unsupported project version: {document.get('version')!r}.") + + +def layout_to_v1(project: Project, evaluation: dict[str, Any] | None = None) -> dict[str, Any]: + """Export a desktop-compatible layout JSON (version 1).""" + document: dict[str, Any] = { + "version": LAYOUT_V1_VERSION, + "unit": "lambda", + "tx": [ + {"name": name, "x": json_number(point.x, 9), "y": json_number(point.y, 9)} + for name, point in zip(project.tx_names, project.layout.tx) + ], + "rx": [ + {"name": name, "x": json_number(point.x, 9), "y": json_number(point.y, 9)} + for name, point in zip(project.rx_names, project.layout.rx) + ], + } + if evaluation is not None: + document["evaluation"] = evaluation + return document + + +def json_number(value: float | None, digits: int = 6) -> float | int | None: + if value is None or not math.isfinite(value): + return None + rounded = round(float(value), digits) + if abs(rounded - round(rounded)) < 10**-digits: + return int(round(rounded)) + return rounded + + +def _parse_number(value: Any) -> float | None: + if isinstance(value, bool) or value is None: + return None + if isinstance(value, (int, float)): + number = float(value) + else: + text = str(value).strip().lower().replace(",", ".") + for suffix in ("ghz", "db", "g"): + if text.endswith(suffix): + text = text[: -len(suffix)].strip() + break + try: + number = float(text) + except ValueError: + return None + return number if math.isfinite(number) else None + + +__all__ = [ + "CHANNEL_MODE_PHYSICAL", + "CHANNEL_MODE_VIRTUAL", + "DBF_DICT_CHANNEL_PATTERN", + "DBF_DICT_CUSTOM", + "DBF_DICT_IDEAL", + "DBF_DICT_IDEAL_REVERSED", + "ChannelPatternBinding", + "DictionarySettings", + "ElementPatternSettings", + "Layout", + "Point", + "Project", + "auto_layout", + "default_project", + "layout_from_v1", + "layout_to_v1", + "project_array", + "project_from_document", + "snap_lambda", +] diff --git a/src/virtual_array/qt_plot.py b/src/virtual_array/qt_plot.py deleted file mode 100644 index c114045..0000000 --- a/src/virtual_array/qt_plot.py +++ /dev/null @@ -1,1917 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from types import SimpleNamespace -from typing import Any, Callable - -import numpy as np -import pyqtgraph as pg -from PySide6 import QtCore, QtGui, QtWidgets - -from .native_theme import TOKENS - - -pg.setConfigOptions(antialias=True) - -rcParams: dict[str, Any] = {} -_SUBPLOT_MARGIN_SCALE = 0.5 -_LARGE_SUBPLOT_LEFT_MARGIN_SCALE = 0.35 -_EQUAL_ASPECT_WIDTH_SCALE = 0.9 -_EQUAL_ASPECT_HEIGHT_SCALE = 1.04 -_LARGE_EQUAL_ASPECT_WIDTH_SCALE = 0.938 -_LARGE_EQUAL_ASPECT_HEIGHT_SCALE = 1.01 -_LARGE_EQUAL_ASPECT_HEIGHT_CAP_SCALE = 0.985 -_LARGE_WIDE_EQUAL_ASPECT_WIDTH_SCALE = 0.629 -_LARGE_WIDE_EQUAL_ASPECT_HEIGHT_SCALE = 0.98 -_COMPACT_EQUAL_ASPECT_WIDTH_SCALE = 0.935 -_WIDE_COMPACT_EQUAL_ASPECT_WIDTH_SCALE = 0.808 -_COMPACT_EQUAL_ASPECT_HEIGHT_SCALE = 1.19 -_WIDE_COMPACT_EQUAL_ASPECT_HEIGHT_SCALE = 1.095 -_LARGE_EQUAL_ASPECT_MARGINS = (3, 3, 14, 0) -_LARGE_WIDE_EQUAL_ASPECT_MARGINS = (5, 12, 31, 0) -_COMPACT_EQUAL_ASPECT_MARGINS = (3, 3, 14, 5) -_WIDE_COMPACT_EQUAL_ASPECT_MARGINS = (5, 12, 31, 0) -_COMPACT_SUBPLOT_MARGINS = (0, 12, 12, 8) -_COMPACT_SUBPLOT_PLOT_MARGINS = (5, 4, 0, 0) -_LARGE_SUBPLOT_PLOT_MARGINS = (-15, 21, 10, 4) -_RECT_PLOT_LEFT_MARGIN = 23 -_RECT_PLOT_TOP_MARGIN = 27 -_RECT_PLOT_RIGHT_MARGIN = 0 -_RECT_PLOT_BOTTOM_MARGIN = 24 -_WIDE_RECT_PLOT_BOTTOM_MARGIN = 34 -_COLORBAR_X_OFFSET = -1 -_COLORBAR_MIN_WIDTH = 67 -_COMPACT_COLORBAR_MIN_WIDTH = 83 -_COLORBAR_TOP_COMPENSATION = -2 -_COLORBAR_BOTTOM_COMPENSATION = 3 -_WIDE_COLORBAR_BOTTOM_COMPENSATION = 12 - - -def _qt_parent(parent: Any) -> QtWidgets.QWidget | None: - """Resolve either a native Qt parent or a transitional Tk-style wrapper.""" - if parent is None: - return None - if isinstance(parent, QtWidgets.QWidget): - return parent - candidate = getattr(parent, "_qt", None) - return candidate if isinstance(candidate, QtWidgets.QWidget) else None - - -def _as_color(value: Any) -> str | None: - return value if isinstance(value, str) and value else None - - -def _cursor_shape(name: str | None) -> QtCore.Qt.CursorShape: - return { - "hand2": QtCore.Qt.CursorShape.PointingHandCursor, - "pointinghand": QtCore.Qt.CursorShape.PointingHandCursor, - "fleur": QtCore.Qt.CursorShape.SizeAllCursor, - "size_all": QtCore.Qt.CursorShape.SizeAllCursor, - "openhand": QtCore.Qt.CursorShape.OpenHandCursor, - "closedhand": QtCore.Qt.CursorShape.ClosedHandCursor, - "sb_h_double_arrow": QtCore.Qt.CursorShape.SizeHorCursor, - "size_hor": QtCore.Qt.CursorShape.SizeHorCursor, - "sb_v_double_arrow": QtCore.Qt.CursorShape.SizeVerCursor, - "size_ver": QtCore.Qt.CursorShape.SizeVerCursor, - "cross": QtCore.Qt.CursorShape.CrossCursor, - "crosshair": QtCore.Qt.CursorShape.CrossCursor, - }.get(name or "", QtCore.Qt.CursorShape.ArrowCursor) - - -def _set_cursor(widget: QtWidgets.QWidget, name: str | None) -> None: - if name: - widget.setCursor(QtGui.QCursor(_cursor_shape(name))) - else: - widget.unsetCursor() - - -def _parse_pad_pair(value: Any) -> tuple[int, int]: - if value is None: - return (0, 0) - if isinstance(value, (int, float)): - size = int(value) - return (size, size) - if isinstance(value, (tuple, list)): - if len(value) == 2: - return (int(value[0]), int(value[1])) - if len(value) == 4: - return (int(value[0]), int(value[2])) - return (0, 0) - - -def _is_no_color(value: Any) -> bool: - return isinstance(value, str) and value.lower() in {"none", "transparent"} - - -def _color(value: Any, alpha: float | None = None) -> QtGui.QColor: - if value is None: - qcolor = QtGui.QColor("#000000") - elif isinstance(value, QtGui.QColor): - qcolor = QtGui.QColor(value) - elif isinstance(value, tuple): - if len(value) >= 3: - scale = 255 if all(isinstance(v, float) and v <= 1 for v in value[:3]) else 1 - qcolor = QtGui.QColor( - int(value[0] * scale), - int(value[1] * scale), - int(value[2] * scale), - ) - else: - qcolor = QtGui.QColor("#000000") - else: - qcolor = QtGui.QColor(str(value)) - if alpha is not None: - qcolor.setAlphaF(max(0.0, min(1.0, float(alpha)))) - return qcolor - - -def _pen( - color: Any = None, - *, - width: float | None = None, - alpha: float | None = None, - linestyle: str | None = None, -) -> QtGui.QPen: - pen = pg.mkPen(_color(color, alpha), width=1.0 if width is None else float(width)) - if linestyle in {"--", "dashed"}: - pen.setStyle(QtCore.Qt.PenStyle.DashLine) - elif linestyle in {":", "dotted"}: - pen.setStyle(QtCore.Qt.PenStyle.DotLine) - return pen - - -def _brush(color: Any = None, *, alpha: float | None = None) -> QtGui.QBrush: - if _is_no_color(color): - return QtGui.QBrush(QtCore.Qt.BrushStyle.NoBrush) - return pg.mkBrush(_color(color, alpha)) - - -def _tick_values(values: Any) -> list[float]: - try: - array = np.asarray(values, dtype=float).ravel() - except Exception: - return [] - return [float(value) for value in array if np.isfinite(value)] - - -def _tick_label(value: float) -> str: - if abs(value - round(value)) < 1e-9: - return str(int(round(value))) - return f"{value:g}" - - -def _text_anchor(ha: str | None, va: str | None) -> tuple[float, float]: - x_anchor = {"left": 0.0, "center": 0.5, "right": 1.0}.get(str(ha or "left"), 0.0) - y_anchor = {"top": 0.0, "center": 0.5, "bottom": 1.0, "baseline": 1.0}.get( - str(va or "top"), - 0.0, - ) - return (x_anchor, y_anchor) - - -def _font_families() -> list[str]: - configured = rcParams.get("font.sans-serif") or rcParams.get("font.family") - if isinstance(configured, str): - values = [configured] - else: - try: - values = [str(value) for value in configured] - except TypeError: - values = [] - values.extend(["Microsoft YaHei", "SimHei", "DejaVu Sans"]) - return list(dict.fromkeys(value for value in values if value)) - - -def _primary_font_family() -> str: - return _font_families()[0] - - -def _font(size: Any = None, weight: Any = None) -> QtGui.QFont | None: - if size is None and weight is None: - return None - font = QtGui.QFont(_primary_font_family()) - if hasattr(font, "setFamilies"): - font.setFamilies(_font_families()) - if size is not None: - try: - font.setPointSizeF(float(size)) - except Exception: - pass - if str(weight).lower() in {"bold", "demibold", "600", "700"}: - font.setBold(True) - return font - - -def _label_style_args(kwargs: dict[str, Any], *, default_size: float | None = None) -> dict[str, Any]: - args: dict[str, Any] = {} - args["font-family"] = ", ".join( - family if family == "sans-serif" else f'"{family}"' - for family in _font_families() - ) - color = kwargs.get("color") - if color: - args["color"] = _color(color).name() - size = kwargs.get("fontsize", default_size) - if size is not None: - try: - args["size"] = f"{float(size):g}pt" - except Exception: - pass - weight = kwargs.get("fontweight") or kwargs.get("weight") - if str(weight).lower() in {"bold", "demibold", "600", "700"}: - args["bold"] = True - elif weight is not None: - args["bold"] = False - return args - - -def _bbox_pen_brush(bbox: Any) -> tuple[QtGui.QPen | None, QtGui.QBrush | None]: - if not isinstance(bbox, dict): - return (None, None) - edge = bbox.get("edgecolor") - face = bbox.get("facecolor") - alpha = bbox.get("alpha") - width = bbox.get("linewidth", 1.0) - pen = ( - QtGui.QPen(QtCore.Qt.PenStyle.NoPen) - if edge is None or _is_no_color(edge) - else _pen(edge, width=width, alpha=alpha) - ) - brush = ( - QtGui.QBrush(QtCore.Qt.BrushStyle.NoBrush) - if face is None or _is_no_color(face) - else _brush(face, alpha=alpha) - ) - return (pen, brush) - - -def _set_text_margin(item: pg.TextItem, margin: float) -> None: - try: - item.textItem.document().setDocumentMargin(float(margin)) - except Exception: - return - - -def _bbox_text_scale( - text: str, - fontsize: Any, - bbox: Any, - rotation: Any, -) -> tuple[float, float] | None: - if not isinstance(bbox, dict) or fontsize is None: - return None - try: - size = float(fontsize) - except Exception: - return None - try: - angle = abs(float(rotation or 0.0)) % 180.0 - except Exception: - angle = 0.0 - is_vertical = 70.0 <= angle <= 110.0 - is_multiline = "\n" in text - - # Qt's QTextDocument uses taller line boxes than matplotlib/Tk for the same - # point size. Keep these corrections local to plot badges so axis chrome - # and plain Tx/Rx labels retain their native pyqtgraph sizing. - if size <= 7.6: - if is_vertical: - return (0.70, 0.92) - if is_multiline: - return (0.99, 0.78) - return (0.92, 0.73) - if size <= 8.6: - return (1.10, 0.78) if not is_multiline else (1.02, 0.80) - if is_multiline: - return (1.07, 0.85) - return (1.00, 0.78) - - -def _apply_bbox_text_scale( - item: pg.TextItem, - text: str, - fontsize: Any, - bbox: Any, - rotation: Any, -) -> None: - # Keep text glyphs at their native aspect ratio; shrinking plot badges with - # transforms makes Qt-rendered labels look vertically compressed. - return - - -def _uses_short_ascii_legend(labels: list[str]) -> bool: - return bool(labels) and all(len(label) <= 2 and label.isascii() for label in labels) - - -class _LabelProxy: - def __init__(self, setter: Callable[[str], None]) -> None: - self._setter = setter - - def set_text(self, text: str) -> None: - self._setter(str(text)) - - def set_fontsize(self, _size: float) -> None: - return - - def set_color(self, _color_value: Any) -> None: - return - - def set_fontweight(self, _weight: str) -> None: - return - - def set_horizontalalignment(self, _alignment: str) -> None: - return - - def set_verticalalignment(self, _alignment: str) -> None: - return - - -class _InvertedDataTransform: - def __init__(self, axes: "Axes") -> None: - self.axes = axes - - def transform(self, point: Any) -> tuple[float, float]: - x, y = point - scene_point = QtCore.QPointF(float(x), float(y)) - data_point = self.axes.plot_item.vb.mapSceneToView(scene_point) - return (float(data_point.x()), float(data_point.y())) - - -class _DataTransform: - def __init__(self, axes: "Axes") -> None: - self.axes = axes - - def inverted(self) -> _InvertedDataTransform: - return _InvertedDataTransform(self.axes) - - -class _Artist: - def __init__(self, item: Any | None = None) -> None: - self.item = item - self._visible = True - - def set_visible(self, visible: bool) -> None: - self._visible = bool(visible) - if self.item is not None and hasattr(self.item, "setVisible"): - self.item.setVisible(self._visible) - - def get_visible(self) -> bool: - return self._visible - - def remove(self) -> None: - if self.item is not None and hasattr(self.item, "getViewBox"): - view_box = self.item.getViewBox() - if view_box is not None: - view_box.removeItem(self.item) - self.item = None - - def set_clip_on(self, _enabled: bool) -> None: - return - - def set_zorder(self, _zorder: int) -> None: - return - - -class _ScatterArtist(_Artist): - def __init__( - self, - item: Any | None = None, - *, - marker_scale: float = 1.55, - size: Any = 28, - ) -> None: - super().__init__(item) - self._marker_scale = marker_scale - self._marker_size = self._mpl_marker_size(size) - - def _mpl_marker_size(self, size: Any) -> float: - data = np.asarray(size, dtype=float) - value = float(data.ravel()[0]) if data.size else 28.0 - return max(3.0, value ** 0.5 * self._marker_scale) - - def set_offsets(self, offsets: Any) -> None: - if self.item is None: - return - data = np.asarray(offsets, dtype=float) - if data.size == 0: - self.item.setData([], []) - return - data = data.reshape((-1, 2)) - self.item.setData(x=data[:, 0], y=data[:, 1]) - self.item.setSize(self._marker_size) - - def set_sizes(self, sizes: Any) -> None: - if self.item is None: - return - self._marker_size = self._mpl_marker_size(sizes) - self.item.setSize(self._marker_size) - - -class _TextArtist(_Artist): - def __init__( - self, - item: pg.TextItem, - x: float = 0.0, - y: float = 0.0, - *, - axes: "Axes | None" = None, - offset_units: str | None = None, - ha: str | None = None, - va: str | None = None, - ) -> None: - super().__init__(item) - self._xy = (float(x), float(y)) - self._offset = (0.0, 0.0) - self._axes = axes - self._offset_units = offset_units - self._ha = ha or "left" - self._va = va or "top" - - @property - def xy(self) -> tuple[float, float]: - return self._xy - - @xy.setter - def xy(self, value: tuple[float, float]) -> None: - self._xy = (float(value[0]), float(value[1])) - self._apply_position() - - def set_text(self, text: str) -> None: - if self.item is not None: - self.item.setText(str(text)) - - def set_position(self, xy: tuple[float, float]) -> None: - self._offset = (float(xy[0]), float(xy[1])) - self._apply_position() - - def _apply_position(self) -> None: - if self.item is None: - return - dx, dy = self._converted_offset() - self.item.setPos(self._xy[0] + dx, self._xy[1] + dy) - - def _converted_offset(self) -> tuple[float, float]: - if self._offset_units != "offset points" or self._axes is None: - return self._offset - view_range = self._axes.plot_item.vb.viewRange() - x_low, x_high = map(float, view_range[0]) - y_low, y_high = map(float, view_range[1]) - view_width = max(1.0, float(self._axes.plot_item.vb.width())) - view_height = max(1.0, float(self._axes.plot_item.vb.height())) - dx_points, dy_points = self._offset - dx_pixels = dx_points * self._axes.figure.dpi / 72.0 - dy_pixels = dy_points * self._axes.figure.dpi / 72.0 - return ( - dx_pixels * (x_high - x_low) / view_width, - dy_pixels * (y_high - y_low) / view_height, - ) - - def _apply_anchor(self) -> None: - if self.item is not None and hasattr(self.item, "setAnchor"): - self.item.setAnchor(_text_anchor(self._ha, self._va)) - - def set_ha(self, value: str) -> None: - self._ha = str(value) - self._apply_anchor() - - def set_va(self, value: str) -> None: - self._va = str(value) - self._apply_anchor() - - -class _ImageArtist(_Artist): - def __init__(self, item: pg.ImageItem, levels: tuple[float, float] | None = None) -> None: - super().__init__(item) - self.levels = levels - - -@dataclass -class Rectangle: - xy: tuple[float, float] - width: float - height: float - kwargs: dict[str, Any] - - def __init__(self, xy: tuple[float, float], width: float, height: float, **kwargs: Any) -> None: - self.xy = xy - self.width = width - self.height = height - self.kwargs = kwargs - - -class _Spine: - def set_color(self, _color_value: Any) -> None: - return - - def set_edgecolor(self, _color_value: Any) -> None: - return - - def set_linewidth(self, _width: float) -> None: - return - - -class _Legend: - def __init__(self, item: pg.LegendItem | None = None) -> None: - self.item = item - - def set_zorder(self, zorder: int) -> None: - if self.item is not None: - self.item.setZValue(float(zorder)) - - def get_frame(self) -> "_Legend": - return self - - def set_facecolor(self, color_value: Any) -> None: - if self.item is None: - return - if color_value in {"none", "None", None}: - brush = QtGui.QBrush(QtCore.Qt.BrushStyle.NoBrush) - else: - brush = _brush(color_value) - self.item.setBrush(brush) - - def set_edgecolor(self, color_value: Any) -> None: - if self.item is None: - return - if color_value in {"none", "None", None}: - pen = QtGui.QPen(QtCore.Qt.PenStyle.NoPen) - else: - pen = _pen(color_value) - self.item.setPen(pen) - - def set_linewidth(self, width: float) -> None: - if self.item is None: - return - pen = self.item.pen - if isinstance(pen, QtGui.QPen): - pen.setWidthF(float(width)) - self.item.setPen(pen) - - def set_alpha(self, alpha: float) -> None: - if self.item is None: - return - brush = self.item.brush - if isinstance(brush, QtGui.QBrush) and brush.style() != QtCore.Qt.BrushStyle.NoBrush: - color = brush.color() - color.setAlphaF(max(0.0, min(1.0, float(alpha)))) - self.item.setBrush(QtGui.QBrush(color)) - - def get_texts(self) -> list[Any]: - if self.item is None: - return [] - return [_LegendText(label, self.item) for _sample, label in self.item.items] - - -class _LegendText: - def __init__(self, label: Any, legend: pg.LegendItem | None = None) -> None: - self.label = label - self.legend = legend - - def set_color(self, color_value: Any) -> None: - color_name = _color(color_value).name() - if self.legend is not None: - try: - self.legend.setLabelTextColor(color_name) - except Exception: - pass - text = getattr(self.label, "text", "") - try: - self.label.setText(text, color=color_name) - except Exception: - return - - def set_fontsize(self, size: float) -> None: - text = getattr(self.label, "text", "") - try: - self.label.setText(text, size=f"{float(size):g}pt") - except Exception: - return - - -class _Colorbar: - def __init__(self, axis: "Axes") -> None: - self.ax = axis - self.outline = SimpleNamespace( - set_edgecolor=lambda _value: None, - set_linewidth=lambda _value: None, - ) - - def set_ticks(self, ticks: Any) -> None: - values = _tick_values(ticks) - self.ax.plot_item.getAxis("right").setTicks( - [[(value, _tick_label(value)) for value in values]] - ) - - def set_label(self, label: str, **kwargs: Any) -> None: - self.ax.plot_item.setLabel("right", str(label), **_label_style_args(kwargs, default_size=8.0)) - - -class Axes: - def __init__(self, figure: "Figure", *, rect: list[float] | None = None) -> None: - self.figure = figure - self.rect = rect - self.widget = pg.PlotWidget(parent=figure.widget) - self.widget.setBackground(_color("#ffffff")) - self.widget.setMinimumSize(1, 1) - self.widget.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Expanding, - QtWidgets.QSizePolicy.Policy.Expanding, - ) - self.plot_item = self.widget.getPlotItem() - self.plot_item.setMenuEnabled(False) - self.plot_item.hideButtons() - view_box = self.plot_item.getViewBox() - view_box.setMouseEnabled(x=False, y=False) - view_box.setMenuEnabled(False) - self.spines = {key: _Spine() for key in ("left", "right", "top", "bottom")} - self.transData = _DataTransform(self) - self.transAxes = object() - self._xlim = (0.0, 1.0) - self._ylim = (0.0, 1.0) - self._major_ticks: dict[str, list[float] | None] = {"bottom": None, "left": None} - self._minor_ticks: dict[str, list[float] | None] = {"bottom": None, "left": None} - self._aspect_equal = False - self._legend: pg.LegendItem | None = None - self._legend_items: list[tuple[Any, str, dict[str, Any]]] = [] - self._button: QtWidgets.QPushButton | None = None - self._grid_styles: dict[str, dict[str, Any]] = {} - self._grid_items: list[Any] = [] - self._is_colorbar = False - - def clear(self) -> None: - if self._legend is not None: - try: - scene = self._legend.scene() - if scene is not None: - scene.removeItem(self._legend) - self.plot_item.legend = None - except Exception: - pass - self._legend = None - self._clear_grid_items() - self.plot_item.clear() - self._legend_items.clear() - self._grid_styles.clear() - self._aspect_equal = False - for axis_name in ("bottom", "left"): - self._major_ticks[axis_name] = None - self._minor_ticks[axis_name] = None - self._reset_axis_ticks(axis_name) - - def set_facecolor(self, color: Any) -> None: - self.widget.setBackground(_color(color)) - - def set_title(self, title: str, **kwargs: Any) -> None: - args = _label_style_args(kwargs, default_size=11.0) - loc = str(kwargs.get("loc", "center")).lower() - if loc in {"left", "center", "right"}: - args["justify"] = loc - self.plot_item.setTitle(str(title), **args) - - def set_xlabel(self, label: str, **kwargs: Any) -> None: - self.plot_item.setLabel("bottom", str(label), **_label_style_args(kwargs, default_size=9.0)) - - def set_ylabel(self, label: str, **kwargs: Any) -> None: - self.plot_item.setLabel("left", str(label), **_label_style_args(kwargs, default_size=9.0)) - - def set_xlim(self, left: float, right: float | None = None) -> None: - if right is None: - left, right = left # type: ignore[misc] - self._xlim = (float(left), float(right)) - self.plot_item.setXRange(self._xlim[0], self._xlim[1], padding=0) - self._refresh_grid() - - def set_ylim(self, bottom: float, top: float | None = None) -> None: - if top is None: - bottom, top = bottom # type: ignore[misc] - self._ylim = (float(bottom), float(top)) - self.plot_item.setYRange(self._ylim[0], self._ylim[1], padding=0) - self._refresh_grid() - - def get_xlim(self) -> tuple[float, float]: - return self._xlim - - def get_ylim(self) -> tuple[float, float]: - return self._ylim - - def set_aspect(self, aspect: str | float, **_: Any) -> None: - self._aspect_equal = aspect == "equal" - self.plot_item.getViewBox().setAspectLocked(self._aspect_equal) - self.figure.sync_equal_axis_layout() - - def grid( - self, - visible: bool = True, - which: str | None = None, - alpha: float | None = None, - **kwargs: Any, - ) -> None: - targets = ["major", "minor"] if which == "both" else [which or "major"] - for target in targets: - if visible: - self._grid_styles[target] = { - "color": kwargs.get("color"), - "linewidth": kwargs.get("linewidth") or kwargs.get("lw"), - "alpha": 0.25 if alpha is None else alpha, - } - else: - self._grid_styles.pop(target, None) - self._refresh_grid() - - def _clear_grid_items(self) -> None: - for item in self._grid_items: - try: - self.plot_item.removeItem(item) - except Exception: - pass - self._grid_items.clear() - - def _refresh_grid(self) -> None: - if not hasattr(self, "_grid_items"): - return - self._clear_grid_items() - if not self._grid_styles: - self.plot_item.showGrid(x=False, y=False) - return - has_manual_ticks = any( - self._major_ticks.get(axis_name) is not None - or self._minor_ticks.get(axis_name) is not None - for axis_name in ("bottom", "left") - ) - if not has_manual_ticks: - style = self._grid_styles.get("major") or next(iter(self._grid_styles.values())) - self.plot_item.showGrid(x=True, y=True, alpha=float(style.get("alpha", 0.25))) - return - self.plot_item.showGrid(x=False, y=False) - for level, ticks_by_axis in ( - ("major", self._major_ticks), - ("minor", self._minor_ticks), - ): - style = self._grid_styles.get(level) - if style is None: - continue - pen = _pen( - style.get("color"), - width=style.get("linewidth"), - alpha=style.get("alpha"), - ) - for value in ticks_by_axis.get("bottom") or []: - item = pg.InfiniteLine(pos=float(value), angle=90, pen=pen, movable=False) - item.setZValue(-100.0 if level == "major" else -110.0) - item.setAcceptedMouseButtons(QtCore.Qt.MouseButton.NoButton) - item.setAcceptHoverEvents(False) - self.plot_item.addItem(item) - self._grid_items.append(item) - for value in ticks_by_axis.get("left") or []: - item = pg.InfiniteLine(pos=float(value), angle=0, pen=pen, movable=False) - item.setZValue(-100.0 if level == "major" else -110.0) - item.setAcceptedMouseButtons(QtCore.Qt.MouseButton.NoButton) - item.setAcceptHoverEvents(False) - self.plot_item.addItem(item) - self._grid_items.append(item) - - def minorticks_on(self) -> None: - return - - def tick_params(self, **kwargs: Any) -> None: - color = kwargs.get("colors") - width = kwargs.get("width") - length = kwargs.get("length") - tick_font = _font(kwargs.get("labelsize")) - if color or width is not None: - pen = _pen(color or "#000000", width=width) - for axis_name in ("left", "bottom", "right"): - self.plot_item.getAxis(axis_name).setPen(pen) - self.plot_item.getAxis(axis_name).setTextPen(pen) - if tick_font is not None: - for axis_name in ("left", "bottom", "right"): - self.plot_item.getAxis(axis_name).setStyle(tickFont=tick_font) - if length is not None: - try: - tick_length = int(round(float(length))) - except Exception: - tick_length = 0 - if tick_length > 0: - for axis_name in ("left", "bottom", "right"): - self.plot_item.getAxis(axis_name).setStyle(tickLength=tick_length) - - def _reset_axis_ticks(self, axis_name: str) -> None: - axis = self.plot_item.getAxis(axis_name) - try: - axis.setTicks(None) - except Exception: - return - - def _apply_axis_ticks(self, axis_name: str) -> None: - major = self._major_ticks[axis_name] - minor = self._minor_ticks[axis_name] - if major is None and minor is None: - self._reset_axis_ticks(axis_name) - return - levels: list[list[tuple[float, str]]] = [] - if major is not None: - levels.append([(value, _tick_label(value)) for value in major]) - if minor is not None: - levels.append([(value, "") for value in minor]) - self.plot_item.getAxis(axis_name).setTicks(levels) - - def _expand_limits_to_ticks(self, axis_name: str, ticks: list[float]) -> None: - finite = [float(value) for value in ticks if np.isfinite(value)] - if not finite: - return - low = min(finite) - high = max(finite) - if axis_name == "bottom": - current_low, current_high = self._xlim - if low < current_low or high > current_high: - self.set_xlim(min(current_low, low), max(current_high, high)) - elif axis_name == "left": - current_low, current_high = self._ylim - if low < current_low or high > current_high: - self.set_ylim(min(current_low, low), max(current_high, high)) - - def set_xticks(self, ticks: Any, **kwargs: Any) -> None: - axis_name = "bottom" - if kwargs.get("minor"): - self._minor_ticks[axis_name] = _tick_values(ticks) - else: - values = _tick_values(ticks) - self._major_ticks[axis_name] = values - self._expand_limits_to_ticks(axis_name, values) - self._apply_axis_ticks(axis_name) - self._refresh_grid() - if self._aspect_equal: - self.figure.sync_equal_axis_layout() - - def set_yticks(self, ticks: Any, **kwargs: Any) -> None: - axis_name = "left" - if kwargs.get("minor"): - self._minor_ticks[axis_name] = _tick_values(ticks) - else: - values = _tick_values(ticks) - self._major_ticks[axis_name] = values - self._expand_limits_to_ticks(axis_name, values) - self._apply_axis_ticks(axis_name) - self._refresh_grid() - if self._aspect_equal: - self.figure.sync_equal_axis_layout() - - def plot(self, x: Any, y: Any = None, **kwargs: Any) -> list[_Artist]: - if y is None: - y = x - x = np.arange(len(y)) - label = kwargs.get("label") - if label == "_nolegend_": - label = None - item = self.plot_item.plot( - np.asarray(x, dtype=float), - np.asarray(y, dtype=float), - pen=_pen( - kwargs.get("color"), - width=kwargs.get("linewidth") or kwargs.get("lw"), - alpha=kwargs.get("alpha"), - linestyle=kwargs.get("linestyle"), - ), - name=label, - ) - if label: - self._legend_items.append((item, str(label), {"kind": "line"})) - return [_Artist(item)] - - def scatter(self, x: Any, y: Any, **kwargs: Any) -> _ScatterArtist: - size = kwargs.get("s", 28) - marker = str(kwargs.get("marker", "o")) - symbol = {"x": "x", "+": "+", "o": "o", "^": "t", "s": "s", "*": "star", "D": "d", "d": "d"}.get( - marker, - "o", - ) - marker_scale = 1.55 - if marker in {"D", "d"}: - marker_scale = 1.9 - elif marker in {"*", "x", "+"}: - marker_scale = 1.35 - color = ( - kwargs.get("color") - or kwargs.get("c") - or kwargs.get("facecolor") - or kwargs.get("facecolors") - or "#000000" - ) - edge = kwargs.get("edgecolors") or kwargs.get("edgecolor") or color - label = kwargs.get("label") - if label == "_nolegend_": - label = None - marker_size = max(3.0, float(np.asarray(size, dtype=float).ravel()[0]) ** 0.5 * marker_scale) - brush = _brush(color, alpha=kwargs.get("alpha")) - pen = _pen(edge, width=kwargs.get("linewidths") or kwargs.get("linewidth") or 1.0) - item = pg.ScatterPlotItem( - x=np.asarray(x, dtype=float), - y=np.asarray(y, dtype=float), - size=marker_size, - symbol=symbol, - brush=brush, - pen=pen, - name=label, - ) - self.plot_item.addItem(item) - if label: - self._legend_items.append( - ( - item, - str(label), - { - "kind": "scatter", - "size": marker_size, - "symbol": symbol, - "brush": brush, - "pen": pen, - }, - ) - ) - return _ScatterArtist(item, marker_scale=marker_scale, size=size) - - def axvline(self, x: float, **kwargs: Any) -> _Artist: - pen = _pen( - kwargs.get("color"), - width=kwargs.get("linewidth"), - alpha=kwargs.get("alpha"), - linestyle=kwargs.get("linestyle"), - ) - item = pg.InfiniteLine( - pos=float(x), - angle=90, - pen=pen, - ) - self.plot_item.addItem(item) - label = kwargs.get("label") - if label and label != "_nolegend_": - self._legend_items.append((pg.PlotDataItem([0, 1], [0, 0], pen=pen), str(label), {"kind": "line"})) - return _Artist(item) - - def axhline(self, y: float, **kwargs: Any) -> _Artist: - pen = _pen( - kwargs.get("color"), - width=kwargs.get("linewidth"), - alpha=kwargs.get("alpha"), - linestyle=kwargs.get("linestyle"), - ) - item = pg.InfiniteLine( - pos=float(y), - angle=0, - pen=pen, - ) - self.plot_item.addItem(item) - label = kwargs.get("label") - if label and label != "_nolegend_": - self._legend_items.append((pg.PlotDataItem([0, 1], [0, 0], pen=pen), str(label), {"kind": "line"})) - return _Artist(item) - - def axvspan(self, xmin: float, xmax: float, **kwargs: Any) -> _Artist: - y0, y1 = self._ylim - rect = QtWidgets.QGraphicsRectItem(float(xmin), y0, float(xmax) - float(xmin), y1 - y0) - rect.setPen(QtGui.QPen(QtCore.Qt.PenStyle.NoPen)) - rect.setBrush(_brush(kwargs.get("color"), alpha=kwargs.get("alpha"))) - zorder = kwargs.get("zorder") - rect.setZValue(float(zorder) if zorder is not None else -10.0) - self.plot_item.addItem(rect) - return _Artist(rect) - - def text(self, x: float, y: float, text: str, transform: Any = None, **kwargs: Any) -> _TextArtist: - color = kwargs.get("color") or "#000000" - bbox = kwargs.get("bbox") - border, fill = _bbox_pen_brush(bbox) - item = pg.TextItem( - str(text), - color=_color(color), - anchor=_text_anchor(kwargs.get("ha"), kwargs.get("va")), - border=border, - fill=fill, - ) - _set_text_margin(item, 1.0 if bbox is not None else 0.0) - font = _font(kwargs.get("fontsize"), kwargs.get("fontweight") or kwargs.get("weight")) - if font is not None: - item.setFont(font) - if kwargs.get("rotation") is not None: - try: - item.setRotation(float(kwargs["rotation"])) - except Exception: - pass - if transform is self.transAxes: - xr = self._xlim[0] + float(x) * (self._xlim[1] - self._xlim[0]) - yr = self._ylim[0] + float(y) * (self._ylim[1] - self._ylim[0]) - else: - xr, yr = float(x), float(y) - item.setPos(xr, yr) - self.plot_item.addItem(item) - _apply_bbox_text_scale( - item, - str(text), - kwargs.get("fontsize"), - bbox, - kwargs.get("rotation"), - ) - return _TextArtist( - item, - xr, - yr, - axes=self, - ha=kwargs.get("ha"), - va=kwargs.get("va"), - ) - - def annotate(self, text: str, xy: tuple[float, float], **kwargs: Any) -> _TextArtist: - xytext = kwargs.get("xytext", xy) - textcoords = kwargs.get("textcoords") - if textcoords is self.transAxes: - artist = self.text( - float(xytext[0]), - float(xytext[1]), - text, - transform=self.transAxes, - **{key: value for key, value in kwargs.items() if key not in {"xytext", "textcoords"}}, - ) - elif textcoords == "offset points": - artist = self.text( - float(xy[0]), - float(xy[1]), - text, - **{key: value for key, value in kwargs.items() if key not in {"xytext", "textcoords"}}, - ) - artist._offset_units = "offset points" - artist.set_position((float(xytext[0]), float(xytext[1]))) - else: - artist = self.text( - float(xy[0]), - float(xy[1]), - text, - **{key: value for key, value in kwargs.items() if key not in {"xytext", "textcoords"}}, - ) - if textcoords is self.transAxes: - artist._xy = (float(xy[0]), float(xy[1])) - else: - artist.xy = (float(xy[0]), float(xy[1])) - return artist - - def imshow(self, data: Any, **kwargs: Any) -> _ImageArtist: - array = np.asarray(data, dtype=float) - item = pg.ImageItem(array.T) - cmap_name = kwargs.get("cmap") - if cmap_name: - try: - cmap = pg.colormap.get(str(cmap_name)) - item.setLookupTable(cmap.getLookupTable(nPts=256)) - except Exception: - pass - levels = None - if kwargs.get("vmin") is not None and kwargs.get("vmax") is not None: - levels = (float(kwargs["vmin"]), float(kwargs["vmax"])) - item.setLevels(levels) - extent = kwargs.get("extent") - if extent is not None: - left, right, bottom, top = map(float, extent) - item.setRect(QtCore.QRectF(left, bottom, right - left, top - bottom)) - self.set_xlim(left, right) - self.set_ylim(bottom, top) - self.plot_item.addItem(item) - return _ImageArtist(item, levels) - - def _legend_anchor(self, loc: str) -> tuple[tuple[int, int], tuple[int, int], tuple[int, int]]: - normalized = loc.replace("_", " ").lower() - mapping = { - "upper right": ((1, 0), (1, 0), (-8, 8)), - "upper left": ((0, 0), (0, 0), (8, 8)), - "lower right": ((1, 1), (1, 1), (-8, -8)), - "lower left": ((0, 1), (0, 1), (8, -8)), - "center right": ((1, 0), (1, 0), (-8, 36)), - "best": ((1, 0), (1, 0), (-8, 8)), - } - return mapping.get(normalized, mapping["upper right"]) - - def legend(self, **kwargs: Any) -> _Legend: - if self._legend is not None: - try: - scene = self._legend.scene() - if scene is not None: - scene.removeItem(self._legend) - self.plot_item.legend = None - except Exception: - pass - self._legend = None - if self._legend_items: - legend = self.plot_item.addLegend(offset=(0, 0)) - self._legend = legend - try: - legend.setContentsMargins(0, 0, 0, 0) - legend.layout.setContentsMargins(0, 0, 0, 0) - legend.layout.setSpacing(0) - legend.layout.setHorizontalSpacing(1) - legend.layout.setVerticalSpacing(0) - except Exception: - pass - fontsize = kwargs.get("fontsize") - if fontsize is not None: - try: - legend.setLabelTextSize(f"{float(fontsize):g}pt") - except Exception: - pass - try: - markerscale = float(kwargs.get("markerscale", 1.0)) - except Exception: - markerscale = 1.0 - for item, label, meta in self._legend_items: - legend_item = item - if meta.get("kind") == "scatter": - legend_item = pg.ScatterPlotItem( - x=[0.0], - y=[0.0], - size=max(3.0, float(meta.get("size", 6.0)) * markerscale), - symbol=meta.get("symbol", "o"), - brush=meta.get("brush"), - pen=meta.get("pen"), - ) - try: - legend.addItem(legend_item, label) - except Exception: - pass - labels = [label for _item, label, _meta in self._legend_items] - item_anchor, parent_anchor, offset = self._legend_anchor(str(kwargs.get("loc", "upper right"))) - if _uses_short_ascii_legend(labels): - legend.setScale(0.66) - legend.anchor(item_anchor, parent_anchor, offset=offset) - if not _uses_short_ascii_legend(labels): - legend.setTransform(QtGui.QTransform.fromScale(1.0, 0.875), True) - return _Legend(legend) - return _Legend() - - def add_patch(self, patch: Rectangle) -> _Artist: - x, y = patch.xy - rect = QtWidgets.QGraphicsRectItem(float(x), float(y), float(patch.width), float(patch.height)) - rect.setPen( - _pen( - patch.kwargs.get("edgecolor"), - width=patch.kwargs.get("linewidth"), - alpha=patch.kwargs.get("alpha"), - linestyle=patch.kwargs.get("linestyle"), - ) - ) - facecolor = patch.kwargs.get("facecolor") - if patch.kwargs.get("fill") is False or facecolor is None or _is_no_color(facecolor): - rect.setBrush(QtGui.QBrush(QtCore.Qt.BrushStyle.NoBrush)) - else: - rect.setBrush(_brush(facecolor, alpha=patch.kwargs.get("alpha"))) - self.plot_item.addItem(rect) - return _Artist(rect) - - -class Figure: - def __init__(self, figsize: tuple[float, float] = (4.0, 3.0), dpi: int = 100) -> None: - self.figsize = figsize - self.dpi = dpi - self.widget = QtWidgets.QWidget() - self.layout = QtWidgets.QGridLayout(self.widget) - self.layout.setContentsMargins(0, 0, 0, 0) - self.layout.setSpacing(0) - self.axes: list[Axes] = [] - self._next_overlay_row = 0 - self._subplot_adjust: dict[str, float] | None = None - - def set_facecolor(self, color: Any) -> None: - self.widget.setStyleSheet(f"background-color: {_color(color).name()};") - - def subplots_adjust(self, **kwargs: Any) -> None: - current = self._subplot_adjust or { - "left": 0.125, - "right": 0.9, - "bottom": 0.11, - "top": 0.88, - } - self._subplot_adjust = { - **current, - **{key: float(value) for key, value in kwargs.items() if value is not None}, - } - self.sync_equal_axis_layout() - - def _subplot_margins(self, width: int, height: int) -> tuple[int, int, int, int]: - if self._subplot_adjust is None: - self.layout.setContentsMargins(0, 0, 0, 0) - return (0, 0, 0, 0) - has_equal_axis = any(axis._aspect_equal and axis.rect is None for axis in self.axes) - if width < 500 or height < 350: - if has_equal_axis: - self.layout.setContentsMargins(0, 0, 0, 0) - return (0, 0, 0, 0) - self.layout.setContentsMargins(*_COMPACT_SUBPLOT_MARGINS) - return _COMPACT_SUBPLOT_MARGINS - left = max(0.0, min(1.0, self._subplot_adjust.get("left", 0.125))) - right = max(left, min(1.0, self._subplot_adjust.get("right", 0.9))) - bottom = max(0.0, min(1.0, self._subplot_adjust.get("bottom", 0.11))) - top = max(bottom, min(1.0, self._subplot_adjust.get("top", 0.88))) - left_scale = ( - _LARGE_SUBPLOT_LEFT_MARGIN_SCALE - if not has_equal_axis and width >= 500 and height >= 350 - else _SUBPLOT_MARGIN_SCALE - ) - margins = ( - int(round(width * left * left_scale)), - int(round(height * (1.0 - top) * _SUBPLOT_MARGIN_SCALE)), - int(round(width * (1.0 - right) * _SUBPLOT_MARGIN_SCALE)), - int(round(height * bottom * _SUBPLOT_MARGIN_SCALE)), - ) - self.layout.setContentsMargins(*margins) - return margins - - def _apply_rect_axes_layout(self, width: int | None = None, height: int | None = None) -> None: - rect_axes = [axis for axis in self.axes if axis.rect is not None] - if not rect_axes: - return - width = int(width if width is not None and width > 0 else self.widget.width()) - height = int(height if height is not None and height > 0 else self.widget.height()) - if width <= 0: - width = int(self.figsize[0] * self.dpi) - if height <= 0: - height = int(self.figsize[1] * self.dpi) - for axis in rect_axes: - rect = axis.rect or [0.0, 0.0, 1.0, 1.0] - left = max(0.0, min(1.0, float(rect[0]))) - bottom = max(0.0, min(1.0, float(rect[1]))) - rect_width = max(0.0, min(1.0 - left, float(rect[2]))) - rect_height = max(0.0, min(1.0 - bottom, float(rect[3]))) - x = int(round(width * left)) - y = int(round(height * (1.0 - bottom - rect_height))) - w = max(1, int(round(width * rect_width))) - h = max(1, int(round(height * rect_height))) - if rect_width < 0.08: - w = max(w, 58, int(round(width * 0.065))) - elif rect_width >= 0.2 and rect_height >= 0.2: - bottom_margin = ( - _WIDE_RECT_PLOT_BOTTOM_MARGIN - if self.figsize[0] >= 3.4 - else _RECT_PLOT_BOTTOM_MARGIN - ) - x -= _RECT_PLOT_LEFT_MARGIN - y -= _RECT_PLOT_TOP_MARGIN - w += _RECT_PLOT_LEFT_MARGIN + _RECT_PLOT_RIGHT_MARGIN - h += _RECT_PLOT_TOP_MARGIN + bottom_margin - if axis._is_colorbar: - colorbar_min_width = ( - _COMPACT_COLORBAR_MIN_WIDTH - if self.figsize[0] < 3.2 - else _COLORBAR_MIN_WIDTH - ) - colorbar_bottom = ( - _WIDE_COLORBAR_BOTTOM_COMPENSATION - if self.figsize[0] >= 3.4 - else _COLORBAR_BOTTOM_COMPENSATION - ) - x += _COLORBAR_X_OFFSET - y -= _COLORBAR_TOP_COMPENSATION - w = max(w, colorbar_min_width) - h += _COLORBAR_TOP_COMPENSATION + colorbar_bottom - axis.widget.setGeometry(x, y, w, h) - axis.widget.raise_() - axis.widget.updateGeometry() - - def _subplot_position(self, args: tuple[Any, ...]) -> tuple[int, int, int, int]: - if not args: - return (0, 0, 1, 1) - code = args[0] - if isinstance(code, int) and 100 <= code <= 999: - nrows = code // 100 - ncols = (code // 10) % 10 - index = code % 10 - if nrows > 0 and ncols > 0 and 1 <= index <= nrows * ncols: - row = (index - 1) // ncols - column = (index - 1) % ncols - return (row, column, 1, 1) - return (0, 0, 1, 1) - - def add_subplot(self, *args: Any, **_kwargs: Any) -> Axes: - axis = Axes(self) - self.axes.append(axis) - row, column, row_span, column_span = self._subplot_position(args) - self.layout.addWidget(axis.widget, row, column, row_span, column_span) - return axis - - def tight_layout(self, *_args: Any, **_kwargs: Any) -> None: - self.sync_equal_axis_layout() - - def add_axes(self, rect: list[float], **_kwargs: Any) -> Axes: - axis = Axes(self, rect=rect) - self.axes.append(axis) - if float(rect[2]) < 0.08: - width = max(58, int(round(self.figsize[0] * self.dpi * float(rect[2]) * 2.2))) - axis.widget.setMinimumWidth(width) - axis.widget.setMaximumWidth(16_777_215) - axis.plot_item.hideAxis("bottom") - axis.widget.show() - self._apply_rect_axes_layout() - return axis - - def sync_equal_axis_layout( - self, - available_w: int | None = None, - available_h: int | None = None, - ) -> None: - parent = self.widget.parentWidget() - if parent is None: - for axis in self.axes: - if axis.rect is None: - parent = axis.widget.parentWidget() - break - if parent is None: - return - available_w = max(1, int(available_w if available_w is not None else parent.width())) - available_h = max(1, int(available_h if available_h is not None else parent.height())) - self._apply_rect_axes_layout(available_w, available_h) - left_margin, top_margin, right_margin, bottom_margin = self._subplot_margins( - available_w, - available_h, - ) - content_w = max(1, available_w - left_margin - right_margin) - content_h = max(1, available_h - top_margin - bottom_margin) - equal_axes = [axis for axis in self.axes if axis._aspect_equal and axis.rect is None] - if len(equal_axes) != 1: - plot_margins = ( - _LARGE_SUBPLOT_PLOT_MARGINS - if content_w >= 500 and content_h >= 350 - else _COMPACT_SUBPLOT_PLOT_MARGINS - ) - for axis in self.axes: - if axis.rect is None: - axis.plot_item.layout.setContentsMargins(*plot_margins) - axis.widget.setMinimumSize(1, 1) - axis.widget.setMaximumSize(16_777_215, 16_777_215) - return - axis = equal_axes[0] - if content_w < 160 or content_h < 120: - axis.widget.setMinimumSize(1, 1) - axis.widget.setMaximumSize(16_777_215, 16_777_215) - return - x_span = abs(axis._xlim[1] - axis._xlim[0]) - y_span = abs(axis._ylim[1] - axis._ylim[0]) - if x_span <= 0 or y_span <= 0: - return - ratio = x_span / y_span - if content_w >= 500 and content_h >= 350: - if ratio >= 1.2: - width_scale = _LARGE_WIDE_EQUAL_ASPECT_WIDTH_SCALE - height_scale = _LARGE_WIDE_EQUAL_ASPECT_HEIGHT_SCALE - plot_margins = _LARGE_WIDE_EQUAL_ASPECT_MARGINS - else: - width_scale = _LARGE_EQUAL_ASPECT_WIDTH_SCALE - height_scale = _LARGE_EQUAL_ASPECT_HEIGHT_SCALE - plot_margins = _LARGE_EQUAL_ASPECT_MARGINS - else: - width_scale = ( - _WIDE_COMPACT_EQUAL_ASPECT_WIDTH_SCALE - if ratio >= 1.2 - else _COMPACT_EQUAL_ASPECT_WIDTH_SCALE - ) - height_scale = ( - _WIDE_COMPACT_EQUAL_ASPECT_HEIGHT_SCALE - if ratio >= 1.2 - else _COMPACT_EQUAL_ASPECT_HEIGHT_SCALE - ) - plot_margins = ( - _WIDE_COMPACT_EQUAL_ASPECT_MARGINS - if ratio >= 1.2 - else _COMPACT_EQUAL_ASPECT_MARGINS - ) - target_w_limit = content_w - target_h_limit = content_h - if content_w >= 500 and content_h >= 350 and ratio < 1.2: - target_h_limit = min( - available_h, - int(round(content_h * _LARGE_EQUAL_ASPECT_HEIGHT_CAP_SCALE)), - ) - target_w = max(80, min(target_w_limit, int(round(content_h * ratio * width_scale)))) - target_h = max(80, min(target_h_limit, int(round(content_w / ratio * height_scale)))) - # Keep an equal-aspect plot visually bounded without turning its current - # render size into a hard window minimum. ``setFixedSize`` made the - # top-level window refuse the documented 1100x650 compact viewport - # after the first layout pass, especially on high-DPI displays. - axis.widget.setMinimumSize(1, 1) - axis.widget.setMaximumSize(target_w, target_h) - axis.widget.resize(target_w, target_h) - axis.plot_item.layout.setContentsMargins(*plot_margins) - axis.widget.updateGeometry() - self.widget.layout().invalidate() - self.layout.setAlignment(axis.widget, QtCore.Qt.AlignmentFlag.AlignCenter) - axis.plot_item.setXRange(axis._xlim[0], axis._xlim[1], padding=0) - axis.plot_item.setYRange(axis._ylim[0], axis._ylim[1], padding=0) - - def colorbar(self, image: _ImageArtist, cax: Axes) -> _Colorbar: - cax._is_colorbar = True - self._apply_rect_axes_layout() - cax.clear() - levels = image.levels or (0.0, 1.0) - gradient = np.linspace(levels[0], levels[1], 128).reshape(128, 1) - cax.imshow( - gradient, - extent=(0, 1, levels[0], levels[1]), - vmin=levels[0], - vmax=levels[1], - cmap="magma", - ) - span = max(abs(float(levels[1]) - float(levels[0])), 1.0) - cax.set_ylim(float(levels[0]) - span * 0.035, float(levels[1]) + span * 0.035) - cax.set_xticks([]) - cax.plot_item.hideAxis("left") - cax.plot_item.showAxis("right") - cax.plot_item.getAxis("right").setTicks( - [[(float(value), _tick_label(float(value))) for value in np.linspace(levels[0], levels[1], 9)]] - ) - return _Colorbar(cax) - - -class FigureCanvasQt(QtWidgets.QWidget): - """Native Qt canvas with a small, temporary Tk geometry compatibility API. - - New callers should pass a ``QWidget`` as ``parent`` and add this canvas to a - Qt layout normally. ``master``, ``get_tk_widget()``, ``grid()`` and - ``pack()`` remain available so the legacy GUI can migrate incrementally. - """ - - _winfo_class = "Canvas" - - def __init__( - self, - figure: Figure, - parent: Any = None, - *, - master: Any | None = None, - ) -> None: - if parent is not None and master is not None and parent is not master: - raise TypeError("pass either parent or master, not both") - owner = parent if parent is not None else master - qt_parent = _qt_parent(owner) - if owner is not None and qt_parent is None: - raise TypeError("parent must be a QWidget or expose a QWidget through '_qt'") - super().__init__(qt_parent) - self.figure = figure - self._qt = self - self._qt._tk_wrapper = self # type: ignore[attr-defined] - self._parent = owner - self._children: list[Any] = [] - self._grid_layout = None - self._pack_layout = None - self._layout_kind = None - self._padding = (0, 0, 0, 0) - self._bindings: list[Any] = [] - self._callbacks: dict[str, dict[int, Callable[[Any], Any]]] = {} - self._next_callback_id = 1 - self._event_axis_by_object: dict[QtCore.QObject, Axes] = {} - self._captured_axis: Axes | None = None - layout = QtWidgets.QVBoxLayout(self) - layout.setContentsMargins(0, 0, 0, 0) - layout.addWidget(figure.widget) - width = int(figure.figsize[0] * figure.dpi) - height = int(figure.figsize[1] * figure.dpi) - self.resize(width, height) - self.setBaseSize(width, height) - self.setMinimumSize(1, 1) - self.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Expanding, - QtWidgets.QSizePolicy.Policy.Expanding, - ) - figure.widget.setMinimumSize(1, 1) - figure.widget.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Expanding, - QtWidgets.QSizePolicy.Policy.Expanding, - ) - self.setMouseTracking(True) - self.installEventFilter(self) - figure.widget.setMouseTracking(True) - figure.widget.installEventFilter(self) - self._install_axis_event_filters() - if owner is not None and hasattr(owner, "_children"): - owner._children.append(self) # type: ignore[arg-type] - - def get_tk_widget(self) -> "FigureCanvasQt": - return self - - def grab_pointer(self, axis: Axes | None = None) -> None: - """Keep delivering pointer events until release. - - This mirrors pointer capture on the web: direct manipulation remains - continuous even when the cursor temporarily leaves the plot surface. - Repeated calls simply retarget the capture, so the interaction stays - interruptible. - """ - - self._captured_axis = axis - self.grabMouse() - - def release_pointer(self) -> None: - """Release a previously captured pointer without raising on teardown.""" - - self._captured_axis = None - if QtWidgets.QWidget.mouseGrabber() is self: - self.releaseMouse() - - def _emit_pointer_cancel(self) -> None: - """Notify interaction owners when the OS revokes mouse capture.""" - - axis = self._captured_axis - if axis is None: - return - self._captured_axis = None - event = SimpleNamespace( - canvas=self, - inaxes=axis, - x=None, - y=None, - xdata=None, - ydata=None, - button=None, - ) - for callback in list(self._callbacks.get("pointer_cancel_event", {}).values()): - callback(event) - - def winfo_children(self) -> list[Any]: - return list(self._children) - - def winfo_class(self) -> str: - return self._winfo_class - - def winfo_x(self) -> int: - return int(self.x()) - - def winfo_y(self) -> int: - return int(self.y()) - - def winfo_rootx(self) -> int: - return int(self.mapToGlobal(QtCore.QPoint(0, 0)).x()) - - def winfo_rooty(self) -> int: - return int(self.mapToGlobal(QtCore.QPoint(0, 0)).y()) - - def winfo_screenwidth(self) -> int: - screen = QtWidgets.QApplication.primaryScreen() - return int(screen.geometry().width()) if screen is not None else 0 - - def winfo_screenheight(self) -> int: - screen = QtWidgets.QApplication.primaryScreen() - return int(screen.geometry().height()) if screen is not None else 0 - - def winfo_width(self) -> int: - return int(self.width()) - - def winfo_height(self) -> int: - return int(self.height()) - - def winfo_geometry(self) -> str: - return f"{self.width()}x{self.height()}+{self.x()}+{self.y()}" - - def configure(self, **kwargs: Any) -> None: - if "cursor" in kwargs: - _set_cursor(self, kwargs.get("cursor")) - bg = _as_color(kwargs.get("bg") or kwargs.get("background")) - if bg: - self.setStyleSheet(f"background-color: {bg};") - if "width" in kwargs: - self.resize(int(kwargs["width"]), self.height()) - self.setBaseSize(int(kwargs["width"]), self.baseSize().height()) - if "height" in kwargs: - self.resize(self.width(), int(kwargs["height"])) - self.setBaseSize(self.baseSize().width(), int(kwargs["height"])) - - config = configure - - def _compat_grid_layout(self) -> QtWidgets.QGridLayout: - if self._parent is None: - raise RuntimeError("grid() requires a parent; use a native Qt layout for new code") - ensure_layout = getattr(self._parent, "_ensure_grid_layout", None) - if callable(ensure_layout): - layout = ensure_layout() - if isinstance(layout, QtWidgets.QGridLayout): - return layout - parent = _qt_parent(self._parent) - if parent is None: - raise TypeError("grid() parent is not backed by QWidget") - layout = parent.layout() - if layout is None: - layout = QtWidgets.QGridLayout(parent) - layout.setContentsMargins(0, 0, 0, 0) - layout.setSpacing(0) - if not isinstance(layout, QtWidgets.QGridLayout): - raise TypeError("grid() requires a QGridLayout; use layout.addWidget(canvas) instead") - return layout - - def _compat_pack_layout(self, side: str | None) -> QtWidgets.QBoxLayout: - if self._parent is None: - raise RuntimeError("pack() requires a parent; use a native Qt layout for new code") - ensure_layout = getattr(self._parent, "_ensure_pack_layout", None) - if callable(ensure_layout): - layout = ensure_layout(side) - if isinstance(layout, QtWidgets.QBoxLayout): - return layout - parent = _qt_parent(self._parent) - if parent is None: - raise TypeError("pack() parent is not backed by QWidget") - layout = parent.layout() - if layout is None: - if side in {"left", "right"}: - layout = QtWidgets.QHBoxLayout(parent) - else: - layout = QtWidgets.QVBoxLayout(parent) - layout.setContentsMargins(0, 0, 0, 0) - layout.setSpacing(0) - if not isinstance(layout, QtWidgets.QBoxLayout): - raise TypeError("pack() requires a QBoxLayout; use layout.addWidget(canvas) instead") - return layout - - def grid( - self, - row: int = 0, - column: int = 0, - rowspan: int = 1, - columnspan: int = 1, - sticky: str | None = None, - padx: Any = None, - pady: Any = None, - **_kwargs: Any, - ) -> None: - """Place the canvas using the legacy Tk-style grid contract.""" - if self._parent is None: - return - layout = self._compat_grid_layout() - pad_left, pad_right = _parse_pad_pair(padx) - pad_top, pad_bottom = _parse_pad_pair(pady) - if pad_left or pad_right: - layout.setHorizontalSpacing( - max(0, layout.horizontalSpacing(), pad_left + pad_right) - ) - if pad_top or pad_bottom: - layout.setVerticalSpacing(max(0, layout.verticalSpacing(), pad_top + pad_bottom)) - - alignment = QtCore.Qt.AlignmentFlag(0) - sticky = sticky or "" - if "w" in sticky and "e" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignLeft - elif "e" in sticky and "w" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignRight - elif "w" not in sticky and "e" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignHCenter - if "n" in sticky and "s" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignTop - elif "s" in sticky and "n" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignBottom - elif "n" not in sticky and "s" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignVCenter - - if alignment: - layout.addWidget(self, row, column, rowspan, columnspan, alignment) - else: - layout.addWidget(self, row, column, rowspan, columnspan) - - parent = self._parent - if hasattr(parent, "_grid_max_row"): - parent._grid_max_row = max(parent._grid_max_row, row + rowspan - 1) - if hasattr(parent, "_grid_max_column"): - parent._grid_max_column = max(parent._grid_max_column, column + columnspan - 1) - sync_grid = getattr(parent, "_sync_grid_slack", None) - if callable(sync_grid): - sync_grid() - - def pack( - self, - side: str | None = None, - fill: str | None = None, - expand: bool = False, - padx: Any = None, - pady: Any = None, - anchor: str | None = None, - **_kwargs: Any, - ) -> None: - """Place the canvas using the legacy Tk-style pack contract.""" - del anchor # Kept for signature compatibility; the prior adapter ignored it too. - if self._parent is None: - return - layout = self._compat_pack_layout(side) - stretch = 1 if expand else 0 - pad_left, pad_right = _parse_pad_pair(padx) - pad_top, pad_bottom = _parse_pad_pair(pady) - is_horizontal = layout.direction() in { - QtWidgets.QBoxLayout.Direction.LeftToRight, - QtWidgets.QBoxLayout.Direction.RightToLeft, - } - before_pad = pad_left if is_horizontal else pad_top - after_pad = pad_right if is_horizontal else pad_bottom - if before_pad: - layout.addSpacing(before_pad) - alignment = QtCore.Qt.AlignmentFlag(0) - if is_horizontal and fill != "both": - alignment |= QtCore.Qt.AlignmentFlag.AlignVCenter - elif not is_horizontal and fill not in {"x", "both"}: - alignment |= QtCore.Qt.AlignmentFlag.AlignHCenter - if alignment: - layout.addWidget(self, stretch, alignment) - else: - layout.addWidget(self, stretch) - if after_pad: - layout.addSpacing(after_pad) - - if fill in {"x", "both"} or expand: - if is_horizontal: - horizontal_policy = QtWidgets.QSizePolicy.Policy.Expanding - vertical_policy = ( - QtWidgets.QSizePolicy.Policy.Expanding - if fill == "both" - else QtWidgets.QSizePolicy.Policy.Preferred - ) - else: - horizontal_policy = ( - QtWidgets.QSizePolicy.Policy.Expanding - if fill in {"x", "both"} - else QtWidgets.QSizePolicy.Policy.Preferred - ) - vertical_policy = ( - QtWidgets.QSizePolicy.Policy.Expanding - if expand or fill == "both" - else QtWidgets.QSizePolicy.Policy.Preferred - ) - self.setSizePolicy(horizontal_policy, vertical_policy) - - def draw_idle(self) -> None: - self.update() - - def draw(self) -> None: - self.update() - - def resizeEvent(self, event: QtGui.QResizeEvent) -> None: # noqa: N802 - self._install_axis_event_filters() - self.figure.sync_equal_axis_layout(event.size().width(), event.size().height()) - super().resizeEvent(event) - - def mpl_connect(self, event_name: str, callback: Callable[[Any], Any]) -> int: - callback_id = self._next_callback_id - self._next_callback_id += 1 - self._callbacks.setdefault(event_name, {})[callback_id] = callback - return callback_id - - def mpl_disconnect(self, callback_id: int) -> None: - for callbacks in self._callbacks.values(): - callbacks.pop(callback_id, None) - - def _install_axis_event_filters(self) -> None: - for axis in self.figure.axes: - axis.widget.setMouseTracking(True) - sources: list[QtCore.QObject] = [axis.widget] - viewport = axis.widget.viewport() if hasattr(axis.widget, "viewport") else None - if viewport is not None: - viewport.setMouseTracking(True) - sources.append(viewport) - scene = axis.widget.scene() if hasattr(axis.widget, "scene") else None - if scene is not None: - sources.append(scene) - for source in sources: - if source in self._event_axis_by_object: - continue - source.installEventFilter(self) - self._event_axis_by_object[source] = axis - - def _axis_at( - self, - scene_pos: QtCore.QPointF, - preferred_axis: Axes | None = None, - ) -> tuple[Axes | None, float | None, float | None]: - if preferred_axis is not None: - plot_item = preferred_axis.plot_item - if plot_item.sceneBoundingRect().contains(scene_pos): - point = plot_item.vb.mapSceneToView(scene_pos) - return preferred_axis, float(point.x()), float(point.y()) - for axis in self.figure.axes: - plot_item = axis.plot_item - if plot_item.sceneBoundingRect().contains(scene_pos): - point = plot_item.vb.mapSceneToView(scene_pos) - return axis, float(point.x()), float(point.y()) - return None, None, None - - def _mouse_button(self, qt_event: Any) -> int | None: - button = qt_event.button() if hasattr(qt_event, "button") else None - if button == QtCore.Qt.MouseButton.LeftButton: - return 1 - if button == QtCore.Qt.MouseButton.MiddleButton: - return 2 - if button == QtCore.Qt.MouseButton.RightButton: - return 3 - return None - - def _event_scene_pos( - self, - watched: QtCore.QObject | None, - qt_event: Any, - preferred_axis: Axes | None, - ) -> QtCore.QPointF: - if hasattr(qt_event, "scenePos"): - return QtCore.QPointF(qt_event.scenePos()) - pos = qt_event.position() if hasattr(qt_event, "position") else qt_event.pos() - point = pos.toPoint() if hasattr(pos, "toPoint") else QtCore.QPoint(int(pos.x()), int(pos.y())) - if preferred_axis is not None and hasattr(preferred_axis.widget, "mapToScene"): - if watched is preferred_axis.widget: - return QtCore.QPointF(preferred_axis.widget.mapToScene(point)) - if isinstance(watched, QtWidgets.QWidget): - global_pos = watched.mapToGlobal(point) - local_pos = preferred_axis.widget.mapFromGlobal(global_pos) - return QtCore.QPointF(preferred_axis.widget.mapToScene(local_pos)) - if isinstance(watched, QtWidgets.QWidget): - global_pos = watched.mapToGlobal(point) - for axis in self.figure.axes: - if hasattr(axis.widget, "mapFromGlobal") and hasattr(axis.widget, "mapToScene"): - local_pos = axis.widget.mapFromGlobal(global_pos) - if axis.widget.rect().contains(local_pos): - return QtCore.QPointF(axis.widget.mapToScene(local_pos)) - return QtCore.QPointF(pos) - - def _emit( - self, - event_name: str, - qt_event: Any, - *, - button: int | None = None, - watched: QtCore.QObject | None = None, - ) -> None: - preferred_axis = ( - self._event_axis_by_object.get(watched) - if watched is not None - else None - ) or self._captured_axis - scene_pos = self._event_scene_pos(watched, qt_event, preferred_axis) - axis, xdata, ydata = self._axis_at(scene_pos, preferred_axis) - event = SimpleNamespace( - canvas=self, - inaxes=axis, - x=float(scene_pos.x()), - y=float(scene_pos.y()), - xdata=xdata, - ydata=ydata, - button=button, - ) - for callback in list(self._callbacks.get(event_name, {}).values()): - callback(event) - - def eventFilter(self, watched: QtCore.QObject, event: QtCore.QEvent) -> bool: - is_axis_source = watched in self._event_axis_by_object - if event.type() in { - QtCore.QEvent.Type.GraphicsSceneMouseMove, - QtCore.QEvent.Type.MouseMove, - }: - if event.type() == QtCore.QEvent.Type.GraphicsSceneMouseMove or not is_axis_source: - self._emit("motion_notify_event", event, watched=watched) - return True - elif event.type() in { - QtCore.QEvent.Type.GraphicsSceneMousePress, - QtCore.QEvent.Type.MouseButtonPress, - }: - if event.type() == QtCore.QEvent.Type.GraphicsSceneMousePress or not is_axis_source: - self._emit("button_press_event", event, button=self._mouse_button(event), watched=watched) - return True - elif event.type() in { - QtCore.QEvent.Type.GraphicsSceneMouseRelease, - QtCore.QEvent.Type.MouseButtonRelease, - }: - if event.type() == QtCore.QEvent.Type.GraphicsSceneMouseRelease or not is_axis_source: - self._emit("button_release_event", event, button=self._mouse_button(event), watched=watched) - return True - elif event.type() == QtCore.QEvent.Type.Leave: - for callback in list(self._callbacks.get("figure_leave_event", {}).values()): - callback(SimpleNamespace(canvas=self, inaxes=None, xdata=None, ydata=None, button=None)) - elif event.type() == QtCore.QEvent.Type.UngrabMouse: - self._emit_pointer_cancel() - return super().eventFilter(watched, event) - - def winfo_class(self) -> str: - return self._winfo_class - - -# Transitional import compatibility. New code should use FigureCanvasQt. -FigureCanvasTkAgg = FigureCanvasQt - - -class MplButton: - def __init__(self, ax: Axes, label: str, color: Any = None, hovercolor: Any = None) -> None: - self.ax = ax - self.button = QtWidgets.QPushButton(label, ax.widget) - self.button.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Expanding, - QtWidgets.QSizePolicy.Policy.Expanding, - ) - layout = QtWidgets.QVBoxLayout(ax.widget) - layout.setContentsMargins(0, 0, 0, 0) - layout.addWidget(self.button) - if color: - hover = _color(hovercolor or color).name() - base = _color(color).name() - self.button.setStyleSheet( - f"QPushButton {{ background-color: {base}; " - f"border: 1px solid {TOKENS.border}; " - f"border-radius: {TOKENS.radius}px; }}" - f"QPushButton:hover {{ background-color: {hover}; }}" - f"QPushButton:pressed {{ background-color: {TOKENS.surface_pressed}; }}" - ) - self.label = _LabelProxy(self.button.setText) - - def on_clicked(self, callback: Callable[[Any], Any]) -> int: - self.button.clicked.connect(lambda _checked=False: callback(SimpleNamespace())) - return 1 diff --git a/src/virtual_array/qt_tk.py b/src/virtual_array/qt_tk.py deleted file mode 100644 index 133ddfc..0000000 --- a/src/virtual_array/qt_tk.py +++ /dev/null @@ -1,3419 +0,0 @@ -from __future__ import annotations - -import itertools -import re -import sys -from pathlib import Path -from types import SimpleNamespace -from typing import Any, Callable - -from PySide6 import QtCore, QtGui, QtWidgets - -from .native_theme import TOKENS - - -class TclError(Exception): - """Compatibility exception used by Tk-oriented GUI code.""" - - -HORIZONTAL = "horizontal" -VERTICAL = "vertical" -LEFT = "left" -RIGHT = "right" -X = "x" -BOTH = "both" -WORD = "word" -SOLID = "solid" -END = "end" -DISABLED = "disabled" -NORMAL = "normal" - - -_DEFAULT_FONT_FAMILY = "Microsoft YaHei" -_ITEM_IDS = itertools.count(1) -_STYLE_CONFIGS: dict[str, dict[str, Any]] = {} -_STYLE_MAPS: dict[str, dict[str, list[tuple[str, Any]]]] = {} -_HIDDEN_NOTEBOOK_TABS: set[str] = set() -_OBJECT_IDS = itertools.count(1) - - -def _ensure_app() -> QtWidgets.QApplication: - app = QtWidgets.QApplication.instance() - if app is None: - app = QtWidgets.QApplication(sys.argv[:1]) - app.setStyle("Fusion") - return app - - -def _qt_parent(parent: Any) -> QtWidgets.QWidget | None: - if parent is None: - return None - return getattr(parent, "_qt", None) - - -def _as_color(value: Any) -> str | None: - if isinstance(value, str) and value: - return value - return None - - -def _parse_padding(value: Any) -> tuple[int, int, int, int]: - if value is None: - return (0, 0, 0, 0) - if isinstance(value, int): - return (value, value, value, value) - if isinstance(value, tuple): - if len(value) == 2: - x, y = value - return (int(x), int(y), int(x), int(y)) - if len(value) == 4: - return tuple(int(part) for part in value) # type: ignore[return-value] - return (0, 0, 0, 0) - - -def _qt_button_text(value: Any) -> str: - return str(value).replace("&", "&&") - - -def _parse_pad_pair(value: Any) -> tuple[int, int]: - if value is None: - return (0, 0) - if isinstance(value, int): - return (int(value), int(value)) - if isinstance(value, tuple): - if len(value) == 2: - return (int(value[0]), int(value[1])) - if len(value) == 4: - return (int(value[0]), int(value[2])) - return (0, 0) - - -def _parse_geometry(value: str) -> tuple[int, int, int | None, int | None] | None: - match = re.match(r"^(\d+)x(\d+)(?:([+-]\d+)([+-]\d+))?$", value) - if not match: - return None - width = int(match.group(1)) - height = int(match.group(2)) - x = int(match.group(3)) if match.group(3) else None - y = int(match.group(4)) if match.group(4) else None - return width, height, x, y - - -def _screen_geometry_limit() -> QtCore.QSize | None: - app = _ensure_app() - screens = app.screens() - if not screens: - return None - width = max(screen.availableGeometry().width() for screen in screens) - height = max(screen.availableGeometry().height() for screen in screens) - return QtCore.QSize(width, height) - - -def _tk_px(value: int | float) -> int: - """Return Qt logical pixels. - - Qt already exposes device-independent logical coordinates when high-DPI - scaling is enabled. Dividing by ``devicePixelRatio`` a second time made - the old compatibility UI shrink at 125%/150% Windows scaling (most - noticeably the header chips). Keeping the logical value lets Qt perform - the only required conversion. - """ - - return max(1, int(round(float(value)))) - - -def _scrollbar_fractions(scrollbar: QtWidgets.QScrollBar) -> tuple[float, float]: - minimum = scrollbar.minimum() - maximum = scrollbar.maximum() - page = max(1, scrollbar.pageStep()) - span = max(1, maximum - minimum + page) - first = (scrollbar.value() - minimum) / span - last = (scrollbar.value() - minimum + page) / span - return (max(0.0, min(1.0, first)), max(0.0, min(1.0, last))) - - -def _scrollbar_view(scrollbar: QtWidgets.QScrollBar, *args: Any) -> tuple[float, float] | None: - if not args: - return _scrollbar_fractions(scrollbar) - command = args[0] - if command == "moveto" and len(args) >= 2: - try: - fraction = float(args[1]) - except (TypeError, ValueError): - return None - span = scrollbar.maximum() - scrollbar.minimum() - scrollbar.setValue(scrollbar.minimum() + int(round(span * fraction))) - return None - if command == "scroll" and len(args) >= 3: - try: - amount = int(args[1]) - except (TypeError, ValueError): - return None - unit = str(args[2]) - step = scrollbar.pageStep() if unit.startswith("page") else scrollbar.singleStep() - scrollbar.setValue(scrollbar.value() + amount * max(1, step)) - return None - - -def _connect_scroll_command( - scrollbar: QtWidgets.QScrollBar, - command: Callable[..., Any] | None, -) -> None: - if command is None: - return - owner = getattr(command, "__self__", None) - if getattr(owner, "_winfo_class", None) == "TScrollbar" and hasattr( - owner, "_attach_qt_scrollbar" - ): - owner._attach_qt_scrollbar(scrollbar) - return - - def emit(*_args: Any) -> None: - first, last = _scrollbar_fractions(scrollbar) - command(first, last) - - refs = getattr(scrollbar, "_tk_scroll_callbacks", []) - refs.append(emit) - scrollbar._tk_scroll_callbacks = refs # type: ignore[attr-defined] - scrollbar.valueChanged.connect(emit) - scrollbar.rangeChanged.connect(lambda *_args: emit()) - QtCore.QTimer.singleShot(0, emit) - - -def _sequence_to_key(sequence: str) -> tuple[str, str]: - cleaned = sequence.strip("<>") - parts = cleaned.split("-") - key = parts[-1] - modifiers = {part.lower() for part in parts[:-1]} - qt_parts: list[str] = [] - if "control" in modifiers or "ctrl" in modifiers: - qt_parts.append("Ctrl") - if "shift" in modifiers: - qt_parts.append("Shift") - qt_key_map = { - "Escape": "Esc", - "Delete": "Del", - "Left": "Left", - "Right": "Right", - "Up": "Up", - "Down": "Down", - } - qt_key = qt_key_map.get(key, key.upper() if len(key) == 1 else key) - qt_parts.append(qt_key) - keysym = { - "Esc": "Escape", - "Del": "Delete", - }.get(qt_key, key) - return "+".join(qt_parts), keysym - - -def _cursor_shape(name: str | None) -> QtCore.Qt.CursorShape: - if name in {"hand2", "pointinghand"}: - return QtCore.Qt.CursorShape.PointingHandCursor - if name in {"fleur", "size_all"}: - return QtCore.Qt.CursorShape.SizeAllCursor - if name in {"sb_h_double_arrow", "size_hor"}: - return QtCore.Qt.CursorShape.SizeHorCursor - if name in {"sb_v_double_arrow", "size_ver"}: - return QtCore.Qt.CursorShape.SizeVerCursor - if name in {"cross", "crosshair"}: - return QtCore.Qt.CursorShape.CrossCursor - return QtCore.Qt.CursorShape.ArrowCursor - - -def _set_cursor(widget: QtWidgets.QWidget, name: str | None) -> None: - if name: - widget.setCursor(QtGui.QCursor(_cursor_shape(name))) - else: - widget.unsetCursor() - - -def _qt_alignment(anchor: str | None = None, justify: str | None = None) -> QtCore.Qt.AlignmentFlag: - anchor = (anchor or "").lower() - justify = (justify or "").lower() - alignment = QtCore.Qt.AlignmentFlag(0) - if anchor in {"center", "c"} or justify == "center": - alignment |= QtCore.Qt.AlignmentFlag.AlignHCenter - elif "e" in anchor or justify == "right": - alignment |= QtCore.Qt.AlignmentFlag.AlignRight - elif "w" in anchor or justify == "left" or not anchor and not justify: - alignment |= QtCore.Qt.AlignmentFlag.AlignLeft - else: - alignment |= QtCore.Qt.AlignmentFlag.AlignHCenter - if "n" in anchor: - alignment |= QtCore.Qt.AlignmentFlag.AlignTop - elif "s" in anchor: - alignment |= QtCore.Qt.AlignmentFlag.AlignBottom - else: - alignment |= QtCore.Qt.AlignmentFlag.AlignVCenter - return alignment - - -def _style_chain(style_name: str | None, default_style: str) -> list[str]: - chain = [default_style] - if style_name and style_name != default_style: - chain.append(style_name) - return chain - - -def _merged_style(style_name: str | None, default_style: str) -> dict[str, Any]: - merged: dict[str, Any] = {} - for name in _style_chain(style_name, default_style): - merged.update(_STYLE_CONFIGS.get(name, {})) - return merged - - -def _merged_maps(style_name: str | None, default_style: str) -> dict[str, list[tuple[str, Any]]]: - merged: dict[str, list[tuple[str, Any]]] = {} - for name in _style_chain(style_name, default_style): - for key, value in _STYLE_MAPS.get(name, {}).items(): - merged[key] = value - return merged - - -def _font_rules(font: Any) -> list[str]: - if not font: - return [] - family = _DEFAULT_FONT_FAMILY - size: int | None = None - bold = False - italic = False - if isinstance(font, tuple): - if font: - family = str(font[0]) - if len(font) > 1: - try: - size = int(font[1]) - except (TypeError, ValueError): - size = None - for part in font[2:]: - text = str(part).lower() - bold = bold or "bold" in text - italic = italic or "italic" in text - elif isinstance(font, str): - family = font - if family.lower().startswith("tkdefaultfont"): - family = _DEFAULT_FONT_FAMILY - elif family.lower().startswith("tkfixedfont"): - family = "Cascadia Mono" - fallback_families = [ - family, - "Microsoft YaHei", - "SimHei", - "Noto Sans CJK SC", - "Segoe UI", - "sans-serif", - ] - unique_families = list(dict.fromkeys(fallback_families)) - rules = [ - "font-family: " - + ", ".join( - name if name == "sans-serif" else f"\"{name}\"" - for name in unique_families - ) - + ";" - ] - if size is not None: - rules.append(f"font-size: {size}pt;") - if bold: - rules.append("font-weight: 700;") - if italic: - rules.append("font-style: italic;") - return rules - - -def _font_from_config(font: Any) -> QtGui.QFont | None: - if not font: - return None - family = _DEFAULT_FONT_FAMILY - size: int | None = None - bold = False - italic = False - if isinstance(font, tuple): - if font: - family = str(font[0]) - if len(font) > 1: - try: - size = int(font[1]) - except (TypeError, ValueError): - size = None - for part in font[2:]: - text = str(part).lower() - bold = bold or "bold" in text - italic = italic or "italic" in text - elif isinstance(font, str): - family = font - if family.lower().startswith("tkdefaultfont"): - family = _DEFAULT_FONT_FAMILY - elif family.lower().startswith("tkfixedfont"): - family = "Cascadia Mono" - qt_font = QtGui.QFont(family) - if hasattr(qt_font, "setFamilies"): - qt_font.setFamilies( - [ - family, - "Microsoft YaHei", - "SimHei", - "Noto Sans CJK SC", - "Segoe UI", - ] - ) - if size is not None: - qt_font.setPointSize(size) - qt_font.setBold(bold) - qt_font.setItalic(italic) - return qt_font - - -def _font_config_with_size(font: Any, size: int) -> Any: - if isinstance(font, tuple): - if not font: - return (_DEFAULT_FONT_FAMILY, size) - return (font[0], size, *font[2:]) - if isinstance(font, str): - return (font, size) - return (_DEFAULT_FONT_FAMILY, size) - - -def _font_family_name(font: Any) -> str: - if isinstance(font, tuple) and font: - return str(font[0]) - if isinstance(font, str): - return font - return "" - - -def _uses_tk_default_font(config: dict[str, Any]) -> bool: - return _font_family_name(config.get("font")).lower().startswith("tkdefaultfont") - - -def _padding_rule(value: Any) -> str | None: - left, top, right, bottom = _parse_padding(value) - if left == top == right == bottom == 0: - return None - return f"padding: {top}px {right}px {bottom}px {left}px;" - - -def _text_width_px(width: int | None, *, average_px: int | float = 9) -> int | None: - if width is None: - return None - return int(round(max(1, int(width)) * float(average_px))) - - -def _header_chip_name_min_width(text: str) -> int: - if len(text) >= 5 and any(ord(char) > 127 for char in text): - return int(round(len(text) * 13.8)) - return 0 - - -def _toolbar_label_min_width( - label: QtWidgets.QLabel, - config: dict[str, Any] | None = None, -) -> int: - text = label.text() - cjk_count = sum(1 for char in text if ord(char) > 127) - if config is not None and _uses_tk_default_font(config): - has_unit_suffix = "(" in text or "(" in text - if has_unit_suffix: - compensation = 14 if cjk_count >= 4 else 9 - else: - compensation = 8 if cjk_count >= 4 else 5 - else: - compensation = 8 if cjk_count >= 4 else 5 - return label.fontMetrics().horizontalAdvance(text) + compensation - - -def _button_minimum_height(config: dict[str, Any], font_metrics: QtGui.QFontMetrics) -> int: - _left, top, _right, bottom = _parse_padding(config.get("padding")) - borderwidth = int(config.get("borderwidth") or 0) - return max(1, font_metrics.height() + top + bottom + borderwidth * 2 + 2) - - -def _allows_layout_expansion(widget: QtWidgets.QWidget) -> bool: - return not isinstance( - widget, - ( - QtWidgets.QAbstractButton, - QtWidgets.QLabel, - QtWidgets.QLineEdit, - QtWidgets.QPlainTextEdit, - QtWidgets.QComboBox, - ), - ) - - -def _mapped_value( - maps: dict[str, list[tuple[str, Any]]], option: str, state: str -) -> Any | None: - for map_state, value in maps.get(option, []): - if map_state == state: - return value - return None - - -def _style_rules(config: dict[str, Any], *, widget_kind: str) -> list[str]: - background = config.get("fieldbackground") if widget_kind == "entry" else None - background = background or config.get("background") - foreground = config.get("foreground") - bordercolor = config.get("bordercolor") or config.get("darkcolor") - borderwidth = config.get("borderwidth") - relief = str(config.get("relief") or "").lower() - padding = config.get("padding") - rules: list[str] = [] - if background: - rules.append(f"background-color: {background};") - if foreground: - rules.append(f"color: {foreground};") - rules.extend(_font_rules(config.get("font"))) - if widget_kind == "checkbutton": - # Keep native radio indicators intact. Setting a widget background or - # border through QSS makes Qt's stylesheet engine replace the platform - # radio painting; on Windows that reduces the selected indicator to a - # lone dot. With only typography and spacing, radio labels naturally - # inherit their parent surface while the native circle remains intact. - rules.append("spacing: 4px;") - return rules - if config.get("selectbackground"): - rules.append(f"selection-background-color: {config['selectbackground']};") - if config.get("selectforeground"): - rules.append(f"selection-color: {config['selectforeground']};") - padding_css = _padding_rule(padding) - if padding_css: - rules.append(padding_css) - if bordercolor or borderwidth or relief in {"solid", "sunken", "raised", "groove", "ridge"}: - width = int(borderwidth if borderwidth is not None else 1) - if widget_kind in {"button", "toolbutton"} and relief == "flat" and width <= 1: - width = 0 - color = bordercolor or ("#cbd5e1" if relief != "flat" and width > 0 else "transparent") - if width == 0: - color = "transparent" - rules.append(f"border: {width}px solid {color};") - if widget_kind in {"button", "entry", "toolbutton"}: - rules.append(f"border-radius: {TOKENS.radius}px;") - elif widget_kind in {"frame", "groupbox"}: - rules.append(f"border-radius: {TOKENS.card_radius}px;") - elif widget_kind in {"button", "toolbutton"}: - rules.append("border: 1px solid transparent;") - rules.append(f"border-radius: {TOKENS.radius}px;") - return rules - - -def _effective_style_config( - style_name: str | None, - default_style: str, - *, - overrides: dict[str, Any] | None = None, -) -> dict[str, Any]: - config = _merged_style(style_name, default_style) - if overrides: - config.update(overrides) - if style_name in {"AppBrand.TLabel", "AppSeparator.TLabel"}: - config = dict(config) - config["font"] = _font_config_with_size(config.get("font"), 10) - elif style_name == "TopMenu.TMenubutton": - config = dict(config) - left, _top, right, _bottom = _parse_padding(config.get("padding")) - config["padding"] = (left, 4, right, 4) - elif style_name in {"WorkspaceTab.TButton", "WorkspaceTabSelected.TButton"}: - config = dict(config) - left, _top, right, _bottom = _parse_padding(config.get("padding")) - config["padding"] = (left, 6, right, 6) - elif style_name in { - "HeaderChipName.TLabel", - "HeaderChipValue.TLabel", - "HeaderChipPatternValue.TLabel", - }: - config = dict(config) - font = config.get("font") - size = 9 - if isinstance(font, tuple) and len(font) > 1: - try: - size = max(9, int(font[1])) - except (TypeError, ValueError): - pass - config["font"] = _font_config_with_size(font, size) - return config - - -def _qss_for_widget( - object_name: str, - style_name: str | None, - default_style: str, - *, - widget_kind: str, - overrides: dict[str, Any] | None = None, -) -> str: - config = _effective_style_config( - style_name, - default_style, - overrides=overrides, - ) - if widget_kind == "radiobutton": - # Transparent QSS propagates into the native indicator on Windows and - # removes its outer circle. Most radios therefore stay entirely native; - # a named surface style may request one opaque fill so toolbar controls - # blend with their parent without replacing the indicator painting. - background = _as_color(config.get("background")) - return ( - f"#{object_name} {{ background-color: {background}; }}" - if background - else "" - ) - maps = _merged_maps(style_name, default_style) - base_rules = _style_rules(config, widget_kind=widget_kind) - selector = f"#{object_name}" - blocks: list[str] = [] - if base_rules: - blocks.append(f"{selector} {{ {' '.join(base_rules)} }}") - - if widget_kind in {"button", "toolbutton"}: - for state, pseudo in (("active", "hover"), ("pressed", "pressed"), ("disabled", "disabled")): - state_config = dict(config) - for option in ("background", "foreground", "bordercolor", "lightcolor", "darkcolor"): - value = _mapped_value(maps, option, state) - if value is not None: - state_config[option] = value - state_rules = _style_rules(state_config, widget_kind=widget_kind) - if state_rules: - blocks.append(f"{selector}:{pseudo} {{ {' '.join(state_rules)} }}") - blocks.append( - f"{selector}:focus {{ border: 2px solid {TOKENS.focus}; }}" - ) - if style_name and "danger" in style_name.lower(): - blocks.append( - f"{selector}:checked {{ background-color: {TOKENS.danger_fill}; " - f"color: {TOKENS.danger}; border: 1px solid {TOKENS.danger}; }}" - ) - else: - blocks.append( - f"{selector}:checked {{ background-color: {TOKENS.accent_tint}; " - f"color: {TOKENS.accent_pressed}; border: 1px solid {TOKENS.accent}; }}" - ) - - if widget_kind == "entry": - selection_bg = config.get("selectbackground") - selection_fg = config.get("selectforeground") - selection_rules = [] - if selection_bg: - selection_rules.append(f"selection-background-color: {selection_bg};") - if selection_fg: - selection_rules.append(f"selection-color: {selection_fg};") - if selection_rules: - blocks.append(f"{selector} {{ {' '.join(selection_rules)} }}") - blocks.append( - f"{selector}:focus {{ border: 2px solid {TOKENS.focus}; }}" - ) - - if widget_kind == "checkbutton": - blocks.append(f"{selector}:focus {{ color: {TOKENS.accent_pressed}; }}") - - if widget_kind == "groupbox": - title_color = config.get("foreground") - title_rules = _font_rules(config.get("font")) - if title_color: - title_rules.append(f"color: {title_color};") - if title_rules: - blocks.append(f"{selector}::title {{ {' '.join(title_rules)} }}") - - if widget_kind == "tree": - heading_config = _merged_style("Treeview.Heading", "Treeview.Heading") - heading_rules = _style_rules(heading_config, widget_kind="frame") - if heading_rules: - blocks.append( - f"{selector} QHeaderView::section {{ {' '.join(heading_rules)} }}" - ) - rowheight = config.get("rowheight") - if rowheight: - blocks.append(f"{selector}::item {{ height: {int(rowheight)}px; }}") - selected_rules = [] - selected_bg = _mapped_value(maps, "background", "selected") - selected_fg = _mapped_value(maps, "foreground", "selected") - if selected_bg: - selected_rules.append(f"background-color: {selected_bg};") - if selected_fg: - selected_rules.append(f"color: {selected_fg};") - if selected_rules: - blocks.append(f"{selector}::item:selected {{ {' '.join(selected_rules)} }}") - blocks.append( - f"{selector}:focus {{ border: 2px solid {TOKENS.focus}; }}" - ) - - if widget_kind == "notebook": - tab_config = _merged_style(f"{style_name}.Tab" if style_name else "TNotebook.Tab", "TNotebook.Tab") - if not tab_config and style_name != "Eval.TNotebook": - tab_config = _merged_style("Eval.TNotebook.Tab", "Eval.TNotebook.Tab") - tab_rules = _style_rules(tab_config, widget_kind="button") - tab_rules.extend( - [ - "min-width: 76px;", - "min-height: 24px;", - "margin-right: 2px;", - ] - ) - if tab_rules: - blocks.append(f"{selector} QTabBar::tab {{ {' '.join(tab_rules)} }}") - unselected_config = dict(tab_config) - unselected_config["foreground"] = ( - unselected_config.get("foreground") or config.get("foreground") or "#111827" - ) - unselected_rules = _style_rules(unselected_config, widget_kind="button") - unselected_rules.extend(["min-width: 76px;", "min-height: 24px;"]) - blocks.append( - f"{selector} QTabBar::tab:!selected {{ {' '.join(unselected_rules)} }}" - ) - selected_config = dict(tab_config) - for option in ("background", "foreground"): - value = _mapped_value( - _merged_maps( - f"{style_name}.Tab" if style_name else "TNotebook.Tab", - "TNotebook.Tab", - ), - option, - "selected", - ) - if value is not None: - selected_config[option] = value - selected_rules = _style_rules(selected_config, widget_kind="button") - selected_rules.extend(["min-width: 76px;", "min-height: 24px;"]) - if selected_rules: - blocks.append(f"{selector} QTabBar::tab:selected {{ {' '.join(selected_rules)} }}") - return "\n".join(blocks) - - -class Variable: - def __init__(self, value: Any = None) -> None: - self._value = value - self._callbacks: list[Callable[[Any], None]] = [] - - def get(self) -> Any: - return self._value - - def set(self, value: Any) -> None: - self._value = value - for callback in list(self._callbacks): - callback(value) - - def _connect(self, callback: Callable[[Any], None]) -> None: - self._callbacks.append(callback) - callback(self._value) - - -class StringVar(Variable): - def __init__(self, value: str = "") -> None: - super().__init__(value) - - def get(self) -> str: - return str(super().get()) - - def set(self, value: Any) -> None: - super().set(str(value)) - - -class DoubleVar(Variable): - def __init__(self, value: float = 0.0) -> None: - super().__init__(float(value)) - - def get(self) -> float: - return float(super().get()) - - def set(self, value: Any) -> None: - super().set(float(value)) - - -class BooleanVar(Variable): - def __init__(self, value: bool = False) -> None: - super().__init__(bool(value)) - - def get(self) -> bool: - return bool(super().get()) - - def set(self, value: Any) -> None: - super().set(bool(value)) - - -class _FocusOutFilter(QtCore.QObject): - def __init__(self, owner: "Widget", callback: Callable[[Any], Any]) -> None: - super().__init__(owner._qt) - self.owner = owner - self.callback = callback - - def eventFilter(self, obj: QtCore.QObject, event: QtCore.QEvent) -> bool: - if event.type() == QtCore.QEvent.Type.FocusOut: - self.owner._invoke_bound(self.callback, keysym="FocusOut") - return False - - -class _SplitterResizeFilter(QtCore.QObject): - def __init__(self, owner: "PanedWindow") -> None: - super().__init__(owner._qt) - self.owner = owner - - def eventFilter(self, obj: QtCore.QObject, event: QtCore.QEvent) -> bool: - if event.type() in { - QtCore.QEvent.Type.Resize, - QtCore.QEvent.Type.Show, - QtCore.QEvent.Type.LayoutRequest, - }: - self.owner._apply_pending_sash() - return False - - -class Widget: - _winfo_class = "Widget" - _default_style = "TWidget" - _style_kind = "frame" - - def __init__( - self, - qt_widget: QtWidgets.QWidget, - parent: Any = None, - *, - padding: Any = None, - width: int | None = None, - height: int | None = None, - style: str | None = None, - **kwargs: Any, - ) -> None: - self._qt = qt_widget - self._qt._tk_wrapper = self # type: ignore[attr-defined] - self._parent = parent - self._children: list[Widget] = [] - self._grid_layout: QtWidgets.QGridLayout | None = None - self._pack_layout: QtWidgets.QBoxLayout | None = None - self._layout_kind: str | None = None - self._grid_row_weights: dict[int, int] = {} - self._grid_column_weights: dict[int, int] = {} - self._grid_row_mins: dict[int, int] = {} - self._grid_column_mins: dict[int, int] = {} - self._grid_max_row = -1 - self._grid_max_column = -1 - self._grid_slack_row: int | None = None - self._grid_slack_column: int | None = None - self._padding = _parse_padding(padding) - self._style_name = style - self._style_overrides: dict[str, Any] = {} - self._bindings: list[Any] = [] - self._textvariable: Variable | None = None - self._variable: Variable | None = None - if not self._qt.objectName(): - self._qt.setObjectName(f"qt_tk_{next(_OBJECT_IDS)}") - if parent is not None and hasattr(parent, "_children"): - parent._children.append(self) - if width is not None: - self._qt.setMinimumWidth(int(width)) - if height is not None: - self._qt.setMinimumHeight(int(height)) - self.configure(**kwargs) - self._apply_style() - # Local QSS is scoped to the widget's object name. Callers assign - # stable names after constructing compatibility widgets, so keep the - # selector in sync instead of leaving the control visually unstyled. - self._qt.objectNameChanged.connect(self._on_object_name_changed) - - def _on_object_name_changed(self, object_name: str) -> None: - if object_name: - self._apply_style() - - def _layout_margins(self) -> tuple[int, int, int, int]: - left, top, right, bottom = self._padding - config = _effective_style_config(self._style_name, self._default_style) - background = str(config.get("background", "")).lower() - if ( - self._style_name in {"Status.TFrame", "StatusInner.TFrame"} - and background in {"#f7fafc", "#f7fbff"} - ) or ( - self._style_name == "ToolbarGroup.TFrame" - and background in {"#ffffff", "#f9fcff"} - ): - left, top, right, bottom = ( - left, - _tk_px(top), - right, - _tk_px(bottom), - ) - if isinstance(self._qt, QtWidgets.QGroupBox): - top += max(18, self._qt.fontMetrics().height() + 6) - return (left, top, right, bottom) - - def _ensure_grid_layout(self) -> QtWidgets.QGridLayout: - if self._grid_layout is None: - if self._layout_kind == "pack": - raise TclError("cannot mix grid and pack in one parent") - self._grid_layout = QtWidgets.QGridLayout(self._qt) - self._grid_layout.setContentsMargins(*self._layout_margins()) - self._grid_layout.setSpacing(0) - self._layout_kind = "grid" - return self._grid_layout - - def _ensure_pack_layout(self, side: str | None = None) -> QtWidgets.QBoxLayout: - if self._pack_layout is None: - if self._layout_kind == "grid": - raise TclError("cannot mix pack and grid in one parent") - orientation = ( - QtWidgets.QBoxLayout.Direction.LeftToRight - if side in {LEFT, RIGHT} - else QtWidgets.QBoxLayout.Direction.TopToBottom - ) - self._pack_layout = QtWidgets.QBoxLayout(orientation, self._qt) - self._pack_layout.setContentsMargins(*self._layout_margins()) - self._pack_layout.setSpacing(0) - self._layout_kind = "pack" - return self._pack_layout - - def grid( - self, - row: int = 0, - column: int = 0, - rowspan: int = 1, - columnspan: int = 1, - sticky: str | None = None, - padx: Any = None, - pady: Any = None, - **_: Any, - ) -> None: - if self._parent is None: - return - layout = self._parent._ensure_grid_layout() - pad_left, pad_right = _parse_pad_pair(padx) - pad_top, pad_bottom = _parse_pad_pair(pady) - horizontal_gap = pad_left + pad_right - vertical_gap = pad_top + pad_bottom - use_padding_wrapper = ( - bool(horizontal_gap or vertical_gap) - and ( - getattr(self._parent, "_winfo_class", None) == "TLabelframe" - or ( - bool(horizontal_gap) - and getattr(self._parent, "_style_name", None) == "Dialog.TFrame" - ) - or getattr(self._parent, "_style_name", None) == "AppMenu.TFrame" - ) - ) - if ( - getattr(self._parent, "_style_name", None) == "Panel.TFrame" - and getattr(self, "_style_name", None) == "PlotPanel.TFrame" - ): - horizontal_gap *= 2 - vertical_gap *= 2 - if ( - getattr(self._parent, "_winfo_class", None) == "Tk" - and self._style_name == "Status.TFrame" - ): - config = _effective_style_config(self._style_name, self._default_style) - if str(config.get("background", "")).lower() == "#f7fafc": - self._qt.setMinimumHeight(max(self._qt.minimumHeight(), 94)) - if horizontal_gap and not use_padding_wrapper: - layout.setHorizontalSpacing(max(0, layout.horizontalSpacing(), horizontal_gap)) - if vertical_gap and not use_padding_wrapper: - layout.setVerticalSpacing(max(0, layout.verticalSpacing(), vertical_gap)) - alignment = QtCore.Qt.AlignmentFlag(0) - sticky = sticky or "" - if "w" in sticky and "e" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignLeft - elif "e" in sticky and "w" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignRight - elif "w" not in sticky and "e" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignHCenter - - if "n" in sticky and "s" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignTop - elif "s" in sticky and "n" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignBottom - elif "n" not in sticky and "s" not in sticky: - alignment |= QtCore.Qt.AlignmentFlag.AlignVCenter - - grid_widget = self._qt - if use_padding_wrapper: - wrapper = QtWidgets.QWidget(_qt_parent(self._parent)) - wrapper.setObjectName(f"qt_tk_gridpad_{next(_OBJECT_IDS)}") - wrapper.setAttribute(QtCore.Qt.WidgetAttribute.WA_StyledBackground, False) - parent_config = _effective_style_config( - getattr(self._parent, "_style_name", None), - getattr(self._parent, "_default_style", "TFrame"), - ) - parent_bg = _as_color(parent_config.get("background")) or "transparent" - wrapper.setStyleSheet(f"background-color: {parent_bg}; border: 0px;") - wrapper_layout = QtWidgets.QGridLayout(wrapper) - wrapper_layout.setContentsMargins(pad_left, pad_top, pad_right, pad_bottom) - wrapper_layout.setSpacing(0) - wrapper_layout.addWidget(self._qt, 0, 0) - wrapper.setSizePolicy(self._qt.sizePolicy()) - self._grid_wrapper = wrapper - grid_widget = wrapper - - if alignment: - layout.addWidget(grid_widget, row, column, rowspan, columnspan, alignment) - else: - layout.addWidget(grid_widget, row, column, rowspan, columnspan) - if getattr(self._parent, "_winfo_class", None) == "Tk" and hasattr( - self._parent, - "_adjust_root_overflow_rows", - ): - QtCore.QTimer.singleShot(0, self._parent._adjust_root_overflow_rows) - self._parent._grid_max_row = max(self._parent._grid_max_row, row + rowspan - 1) - self._parent._grid_max_column = max( - self._parent._grid_max_column, - column + columnspan - 1, - ) - self._parent._sync_grid_slack() - column_weighted = any( - self._parent._grid_column_weights.get(index, 0) > 0 - for index in range(column, column + columnspan) - ) - row_weighted = any( - self._parent._grid_row_weights.get(index, 0) > 0 - for index in range(row, row + rowspan) - ) - if ( - sticky - and "w" in sticky - and "e" in sticky - and column_weighted - and _allows_layout_expansion(self._qt) - ): - self._qt.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Expanding, - self._qt.sizePolicy().verticalPolicy(), - ) - if use_padding_wrapper: - grid_widget.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Expanding, - grid_widget.sizePolicy().verticalPolicy(), - ) - if ( - sticky - and "n" in sticky - and "s" in sticky - and row_weighted - and _allows_layout_expansion(self._qt) - ): - self._qt.setSizePolicy( - self._qt.sizePolicy().horizontalPolicy(), - QtWidgets.QSizePolicy.Policy.Expanding, - ) - if use_padding_wrapper: - grid_widget.setSizePolicy( - grid_widget.sizePolicy().horizontalPolicy(), - QtWidgets.QSizePolicy.Policy.Expanding, - ) - - def pack( - self, - side: str | None = None, - fill: str | None = None, - expand: bool = False, - padx: Any = None, - pady: Any = None, - anchor: str | None = None, - **_: Any, - ) -> None: - if self._parent is None: - return - layout = self._parent._ensure_pack_layout(side) - stretch = 1 if expand else 0 - pad_left, pad_right = _parse_pad_pair(padx) - pad_top, pad_bottom = _parse_pad_pair(pady) - is_horizontal = layout.direction() in { - QtWidgets.QBoxLayout.Direction.LeftToRight, - QtWidgets.QBoxLayout.Direction.RightToLeft, - } - before_pad = pad_left if is_horizontal else pad_top - after_pad = pad_right if is_horizontal else pad_bottom - if before_pad: - layout.addSpacing(before_pad) - alignment = QtCore.Qt.AlignmentFlag(0) - if is_horizontal and fill != BOTH: - alignment |= QtCore.Qt.AlignmentFlag.AlignVCenter - elif not is_horizontal and fill not in {X, BOTH}: - alignment |= QtCore.Qt.AlignmentFlag.AlignHCenter - if alignment: - layout.addWidget(self._qt, stretch, alignment) - else: - layout.addWidget(self._qt, stretch) - if after_pad: - layout.addSpacing(after_pad) - if fill in {X, BOTH} or expand: - if is_horizontal: - horizontal_policy = ( - QtWidgets.QSizePolicy.Policy.Expanding - if expand or fill in {X, BOTH} - else QtWidgets.QSizePolicy.Policy.Preferred - ) - vertical_policy = ( - QtWidgets.QSizePolicy.Policy.Expanding - if fill == BOTH - else QtWidgets.QSizePolicy.Policy.Preferred - ) - else: - horizontal_policy = ( - QtWidgets.QSizePolicy.Policy.Expanding - if fill in {X, BOTH} - else QtWidgets.QSizePolicy.Policy.Preferred - ) - vertical_policy = ( - QtWidgets.QSizePolicy.Policy.Expanding - if expand or fill == BOTH - else QtWidgets.QSizePolicy.Policy.Preferred - ) - self._qt.setSizePolicy( - horizontal_policy, - vertical_policy, - ) - - def grid_rowconfigure( - self, - index: int, - weight: int = 0, - minsize: int | None = None, - **_: Any, - ) -> None: - layout = self._ensure_grid_layout() - self._grid_row_weights[index] = weight - self._grid_max_row = max(self._grid_max_row, index) - layout.setRowStretch(index, weight) - if minsize is not None: - minimum = int(minsize) - self._grid_row_mins[index] = minimum - layout.setRowMinimumHeight(index, minimum) - self._sync_grid_slack() - - def grid_columnconfigure( - self, - index: int, - weight: int = 0, - minsize: int | None = None, - **_: Any, - ) -> None: - layout = self._ensure_grid_layout() - self._grid_column_weights[index] = weight - self._grid_max_column = max(self._grid_max_column, index) - layout.setColumnStretch(index, weight) - if minsize is not None: - minimum = int(minsize) - if self._style_name == "Header.TFrame" and index > 0 and minimum >= 90: - minimum = max(1, minimum - 6) - self._grid_column_mins[index] = minimum - layout.setColumnMinimumWidth(index, minimum) - self._sync_grid_slack() - - def _sync_grid_slack(self) -> None: - if self._grid_layout is None: - return - if self._grid_max_column >= 0: - has_column_weight = any( - self._grid_column_weights.get(index, 0) > 0 - for index in range(self._grid_max_column + 1) - ) - slack_column = self._grid_max_column + 1 - if self._grid_slack_column is not None and self._grid_slack_column != slack_column: - self._grid_layout.setColumnStretch( - self._grid_slack_column, - self._grid_column_weights.get(self._grid_slack_column, 0), - ) - self._grid_layout.setColumnStretch(slack_column, 0 if has_column_weight else 1) - self._grid_layout.setColumnMinimumWidth(slack_column, 0) - self._grid_slack_column = slack_column - if self._grid_max_row >= 0: - has_row_weight = any( - self._grid_row_weights.get(index, 0) > 0 - for index in range(self._grid_max_row + 1) - ) - slack_row = self._grid_max_row + 1 - if self._grid_slack_row is not None and self._grid_slack_row != slack_row: - self._grid_layout.setRowStretch( - self._grid_slack_row, - self._grid_row_weights.get(self._grid_slack_row, 0), - ) - self._grid_layout.setRowStretch(slack_row, 0 if has_row_weight else 1) - self._grid_layout.setRowMinimumHeight(slack_row, 0) - self._grid_slack_row = slack_row - - def grid_propagate(self, _enabled: bool) -> None: - return - - def configure(self, **kwargs: Any) -> None: - if not kwargs: - self._apply_style() - return - if "style" in kwargs: - self._style_name = kwargs["style"] - bg = _as_color(kwargs.get("bg") or kwargs.get("background")) - fg = _as_color(kwargs.get("fg") or kwargs.get("foreground")) - if bg: - self._style_overrides["background"] = bg - if fg: - self._style_overrides["foreground"] = fg - if "font" in kwargs and kwargs["font"] is not None: - self._style_overrides["font"] = kwargs["font"] - if "relief" in kwargs and kwargs["relief"] is not None: - self._style_overrides["relief"] = kwargs["relief"] - if "borderwidth" in kwargs and kwargs["borderwidth"] is not None: - self._style_overrides["borderwidth"] = kwargs["borderwidth"] - if "selectbackground" in kwargs and kwargs["selectbackground"] is not None: - self._style_overrides["selectbackground"] = kwargs["selectbackground"] - if "selectforeground" in kwargs and kwargs["selectforeground"] is not None: - self._style_overrides["selectforeground"] = kwargs["selectforeground"] - if "padding" in kwargs and kwargs["padding"] is not None: - self._style_overrides["padding"] = kwargs["padding"] - elif "padx" in kwargs or "pady" in kwargs: - padx = int(kwargs.get("padx") or 0) - pady = int(kwargs.get("pady") or 0) - self._style_overrides["padding"] = (padx, pady, padx, pady) - if "cursor" in kwargs: - _set_cursor(self._qt, kwargs.get("cursor")) - if "state" in kwargs: - state = kwargs["state"] - self._qt.setEnabled(state != DISABLED) - if "width" in kwargs and kwargs["width"] is not None: - self._qt.setMinimumWidth(int(kwargs["width"])) - if "height" in kwargs and kwargs["height"] is not None: - self._qt.setMinimumHeight(int(kwargs["height"])) - self._apply_style() - - config = configure - - def _apply_style(self) -> None: - config = _effective_style_config( - self._style_name, - self._default_style, - overrides=self._style_overrides, - ) - font = _font_from_config(config.get("font")) - if font is not None: - self._qt.setFont(font) - stylesheet = _qss_for_widget( - self._qt.objectName(), - self._style_name, - self._default_style, - widget_kind=self._style_kind, - overrides=self._style_overrides, - ) - self._qt.setStyleSheet(stylesheet) - - def cget(self, option: str) -> Any: - if option == "style": - return self._style_name - if option == "text": - if hasattr(self, "_text_value"): - return self._text_value - if hasattr(self._qt, "text"): - return self._qt.text() - return None - - def bind(self, sequence: str, callback: Callable[[Any], Any], **_: Any) -> None: - if sequence.startswith("<<"): - return - qt_sequence, keysym = _sequence_to_key(sequence) - if sequence == "" and isinstance(self._qt, QtWidgets.QLineEdit): - self._qt.returnPressed.connect( - lambda cb=callback, key=keysym: self._invoke_bound(cb, keysym=key) - ) - return - if sequence == "": - filt = _FocusOutFilter(self, callback) - self._qt.installEventFilter(filt) - self._bindings.append(filt) - return - shortcut = QtGui.QShortcut(QtGui.QKeySequence(qt_sequence), self._qt) - shortcut.activated.connect( - lambda cb=callback, key=keysym: self._invoke_bound(cb, keysym=key) - ) - self._bindings.append(shortcut) - - def _invoke_bound(self, callback: Callable[[Any], Any], *, keysym: str) -> None: - focus = QtWidgets.QApplication.focusWidget() - widget = getattr(focus, "_tk_wrapper", None) if focus is not None else None - callback(SimpleNamespace(keysym=keysym, widget=widget)) - - def focus_set(self) -> None: - self._qt.setFocus(QtCore.Qt.FocusReason.OtherFocusReason) - - def winfo_children(self) -> list["Widget"]: - return list(self._children) - - def winfo_class(self) -> str: - return self._winfo_class - - def winfo_x(self) -> int: - return int(self._qt.x()) - - def winfo_y(self) -> int: - return int(self._qt.y()) - - def winfo_rootx(self) -> int: - return int(self._qt.mapToGlobal(QtCore.QPoint(0, 0)).x()) - - def winfo_rooty(self) -> int: - return int(self._qt.mapToGlobal(QtCore.QPoint(0, 0)).y()) - - def winfo_screenwidth(self) -> int: - screen = _ensure_app().primaryScreen() - return int(screen.geometry().width()) if screen is not None else 0 - - def winfo_screenheight(self) -> int: - screen = _ensure_app().primaryScreen() - return int(screen.geometry().height()) if screen is not None else 0 - - def winfo_width(self) -> int: - return int(self._qt.width()) - - def winfo_height(self) -> int: - return int(self._qt.height()) - - def winfo_geometry(self) -> str: - geo = self._qt.geometry() - return f"{geo.width()}x{geo.height()}+{geo.x()}+{geo.y()}" - - def update_idletasks(self) -> None: - QtWidgets.QApplication.processEvents() - - def update(self) -> None: - QtWidgets.QApplication.processEvents() - - def destroy(self) -> None: - self._qt.close() - - -class Tk(Widget): - _winfo_class = "Tk" - _default_style = "TFrame" - _style_kind = "frame" - - def __init__(self, window: QtWidgets.QMainWindow | None = None) -> None: - self._app = _ensure_app() - self._window = window if window is not None else _MainWindow(self) - central = self._window.centralWidget() - if central is None: - central = QtWidgets.QWidget() - self._window.setCentralWidget(central) - self._close_callback: Callable[[], Any] | None = None - self._destroying = False - self._pending_geometry_size: tuple[int, int] | None = None - self._pending_resizable: tuple[bool, bool] | None = None - super().__init__(central, None) - self._qt = central - self._window._tk_owner = self # type: ignore[attr-defined] - self._window_filter: _WindowEventFilter | None = None - if not isinstance(self._window, _MainWindow): - self._window_filter = _WindowEventFilter(self) - self._window.installEventFilter(self._window_filter) - - def title(self, text: str) -> None: - self._window.setWindowTitle(text) - - def configure(self, **kwargs: Any) -> None: - super().configure(**kwargs) - bg = _as_color(kwargs.get("bg") or kwargs.get("background")) - if bg: - self._window.setStyleSheet(f"background-color: {bg};") - - def option_add(self, *_args: Any, **_kwargs: Any) -> None: - return - - def geometry(self, value: str | None = None) -> str: - if value is None: - geo = self._window.geometry() - return f"{geo.width()}x{geo.height()}+{geo.x()}+{geo.y()}" - parsed = _parse_geometry(value) - if parsed is None: - raise TclError(f"bad geometry specifier: {value}") - width, height, x, y = parsed - screen = self._app.screenAt(QtGui.QCursor.pos()) or self._app.primaryScreen() - available = screen.availableGeometry() if screen is not None else QtCore.QRect() - if available.isValid(): - width = min(width, max(1, available.width())) - height = min(height, max(1, available.height())) - if x is not None and y is not None: - x = min(max(x, available.left()), max(available.left(), available.right() - width + 1)) - y = min(max(y, available.top()), max(available.top(), available.bottom() - height + 1)) - self._window.resize(width, height) - self._pending_geometry_size = None if self._window.isVisible() else (width, height) - if x is not None and y is not None: - self._window.move(x, y) - return value - - def minsize(self, width: int, height: int) -> None: - screen = self._window.screen() or self._app.primaryScreen() - available = screen.availableGeometry() if screen is not None else QtCore.QRect() - if available.isValid(): - width = min(width, max(1, available.width())) - height = min(height, max(1, available.height())) - self._window.setMinimumSize(width, height) - - def resizable(self, width: bool, height: bool) -> None: - if not width or not height: - for child in self._children: - if ( - getattr(child, "_style_name", None) == "Status.TFrame" - and getattr(child, "_parent", None) is self - ): - config = _effective_style_config(child._style_name, child._default_style) - if str(config.get("background", "")).lower() == "#f7fbff": - child._qt.setMinimumHeight(max(child._qt.minimumHeight(), 79)) - self._app.processEvents() - current_y = self._window.geometry().y() - hint = self._window.sizeHint() - if hint.isValid(): - current_before_hint = self._window.size() - target_width = current_before_hint.width() - target_height = current_before_hint.height() - screen = self._app.primaryScreen() - screen_rect = screen.geometry() if screen is not None else QtCore.QRect() - if not width: - target_width = max(target_width, min(hint.width(), screen_rect.width())) - if not height: - if screen_rect.isValid(): - max_height = max(1, screen_rect.bottom() - current_y + 1) - if target_width >= screen_rect.width(): - target_height = max_height - else: - target_height = min(max(target_height, hint.height()), max_height) - else: - target_height = max(target_height, hint.height()) - if target_width != current_before_hint.width() or target_height != current_before_hint.height(): - self._window.resize(target_width, target_height) - current = self._window.size() - minimum = self._window.minimumSize() - maximum_width = current.width() if not width else 16_777_215 - maximum_height = current.height() if not height else 16_777_215 - if not self._window.isVisible(): - self._pending_resizable = (width, height) - return - self._window.setMinimumSize( - current.width() if not width else minimum.width(), - current.height() if not height else minimum.height(), - ) - self._window.setMaximumSize(maximum_width, maximum_height) - self._pending_resizable = None - - def _apply_pending_geometry(self) -> None: - if self._pending_geometry_size is None or not self._window.isVisible(): - return - width, height = self._pending_geometry_size - if self._window.width() != width or self._window.height() != height: - self._window.resize(width, height) - self._app.processEvents() - self._pending_geometry_size = None - - def _apply_pending_resizable(self) -> None: - if self._pending_resizable is None or not self._window.isVisible(): - return - width, height = self._pending_resizable - current = self._window.size() - minimum = self._window.minimumSize() - self._window.setMinimumSize( - current.width() if not width else minimum.width(), - current.height() if not height else minimum.height(), - ) - self._window.setMaximumSize( - current.width() if not width else 16_777_215, - current.height() if not height else 16_777_215, - ) - self._pending_resizable = None - - def protocol(self, name: str, callback: Callable[[], Any]) -> None: - if name == "WM_DELETE_WINDOW": - self._close_callback = callback - - def bind(self, sequence: str, callback: Callable[[Any], Any]) -> None: - qt_sequence, keysym = _sequence_to_key(sequence) - shortcut = QtGui.QShortcut(QtGui.QKeySequence(qt_sequence), self._window) - shortcut.activated.connect( - lambda cb=callback, key=keysym: self._invoke_bound(cb, keysym=key) - ) - self._bindings.append(shortcut) - - def after(self, delay_ms: int, callback: Callable[[], Any]) -> str: - timer = QtCore.QTimer(self._window) - timer.setSingleShot(True) - timer.timeout.connect(callback) - timer.start(delay_ms) - timer_id = f"after-{id(timer)}" - if not hasattr(self, "_timers"): - self._timers = {} - self._timers[timer_id] = timer - timer.timeout.connect(lambda key=timer_id: self._timers.pop(key, None)) - return timer_id - - def after_idle(self, callback: Callable[[], Any]) -> str: - return self.after(0, callback) - - def after_cancel(self, after_id: str) -> None: - timer = getattr(self, "_timers", {}).pop(after_id, None) - if timer is not None: - timer.stop() - - def _adjust_root_overflow_rows(self) -> None: - layout = self._grid_layout - if layout is None: - return - status_children = [ - child - for child in self._children - if getattr(child, "_style_name", None) == "Status.TFrame" - and getattr(child, "_parent", None) is self - ] - if not status_children: - return - status = status_children[-1]._qt - requested_workspace_min = self._grid_row_mins.get(2, layout.rowMinimumHeight(2)) - if requested_workspace_min <= 0: - return - menu_height = next( - ( - child._qt.height() - for child in self._children - if getattr(child, "_style_name", None) == "AppMenu.TFrame" - ), - layout.rowMinimumHeight(0), - ) - header_height = next( - ( - child._qt.height() - for child in self._children - if getattr(child, "_style_name", None) == "Header.TFrame" - ), - layout.rowMinimumHeight(1), - ) - status_hint = status.sizeHint().height() - required_height = menu_height + header_height + requested_workspace_min + status_hint - current_height = self._qt.height() - if required_height > current_height and not self._window.isMaximized(): - screen = self._app.primaryScreen() - screen_rect = screen.geometry() if screen is not None else QtCore.QRect() - target_height = required_height - if screen_rect.isValid(): - current_y = self._window.geometry().y() - target_height = min(target_height, max(1, screen_rect.bottom() - current_y + 1)) - if target_height > current_height: - self._window.resize(self._window.width(), int(target_height)) - self._app.processEvents() - current_height = self._qt.height() - status_hint = status.sizeHint().height() - required_height = ( - menu_height - + header_height - + requested_workspace_min - + status_hint - ) - if current_height >= required_height: - if layout.rowMinimumHeight(2) != requested_workspace_min: - layout.setRowMinimumHeight(2, requested_workspace_min) - self._qt.updateGeometry() - if status.maximumHeight() != 16_777_215: - status.setMaximumHeight(16_777_215) - status.updateGeometry() - return - - available_for_workspace = current_height - menu_height - header_height - status_hint - if available_for_workspace > 0: - workspace_min = min(requested_workspace_min, max(1, int(available_for_workspace))) - if layout.rowMinimumHeight(2) != workspace_min: - layout.setRowMinimumHeight(2, workspace_min) - self._qt.updateGeometry() - else: - workspace_min = layout.rowMinimumHeight(2) - available_for_status = current_height - menu_height - header_height - workspace_min - if available_for_status <= 0: - return - desired_max = max(1, int(available_for_status)) - if desired_max < status_hint: - if status.maximumHeight() != desired_max: - status.setMaximumHeight(desired_max) - status.updateGeometry() - elif status.maximumHeight() != 16_777_215: - status.setMaximumHeight(16_777_215) - status.updateGeometry() - - def mainloop(self) -> None: - self._window.show() - self._apply_pending_geometry() - self._apply_pending_resizable() - self._adjust_root_overflow_rows() - self._app.processEvents() - self._app.exec() - - def destroy(self) -> None: - self._destroying = True - self._window.close() - self._app.quit() - - def state(self, value: str | None = None) -> str: - if value is None: - if self._window.isMinimized(): - return "iconic" - if self._window.isMaximized(): - return "zoomed" - return "normal" - if value == "zoomed": - self._window.showMaximized() - elif value == "iconic": - self._window.showMinimized() - elif value == "normal": - self._window.showNormal() - return value - - def update_idletasks(self) -> None: - self._app.processEvents() - self._apply_pending_geometry() - self._apply_pending_resizable() - - def update(self) -> None: - self._app.processEvents() - self._apply_pending_geometry() - self._apply_pending_resizable() - - def iconbitmap(self, default: str | None = None, **_: Any) -> None: - if default: - self._window.setWindowIcon(QtGui.QIcon(default)) - - def iconphoto(self, _default: bool, image: "PhotoImage") -> None: - self._window.setWindowIcon(QtGui.QIcon(image.pixmap)) - - -class _MainWindow(QtWidgets.QMainWindow): - def __init__(self, owner: Tk) -> None: - super().__init__() - self.owner = owner - - def resizeEvent(self, event: QtGui.QResizeEvent) -> None: # noqa: N802 - super().resizeEvent(event) - QtCore.QTimer.singleShot(0, self.owner._adjust_root_overflow_rows) - - def closeEvent(self, event: QtGui.QCloseEvent) -> None: - if self.owner._destroying: - event.accept() - return - if self.owner._close_callback is not None: - self.owner._close_callback() - if self.owner._destroying: - event.accept() - else: - event.ignore() - return - event.accept() - - -class _WindowEventFilter(QtCore.QObject): - """Give an externally supplied QMainWindow the same lifecycle hooks.""" - - def __init__(self, owner: Tk) -> None: - super().__init__(owner._window) - self.owner = owner - - def eventFilter(self, watched: QtCore.QObject, event: QtCore.QEvent) -> bool: - if event.type() == QtCore.QEvent.Type.Resize: - QtCore.QTimer.singleShot(0, self.owner._adjust_root_overflow_rows) - elif event.type() == QtCore.QEvent.Type.Close and not self.owner._destroying: - if self.owner._close_callback is not None: - self.owner._close_callback() - if not self.owner._destroying: - event.ignore() - return True - return super().eventFilter(watched, event) - - -class Toplevel(Widget): - _winfo_class = "Toplevel" - _default_style = "TFrame" - _style_kind = "frame" - - def __init__(self, parent: Any = None, **kwargs: Any) -> None: - _ensure_app() - dialog = _Dialog(self) - qt_parent = _qt_parent(parent) - if qt_parent is not None: - dialog.setParent(qt_parent.window(), QtCore.Qt.WindowType.Dialog) - self._close_callback: Callable[[], Any] | None = None - self._destroying = False - super().__init__(dialog, parent, **kwargs) - dialog.resize(640, 480) - # A Toplevel is assembled synchronously after construction. Showing - # the empty QDialog here exposes an unlaid-out backing store (black on - # Windows) and can leave stale child borders until the next resize. - # Defer only to the next event-loop turn so callers keep Tk's modeless - # behaviour while the very first visible frame is complete. - self._initial_show_timer = QtCore.QTimer(dialog) - self._initial_show_timer.setSingleShot(True) - self._initial_show_timer.timeout.connect(self._show_when_ready) - self._initial_show_timer.start(0) - - def _activate_layout(self) -> None: - self._qt.ensurePolished() - layout = self._qt.layout() - if layout is not None: - layout.activate() - - def _show_when_ready(self) -> None: - if self._destroying: - return - self._activate_layout() - self._qt.show() - - def title(self, text: str) -> None: - self._qt.setWindowTitle(text) - - def geometry(self, value: str | None = None) -> str: - if value is None: - return self.winfo_geometry() - parsed = _parse_geometry(value) - if parsed is None: - raise TclError(f"bad geometry specifier: {value}") - width, height, x, y = parsed - self._qt.resize(width, height) - if x is not None and y is not None: - self._qt.move(x, y) - else: - self._qt.move(0, 0) - return value - - def minsize(self, width: int, height: int) -> None: - self._qt.setMinimumSize(width, height) - - def transient(self, parent: Any) -> None: - qt_parent = _qt_parent(parent) - if qt_parent is not None: - was_visible = self._qt.isVisible() - self._qt.setParent(qt_parent.window(), QtCore.Qt.WindowType.Dialog) - if was_visible: - self._qt.show() - - def grab_set(self) -> None: - self._qt.setModal(True) - - def wait_window(self) -> None: - if isinstance(self._qt, QtWidgets.QDialog): - self._initial_show_timer.stop() - self._activate_layout() - self._qt.setModal(True) - self._qt.exec() - - def protocol(self, name: str, callback: Callable[[], Any]) -> None: - if name == "WM_DELETE_WINDOW": - self._close_callback = callback - - def destroy(self) -> None: - self._initial_show_timer.stop() - self._destroying = True - if isinstance(self._qt, QtWidgets.QDialog): - self._qt.accept() - else: - self._qt.close() - - -class _Dialog(QtWidgets.QDialog): - def __init__(self, owner: Toplevel) -> None: - super().__init__() - self.owner = owner - - def closeEvent(self, event: QtGui.QCloseEvent) -> None: - if self.owner._destroying: - event.accept() - return - if self.owner._close_callback is not None: - self.owner._close_callback() - if self.owner._destroying: - event.accept() - else: - event.ignore() - return - event.accept() - - -class Frame(Widget): - _winfo_class = "TFrame" - _default_style = "TFrame" - _style_kind = "frame" - - def __init__(self, parent: Any = None, **kwargs: Any) -> None: - width = kwargs.pop("width", None) - height = kwargs.pop("height", None) - frame = QtWidgets.QWidget(_qt_parent(parent)) - if width is not None or height is not None: - frame.resize(int(width or frame.width()), int(height or frame.height())) - frame.setBaseSize(int(width or 0), int(height or 0)) - super().__init__(frame, parent, **kwargs) - - -class LabelFrame(Widget): - _winfo_class = "TLabelframe" - _default_style = "TLabelframe" - _style_kind = "groupbox" - - def __init__(self, parent: Any = None, text: str = "", **kwargs: Any) -> None: - self._text_value = str(text) - super().__init__(QtWidgets.QGroupBox(text, _qt_parent(parent)), parent, **kwargs) - - def configure(self, **kwargs: Any) -> None: - text = kwargs.pop("text", None) - if text is not None: - self._text_value = str(text) - self._qt.setTitle(self._text_value) - super().configure(**kwargs) - - -class Label(Widget): - _winfo_class = "TLabel" - _default_style = "TLabel" - _style_kind = "label" - - def __init__( - self, - parent: Any = None, - text: str | None = None, - textvariable: Variable | None = None, - image: Any = None, - anchor: str | None = None, - justify: str | None = None, - **kwargs: Any, - ) -> None: - label = QtWidgets.QLabel(_qt_parent(parent)) - self._text_value = "" if text is None else str(text) - label.setText(self._text_value) - wraplength = kwargs.pop("wraplength", None) - label.setWordWrap(wraplength is not None and int(wraplength) > 0) - if wraplength is not None and int(wraplength) > 0: - wrap_px = int(wraplength) - if wrap_px <= 120: - label.setMinimumWidth(_tk_px(wrap_px)) - label.setAlignment(_qt_alignment(anchor, justify)) - char_width = kwargs.pop("width", None) - style_name = kwargs.get("style") - if char_width is not None: - minimum_width = _text_width_px(int(char_width), average_px=7) or 0 - if style_name in { - "HeaderChipValue.TLabel", - "HeaderChipPatternValue.TLabel", - }: - minimum_width += 4 - label.setMinimumWidth(minimum_width) - super().__init__(label, parent, **kwargs) - if self._style_name == "HeaderTitle.TLabel": - config = _effective_style_config(self._style_name, self._default_style) - is_light_header = str(config.get("background", "")).lower() == "#f5faff" - label.setMinimumHeight(17 if is_light_header else 21) - minimum_width = ( - 246 - if is_light_header - else 106 - ) - label.setMinimumWidth(max(label.minimumWidth(), minimum_width)) - if self._style_name == "Toolbar.TLabel": - config = _effective_style_config(self._style_name, self._default_style) - label.setMinimumHeight(17 if _uses_tk_default_font(config) else 21) - # Toolbar copy changes with the active locale. A minimum captured - # from the first language made the command bar permanently wider - # even after a shorter translation was selected. - label.setMinimumWidth(0) - label.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Preferred, - QtWidgets.QSizePolicy.Policy.Preferred, - ) - if self._style_name == "Muted.TLabel": - config = _effective_style_config(self._style_name, self._default_style) - if not _uses_tk_default_font(config): - label.setMinimumHeight(max(label.minimumHeight(), 21)) - if self._style_name == "Card.TLabel": - config = _effective_style_config(self._style_name, self._default_style) - if str(config.get("background", "")).lower() == "#ffffff": - label.setMinimumHeight(max(label.minimumHeight(), 20)) - if wraplength is not None and int(wraplength) >= 600: - target_height = 43 if _uses_tk_default_font(config) else 55 - label.setMinimumHeight(max(label.minimumHeight(), target_height)) - if self._style_name in { - "HeaderChipName.TLabel", - "HeaderChipValue.TLabel", - "HeaderChipPatternValue.TLabel", - }: - config = _effective_style_config(self._style_name, self._default_style) - is_light_header = str(config.get("background", "")).lower() == "#f8fbff" - label.setMinimumHeight(_tk_px(21) if is_light_header else 21) - if self._style_name == "HeaderChipName.TLabel": - label.setMinimumWidth( - max(label.minimumWidth(), _header_chip_name_min_width(label.text())) - ) - if image is not None and hasattr(image, "pixmap"): - pixmap = image.pixmap - config = _effective_style_config(self._style_name, self._default_style) - if ( - self._style_name == "AppLogo.TLabel" - and str(config.get("background", "")).lower() == "#fbfdff" - and not pixmap.isNull() - ): - size = 52 - pixmap = pixmap.scaled( - size, - size, - QtCore.Qt.AspectRatioMode.KeepAspectRatio, - QtCore.Qt.TransformationMode.SmoothTransformation, - ) - label.setPixmap(pixmap) - if textvariable is not None: - self._textvariable = textvariable - textvariable._connect(self._set_text) - - def _set_text(self, value: Any) -> None: - self._text_value = str(value) - self._qt.setText(self._text_value) - - def configure(self, **kwargs: Any) -> None: - text = kwargs.pop("text", None) - textvariable = kwargs.pop("textvariable", None) - image = kwargs.pop("image", None) - wraplength = kwargs.pop("wraplength", None) - anchor = kwargs.pop("anchor", None) - justify = kwargs.pop("justify", None) - if text is not None: - self._set_text(text) - if image is not None and hasattr(image, "pixmap"): - pixmap = image.pixmap - config = _effective_style_config(self._style_name, self._default_style) - if ( - self._style_name == "AppLogo.TLabel" - and str(config.get("background", "")).lower() == "#fbfdff" - and not pixmap.isNull() - ): - size = 52 - pixmap = pixmap.scaled( - size, - size, - QtCore.Qt.AspectRatioMode.KeepAspectRatio, - QtCore.Qt.TransformationMode.SmoothTransformation, - ) - self._qt.setPixmap(pixmap) - if textvariable is not None: - self._textvariable = textvariable - textvariable._connect(self._set_text) - if wraplength is not None: - wrap_px = int(wraplength) - self._qt.setWordWrap(wrap_px > 0) - if wrap_px > 0: - if wrap_px <= 120: - self._qt.setMinimumWidth(max(self._qt.minimumWidth(), wrap_px)) - else: - self._qt.setMaximumWidth(16_777_215) - if anchor is not None or justify is not None: - self._qt.setAlignment(_qt_alignment(anchor, justify)) - super().configure(**kwargs) - if self._style_name == "Toolbar.TLabel": - config = _effective_style_config(self._style_name, self._default_style) - self._qt.setMinimumHeight( - max(self._qt.minimumHeight(), 17 if _uses_tk_default_font(config) else 21) - ) - self._qt.setMinimumWidth( - max(self._qt.minimumWidth(), _toolbar_label_min_width(self._qt, config)) - ) - if self._style_name == "Muted.TLabel": - config = _effective_style_config(self._style_name, self._default_style) - if not _uses_tk_default_font(config): - self._qt.setMinimumHeight(max(self._qt.minimumHeight(), 21)) - if self._style_name == "Card.TLabel" and wraplength is not None and int(wraplength) >= 600: - config = _effective_style_config(self._style_name, self._default_style) - target_height = 43 if _uses_tk_default_font(config) else 55 - self._qt.setMinimumHeight(max(self._qt.minimumHeight(), target_height)) - - -class Button(Widget): - _winfo_class = "TButton" - _default_style = "TButton" - _style_kind = "button" - - def __init__( - self, - parent: Any = None, - text: str = "", - command: Callable[[], Any] | None = None, - **kwargs: Any, - ) -> None: - self._text_value = str(text) - button = QtWidgets.QPushButton(_qt_button_text(text), _qt_parent(parent)) - char_width = kwargs.pop("width", None) - if char_width is not None: - style_name = kwargs.get("style") - average_px = ( - 10.1 - if style_name in {"WorkspaceTab.TButton", "WorkspaceTabSelected.TButton"} - else 10.4 - if style_name == "ToolbarPrimary.TButton" - else 9.75 - if style_name is not None and str(style_name).startswith("Compact") - else 9 - ) - button.setMinimumWidth(max(1, int(round(int(char_width) * average_px)))) - super().__init__(button, parent, **kwargs) - config = _effective_style_config(self._style_name, self._default_style) - button.setMinimumHeight( - max(button.minimumHeight(), _button_minimum_height(config, button.fontMetrics())) - ) - if self._style_name is not None and str(self._style_name).startswith("Compact"): - if _uses_tk_default_font(config): - button.setFixedHeight(26) - else: - button.setMinimumHeight(max(button.minimumHeight(), 29)) - if self._style_name == "ToolbarPrimary.TButton" and _uses_tk_default_font(config): - button.setFixedHeight(28) - if self._style_name == "Large.TButton": - button.setMinimumWidth(max(button.minimumWidth(), 107)) - if _uses_tk_default_font(config): - button.setFixedHeight(33) - else: - button.setMinimumHeight(max(button.minimumHeight(), 37)) - if self._style_name in {"DialogButton.TButton", "DialogDanger.TButton"}: - button.setMinimumWidth(max(button.minimumWidth(), 107)) - if _uses_tk_default_font(config): - button.setFixedHeight(33) - else: - button.setMinimumHeight(max(button.minimumHeight(), 37)) - self._command = command - if command is not None: - button.clicked.connect(lambda _checked=False, cb=command: cb()) - - def configure(self, **kwargs: Any) -> None: - text = kwargs.pop("text", None) - command = kwargs.pop("command", None) - if text is not None: - self._text_value = str(text) - self._qt.setText(_qt_button_text(text)) - if command is not None: - try: - self._qt.clicked.disconnect() - except RuntimeError: - pass - self._qt.clicked.connect(lambda _checked=False, cb=command: cb()) - self._command = command - super().configure(**kwargs) - - -class Menubutton(Button): - _winfo_class = "TMenubutton" - _default_style = "TMenubutton" - _style_kind = "toolbutton" - - def __init__(self, parent: Any = None, text: str = "", **kwargs: Any) -> None: - tool_button = QtWidgets.QToolButton(_qt_parent(parent)) - self._text_value = str(text) - tool_button.setText(_qt_button_text(text)) - tool_button.setPopupMode(QtWidgets.QToolButton.ToolButtonPopupMode.InstantPopup) - char_width = kwargs.pop("width", None) - if char_width is not None: - style_name = kwargs.get("style") - if style_name == "TopMenu.TMenubutton": - config = _effective_style_config(style_name, self._default_style) - average_px = 17.4 if _uses_tk_default_font(config) else 16.4 - tool_button.setFixedWidth(max(1, int(round(int(char_width) * average_px)))) - else: - tool_button.setMinimumWidth(max(1, int(round(int(char_width) * 15.5)))) - Widget.__init__(self, tool_button, parent, **kwargs) - - def configure(self, **kwargs: Any) -> None: - menu = kwargs.pop("menu", None) - text = kwargs.pop("text", None) - if text is not None: - self._text_value = str(text) - self._qt.setText(_qt_button_text(text)) - if menu is not None: - self._qt.setMenu(menu._menu) - Widget.configure(self, **kwargs) - - -class Entry(Widget): - _winfo_class = "TEntry" - _default_style = "TEntry" - _style_kind = "entry" - - def __init__( - self, - parent: Any = None, - textvariable: Variable | None = None, - width: int | None = None, - justify: str | None = None, - **kwargs: Any, - ) -> None: - line = QtWidgets.QLineEdit(_qt_parent(parent)) - requested_width = _text_width_px(width, average_px=9.25) - super().__init__(line, parent, **kwargs) - if requested_width is not None: - line.setFixedWidth(requested_width) - config = _effective_style_config(self._style_name, self._default_style) - line.setFixedHeight(25 if _uses_tk_default_font(config) else 29) - if justify == "right": - line.setAlignment(QtCore.Qt.AlignmentFlag.AlignRight) - self._textvariable = textvariable - self._updating = False - if textvariable is not None: - textvariable._connect(self._set_from_variable) - line.textChanged.connect(lambda value: self._set_variable(value)) - - def _set_from_variable(self, value: Any) -> None: - if self._qt.text() == str(value): - return - self._updating = True - self._qt.setText(str(value)) - self._updating = False - - def _set_variable(self, value: str) -> None: - if self._updating or self._textvariable is None: - return - self._textvariable.set(value) - - def get(self) -> str: - return self._qt.text() - - def selection_range(self, start: int, end: Any) -> None: - length = len(self._qt.text()) if end == END else int(end) - start - self._qt.setSelection(start, length) - - -class Radiobutton(Widget): - _winfo_class = "TRadiobutton" - _default_style = "TRadiobutton" - _style_kind = "radiobutton" - - def __init__( - self, - parent: Any = None, - text: str = "", - variable: Variable | None = None, - value: Any = None, - command: Callable[[], Any] | None = None, - **kwargs: Any, - ) -> None: - self._text_value = str(text) - button = QtWidgets.QRadioButton(_qt_button_text(text), _qt_parent(parent)) - button.setAutoExclusive(False) - super().__init__(button, parent, **kwargs) - config = _effective_style_config(self._style_name, self._default_style) - button.setMinimumHeight( - max(button.minimumHeight(), 19 if _uses_tk_default_font(config) else 23) - ) - if _uses_tk_default_font(config) and any(ord(char) > 127 for char in text): - button.setMinimumWidth(max(button.minimumWidth(), button.sizeHint().width() + 3)) - self._variable = variable - self._value = value - self._command = command - if variable is not None: - variable._connect(lambda current: button.setChecked(current == value)) - button.toggled.connect(self._on_toggled) - - def _on_toggled(self, checked: bool) -> None: - if not checked: - if self._variable is not None and self._variable.get() == self._value: - self._qt.setChecked(True) - return - if self._variable is not None: - self._variable.set(self._value) - if self._command is not None: - self._command() - - def configure(self, **kwargs: Any) -> None: - text = kwargs.pop("text", None) - if text is not None: - self._text_value = str(text) - self._qt.setText(_qt_button_text(text)) - super().configure(**kwargs) - - -class AppleSwitch(QtWidgets.QCheckBox): - """Accessible macOS-style switch with an interruptible thumb transition. - - This remains a real :class:`QCheckBox`, so Qt continues to provide the - checked state, keyboard handling, focus behavior, and accessibility role. - Only its presentation is custom-painted. - """ - - _TRACK_WIDTH = 36 - _TRACK_HEIGHT = 20 - _THUMB_INSET = 2 - _TEXT_GAP = 8 - _ANIMATION_DURATION_MS = 180 - - def __init__( - self, - text: str | QtWidgets.QWidget = "", - parent: QtWidgets.QWidget | None = None, - ) -> None: - if isinstance(text, QtWidgets.QWidget) and parent is None: - parent = text - text = "" - text = str(text) - super().__init__(text, parent) - self._switch_position = 1.0 if self.isChecked() else 0.0 - self._switch_animation_target = self._switch_position - self._animation_duration_ms = self._ANIMATION_DURATION_MS - self._switch_animation = QtCore.QPropertyAnimation( - self, - b"switch_position", - self, - ) - self._switch_animation.setEasingCurve(QtCore.QEasingCurve.Type.OutCubic) - self._switch_animation.finished.connect(self._finish_switch_animation) - self.toggled.connect(self._animate_to_checked_state) - self.setAttribute(QtCore.Qt.WidgetAttribute.WA_Hover, True) - self.setMinimumHeight(self._TRACK_HEIGHT + 8) - self.setAccessibleName(self._accessible_label(text)) - - @staticmethod - def _accessible_label(text: str) -> str: - escaped_ampersand = "\N{BYTE ORDER MARK}" - return ( - str(text) - .replace("&&", escaped_ampersand) - .replace("&", "") - .replace(escaped_ampersand, "&") - ) - - def setText(self, text: str) -> None: # noqa: N802 - super().setText(text) - self.setAccessibleName(self._accessible_label(text)) - self.updateGeometry() - self.update() - - def switchPosition(self) -> float: # noqa: N802 - return self._switch_position - - def setSwitchPosition(self, value: float) -> None: # noqa: N802 - position = max(0.0, min(1.0, float(value))) - if abs(position - self._switch_position) < 0.0001: - return - self._switch_position = position - self.update() - - switch_position = QtCore.Property( - float, - switchPosition, - setSwitchPosition, - ) - - def animationDuration(self) -> int: # noqa: N802 - return self._animation_duration_ms - - def setAnimationDuration(self, duration_ms: int) -> None: # noqa: N802 - self._animation_duration_ms = max(0, int(duration_ms)) - - def _animations_enabled(self) -> bool: - option = QtWidgets.QStyleOption() - option.initFrom(self) - return bool( - self.style().styleHint( - QtWidgets.QStyle.StyleHint.SH_Widget_Animate, - option, - self, - ) - ) - - def _animate_to_checked_state(self, checked: bool) -> None: - target = 1.0 if checked else 0.0 - self._switch_animation_target = target - self._switch_animation.stop() - if ( - self._animation_duration_ms <= 0 - or not self.isVisible() - or not self._animations_enabled() - ): - self.setSwitchPosition(target) - return - # Restart from the live presentation value so rapid reversals never - # jump to the previous logical endpoint. - self._switch_animation.setStartValue(self._switch_position) - self._switch_animation.setEndValue(target) - self._switch_animation.setDuration(self._animation_duration_ms) - self._switch_animation.start() - - def _finish_switch_animation(self) -> None: - self.setSwitchPosition(self._switch_animation_target) - - @staticmethod - def _mix_color(start: QtGui.QColor, end: QtGui.QColor, amount: float) -> QtGui.QColor: - amount = max(0.0, min(1.0, amount)) - return QtGui.QColor.fromRgbF( - start.redF() + (end.redF() - start.redF()) * amount, - start.greenF() + (end.greenF() - start.greenF()) * amount, - start.blueF() + (end.blueF() - start.blueF()) * amount, - start.alphaF() + (end.alphaF() - start.alphaF()) * amount, - ) - - def sizeHint(self) -> QtCore.QSize: # noqa: N802 - text_width = self.fontMetrics().horizontalAdvance( - self._accessible_label(self.text()) - ) - width = self._TRACK_WIDTH + 6 - if text_width: - width += self._TEXT_GAP + text_width - return QtCore.QSize( - max(width, super().sizeHint().width()), - max(self._TRACK_HEIGHT + 8, self.fontMetrics().height() + 8), - ) - - def minimumSizeHint(self) -> QtCore.QSize: # noqa: N802 - return self.sizeHint() - - def paintEvent(self, _event: QtGui.QPaintEvent) -> None: # noqa: N802 - option = QtWidgets.QStyleOption() - option.initFrom(self) - painter = QtWidgets.QStylePainter(self) - painter.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing, True) - self.style().drawPrimitive( - QtWidgets.QStyle.PrimitiveElement.PE_Widget, - option, - painter, - self, - ) - - track_y = (self.height() - self._TRACK_HEIGHT) // 2 - logical_track = QtCore.QRect( - 3, - track_y, - self._TRACK_WIDTH, - self._TRACK_HEIGHT, - ) - track = self.style().visualRect(self.layoutDirection(), self.rect(), logical_track) - - off_color = QtGui.QColor("#B0B0B5") - on_color = QtGui.QColor("#34C759") - track_color = self._mix_color(off_color, on_color, self._switch_position) - if self.isDown(): - track_color = track_color.darker(112) - elif self.underMouse(): - track_color = track_color.darker(105) - if not self.isEnabled(): - track_color.setAlphaF(0.42) - - radius = self._TRACK_HEIGHT / 2.0 - if self.hasFocus(): - focus_rect = QtCore.QRectF(track).adjusted(-2.0, -2.0, 2.0, 2.0) - focus_color = QtGui.QColor(TOKENS.focus) - focus_color.setAlphaF(0.75 if self.isEnabled() else 0.35) - painter.setPen(QtGui.QPen(focus_color, 2.0)) - painter.setBrush(QtCore.Qt.BrushStyle.NoBrush) - painter.drawRoundedRect(focus_rect, radius + 2.0, radius + 2.0) - - painter.setPen(QtCore.Qt.PenStyle.NoPen) - painter.setBrush(track_color) - painter.drawRoundedRect(QtCore.QRectF(track), radius, radius) - - thumb_diameter = self._TRACK_HEIGHT - 2 * self._THUMB_INSET - travel = self._TRACK_WIDTH - thumb_diameter - 2 * self._THUMB_INSET - visual_position = self._switch_position - if self.layoutDirection() == QtCore.Qt.LayoutDirection.RightToLeft: - visual_position = 1.0 - visual_position - thumb_x = ( - track.left() - + self._THUMB_INSET - + travel * visual_position - ) - thumb_y = track.top() + self._THUMB_INSET - thumb_rect = QtCore.QRectF( - thumb_x, - thumb_y, - thumb_diameter, - thumb_diameter, - ) - - shadow = QtGui.QColor(0, 0, 0, 52 if self.isEnabled() else 24) - painter.setBrush(shadow) - painter.drawEllipse(thumb_rect.translated(0.0, 1.0)) - thumb_color = QtGui.QColor("#FFFFFF") - if not self.isEnabled(): - thumb_color.setAlphaF(0.72) - painter.setBrush(thumb_color) - painter.setPen(QtGui.QPen(QtGui.QColor(0, 0, 0, 22), 0.7)) - painter.drawEllipse(thumb_rect) - - if self.text(): - logical_text = QtCore.QRect( - logical_track.right() + 1 + self._TEXT_GAP, - 0, - max(0, self.width() - logical_track.right() - self._TEXT_GAP - 4), - self.height(), - ) - text_rect = self.style().visualRect( - self.layoutDirection(), - self.rect(), - logical_text, - ) - color_group = ( - QtGui.QPalette.ColorGroup.Active - if self.isEnabled() - else QtGui.QPalette.ColorGroup.Disabled - ) - painter.setPen( - self.palette().color(color_group, QtGui.QPalette.ColorRole.WindowText) - ) - flags = ( - QtCore.Qt.AlignmentFlag.AlignVCenter - | QtCore.Qt.AlignmentFlag.AlignLeft - | QtCore.Qt.TextFlag.TextShowMnemonic - ) - if self.layoutDirection() == QtCore.Qt.LayoutDirection.RightToLeft: - flags &= ~QtCore.Qt.AlignmentFlag.AlignLeft - flags |= QtCore.Qt.AlignmentFlag.AlignRight - painter.drawText(text_rect, int(flags), self.text()) - - def enterEvent(self, event: QtCore.QEvent) -> None: # noqa: N802 - super().enterEvent(event) - self.update() - - def leaveEvent(self, event: QtCore.QEvent) -> None: # noqa: N802 - super().leaveEvent(event) - self.update() - - def mousePressEvent(self, event: QtGui.QMouseEvent) -> None: # noqa: N802 - super().mousePressEvent(event) - self.update() - - def mouseReleaseEvent(self, event: QtGui.QMouseEvent) -> None: # noqa: N802 - super().mouseReleaseEvent(event) - self.update() - - -class Checkbutton(Widget): - _winfo_class = "TCheckbutton" - _default_style = "TCheckbutton" - _style_kind = "checkbutton" - - def __init__( - self, - parent: Any = None, - text: str = "", - variable: Variable | None = None, - command: Callable[[], Any] | None = None, - **kwargs: Any, - ) -> None: - self._text_value = str(text) - button = AppleSwitch(_qt_button_text(text), _qt_parent(parent)) - super().__init__(button, parent, **kwargs) - config = _effective_style_config(self._style_name, self._default_style) - button.setMinimumHeight( - max(button.minimumHeight(), 19 if _uses_tk_default_font(config) else 23) - ) - self._variable = variable - self._command = command - if variable is not None: - variable._connect(lambda current: button.setChecked(bool(current))) - button.toggled.connect(self._on_toggled) - - def _on_toggled(self, checked: bool) -> None: - if self._variable is not None: - self._variable.set(bool(checked)) - if self._command is not None: - self._command() - - def configure(self, **kwargs: Any) -> None: - text = kwargs.pop("text", None) - if text is not None: - self._text_value = str(text) - self._qt.setText(_qt_button_text(text)) - super().configure(**kwargs) - - -class Separator(Widget): - _winfo_class = "TSeparator" - _default_style = "TSeparator" - _style_kind = "frame" - - def __init__(self, parent: Any = None, orient: str = HORIZONTAL, **kwargs: Any) -> None: - line = QtWidgets.QFrame(_qt_parent(parent)) - line.setFrameShape( - QtWidgets.QFrame.Shape.VLine - if orient == VERTICAL - else QtWidgets.QFrame.Shape.HLine - ) - line.setFrameShadow(QtWidgets.QFrame.Shadow.Sunken) - if orient == VERTICAL: - line.setFixedWidth(2) - line.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Fixed, - QtWidgets.QSizePolicy.Policy.Expanding, - ) - else: - line.setFixedHeight(2) - line.setSizePolicy( - QtWidgets.QSizePolicy.Policy.Expanding, - QtWidgets.QSizePolicy.Policy.Fixed, - ) - super().__init__(line, parent, **kwargs) - - -class Scrollbar(Widget): - _winfo_class = "TScrollbar" - _default_style = "TScrollbar" - _style_kind = "frame" - - def __init__( - self, - parent: Any = None, - orient: str = VERTICAL, - command: Callable[..., Any] | None = None, - **kwargs: Any, - ) -> None: - bar = QtWidgets.QScrollBar( - QtCore.Qt.Orientation.Vertical - if orient == VERTICAL - else QtCore.Qt.Orientation.Horizontal, - _qt_parent(parent), - ) - super().__init__(bar, parent, **kwargs) - self.command = command - self._target_scrollbar: QtWidgets.QScrollBar | None = None - self._syncing = False - self._qt.valueChanged.connect(self._on_value_changed) - - def _attach_qt_scrollbar(self, scrollbar: QtWidgets.QScrollBar) -> None: - self._target_scrollbar = scrollbar - scrollbar.valueChanged.connect(lambda *_args: self._sync_from_target()) - scrollbar.rangeChanged.connect(lambda *_args: self._sync_from_target()) - self._sync_from_target() - - def _sync_from_target(self) -> None: - if self._target_scrollbar is None: - return - self._syncing = True - try: - self._qt.setRange( - self._target_scrollbar.minimum(), - self._target_scrollbar.maximum(), - ) - self._qt.setSingleStep(max(1, self._target_scrollbar.singleStep())) - self._qt.setPageStep(max(1, self._target_scrollbar.pageStep())) - self._qt.setValue(self._target_scrollbar.value()) - finally: - self._syncing = False - - def _on_value_changed(self, value: int) -> None: - if self._syncing: - return - if self._target_scrollbar is not None: - self._target_scrollbar.setValue(value) - return - if self.command is not None: - maximum = max(1, self._qt.maximum() - self._qt.minimum()) - self.command("moveto", (value - self._qt.minimum()) / maximum) - - def set(self, *args: Any) -> None: - if self._target_scrollbar is not None: - self._sync_from_target() - return - if len(args) < 2: - return - try: - first = max(0.0, min(1.0, float(args[0]))) - last = max(first, min(1.0, float(args[1]))) - except (TypeError, ValueError): - return - scale = 1000 - page = max(1, int(round((last - first) * scale))) - self._syncing = True - try: - self._qt.setPageStep(page) - self._qt.setRange(0, max(0, scale - page)) - self._qt.setValue(min(self._qt.maximum(), int(round(first * scale)))) - finally: - self._syncing = False - - -class Text(Widget): - _winfo_class = "Text" - _default_style = "TEntry" - _style_kind = "entry" - - def __init__(self, parent: Any = None, **kwargs: Any) -> None: - text = QtWidgets.QPlainTextEdit(_qt_parent(parent)) - super().__init__(text, parent, **kwargs) - - def insert(self, _index: str, text: str) -> None: - self._qt.setPlainText(text) - - def configure(self, **kwargs: Any) -> None: - yscrollcommand = kwargs.pop("yscrollcommand", None) - if yscrollcommand is not None: - _connect_scroll_command(self._qt.verticalScrollBar(), yscrollcommand) - self._qt.setVerticalScrollBarPolicy( - QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff - ) - if kwargs.get("wrap") == WORD: - self._qt.setLineWrapMode(QtWidgets.QPlainTextEdit.LineWrapMode.WidgetWidth) - self._qt.setHorizontalScrollBarPolicy( - QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff - ) - state = kwargs.pop("state", None) - if state is not None: - self._qt.setReadOnly(state == DISABLED) - super().configure(**kwargs) - - def yview(self, *args: Any) -> tuple[float, float] | None: - return _scrollbar_view(self._qt.verticalScrollBar(), *args) - - -class Canvas(Widget): - _winfo_class = "Canvas" - _default_style = "TFrame" - _style_kind = "frame" - - def __init__(self, parent: Any = None, width: int = 16, height: int = 16, **kwargs: Any) -> None: - widget = QtWidgets.QWidget(_qt_parent(parent)) - widget.setMinimumSize(width, height) - super().__init__(widget, parent, **kwargs) - self._items: dict[int, dict[str, Any]] = {} - - def create_oval(self, *coords: Any, **kwargs: Any) -> int: - item_id = next(_ITEM_IDS) - self._items[item_id] = {"coords": coords, **kwargs} - return item_id - - def itemconfig(self, item_id: int, **kwargs: Any) -> None: - self._items.setdefault(item_id, {}).update(kwargs) - - -class Combobox(Entry): - _winfo_class = "TCombobox" - - -class Scale(Widget): - _winfo_class = "TScale" - _default_style = "TScale" - _style_kind = "frame" - - def __init__(self, parent: Any = None, orient: str = HORIZONTAL, **kwargs: Any) -> None: - slider = QtWidgets.QSlider( - QtCore.Qt.Orientation.Horizontal - if orient == HORIZONTAL - else QtCore.Qt.Orientation.Vertical, - _qt_parent(parent), - ) - super().__init__(slider, parent, **kwargs) - - -class Notebook(Widget): - _winfo_class = "TNotebook" - _default_style = "TNotebook" - _style_kind = "notebook" - - def __init__(self, parent: Any = None, **kwargs: Any) -> None: - notebook = QtWidgets.QTabWidget(_qt_parent(parent)) - notebook.setDocumentMode(True) - notebook.setUsesScrollButtons(False) - notebook.setElideMode(QtCore.Qt.TextElideMode.ElideNone) - notebook.tabBar().setExpanding(False) - notebook.tabBar().setDrawBase(False) - super().__init__(notebook, parent, **kwargs) - self._tabs: dict[Widget, int] = {} - self._tab_widgets: list[Widget] = [] - self._tab_changed_callbacks: list[Callable[[Any], Any]] = [] - self._qt.currentChanged.connect(self._emit_tab_changed) - self._sync_tab_visibility() - - def add(self, child: Widget, text: str = "", **_: Any) -> None: - index = self._qt.addTab(child._qt, text) - self._tabs[child] = index - self._tab_widgets.append(child) - if len(self._tab_widgets) == 1: - self.select(0) - else: - self._apply_tab_button_styles() - self._sync_tab_visibility() - - def _tab_index(self, child: Widget | int) -> int | None: - if isinstance(child, int): - if 0 <= child < self._qt.count(): - return int(child) - return None - return self._tabs.get(child) - - def tabs(self) -> tuple[Widget, ...]: - return tuple(self._tab_widgets) - - def tab(self, child: Widget | int, option: str | None = None, **kwargs: Any) -> Any: - index = self._tab_index(child) - if index is None: - return - if option is not None and not kwargs: - if option == "text": - return self._qt.tabText(index) - return None - if "text" in kwargs: - self._qt.setTabText(index, str(kwargs["text"])) - self._apply_tab_button_styles() - self._sync_tab_visibility() - - def select(self, child: Widget | int | None = None) -> Widget | None: - if child is None: - index = self._qt.currentIndex() - for page, page_index in self._tabs.items(): - if page_index == index: - return page - return None - index = child if isinstance(child, int) else self._tabs.get(child) - if index is not None: - self._qt.setCurrentIndex(index) - self._apply_tab_button_styles() - self._sync_tab_visibility() - return None - - def index(self, child: Widget | None) -> int: - if child is None: - raise TclError("bad notebook tab") - index = self._tabs.get(child) - if index is None: - raise TclError("bad notebook tab") - return index - - def bind(self, sequence: str, callback: Callable[[Any], Any], **_: Any) -> None: - if sequence == "<>": - self._tab_changed_callbacks.append(callback) - return - super().bind(sequence, callback) - - def _emit_tab_changed(self, _index: int) -> None: - if not hasattr(self, "_tab_changed_callbacks"): - return - event = SimpleNamespace(widget=self) - for callback in list(self._tab_changed_callbacks): - callback(event) - - def _apply_style(self) -> None: - super()._apply_style() - self._apply_tab_button_styles() - self._sync_tab_visibility() - - def _sync_tab_visibility(self) -> None: - tab_bar = self._qt.tabBar() - hidden = self._style_name in _HIDDEN_NOTEBOOK_TABS - if hasattr(self._qt, "setTabBarAutoHide"): - self._qt.setTabBarAutoHide(False) - tab_bar.setVisible(not hidden) - if not hidden: - tab_bar.setMinimumHeight(max(24, tab_bar.sizeHint().height())) - - def _apply_tab_button_styles(self) -> None: - if not hasattr(self, "_tab_widgets"): - return - tab_style = f"{self._style_name}.Tab" if self._style_name else "TNotebook.Tab" - default_style = "TNotebook.Tab" - tab_config = _merged_style(tab_style, default_style) - tab_maps = _merged_maps(tab_style, default_style) - selected_config = dict(tab_config) - unselected_config = dict(tab_config) - hover_config = dict(tab_config) - for option in ("background", "foreground", "bordercolor"): - selected_value = _mapped_value(tab_maps, option, "selected") - active_value = _mapped_value(tab_maps, option, "active") - if selected_value is not None: - selected_config[option] = selected_value - if active_value is not None: - hover_config[option] = active_value - - for config in (selected_config, unselected_config, hover_config): - config.setdefault("bordercolor", TOKENS.border) - config.setdefault("borderwidth", 1) - - tab_font = _font_from_config(tab_config.get("font")) - font_height = QtGui.QFontMetrics(tab_font or self._qt.font()).height() - tab_height = max(28, font_height + 10) - if self._style_name == "Eval.TNotebook": - tab_height = max(tab_height, 33) - self._qt.tabBar().setMinimumHeight(tab_height) - pane_config = _merged_style(self._style_name, self._default_style) - pane_bg = pane_config.get("background") or "#ffffff" - if tab_font is not None: - self._qt.tabBar().setFont(tab_font) - - if self._style_name == "Workspace.TNotebook": - tab_height = max(40, font_height + 12) - self._qt.setDocumentMode(True) - self._qt.tabBar().setDrawBase(False) - self._qt.tabBar().setMinimumHeight(tab_height) - self._qt.setStyleSheet( - "\n".join( - [ - "QTabWidget::pane { " - f"background: {TOKENS.surface}; border: 0; top: 0px; " - "}", - "QTabWidget::tab-bar { left: 0px; }", - "QTabBar { " - f"background: {TOKENS.surface}; " - f"border: 0; border-bottom: 1px solid {TOKENS.border}; " - "padding: 0; }", - "QTabBar::tab { " - f"min-height: {tab_height - 2}px; min-width: 120px; padding: 0 20px; " - f"background: transparent; color: {TOKENS.text_secondary}; " - "font-weight: 600; border: 0; " - "border-bottom: 2px solid transparent; border-radius: 0; margin: 0; " - "}", - "QTabBar::tab:hover:!selected { " - f"background: {TOKENS.surface_hover}; color: {TOKENS.text}; " - "}", - "QTabBar::tab:selected { " - f"background: {TOKENS.surface}; color: {TOKENS.accent_pressed}; " - f"border: 0; border-bottom: 2px solid {TOKENS.accent}; " - "}", - "QTabBar::tab:focus { " - f"background: {TOKENS.accent_tint}; color: {TOKENS.accent_pressed}; " - f"border: 0; border-bottom: 3px solid {TOKENS.accent}; " - "}", - ] - ) - ) - return - - pane_border = TOKENS.border - unselected_rules = _style_rules( - {**unselected_config, "padding": None}, - widget_kind="button", - ) - selected_rules = _style_rules( - {**selected_config, "padding": None}, - widget_kind="button", - ) - hover_rules = _style_rules( - {**hover_config, "padding": None}, - widget_kind="button", - ) - common_tab_rules = [ - "padding: 0px 8px;", - f"min-height: {tab_height - 2}px;", - "min-width: 0px;", - "margin: 0px;", - f"border: 1px solid {pane_border};", - "border-bottom-left-radius: 0px;", - "border-bottom-right-radius: 0px;", - ] - if self._style_name == "Eval.TNotebook": - common_tab_rules.extend( - [ - "padding: 0px 10px;", - "margin-right: -1px;", - "border-top-left-radius: 0px;", - "border-top-right-radius: 0px;", - ] - ) - pane_padding = ( - "padding-left: 1px; padding-right: 1px; padding-bottom: 1px;" - if self._style_name == "Eval.TNotebook" - else "" - ) - stylesheet = "\n".join( - [ - "QTabWidget::pane { " - f"background-color: {pane_bg}; border: 1px solid {pane_border}; top: -1px; " - f"{pane_padding}" - " }", - "QTabWidget::tab-bar { left: 0px; }", - "QTabBar::tab { " + " ".join(unselected_rules + common_tab_rules) + " }", - "QTabBar::tab:selected { " - + " ".join(selected_rules + common_tab_rules + [f"border-bottom-color: {pane_bg};"]) - + " }", - "QTabBar::tab:hover { " + " ".join(hover_rules + common_tab_rules) + " }", - ] - ) - self._qt.setStyleSheet(stylesheet) - - -class PanedWindow(Widget): - _winfo_class = "TPanedwindow" - _default_style = "TPanedwindow" - _style_kind = "frame" - - def __init__(self, parent: Any = None, orient: str = HORIZONTAL, **kwargs: Any) -> None: - splitter = QtWidgets.QSplitter( - QtCore.Qt.Orientation.Horizontal - if orient == HORIZONTAL - else QtCore.Qt.Orientation.Vertical, - _qt_parent(parent), - ) - splitter.setHandleWidth(6) - super().__init__(splitter, parent, **kwargs) - self._pending_sash: tuple[int, int] | None = None - self._splitter_filter = _SplitterResizeFilter(self) - splitter.installEventFilter(self._splitter_filter) - - def add(self, child: Widget, weight: int = 1, **_: Any) -> None: - self._qt.addWidget(child._qt) - self._qt.setStretchFactor(self._qt.count() - 1, int(weight)) - - def sashpos(self, index: int, position: int) -> None: - self._pending_sash = (int(index), int(position)) - self._apply_pending_sash() - - def _apply_pending_sash(self) -> None: - if self._pending_sash is None: - return - index, position = self._pending_sash - sizes = self._qt.sizes() - if len(sizes) < 2: - return - total = self._qt.width() - if self._qt.orientation() == QtCore.Qt.Orientation.Vertical: - total = self._qt.height() - handle_total = max(0, self._qt.count() - 1) * self._qt.handleWidth() - total = max(sum(sizes) + handle_total, total, position + 1) - available = max(1, total - handle_total) - if index != 0: - return - sizes[0] = max(1, min(position, available - 1)) - sizes[1] = max(1, available - sizes[0]) - self._qt.setSizes(sizes) - - -class _TreeTableModel(QtCore.QAbstractTableModel): - """Small model backing the transitional Treeview API with QTableView.""" - - def __init__(self, owner: "Treeview") -> None: - super().__init__(owner._qt) - self.owner = owner - - def rowCount(self, parent: QtCore.QModelIndex = QtCore.QModelIndex()) -> int: - return 0 if parent.isValid() else len(self.owner._rows) - - def columnCount(self, parent: QtCore.QModelIndex = QtCore.QModelIndex()) -> int: - return 0 if parent.isValid() else len(self.owner._columns) - - def data(self, index: QtCore.QModelIndex, role: int = QtCore.Qt.ItemDataRole.DisplayRole) -> Any: - if not index.isValid(): - return None - row = index.row() - column = index.column() - if row >= len(self.owner._rows) or column >= len(self.owner._columns): - return None - value = self.owner._rows[row][column] - if role == QtCore.Qt.ItemDataRole.DisplayRole: - return value - if role == QtCore.Qt.ItemDataRole.ToolTipRole: - return value - if role == QtCore.Qt.ItemDataRole.TextAlignmentRole: - return self.owner._column_alignment(column) - item_id = self.owner._items[row] - tags = self.owner._item_tags.get(item_id, ()) - if role in { - QtCore.Qt.ItemDataRole.BackgroundRole, - QtCore.Qt.ItemDataRole.ForegroundRole, - }: - style: dict[str, Any] = {} - for tag in tags: - style.update(self.owner._tag_styles.get(tag, {})) - key = ( - "background" - if role == QtCore.Qt.ItemDataRole.BackgroundRole - else "foreground" - ) - color = _as_color(style.get(key)) - return QtGui.QBrush(QtGui.QColor(color)) if color else None - return None - - def headerData( - self, - section: int, - orientation: QtCore.Qt.Orientation, - role: int = QtCore.Qt.ItemDataRole.DisplayRole, - ) -> Any: - if ( - orientation == QtCore.Qt.Orientation.Horizontal - and role == QtCore.Qt.ItemDataRole.DisplayRole - and section < len(self.owner._columns) - ): - column = self.owner._columns[section] - return self.owner._headings.get(column, column) - return None - - def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlag: - if not index.isValid(): - return QtCore.Qt.ItemFlag.NoItemFlags - return ( - QtCore.Qt.ItemFlag.ItemIsEnabled - | QtCore.Qt.ItemFlag.ItemIsSelectable - ) - - -class Treeview(Widget): - _winfo_class = "Treeview" - _default_style = "Treeview" - _style_kind = "tree" - - def __init__( - self, - parent: Any = None, - columns: tuple[str, ...] | list[str] = (), - show: str | None = None, - height: int | None = None, - **kwargs: Any, - ) -> None: - table = QtWidgets.QTableView(_qt_parent(parent)) - table.verticalHeader().setVisible(False) - table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows) - table.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection) - super().__init__(table, parent, **kwargs) - self._columns: list[str] = [] - self._items: list[str] = [] - self._rows: list[list[str]] = [] - self._item_rows: dict[str, int] = {} - self._headings: dict[str, str] = {} - self._column_anchors: dict[str, str] = {} - self._item_tags: dict[str, tuple[str, ...]] = {} - self._tag_styles: dict[str, dict[str, Any]] = {} - self._model = _TreeTableModel(self) - table.setModel(self._model) - table.setAlternatingRowColors(False) - self._sync_tree_dimensions() - if height is not None: - rowheight = table.verticalHeader().defaultSectionSize() - header_height = table.horizontalHeader().height() - table.setMinimumHeight(header_height + height * rowheight + 2) - self.configure(columns=columns) - - def _sync_tree_dimensions(self) -> None: - config = _effective_style_config(self._style_name, self._default_style) - rowheight = config.get("rowheight") - if rowheight: - height = int(rowheight) - self._qt.verticalHeader().setMinimumSectionSize(height) - self._qt.verticalHeader().setDefaultSectionSize(height) - for row in range(self._model.rowCount()): - self._qt.setRowHeight(row, height) - - def configure(self, **kwargs: Any) -> None: - columns = kwargs.pop("columns", None) - kwargs.pop("displaycolumns", None) - yscrollcommand = kwargs.pop("yscrollcommand", None) - xscrollcommand = kwargs.pop("xscrollcommand", None) - if columns is not None: - self._model.beginResetModel() - self._columns = list(columns) - width = len(self._columns) - self._rows = [ - (row[:width] + [""] * max(0, width - len(row))) - for row in self._rows - ] - self._model.endResetModel() - if yscrollcommand is not None: - _connect_scroll_command(self._qt.verticalScrollBar(), yscrollcommand) - self._qt.setVerticalScrollBarPolicy( - QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff - ) - if xscrollcommand is not None: - _connect_scroll_command(self._qt.horizontalScrollBar(), xscrollcommand) - self._qt.setHorizontalScrollBarPolicy( - QtCore.Qt.ScrollBarPolicy.ScrollBarAlwaysOff - ) - super().configure(**kwargs) - - def heading(self, column: str, text: str = "", **_: Any) -> None: - self._headings[column] = text - if column in self._columns: - index = self._columns.index(column) - self._model.headerDataChanged.emit( - QtCore.Qt.Orientation.Horizontal, - index, - index, - ) - - def column( - self, - column: str, - width: int | None = None, - minwidth: int | None = None, - anchor: str | None = None, - stretch: bool = True, - **_: Any, - ) -> None: - if column not in self._columns: - return - index = self._columns.index(column) - if anchor is not None: - self._column_anchors[column] = anchor - if width is not None: - self._qt.setColumnWidth(index, width) - if minwidth is not None: - self._qt.horizontalHeader().setMinimumSectionSize(max(1, int(minwidth))) - mode = ( - QtWidgets.QHeaderView.ResizeMode.Stretch - if stretch - else QtWidgets.QHeaderView.ResizeMode.Interactive - ) - self._qt.horizontalHeader().setSectionResizeMode(index, mode) - if self._model.rowCount(): - self._model.dataChanged.emit( - self._model.index(0, index), - self._model.index(self._model.rowCount() - 1, index), - [QtCore.Qt.ItemDataRole.TextAlignmentRole], - ) - - def _column_alignment(self, index: int) -> QtCore.Qt.AlignmentFlag: - column = self._columns[index] if index < len(self._columns) else "" - return _qt_alignment(self._column_anchors.get(column, "center"), None) - - def insert( - self, - _parent: str, - _index: Any, - iid: str | None = None, - values: tuple[Any, ...] | list[Any] = (), - tags: tuple[str, ...] | list[str] = (), - **_: Any, - ) -> str: - item_id = iid or f"I{next(_ITEM_IDS)}" - row = len(self._rows) - self._model.beginInsertRows(QtCore.QModelIndex(), row, row) - self._items.append(item_id) - self._item_rows[item_id] = row - self._item_tags[item_id] = tuple(str(tag) for tag in tags) - row_values = [str(value) for value in values[: len(self._columns)]] - row_values.extend([""] * (len(self._columns) - len(row_values))) - self._rows.append(row_values) - self._model.endInsertRows() - self._sync_tree_dimensions() - return item_id - - def set_rows( - self, - rows: list[tuple[Any, ...] | list[Any]], - *, - iids: list[str] | None = None, - ) -> tuple[str, ...]: - """Replace all table rows with one model reset. - - Large engineering matrices should not pay the per-row layout cost of - repeated ``insert`` calls. A single reset keeps refresh time linear - and gives Qt one opportunity to recompute row geometry. - """ - - width = len(self._columns) - item_ids = list(iids or (f"I{next(_ITEM_IDS)}" for _ in rows)) - if len(item_ids) != len(rows): - raise ValueError("iids must match the number of rows") - self._model.beginResetModel() - self._items = item_ids - self._rows = [] - self._item_tags = {item_id: () for item_id in item_ids} - for values in rows: - row_values = [str(value) for value in values[:width]] - row_values.extend([""] * (width - len(row_values))) - self._rows.append(row_values) - self._rebuild_rows() - self._model.endResetModel() - self._sync_tree_dimensions() - return tuple(item_ids) - - def delete(self, *items: str) -> None: - if not items: - return - removed = set(items) - self._model.beginResetModel() - kept = [ - (item_id, row) - for item_id, row in zip(self._items, self._rows) - if item_id not in removed - ] - self._items = [item_id for item_id, _row in kept] - self._rows = [row for _item_id, row in kept] - for item_id in removed: - self._item_tags.pop(item_id, None) - self._rebuild_rows() - self._model.endResetModel() - - def _rebuild_rows(self) -> None: - self._item_rows = {item_id: index for index, item_id in enumerate(self._items)} - - def get_children(self) -> tuple[str, ...]: - return tuple(self._items) - - def selection(self) -> tuple[str, ...]: - rows = {index.row() for index in self._qt.selectionModel().selectedRows()} - return tuple(self._items[row] for row in sorted(rows) if row < len(self._items)) - - def selection_set(self, item_id: str) -> None: - row = self._item_rows.get(item_id) - if row is not None: - self._qt.selectRow(row) - - def focus(self, item_id: str | None = None) -> str | None: - if item_id is not None: - self.selection_set(item_id) - return item_id - selected = self.selection() - return selected[0] if selected else None - - def tag_configure(self, tag: str, **kwargs: Any) -> None: - self._tag_styles.setdefault(tag, {}).update(kwargs) - if self._model.rowCount() and self._model.columnCount(): - self._model.dataChanged.emit( - self._model.index(0, 0), - self._model.index( - self._model.rowCount() - 1, - self._model.columnCount() - 1, - ), - [ - QtCore.Qt.ItemDataRole.BackgroundRole, - QtCore.Qt.ItemDataRole.ForegroundRole, - ], - ) - - def yview(self, *args: Any) -> tuple[float, float] | None: - return _scrollbar_view(self._qt.verticalScrollBar(), *args) - - def xview(self, *args: Any) -> tuple[float, float] | None: - return _scrollbar_view(self._qt.horizontalScrollBar(), *args) - - -class Menu: - def __init__(self, parent: Any = None, tearoff: bool = False, **_: Any) -> None: - self._parent = parent - self._menu = QtWidgets.QMenu(_qt_parent(parent)) - self._entries: list[dict[str, Any]] = [] - self._style_options: dict[str, Any] = {} - - def configure(self, **kwargs: Any) -> None: - self._style_options.update(kwargs) - options = self._style_options - bg = _as_color(options.get("background")) - fg = _as_color(options.get("foreground")) - active_bg = _as_color(options.get("activebackground")) - active_fg = _as_color(options.get("activeforeground")) - disabled_fg = _as_color(options.get("disabledforeground")) - bordercolor = _as_color(options.get("bordercolor")) or "#cbd5e1" - borderwidth = int(options.get("borderwidth") or 1) - rules = [] - if bg: - rules.append(f"background-color: {bg};") - if fg: - rules.append(f"color: {fg};") - rules.extend(_font_rules(options.get("font"))) - rules.append(f"border: {borderwidth}px solid {bordercolor};") - blocks = [f"QMenu {{ {' '.join(rules)} padding: 2px; }}"] - item_rules = ["padding: 5px 28px 5px 12px;"] - if bg: - item_rules.append(f"background-color: {bg};") - blocks.append(f"QMenu::item {{ {' '.join(item_rules)} }}") - selected_rules = [] - if active_bg: - selected_rules.append(f"background-color: {active_bg};") - if active_fg: - selected_rules.append(f"color: {active_fg};") - if selected_rules: - blocks.append(f"QMenu::item:selected {{ {' '.join(selected_rules)} }}") - if disabled_fg: - blocks.append(f"QMenu::item:disabled {{ color: {disabled_fg}; }}") - blocks.append( - "QMenu::separator { height: 1px; " - f"background: {bordercolor}; margin: 4px 8px; }}" - ) - self._menu.setStyleSheet("\n".join(blocks)) - - config = configure - - def add_command( - self, - label: str, - command: Callable[[], Any] | None = None, - **kwargs: Any, - ) -> None: - action = self._menu.addAction(label) - state = str(kwargs.get("state", NORMAL)) - action.setEnabled(state != DISABLED) - if command is not None: - action.triggered.connect(lambda _checked=False, cb=command: cb()) - self._entries.append( - { - "type": "command", - "label": str(label), - "state": state, - "command": command, - "action": action, - } - ) - - def add_separator(self) -> None: - action = self._menu.addSeparator() - self._entries.append({"type": "separator", "action": action}) - - def delete(self, start: int, end: Any = None) -> None: - self._menu.clear() - self._entries.clear() - - def index(self, index: Any) -> int | None: - if index == END: - return len(self._entries) - 1 if self._entries else None - return int(index) - - def type(self, index: int) -> str: - return str(self._entries[index]["type"]) - - def entryconfigure(self, index: int, **kwargs: Any) -> None: - entry = self._entries[int(index)] - action = entry.get("action") - if "label" in kwargs and action is not None: - entry["label"] = str(kwargs["label"]) - action.setText(entry["label"]) - if "state" in kwargs and action is not None: - state = str(kwargs["state"]) - entry["state"] = state - action.setEnabled(state != DISABLED) - - def entrycget(self, index: int, option: str) -> str: - entry = self._entries[int(index)] - normalized = str(option).lstrip("-") - if normalized == "label": - return str(entry.get("label", "")) - if normalized == "state": - return str(entry.get("state", NORMAL)) - if normalized == "menu" and "menu" in entry: - return str(entry["menu"]) - raise TclError(f"unknown option {option!r}") - - def invoke(self, index: int) -> Any: - entry = self._entries[int(index)] - if entry.get("type") != "command" or entry.get("state", NORMAL) == DISABLED: - return None - command = entry.get("command") - if command is not None: - return command() - action = entry.get("action") - if action is not None: - action.trigger() - return None - - def nametowidget(self, *_args: Any, **_kwargs: Any) -> Any: - raise TclError("no named widget") - - -class Style: - def __init__(self, _root: Any = None) -> None: - return - - def theme_use(self, _name: str) -> None: - return - - def configure(self, style_name: str, **kwargs: Any) -> None: - _STYLE_CONFIGS.setdefault(style_name, {}).update(kwargs) - - def map(self, style_name: str, **kwargs: Any) -> None: - style_maps = _STYLE_MAPS.setdefault(style_name, {}) - for option, values in kwargs.items(): - normalized: list[tuple[str, Any]] = [] - for value in values: - if isinstance(value, tuple) and len(value) >= 2: - normalized.append((str(value[0]), value[-1])) - style_maps[option] = normalized - - def layout(self, style_name: str, layout_spec: Any = None, **_kwargs: Any) -> None: - if style_name.endswith(".Tab") and layout_spec == []: - _HIDDEN_NOTEBOOK_TABS.add(style_name[: -len(".Tab")]) - - -class PhotoImage: - def __init__(self, file: str | None = None, **_: Any) -> None: - self.file = file - self.pixmap = QtGui.QPixmap(file) if file else QtGui.QPixmap() - - -def _file_filter(filetypes: Any) -> str: - if not filetypes: - return "All Files (*)" - parts = [] - for label, pattern in filetypes: - if isinstance(pattern, (tuple, list)): - pattern_text = " ".join(pattern) - else: - pattern_text = str(pattern) - parts.append(f"{label} ({pattern_text})") - return ";;".join(parts) - - -class _FileDialog: - def askopenfilename(self, **kwargs: Any) -> str: - _ensure_app() - path, _filter = QtWidgets.QFileDialog.getOpenFileName( - _qt_parent(kwargs.get("parent")), - kwargs.get("title", "Open"), - str(kwargs.get("initialdir") or Path.home()), - _file_filter(kwargs.get("filetypes")), - ) - return path - - def asksaveasfilename(self, **kwargs: Any) -> str: - _ensure_app() - initialdir = Path(kwargs.get("initialdir") or Path.home()) - initialfile = kwargs.get("initialfile") - start = str(initialdir / initialfile) if initialfile else str(initialdir) - path, _filter = QtWidgets.QFileDialog.getSaveFileName( - _qt_parent(kwargs.get("parent")), - kwargs.get("title", "Save"), - start, - _file_filter(kwargs.get("filetypes")), - ) - if path and kwargs.get("defaultextension") and "." not in Path(path).name: - path += str(kwargs["defaultextension"]) - return path - - -class _MessageBox: - def showinfo(self, title: str, message: str) -> None: - _ensure_app() - QtWidgets.QMessageBox.information(None, title, message) - - def showerror(self, title: str, message: str) -> None: - _ensure_app() - QtWidgets.QMessageBox.critical(None, title, message) - - -filedialog = _FileDialog() -messagebox = _MessageBox() - - -tk = SimpleNamespace( - BooleanVar=BooleanVar, - BOTH=BOTH, - Button=Button, - Canvas=Canvas, - Checkbutton=Checkbutton, - Combobox=Combobox, - DISABLED=DISABLED, - DoubleVar=DoubleVar, - END=END, - Entry=Entry, - Frame=Frame, - HORIZONTAL=HORIZONTAL, - Label=Label, - LabelFrame=LabelFrame, - LEFT=LEFT, - Menu=Menu, - Menubutton=Menubutton, - NORMAL=NORMAL, - Notebook=Notebook, - PanedWindow=PanedWindow, - PhotoImage=PhotoImage, - Radiobutton=Radiobutton, - RIGHT=RIGHT, - Scale=Scale, - Scrollbar=Scrollbar, - Separator=Separator, - SOLID=SOLID, - StringVar=StringVar, - Style=Style, - TclError=TclError, - Text=Text, - Tk=Tk, - Toplevel=Toplevel, - Treeview=Treeview, - VERTICAL=VERTICAL, - Widget=Widget, - WORD=WORD, - X=X, -) - -ttk = SimpleNamespace( - Button=Button, - Checkbutton=Checkbutton, - Combobox=Combobox, - Entry=Entry, - Frame=Frame, - Label=Label, - LabelFrame=LabelFrame, - Menubutton=Menubutton, - Notebook=Notebook, - PanedWindow=PanedWindow, - Radiobutton=Radiobutton, - Scale=Scale, - Scrollbar=Scrollbar, - Separator=Separator, - Style=Style, - Treeview=Treeview, -) diff --git a/src/virtual_array/server/__init__.py b/src/virtual_array/server/__init__.py new file mode 100644 index 0000000..a6f768a --- /dev/null +++ b/src/virtual_array/server/__init__.py @@ -0,0 +1,5 @@ +"""HTTP server: FastAPI application serving the API and the web client.""" + +from .app import create_app + +__all__ = ["create_app"] diff --git a/src/virtual_array/server/app.py b/src/virtual_array/server/app.py new file mode 100644 index 0000000..426b404 --- /dev/null +++ b/src/virtual_array/server/app.py @@ -0,0 +1,515 @@ +from __future__ import annotations + +import io +import json +import logging +import os +import zipfile +from contextlib import asynccontextmanager +from dataclasses import asdict +from pathlib import Path +from typing import Any, Literal + +from fastapi import FastAPI, File, HTTPException, Request, UploadFile +from fastapi.exceptions import RequestValidationError +from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel, Field, ValidationError + +from ..analysis import DBF_SCAN_FOV, DBF_SCAN_GRID_SIZE, DBF_SCAN_STEP_DEG +from ..assets import MAX_ASSET_BYTES, AssetNotFoundError, AssetStore, sanitize_filename +from ..engine import Engine, ProjectComputationError +from ..logging_config import configure_logging +from ..project import ( + GRID_STEP_LAMBDA, + MAX_RX_COUNT, + MAX_TX_COUNT, + ChannelPatternBinding, + Layout, + Project, + auto_layout, + default_project, + project_from_document, +) +from ..version import APP_VERSION +from .jobs import JobManager, JobNotFoundError, zip_directory +from .store import ProjectNotFoundError, ProjectStore + +LOGGER = logging.getLogger(__name__) +DATA_DIR_ENV = "MIMO_DATA_DIR" +WEB_DIST_ENV = "MIMO_WEB_DIST" +MAX_2D_FRAMES_PER_REQUEST = 24 +MAX_BUNDLE_BYTES = 128 * 1024 * 1024 + + +def default_data_dir() -> Path: + override = os.environ.get(DATA_DIR_ENV) + if override: + return Path(override).expanduser() + return Path.cwd() / "data" + + +def default_static_dir() -> Path: + override = os.environ.get(WEB_DIST_ENV) + if override: + return Path(override).expanduser() + return Path(__file__).resolve().parent / "static" + + +# ── Request models ─────────────────────────────────────────────────── + + +class ProjectRequest(BaseModel): + project: Project + + +class AutoLayoutRequest(BaseModel): + tx_count: int = Field(ge=1, le=MAX_TX_COUNT) + rx_count: int = Field(ge=1, le=MAX_RX_COUNT) + + +class BankRequest(ProjectRequest): + axis: Literal["azimuth", "elevation"] + + +class TrueAngle(BaseModel): + azimuth: float = Field(ge=DBF_SCAN_FOV[0], le=DBF_SCAN_FOV[1]) + elevation: float = Field(ge=DBF_SCAN_FOV[0], le=DBF_SCAN_FOV[1]) + + +class Dbf2dRequest(ProjectRequest): + frames: list[TrueAngle] = Field(min_length=1, max_length=MAX_2D_FRAMES_PER_REQUEST) + + +class ElementPatternPreviewRequest(BaseModel): + asset: str + swap_axes: bool = False + + +class ChannelPatternResolveRequest(ProjectRequest): + asset: str + kind: Literal["amplitude", "phase"] + plane: Literal["horizontal", "elevation"] + target: Literal["physical", "virtual"] = "physical" + channel: str | None = None + + +class DictionaryPreviewRequest(ProjectRequest): + axis: Literal["azimuth", "elevation"] = "azimuth" + + +class ImportDocumentRequest(BaseModel): + document: Any + + +class AngleRangeModel(BaseModel): + start: float = Field(ge=DBF_SCAN_FOV[0], le=DBF_SCAN_FOV[1]) + stop: float = Field(ge=DBF_SCAN_FOV[0], le=DBF_SCAN_FOV[1]) + + +class ReportOptionsModel(BaseModel): + title: str = Field(default="当前配置测角性能报告", min_length=1, max_length=100) + azimuth_focus: AngleRangeModel = AngleRangeModel(start=-70, stop=70) + elevation_focus: AngleRangeModel = AngleRangeModel(start=-15, stop=15) + azimuth_hold: AngleRangeModel = AngleRangeModel(start=-70, stop=70) + elevation_hold: AngleRangeModel = AngleRangeModel(start=-15, stop=15) + azimuth_hold_stride_frames: int = 1 + elevation_hold_stride_frames: int = 1 + error_limit_deg: float = 1.0 + spectrum_floor_db: float = -40.0 + include_raw_data: bool = True + include_spectrum_db: bool = True + include_spectrum_magnitude: bool = False + language: Literal["zh", "en", "ja"] = "zh" + + +class ReportRequest(ProjectRequest): + options: ReportOptionsModel = ReportOptionsModel() + + +class AngleErrorImageRequest(ProjectRequest): + error_limit_deg: float = 1.0 + language: Literal["zh", "en", "ja"] = "zh" + + +class SaveProjectRequest(ProjectRequest): + pass + + +# ── Application ────────────────────────────────────────────────────── + + +def create_app(data_dir: str | Path | None = None, static_dir: str | Path | None = None) -> FastAPI: + root = Path(data_dir) if data_dir is not None else default_data_dir() + root.mkdir(parents=True, exist_ok=True) + assets = AssetStore(root / "assets") + engine = Engine(assets) + projects = ProjectStore(root / "projects") + jobs = JobManager(root / "jobs") + web_root = Path(static_dir) if static_dir is not None else default_static_dir() + + @asynccontextmanager + async def lifespan(_app: FastAPI): # noqa: ANN202 + yield + jobs.shutdown() + + app = FastAPI( + title="MIMO Array Visualizer", + version=APP_VERSION, + lifespan=lifespan, + docs_url="/api/docs", + openapi_url="/api/openapi.json", + redoc_url=None, + ) + app.state.engine = engine + app.state.assets = assets + app.state.projects = projects + app.state.jobs = jobs + app.state.data_dir = root + + @app.exception_handler(ProjectComputationError) + async def computation_error(_request: Request, exc: ProjectComputationError) -> JSONResponse: + return JSONResponse(status_code=422, content={"detail": str(exc)}) + + @app.exception_handler(AssetNotFoundError) + async def asset_missing(_request: Request, exc: AssetNotFoundError) -> JSONResponse: + return JSONResponse(status_code=404, content={"detail": f"Asset not found: {exc}"}) + + @app.exception_handler(RequestValidationError) + async def validation_error(_request: Request, exc: RequestValidationError) -> JSONResponse: + messages = [] + for error in exc.errors(): + location = ".".join(str(part) for part in error.get("loc", ()) if part != "body") + messages.append(f"{location}: {error.get('msg')}" if location else str(error.get("msg"))) + return JSONResponse(status_code=422, content={"detail": "; ".join(messages)}) + + def bad_request(exc: Exception) -> HTTPException: + return HTTPException(status_code=422, detail=str(exc)) + + # ── Meta ───────────────────────────────────────────────────────── + + @app.get("/api/health") + def health() -> dict[str, Any]: + return {"status": "ok", "version": APP_VERSION} + + @app.get("/api/config") + def config() -> dict[str, Any]: + return { + "version": APP_VERSION, + "default_project": default_project().model_dump(mode="json"), + "limits": { + "max_tx": MAX_TX_COUNT, + "max_rx": MAX_RX_COUNT, + "grid_step_lambda": GRID_STEP_LAMBDA, + "max_asset_bytes": MAX_ASSET_BYTES, + "max_2d_frames_per_request": MAX_2D_FRAMES_PER_REQUEST, + }, + "dbf": { + "scan_fov": list(DBF_SCAN_FOV), + "scan_step_deg": DBF_SCAN_STEP_DEG, + "scan_grid_size": DBF_SCAN_GRID_SIZE, + }, + } + + @app.post("/api/layout/auto") + def layout_auto(request: AutoLayoutRequest) -> Layout: + return auto_layout(request.tx_count, request.rx_count) + + # ── Analysis ───────────────────────────────────────────────────── + + @app.post("/api/evaluate") + def evaluate(request: ProjectRequest) -> dict[str, Any]: + return engine.evaluate(request.project) + + @app.post("/api/dbf/bank") + def dbf_bank(request: BankRequest) -> dict[str, Any]: + return engine.dbf_bank(request.project, request.axis) + + @app.post("/api/dbf/2d") + def dbf_2d(request: Dbf2dRequest) -> dict[str, Any]: + frames = [(frame.azimuth, frame.elevation) for frame in request.frames] + return engine.dbf_2d(request.project, frames) + + # ── Imported data ──────────────────────────────────────────────── + + @app.post("/api/assets") + async def upload_asset(file: UploadFile = File(...)) -> dict[str, Any]: + content = await file.read(MAX_ASSET_BYTES + 1) + try: + info = assets.add(file.filename or "upload.csv", content) + except ValueError as exc: + raise bad_request(exc) from exc + return asdict(info) + + @app.get("/api/assets/{asset_id}") + def asset_info(asset_id: str) -> dict[str, Any]: + return asdict(assets.info(asset_id)) + + @app.post("/api/element-pattern/preview") + def element_pattern_preview(request: ElementPatternPreviewRequest) -> dict[str, Any]: + try: + return engine.element_pattern_preview(request.asset, request.swap_axes) + except ValueError as exc: + raise bad_request(exc) from exc + + @app.post("/api/channel-patterns/resolve") + def channel_patterns_resolve(request: ChannelPatternResolveRequest) -> list[ChannelPatternBinding]: + try: + return engine.resolve_channel_patterns( + request.project, + request.asset, + request.kind, + request.plane, + request.target, + channel=request.channel, + ) + except ValueError as exc: + raise bad_request(exc) from exc + + @app.post("/api/dictionary/preview") + def dictionary_preview(request: DictionaryPreviewRequest) -> dict[str, Any]: + return engine.dictionary_preview(request.project, request.axis) + + # ── Import / export ────────────────────────────────────────────── + + @app.post("/api/import/document") + def import_document(request: ImportDocumentRequest) -> dict[str, Any]: + try: + project = project_from_document(request.document) + except (ValueError, ValidationError) as exc: + raise bad_request(exc) from exc + missing = sorted(asset for asset in project.asset_ids() if not assets.exists(asset)) + return {"project": project.model_dump(mode="json"), "missing_assets": missing} + + @app.post("/api/export/layout") + def export_layout(request: ProjectRequest) -> dict[str, Any]: + return engine.layout_document(request.project) + + @app.post("/api/export/bundle") + def export_bundle(request: ProjectRequest) -> Response: + project = request.project + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr( + "project.json", + json.dumps(project.model_dump(mode="json"), ensure_ascii=False, indent=2), + ) + for asset_id in sorted(project.asset_ids()): + info = assets.info(asset_id) + archive.write(assets.path(asset_id), arcname=f"assets/{asset_id}/{info.filename}") + filename = sanitize_filename(f"{project.name}.mimo.zip") + return Response( + content=buffer.getvalue(), + media_type="application/zip", + headers={"Content-Disposition": _content_disposition(filename)}, + ) + + @app.post("/api/import/bundle") + async def import_bundle(file: UploadFile = File(...)) -> dict[str, Any]: + content = await file.read(MAX_BUNDLE_BYTES + 1) + if len(content) > MAX_BUNDLE_BYTES: + raise HTTPException(status_code=413, detail="Project bundle is too large.") + try: + archive = zipfile.ZipFile(io.BytesIO(content)) + except zipfile.BadZipFile as exc: + raise bad_request(ValueError("Not a valid project bundle (.zip).")) from exc + with archive: + try: + document = json.loads(archive.read("project.json").decode("utf-8")) + except KeyError as exc: + raise bad_request(ValueError("Bundle has no project.json.")) from exc + remap: dict[str, str] = {} + for name in archive.namelist(): + parts = name.split("/") + if len(parts) != 3 or parts[0] != "assets" or not parts[2]: + continue + data = archive.read(name) + if len(data) > MAX_ASSET_BYTES: + raise bad_request(ValueError(f"Bundled file {parts[2]} is too large.")) + info = assets.add(parts[2], data) + remap[parts[1]] = info.id + text = json.dumps(document) + for old_id, new_id in remap.items(): + text = text.replace(old_id, new_id) + try: + project = project_from_document(json.loads(text)) + except (ValueError, ValidationError) as exc: + raise bad_request(exc) from exc + missing = sorted(asset for asset in project.asset_ids() if not assets.exists(asset)) + return {"project": project.model_dump(mode="json"), "missing_assets": missing} + + # ── Project library ────────────────────────────────────────────── + + @app.get("/api/projects") + def list_projects() -> list[dict[str, Any]]: + return projects.list() + + @app.post("/api/projects") + def create_project(request: SaveProjectRequest) -> dict[str, Any]: + return projects.create(request.project) + + @app.get("/api/projects/{project_id}") + def get_project(project_id: str) -> dict[str, Any]: + try: + return projects.get(project_id) + except ProjectNotFoundError as exc: + raise HTTPException(status_code=404, detail="Project not found.") from exc + + @app.put("/api/projects/{project_id}") + def update_project(project_id: str, request: SaveProjectRequest) -> dict[str, Any]: + try: + return projects.update(project_id, request.project) + except ProjectNotFoundError as exc: + raise HTTPException(status_code=404, detail="Project not found.") from exc + + @app.delete("/api/projects/{project_id}", status_code=204) + def delete_project(project_id: str) -> Response: + try: + projects.delete(project_id) + except ProjectNotFoundError as exc: + raise HTTPException(status_code=404, detail="Project not found.") from exc + return Response(status_code=204) + + # ── Exports (background jobs) ──────────────────────────────────── + + @app.post("/api/reports") + def create_report(request: ReportRequest) -> dict[str, Any]: + from ..performance_report import ( + AngleRange, + PerformanceReportOptions, + generate_performance_report, + ) + + snapshot = engine.report_snapshot(request.project) + settings = request.options + filename = sanitize_filename(f"{settings.title}.pdf") + if not filename.lower().endswith(".pdf"): + filename += ".pdf" + try: + # Validate eagerly so option errors return 422 instead of a failed job. + template = PerformanceReportOptions( + output_path=Path(filename), + title=settings.title, + azimuth_focus=AngleRange(settings.azimuth_focus.start, settings.azimuth_focus.stop), + elevation_focus=AngleRange( + settings.elevation_focus.start, settings.elevation_focus.stop + ), + azimuth_hold=AngleRange(settings.azimuth_hold.start, settings.azimuth_hold.stop), + elevation_hold=AngleRange( + settings.elevation_hold.start, settings.elevation_hold.stop + ), + error_limit_deg=settings.error_limit_deg, + spectrum_floor_db=settings.spectrum_floor_db, + include_raw_data=settings.include_raw_data, + language=settings.language, + include_spectrum_db=settings.include_spectrum_db, + include_spectrum_magnitude=settings.include_spectrum_magnitude, + azimuth_hold_stride_frames=settings.azimuth_hold_stride_frames, + elevation_hold_stride_frames=settings.elevation_hold_stride_frames, + ) + except ValueError as exc: + raise bad_request(exc) from exc + + def body(directory: Path, progress) -> Path: # noqa: ANN001 + from dataclasses import replace + + options = replace(template, output_path=directory / filename) + artifacts = generate_performance_report(snapshot, options, progress) + if not options.include_raw_data: + return artifacts.pdf_path + target = directory / f"{Path(filename).stem}.zip" + return zip_directory(list(artifacts.files), directory, target) + + return jobs.submit("report", body).payload() + + @app.post("/api/angle-error-image") + def create_angle_error_image(request: AngleErrorImageRequest) -> dict[str, Any]: + from ..performance_report import AngleErrorImageOptions, generate_angle_error_image + + snapshot = engine.report_snapshot(request.project) + filename = sanitize_filename(f"{request.project.name}-angle-error.png") + try: + template = AngleErrorImageOptions( + output_path=Path(filename), + error_limit_deg=request.error_limit_deg, + language=request.language, + ) + except ValueError as exc: + raise bad_request(exc) from exc + + def body(directory: Path, progress) -> Path: # noqa: ANN001 + from dataclasses import replace + + options = replace(template, output_path=directory / filename) + return generate_angle_error_image(snapshot, options, progress).png_path + + return jobs.submit("angle_image", body).payload() + + @app.get("/api/jobs/{job_id}") + def job_status(job_id: str) -> dict[str, Any]: + try: + return jobs.get(job_id).payload() + except JobNotFoundError as exc: + raise HTTPException(status_code=404, detail="Job not found.") from exc + + @app.post("/api/jobs/{job_id}/cancel") + def job_cancel(job_id: str) -> dict[str, Any]: + try: + return jobs.cancel(job_id).payload() + except JobNotFoundError as exc: + raise HTTPException(status_code=404, detail="Job not found.") from exc + + @app.get("/api/jobs/{job_id}/download") + def job_download(job_id: str) -> FileResponse: + try: + job = jobs.get(job_id) + except JobNotFoundError as exc: + raise HTTPException(status_code=404, detail="Job not found.") from exc + if job.status != "succeeded" or job.download_path is None: + raise HTTPException(status_code=409, detail="The export is not ready.") + return FileResponse(job.download_path, filename=job.download_name) + + @app.api_route("/api/{path:path}", methods=["GET", "POST", "PUT", "DELETE"]) + def api_not_found(path: str) -> None: + raise HTTPException(status_code=404, detail=f"Unknown API endpoint: /api/{path}") + + _mount_web_client(app, web_root) + return app + + +def _mount_web_client(app: FastAPI, web_root: Path) -> None: + index = web_root / "index.html" + if not index.is_file(): + LOGGER.warning("Web client not found at %s; serving API only.", web_root) + + @app.get("/", include_in_schema=False) + def missing_client() -> HTMLResponse: + return HTMLResponse( + "

MIMO Array Visualizer API

" + "

The web client has not been built. Run npm run build " + "in web/, or open /api/docs.

" + ) + + return + + assets_dir = web_root / "assets" + if assets_dir.is_dir(): + app.mount("/assets", StaticFiles(directory=assets_dir), name="web-assets") + + @app.get("/{path:path}", include_in_schema=False) + def web_client(path: str) -> FileResponse: + candidate = (web_root / path).resolve() + if path and candidate.is_file() and web_root.resolve() in candidate.parents: + return FileResponse(candidate) + return FileResponse(index, headers={"Cache-Control": "no-cache"}) + + +def _content_disposition(filename: str) -> str: + from urllib.parse import quote + + ascii_name = filename.encode("ascii", "ignore").decode() or "project.mimo.zip" + return f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(filename)}" + + +def configure_server_logging(data_dir: Path) -> Path: + return configure_logging(data_dir / "logs") diff --git a/src/virtual_array/server/cli.py b/src/virtual_array/server/cli.py new file mode 100644 index 0000000..708472d --- /dev/null +++ b/src/virtual_array/server/cli.py @@ -0,0 +1,69 @@ +"""``mimo-array-server`` command: run the web workbench on a local server.""" + +from __future__ import annotations + +import argparse +import logging +import os +from pathlib import Path + +from ..version import APP_VERSION +from .app import DATA_DIR_ENV, configure_server_logging, create_app, default_data_dir + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="mimo-array-server", + description="Serve the MIMO Array Visualizer web workbench.", + ) + parser.add_argument( + "--host", + default=os.environ.get("MIMO_HOST", "127.0.0.1"), + help="Bind address (default 127.0.0.1; use 0.0.0.0 to allow other machines).", + ) + parser.add_argument( + "--port", + type=int, + default=int(os.environ.get("MIMO_PORT", "8000")), + help="TCP port (default 8000).", + ) + parser.add_argument( + "--data-dir", + type=Path, + default=None, + help=f"Directory for projects, uploaded files and exports (env {DATA_DIR_ENV}; default ./data).", + ) + parser.add_argument( + "--static-dir", + type=Path, + default=None, + help="Built web client directory (default: the copy bundled in the package).", + ) + parser.add_argument("--version", action="version", version=f"%(prog)s {APP_VERSION}") + return parser + + +def main(argv: list[str] | None = None) -> None: + import uvicorn + + args = build_parser().parse_args(argv) + data_dir = (args.data_dir or default_data_dir()).expanduser().resolve() + data_dir.mkdir(parents=True, exist_ok=True) + log_path = configure_server_logging(data_dir) + logging.getLogger(__name__).info( + "Starting MIMO Array Visualizer %s on %s:%s (data: %s)", + APP_VERSION, + args.host, + args.port, + data_dir, + ) + print(f"MIMO Array Visualizer {APP_VERSION}") + print(f" URL: http://{'localhost' if args.host in {'127.0.0.1', '0.0.0.0'} else args.host}:{args.port}/") + print(f" Data dir: {data_dir}") + print(f" Log file: {log_path}") + app = create_app(data_dir=data_dir, static_dir=args.static_dir) + uvicorn.run(app, host=args.host, port=args.port, log_level="info") + + +if __name__ == "__main__": + main() diff --git a/src/virtual_array/server/jobs.py b/src/virtual_array/server/jobs.py new file mode 100644 index 0000000..39a4708 --- /dev/null +++ b/src/virtual_array/server/jobs.py @@ -0,0 +1,141 @@ +"""Background jobs for long-running exports (PDF reports, angle-error images).""" + +from __future__ import annotations + +import logging +import re +import shutil +import threading +import time +import uuid +import zipfile +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +LOGGER = logging.getLogger(__name__) +JOB_RETENTION_SECONDS = 24 * 3600 +_JOB_ID_RE = re.compile(r"^[0-9a-f]{32}$") + + +class JobCancelledError(Exception): + pass + + +class JobNotFoundError(KeyError): + pass + + +@dataclass +class Job: + id: str + kind: str + directory: Path + status: str = "queued" # queued | running | succeeded | failed | cancelled + progress: int = 0 + message: str = "" + error: str | None = None + download_name: str | None = None + download_path: Path | None = None + created_at: float = field(default_factory=time.time) + cancel_requested: bool = False + + def payload(self) -> dict[str, Any]: + return { + "id": self.id, + "kind": self.kind, + "status": self.status, + "progress": self.progress, + "message": self.message, + "error": self.error, + "download_name": self.download_name, + } + + +# A job body receives (output directory, progress callback) and returns the +# file to offer for download. +JobBody = Callable[[Path, Callable[[int, str], None]], Path] + + +class JobManager: + def __init__(self, root: str | Path, max_workers: int = 2) -> None: + self.root = Path(root) + self.root.mkdir(parents=True, exist_ok=True) + self._jobs: dict[str, Job] = {} + self._lock = threading.Lock() + self._executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="export") + self.cleanup() + + def submit(self, kind: str, body: JobBody) -> Job: + job_id = uuid.uuid4().hex + job = Job(id=job_id, kind=kind, directory=self.root / job_id) + job.directory.mkdir(parents=True, exist_ok=True) + with self._lock: + self._jobs[job_id] = job + self._executor.submit(self._run, job, body) + return job + + def get(self, job_id: str) -> Job: + if not _JOB_ID_RE.fullmatch(job_id or ""): + raise JobNotFoundError(job_id) + with self._lock: + job = self._jobs.get(job_id) + if job is None: + raise JobNotFoundError(job_id) + return job + + def cancel(self, job_id: str) -> Job: + job = self.get(job_id) + if job.status in {"queued", "running"}: + job.cancel_requested = True + return job + + def cleanup(self) -> None: + cutoff = time.time() - JOB_RETENTION_SECONDS + with self._lock: + for job_id in [key for key, job in self._jobs.items() if job.created_at < cutoff]: + self._jobs.pop(job_id, None) + for directory in self.root.iterdir(): + if directory.is_dir() and directory.stat().st_mtime < cutoff: + shutil.rmtree(directory, ignore_errors=True) + + def shutdown(self) -> None: + self._executor.shutdown(wait=False, cancel_futures=True) + + def _run(self, job: Job, body: JobBody) -> None: + if job.cancel_requested: + job.status = "cancelled" + return + job.status = "running" + + def progress(percent: int, message: str) -> None: + if job.cancel_requested: + raise JobCancelledError() + job.progress = max(job.progress, min(100, int(percent))) + job.message = message + + try: + result = body(job.directory, progress) + except JobCancelledError: + job.status = "cancelled" + shutil.rmtree(job.directory, ignore_errors=True) + return + except Exception as exc: # noqa: BLE001 - reported to the client + LOGGER.exception("Export job %s failed", job.id) + job.status = "failed" + job.error = str(exc) or exc.__class__.__name__ + return + job.download_path = result + job.download_name = result.name + job.progress = 100 + job.status = "succeeded" + self.cleanup() + + +def zip_directory(files: list[Path], base: Path, target: Path) -> Path: + with zipfile.ZipFile(target, "w", compression=zipfile.ZIP_DEFLATED) as archive: + for path in files: + archive.write(path, arcname=str(path.relative_to(base))) + return target diff --git a/src/virtual_array/server/store.py b/src/virtual_array/server/store.py new file mode 100644 index 0000000..f10c737 --- /dev/null +++ b/src/virtual_array/server/store.py @@ -0,0 +1,104 @@ +"""File-backed project library shared by everyone using one server.""" + +from __future__ import annotations + +import json +import re +import threading +import uuid +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from ..project import Project + +_PROJECT_ID_RE = re.compile(r"^[0-9a-f]{32}$") + + +class ProjectNotFoundError(KeyError): + pass + + +class ProjectStore: + def __init__(self, root: str | Path) -> None: + self.root = Path(root) + self.root.mkdir(parents=True, exist_ok=True) + self._lock = threading.Lock() + + def list(self) -> list[dict[str, Any]]: + entries = [] + for path in self.root.glob("*.json"): + try: + record = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + continue + entries.append(_summary(record)) + entries.sort(key=lambda item: item["updated_at"], reverse=True) + return entries + + def get(self, project_id: str) -> dict[str, Any]: + path = self._path(project_id) + if not path.is_file(): + raise ProjectNotFoundError(project_id) + return json.loads(path.read_text(encoding="utf-8")) + + def create(self, project: Project) -> dict[str, Any]: + project_id = uuid.uuid4().hex + now = _now() + record = { + "id": project_id, + "created_at": now, + "updated_at": now, + "project": project.model_dump(mode="json"), + } + self._write(project_id, record) + return record + + def update(self, project_id: str, project: Project) -> dict[str, Any]: + with self._lock: + record = self.get(project_id) + record["project"] = project.model_dump(mode="json") + record["updated_at"] = _now() + self._write(project_id, record, locked=True) + return record + + def delete(self, project_id: str) -> None: + path = self._path(project_id) + if not path.is_file(): + raise ProjectNotFoundError(project_id) + path.unlink() + + def _path(self, project_id: str) -> Path: + if not _PROJECT_ID_RE.fullmatch(project_id or ""): + raise ProjectNotFoundError(project_id) + return self.root / f"{project_id}.json" + + def _write(self, project_id: str, record: dict[str, Any], locked: bool = False) -> None: + path = self._path(project_id) + temporary = path.with_suffix(".json.tmp") + text = json.dumps(record, ensure_ascii=False, indent=2) + if locked: + temporary.write_text(text, encoding="utf-8") + temporary.replace(path) + return + with self._lock: + temporary.write_text(text, encoding="utf-8") + temporary.replace(path) + + +def _summary(record: dict[str, Any]) -> dict[str, Any]: + project = record.get("project", {}) + layout = project.get("layout", {}) + return { + "id": record.get("id"), + "name": project.get("name", ""), + "created_at": record.get("created_at", ""), + "updated_at": record.get("updated_at", ""), + "tx_count": len(layout.get("tx", [])), + "rx_count": len(layout.get("rx", [])), + "frequency_ghz": project.get("frequency_ghz"), + } + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds") diff --git a/src/virtual_array/user_manual.py b/src/virtual_array/user_manual.py deleted file mode 100644 index 7640244..0000000 --- a/src/virtual_array/user_manual.py +++ /dev/null @@ -1,1647 +0,0 @@ -"""Structured, localized user-manual content for the desktop application. - -The manual is intentionally task oriented. It explains what a control is for, -how to use it, what result to expect, and what to check when the result differs -from expectations. Mathematical background belongs in engineering documents, -not in this in-app guide. -""" - -from __future__ import annotations - -from dataclasses import dataclass -import html - - -@dataclass(frozen=True, slots=True) -class ManualSection: - """One scannable section within a manual chapter.""" - - heading: str - paragraphs: tuple[str, ...] = () - steps: tuple[str, ...] = () - bullets: tuple[str, ...] = () - note: str | None = None - warning: str | None = None - - -@dataclass(frozen=True, slots=True) -class ManualChapter: - """A stable manual chapter that can be shown in navigation and search.""" - - key: str - title: str - summary: str - sections: tuple[ManualSection, ...] - - -MANUAL_CHAPTER_IDS = ( - "quick_start", - "workspace", - "layout_editing", - "virtual_overview", - "global_controls", - "dbf_1d", - "dbf_2d", - "dbf_dictionary", - "channel_patterns", - "files_reports", - "shortcuts_state", - "troubleshooting", -) - -_SUPPORTED_LANGUAGES = frozenset({"zh", "en", "ja"}) - - -def _zh_chapters() -> tuple[ManualChapter, ...]: - return ( - ManualChapter( - "quick_start", - "快速开始", - "从空白布局到完成一次可复现检查的最短操作流程。第一次使用时,按本章顺序操作即可。", - ( - ManualSection( - "开始前确认", - paragraphs=( - "程序启动后会恢复上次关闭时的阵列、频率、显示方式、活动页签和窗口布局。先看顶部状态标签,确认当前频率、DBF 字典和通道幅相状态是否符合本次任务。", - ), - bullets=( - "如果要从头开始,在“物理与虚拟阵列”页点击“清空”,布局会回到 1T1R 起始状态。", - "如果已有阵面文件,使用“文件 > 导入阵面JSON”;该操作只读取 TX/RX 坐标。", - "如果没有现成布局,可在底部输入 T、R 数量并点击“应用阵列”。T 和 R 都允许 1 到 16。", - ), - note="状态栏会持续显示最近一次操作的结果。遇到没有明显变化的情况,先读状态栏。", - ), - ManualSection( - "完成一次基础检查", - steps=( - "在物理阵列中添加、拖动或自动生成 TX/RX,确认通道名称和位置正确。坐标在界面中统一按 λ 显示。", - "在底部输入工作频率并按 Enter,或将焦点移出输入框;再设置竞争峰裕量。", - "查看虚拟阵列中的唯一点、重复点和 TX/RX 组合提示,再查看右侧总览中的通道数、口径和分辨率。", - "切换到“1D DBF”,分别检查方位和俯仰。拖动真实角标线,或点击播放观察峰值是否连续跟随。", - "当方位和俯仰都具备有效孔径时,切换到“2D DBF”,拖动十字线检查关注角度。", - "使用“文件 > 导出阵面JSON”保存坐标;需要交付结果时,再输出当前配置性能报告。", - ), - ), - ManualSection( - "结果应该是什么样", - bullets=( - "有效方向会显示曲线、真实角、估计峰值和测角指标。", - "没有有效孔径的方向会显示中性能力提示,而不是平直曲线或伪热图。", - "重复虚拟点、边界限制或竞争峰不足会在图表、总览或状态提示中明确标出。", - ), - warning="不要只看一张静态图就保存结论。至少拖动或播放一遍关注角度范围,并确认当前使用的字典和通道幅相状态。", - ), - ), - ), - ManualChapter( - "workspace", - "主窗口与三页工作区", - "认识主窗口各区域,知道每一页适合完成什么任务,以及哪些信息会随布局变化自动刷新。", - ( - ManualSection( - "窗口区域", - bullets=( - "菜单栏:导入导出、撤销重做、通道幅相、DBF 字典、语言和帮助。", - "顶部标题区:只显示频率、当前 DBF 字典和通道幅相三个全局状态。", - "主页签:物理与虚拟阵列、1D DBF、2D DBF。可用鼠标或 Ctrl+1、Ctrl+2、Ctrl+3 切换。", - "右侧总览:显示阵列规模、虚拟通道利用、口径、分辨率和测角评估。", - "底部命令栏:频率、竞争峰裕量、自动排阵和 DBF 显示方式。", - "状态栏:显示导入、拖动、播放、错误恢复和报告生成等最近操作。", - ), - ), - ManualSection( - "三页分别做什么", - bullets=( - "物理与虚拟阵列:编辑真实 TX/RX 位置,对照虚拟点,并读取总览指标。", - "1D DBF:单独检查方位或俯仰;即使只有一个方向有效,仍可继续使用有效的一侧。", - "2D DBF:同时检查方位和俯仰;只有两个方向都有有效孔径时才显示热图和播放控件。", - ), - note="如果 2D 页提示能力不足,但 1D 的某一方向可用,请直接转到 1D 页,不需要为了显示 2D 图而修改本来正确的单轴阵列。", - ), - ManualSection( - "调整窗口", - steps=( - "拖动主区域与右侧总览之间的分隔条,给图表或指标留出更多空间。", - "调整窗口大小时,等待短暂刷新结束再读取图表;程序会对连续缩放进行防抖处理。", - "长文件名或被省略的状态文本可悬停查看完整 tooltip。", - ), - bullets=( - "窗口最小尺寸为 1100×650;较小屏幕上应优先收窄总览侧栏。", - "窗口位置和分隔条比例会在正常关闭时保存,下次启动自动恢复并限制在当前屏幕工作区内。", - ), - ), - ), - ), - ManualChapter( - "layout_editing", - "编辑 TX/RX 阵列", - "添加、选择、拖动、键盘微调、删除和自动排阵。所有坐标都按 λ 展示,布局变化后相关视图自动更新。", - ( - ManualSection( - "添加与自动排阵", - steps=( - "点击“+TX”或“+RX”添加一个通道。新通道会放在同类通道右侧的空闲网格位置并自动选中。", - "需要一次建立完整阵列时,在底部“自动排阵”中分别输入 T 和 R 数量。", - "点击“应用阵列”或在数量输入框中按 Enter。程序会替换当前布局并立即刷新。", - ), - bullets=( - "TX 数量范围为 1~16,RX 数量范围为 1~16。", - "添加、自动排阵、清空、导入、拖动和键盘移动都可撤销。", - "“清空”并非生成零通道,而是恢复为可用的 1T1R 起始布局。", - ), - warning="“应用阵列”和“清空”会替换当前坐标。需要保留当前布局时,先导出阵面 JSON。", - ), - ManualSection( - "选择、拖动与精确移动", - steps=( - "在物理阵列图中单击 TX 或 RX 将其选中。", - "按住鼠标左键拖动;接近边缘时绘图区会扩展。松开后位置吸附到 0.5λ 显示网格,并重新计算全部结果。", - "选中通道后按方向键,每次沿显示网格移动 0.5λ。输入框获得焦点时,方向键仍用于编辑输入,不会移动阵元。", - "拖动尚未结束时按 Esc,可恢复拖动前的位置;未拖动时按 Esc 会取消选择或退出删除模式。", - ), - note="通道移动后会按位置重新整理同类通道编号。依赖 Tx1、Rx1 等名称的外部文件应在布局最终确定后再导入。", - ), - ManualSection( - "删除与历史", - steps=( - "选中通道后按 Delete,可直接删除当前通道。", - "没有选中通道时,点击“删除”或按 Delete 会进入持续删除模式;随后直接点击多个通道。", - "再次点击“删除”或按 Esc 退出删除模式。", - "使用“编辑 > 撤销阵列编辑”和“重做阵列编辑”恢复最近操作。", - ), - bullets=( - "每一类至少保留 1 个通道,因此最后一个 TX 或最后一个 RX 不能删除。", - "历史最多保存 50 步,只覆盖阵列布局编辑,不覆盖频率、字典或通道幅相。", - ), - ), - ), - ), - ManualChapter( - "virtual_overview", - "虚拟阵列与总览指标", - "用虚拟点和右侧总览快速确认阵列是否按预期组合、是否存在重复点,以及哪些方向具备有效能力。", - ( - ManualSection( - "查看虚拟阵列", - steps=( - "完成物理阵列编辑后,查看右侧虚拟阵列图;每个点来自一组 TX/RX 组合。", - "将鼠标悬停在虚拟点附近,读取该点对应的通道组合和坐标。", - "对照唯一虚拟点数与总虚拟通道数;两者不一致时,说明存在重合点。", - ), - bullets=( - "TX、RX 和虚拟阵列坐标均按 λ 显示,右侧口径同时换算为 mm。", - "重复点不会被静默忽略,利用率和重复提示会反映它们。", - ), - ), - ManualSection( - "读取阵列总览", - bullets=( - "通道数:当前 T×R 规模。", - "虚拟通道:唯一点/全部组合,以及对应利用率。", - "方位/俯仰口径:当前方向上的有效展开,按工作频率换算为 mm。", - "方位/俯仰分辨率:用于比较不同布局;显示不可用时表示该方向没有有效展开。", - "能力提示:只有一个方向有效时保留该方向的 1D 结果;两个方向都有效时才开放 2D。", - ), - note="频率变化会改变 mm 换算,但不会改变图中按 λ 表示的坐标。比较两个布局时,请确认频率一致。", - ), - ManualSection( - "读取测角评估", - bullets=( - "不折叠范围:当前设置下可连续使用的真实角区间。", - "范围内误差:在显示范围内观察最大误差是否满足任务要求。", - "竞争峰裕量:与底部设置的判据一起判断峰值是否足够明确。", - "截断原因:说明范围为何在某一侧停止,例如到达数据边界、阵列边界或谱可靠性不足。", - ), - warning="总览是当前字典、通道幅相、频率和布局共同作用下的结果。更换其中任何一项后,都应重新核对总览。", - ), - ), - ), - ManualChapter( - "global_controls", - "全局参数与显示", - "底部命令栏中的设置会影响尺寸换算、可靠性判断、布局和图表显示。", - ( - ManualSection( - "频率", - steps=( - "点击频率输入框,输入正数;可直接输入数字,也可带 GHz 或 G 后缀。", - "按 Enter 或将焦点移出输入框以应用。", - "查看顶部频率标签和右侧 mm 口径,确认新值已经生效。", - ), - note="输入为空、非数字、零或负数时,程序会恢复最近一次有效频率,并在状态栏说明。", - ), - ManualSection( - "竞争峰裕量", - steps=( - "输入不小于 0 的 dB 数值。", - "按 Enter 或移出焦点应用,随后查看测角评估中的裕量和截断原因。", - ), - paragraphs=( - "该值是操作判据:设得更严格时,可用角区可能缩小;设得更宽松时,需要人工更谨慎地检查相邻竞争峰。", - ), - warning="不要为了扩大可用范围而随意降低裕量。应使用项目验收要求或团队约定的值。", - ), - ManualSection( - "自动排阵与 DBF 显示", - bullets=( - "自动排阵:输入 1–16 的 T/R 数量并应用,快速得到一个可继续拖动修改的起始布局。默认沿水平方向排列,通常先形成方位孔径;要使用俯仰或 2D DBF,需再将部分通道沿 y 方向拉开。", - "dB:适合查看低电平区域、旁瓣和竞争峰。", - "模值:适合快速观察主峰轮廓和热图边界。", - "切换 dB/模值只改变显示标尺,不改变当前布局、字典或真实角。", - ), - ), - ), - ), - ManualChapter( - "dbf_1d", - "1D DBF:方位与俯仰", - "分别检查方位和俯仰角谱,使用拖动、播放、暂停和停止确认峰值在关注范围内连续跟随。", - ( - ManualSection( - "开始检查", - steps=( - "切换到“1D DBF”。左侧为方位,右侧为俯仰。", - "确认图中的真实角标线、估计峰值标记、当前帧和角度文字可见。", - "将鼠标悬停在曲线上读取角度和显示值。", - "靠近真实角标线后按住左键拖动,松开时停在新的真实角。", - ), - bullets=( - "一个方向没有孔径时,该侧显示能力提示并禁用播放;另一侧若有效,仍可正常使用。", - "拖动真实角会暂停当前扫描,并立即更新该方向的曲线和指标。", - ), - ), - ManualSection( - "播放、暂停与停止", - steps=( - "点击“播放”,真实角会从 -90° 扫描到 +90°。", - "播放过程中再次点击同一按钮可暂停;按钮和状态栏会显示暂停位置。", - "暂停后再次点击可继续。点击“停止”会结束当前方向的扫描。", - "切换到另一个方向播放时,当前扫描状态会按界面提示更新。", - ), - note="播放用于发现跳变或竞争峰,拖动用于复查具体角度。建议先播放,再对异常区间逐点拖动。", - ), - ManualSection( - "判断结果", - bullets=( - "估计峰值应在关注范围内稳定跟随真实角,不应突然跳到远处。", - "查看峰值与真实角的偏差,同时查看竞争峰裕量和截断原因。", - "在 dB 显示下检查是否出现接近主峰的竞争峰;在模值显示下复核主峰轮廓。", - ), - warning="如果曲线与预期方向相反,先确认当前 DBF 字典是否选错了“理想反向相位”或导入字典的相位反向选项,不要先修改阵列坐标。", - ), - ), - ), - ManualChapter( - "dbf_2d", - "2D DBF 热图", - "在方位和俯仰都有效时,同时查看两个方向,并用独立播放或拖动十字线检查二维关注区域。", - ( - ManualSection( - "使用条件与图中标记", - bullets=( - "只有方位和俯仰都具备有效孔径时,2D 热图才可用。", - "白色十字线表示当前真实方位和真实俯仰,峰值标记表示当前估计位置。", - "颜色条随 dB/模值切换同步变化;顶部轻量徽标显示当前角度或峰值信息。", - ), - note="若页面显示能力提示,先回到物理页增加相应方向的阵列展开;如果设计本来就是单轴阵列,应改用 1D DBF。", - ), - ManualSection( - "播放和拖动", - steps=( - "点击“播放方位”只改变真实方位,点击“播放俯仰”只改变真实俯仰。", - "两个按钮可以同时开启,使两个方向同时循环。再次点击某个按钮只暂停对应方向。", - "点击“停止”会同时结束两个方向的播放。", - "将鼠标移到十字线附近,按住左键拖动,可同时设置两个真实角;拖动会停止自动播放。", - "悬停热图读取当前位置的方位、俯仰和显示值。", - ), - ), - ManualSection( - "二维复查建议", - bullets=( - "先分别播放方位和俯仰,确认单轴变化没有异常,再同时播放。", - "将十字线拖到项目关注区域的中心、边缘和四角,记录峰值是否仍靠近真实角。", - "出现多个相近亮区时,切到 dB 显示并结合 1D 页逐轴定位问题。", - ), - warning="2D 热图适合定位问题,不应代替性能报告中的范围统计。需要交付或批量比较时请输出报告。", - ), - ), - ), - ManualChapter( - "dbf_dictionary", - "配置 DBF 字典", - "选择测角使用的四种字典,预览方位或俯仰矩阵,并在导入外部数据时明确物理/虚拟通道目标。", - ( - ManualSection( - "四种模式", - bullets=( - "理想几何字典:默认模式,适合先检查阵列布局和基本交互。", - "理想反向相位字典:用于快速核对外部数据或系统的方向约定。", - "通道幅相校准字典:使用“配置通道幅相”中当前已导入的数据;未配置的通道保持理想。", - "导入 CSV/XLSX 字典:使用外部仿真、标定或实测表格,可分别加载方位和俯仰。", - ), - note="选择单选项只更新预览;必须点击“应用字典”,主窗口才切换到该模式。关闭弹窗不会应用尚未确认的模式。", - ), - ManualSection( - "导入外部字典", - steps=( - "先选择导入目标:“物理通道”对应 Tx1、Tx2、Rx1…;“虚拟通道”对应 Tx1Rx1、Tx1Rx2…的顺序。", - "点击“加载方位字典”或“加载俯仰字典”,选择 CSV、TSV、XLSX 或 XLSM。", - "切换方位/俯仰预览,核对角度行数、通道列数、文件名和目标类型。", - "按需要勾选“导入字典相位反向”或“按 0° 相位校准”,并再次查看预览。", - "至少加载一个方向后选择“导入 CSV/XLSX 字典”,点击“应用字典”。", - ), - bullets=( - "表格需要表头、角度列和通道数据列;优先使用与当前通道一致的列名。", - "普通实数数据按相位角读取;包含复数格式的数据按复数响应读取。", - "可以只加载一个方向;未加载的方向继续使用默认数据。", - ), - warning="导入前先固定阵列通道数量和编号。之后改变 T/R 数量可能使外部字典的列数或列名不再匹配。", - ), - ManualSection( - "预览与质量提示", - bullets=( - "预览表显示当前方向各角度、各通道的相位,列多时可横向滚动。", - "质量提示会列出有效行、竞争峰、零数据行和有效秩等检查结果。", - "黄色或红色提示用于要求人工复核;提示本身不会阻止点击应用。", - "加载错误会弹出具体原因。修正源文件后重新加载,不需要重启程序。", - ), - note="质量提示是导入检查,不是项目验收结论。应用后仍要回到 1D/2D 页检查关注角度。", - ), - ), - ), - ManualChapter( - "channel_patterns", - "配置通道幅相", - "为物理通道或虚拟通道加载水平/俯仰的幅度与相位数据,支持汇总文件和单通道文件。", - ( - ManualSection( - "选择目标和数据槽", - bullets=( - "物理通道目标:表格列出 Tx1…和 Rx1…,适合按真实收发通道配置。", - "虚拟通道目标:表格列出 Tx1Rx1、Tx1Rx2…,适合直接配置组合通道。", - "每个目标都有四个独立槽:幅度-水平、幅度-俯仰、相位-水平、相位-俯仰。", - "未导入的槽保持理想,不要求一次把所有通道和四个槽全部填满。", - ), - note="切换物理/虚拟目标只改变当前表格和导入映射,不会清除另一类已经加载的数据。", - ), - ManualSection( - "导入汇总文件", - steps=( - "选择“物理通道”或“虚拟通道”目标。", - "点击对应的“加载汇总”按钮,明确本次文件属于幅度/相位以及水平/俯仰。", - "选择 CSV、TSV、XLSX 或 XLSM 文件。文件应包含角度列和多个数据列。", - "导入后检查表格每行显示的文件名与列名,并观察顶部通道幅相状态。", - ), - bullets=( - "物理目标按当前 Tx/Rx 通道规则和可识别列名映射。", - "虚拟目标按 Tx1Rx1、Tx1Rx2,直到最后一个 Tx/Rx 组合的顺序映射;显式通道列名优先。", - "角度列可使用 Theta、Angle、Azimuth、Az 或 Deg 等常见名称。", - ), - warning="汇总列数或列名与当前目标不匹配时会拒绝导入。不要靠增删空列绕过检查,应修正目标选择或源文件表头。", - ), - ManualSection( - "单通道修改、清除与生效时机", - steps=( - "在表格中选中一个通道。", - "点击底部对应“设置”按钮,给该通道加载一个数据文件。单通道文件使用角度列后的第一个数据列。", - "需要撤销某一通道时点击“清除选中通道”;需要全部恢复理想状态时点击“清空全部”。", - "返回主窗口后检查 1D/2D 图和顶部通道幅相状态。", - ), - bullets=( - "每次导入或清除都会立即重新计算;“完成”只关闭窗口,不提供回滚。", - "通道幅相不会写入本地 state.json,也不会写入阵面 JSON;重启程序后需要重新导入。", - "如果准备使用“通道幅相校准字典”,先完成本章配置,再到 DBF 字典窗口应用该模式。", - ), - ), - ), - ), - ManualChapter( - "files_reports", - "阵面文件与性能报告", - "区分可再次编辑的阵面坐标文件、当前会话配置和用于交付的 PDF/PNG/CSV/JSON 报告。", - ( - ManualSection( - "导入与导出阵面 JSON", - steps=( - "使用“文件 > 导出阵面JSON”选择保存位置。默认建议放在 outputs 目录。", - "需要恢复坐标时,使用“文件 > 导入阵面JSON”选择文件。", - "导入成功后核对状态栏中的第一个 TX/RX、坐标范围和图中通道数量。", - ), - bullets=( - "文件保存 TX/RX 坐标,并附带导出时的 evaluation 快照,便于审阅。", - "重新导入时只恢复 TX/RX 坐标;evaluation 不会反向恢复频率、DBF 字典或通道幅相。", - "导入要求 TX 和 RX 都非空、各不超过 16 个,并使用受支持的版本和 λ 单位。", - ), - warning="阵面 JSON 不是完整工程包。要复现校准结果,还需保存原始字典、通道幅相文件和所用参数。", - ), - ManualSection( - "输出当前配置性能报告", - steps=( - "选择“文件 > 输出报告”,直接打开“输出报告”设置窗口。若方位和俯仰都不可用,该功能不可执行。", - "选择 PDF 路径并填写报告标题。已有文件会在生成前询问是否覆盖。", - "分别设置可用方向的性能关注真角范围;起始角不得大于终止角。", - "设置角谱 Hold 真角范围,或勾选跟随关注范围;再为每个方向设置 Hold 曲线间隔。当前 1°/帧,界面会同时显示范围帧数与实际绘制曲线数,并始终保留起止帧。", - "设置测角误差门限和 dB 图显示下限,并至少选择 dB 或模值中的一种角谱纵坐标。", - "按需勾选“同时导出可复现原始数据(CSV/JSON)”,然后点击“输出报告”。", - "点击“输出报告”或“仅输出测角误差 PNG”不会关闭设置窗口;导出完成后可沿用当前配置继续输出另一种,只有点击“取消”或关闭窗口才退出。", - ), - ), - ManualSection( - "单独输出测角误差 PNG", - bullets=( - "在“输出报告”设置窗口中确认报告输出目录和测角误差门限,然后点击“仅输出测角误差 PNG”。", - "PNG 继承同一窗口中的报告输出目录和测角误差门限;无需另选保存位置,也不会同时生成 PDF。", - "横轴最多输出 -90°..+90°;若通道幅相或自定义 DBF 字典覆盖不足,则只输出各输入源共同具备的最大角度范围。", - "纵轴取无折叠区内测角误差绝对值峰值与测角误差门限两者的较大值,乘以 1.5 后向上取整;无折叠区外的折返误差不参与量程。", - "独立 PNG 将全部测角误差样本绘制为同一条普通蓝色曲线。无折叠区外的折返误差不参与 Y 轴量程计算;超出纵轴范围的部分由坐标轴自然裁切。", - "独立 PNG 不显示关注范围或无折叠区背景带,不以红色 × 对不可靠帧作特殊标记,也不显示缩放说明;PDF 报告仍保留这些诊断信息。PNG 与 PDF 测角误差页继续共用 plot-kit 视觉规范。", - ), - ), - ManualSection( - "生成过程与输出内容", - bullets=( - "生成在后台执行,进度窗口会显示当前阶段,主窗口不会因绘图而长期无响应。", - "点击取消后,会等当前绘图步骤安全结束再停止。", - "PDF 包含当前配置摘要、关注范围统计和所选角谱页面;每种角谱单独占页。", - "Hold 曲线间隔只降低叠加图密度;Max-Hold 包络、性能统计及可复现数据仍使用范围内全部 1° 帧。", - "选择原始数据后,会在报告旁生成数据目录,其中包含全帧 CSV 和记录实际绘制角度的报告清单 JSON。", - ), - note="角谱页数由可用方向和所选纵坐标种类决定;Hold 范围越大、曲线间隔越小,叠加图越密,文件和生成时间也可能增加。", - ), - ), - ), - ManualChapter( - "shortcuts_state", - "快捷键、撤销与启动恢复", - "使用键盘提高编辑效率,并明确哪些内容会自动恢复、哪些内容必须另行保存。", - ( - ManualSection( - "常用快捷键", - bullets=( - "Ctrl+O:导入阵面 JSON。", - "Ctrl+S:导出阵面 JSON。", - "Ctrl+Z:撤销阵列编辑。Ctrl+Y 或 Ctrl+Shift+Z:按当前操作系统标准重做阵列编辑。", - "Ctrl+R 或 Ctrl+G:重新计算并刷新全部视图。", - "Ctrl+F:聚焦频率输入框并选中现有内容。", - "Ctrl+1 / Ctrl+2 / Ctrl+3:切换物理与虚拟阵列、1D DBF、2D DBF。", - "方向键:移动当前选中的 TX/RX。", - "Delete:删除选中通道;无选择时进入删除模式。", - "Esc:退出删除模式、取消正在进行的拖动,或清除当前选择。", - ), - note="输入框获得焦点时,方向键和 Delete 保持文字编辑行为,不会误改阵列。", - ), - ManualSection( - "撤销和重做范围", - bullets=( - "可撤销:添加、删除、拖动、方向键移动、清空、自动排阵和导入阵面。", - "不可撤销:频率、竞争峰裕量、语言、DBF 显示、字典和通道幅相。", - "最多保留 50 步;执行新布局编辑后,原有重做分支会清空。", - ), - warning="通道幅相导入会立即生效且不进入撤销栈。导入前应确认目标和槽位,必要时保留源文件清单。", - ), - ManualSection( - "正常关闭后自动恢复", - bullets=( - "会恢复:语言、最近使用目录、频率、竞争峰裕量、DBF 显示方式、阵列坐标、窗口大小/位置、最大化状态、活动页签和分隔条比例。", - "DBF 字典模式及外部字典路径会尝试恢复;源文件不存在或无法读取时会退回安全模式。", - "不会恢复:通道幅相表格中的导入内容。下次启动需要重新导入。", - "自动恢复依赖正常关闭;异常终止时,最近一次会话修改可能尚未写入。", - ), - ), - ), - ), - ManualChapter( - "troubleshooting", - "常见问题与排错", - "从能力提示、输入恢复、文件导入、字典映射、报告生成和日志位置快速定位问题。", - ( - ManualSection( - "图表为空或控件被禁用", - bullets=( - "1T1R:没有方向孔径,1D 和 2D 显示能力提示是正常状态。", - "只有一条轴有展开:在 1D 页使用有效方向;2D 页会提示返回 1D。", - "希望启用某个方向:拖开该方向上的 TX/RX,或使用自动排阵后再微调。", - "布局已改变但图未更新:按 Ctrl+R 或 Ctrl+G;仍无变化时查看状态栏是否恢复了无效输入。", - ), - ), - ManualSection( - "结果异常或突然跳变", - steps=( - "确认顶部显示的字典模式和通道幅相状态。", - "切回理想几何字典,判断异常来自布局还是外部数据。", - "检查虚拟阵列是否有大量重复点,并查看竞争峰裕量和截断原因。", - "如果方向完全相反,检查反向相位模式和导入字典的相位反向选项。", - "用 1D 拖动定位具体角度,再到 2D 复查,不要同时修改多个配置。", - ), - note="每次只改一项并记录前后状态,能更快判断问题来源。", - ), - ManualSection( - "文件或报告失败", - bullets=( - "阵面 JSON:检查文件版本、单位、tx/rx 非空、数量不超过 16,以及坐标是否为数字。", - "通道幅相:检查角度列、数据列、物理/虚拟目标、列数和通道名称;关闭占用文件的表格软件后重试。", - "外部字典:检查至少有一个方向文件、通道目标与当前阵列一致、表头完整且数据可解析。", - "性能报告:检查至少一个方向可用、范围起止顺序正确、至少选择 dB 或模值,并确认输出目录可写。", - "报告取消后仍显示处理中:等待当前绘图步骤结束,程序会安全停止。", - ), - warning="错误弹窗中的具体文字和“帮助 > 关于”所示日志路径是排错依据。提交问题时请同时提供日志、阵面 JSON、所用外部文件名和复现步骤。", - ), - ), - ), - ) - - -def _en_chapters() -> tuple[ManualChapter, ...]: - return ( - ManualChapter( - "quick_start", - "Quick start", - "The shortest path from an empty layout to a repeatable check. Follow this chapter in order on your first run.", - ( - ManualSection( - "Before you begin", - paragraphs=( - "At startup, the app restores the last layout, frequency, display mode, active page, and window arrangement. Check the three header badges for frequency, DBF dictionary, and channel amplitude/phase before starting a new task.", - ), - bullets=( - "For a clean start, open Physical & Virtual and select Clear; the layout returns to the 1T1R starter state.", - "If an array file already exists, use File > Import Array JSON. This restores Tx/Rx coordinates only.", - "Otherwise enter the T and R counts in Auto Array and select Apply Array. Both counts accept 1 through 16.", - ), - note="The status bar reports the latest action. If a result appears unchanged, read the status bar first.", - ), - ManualSection( - "Run a basic check", - steps=( - "Add, drag, or auto-arrange Tx/Rx elements and verify the channel names and positions. Coordinates are shown in λ.", - "Enter the operating frequency and press Enter or leave the field, then set the competing-peak margin.", - "Inspect unique and duplicate points in the virtual array, then read channel count, aperture, and resolution in the overview.", - "Open 1D DBF. Drag each true-angle marker or select Play to confirm that the peak follows continuously in azimuth and elevation.", - "When both axes have usable aperture, open 2D DBF and drag the crosshair through the angles of interest.", - "Save coordinates with File > Export Array JSON. Export a performance report when results need to be reviewed or delivered.", - ), - ), - ManualSection( - "Expected result", - bullets=( - "A usable axis shows its spectrum, true angle, estimated peak, and angle metrics.", - "An axis without aperture shows a neutral capability message instead of a flat spectrum or misleading heatmap.", - "Duplicate virtual points, boundary limits, and insufficient peak margin are called out in the plots, overview, or status text.", - ), - warning="Do not conclude from one static frame. Drag or play through the required angle range and verify the active dictionary and channel-data state.", - ), - ), - ), - ManualChapter( - "workspace", - "Main window and workspaces", - "Learn what each area and page is for, and which information refreshes automatically after a layout change.", - ( - ManualSection( - "Window areas", - bullets=( - "Menu bar: import/export, undo/redo, channel data, DBF dictionary, language, and help.", - "Header: global frequency, DBF dictionary, and channel amplitude/phase status.", - "Pages: Physical & Virtual, 1D DBF, and 2D DBF. Use the mouse or Ctrl+1, Ctrl+2, and Ctrl+3.", - "Overview sidebar: array size, virtual-channel use, aperture, resolution, and angle evaluation.", - "Command bar: frequency, competing-peak margin, Auto Array, and DBF display scale.", - "Status bar: the latest import, edit, playback, input recovery, or report action.", - ), - ), - ManualSection( - "Choose the right page", - bullets=( - "Physical & Virtual: edit real Tx/Rx positions, inspect virtual points, and read overview metrics.", - "1D DBF: inspect azimuth or elevation independently; one usable axis remains available even when the other is not.", - "2D DBF: inspect azimuth and elevation together; it requires usable aperture on both axes.", - ), - note="If 2D reports limited capability but one 1D axis is usable, work in 1D. Do not alter a correct single-axis design merely to make a 2D plot appear.", - ), - ManualSection( - "Resize the workspace", - steps=( - "Drag the splitter between the main plots and overview to allocate more room to either side.", - "After resizing the window, allow the short debounced refresh to complete before reading the plots.", - "Hover truncated file names or status text to see the complete tooltip.", - ), - bullets=( - "The minimum window size is 1100×650. On a small display, narrow the overview sidebar first.", - "Window geometry and splitter sizes are saved at normal close and restored inside the current screen work area.", - ), - ), - ), - ), - ManualChapter( - "layout_editing", - "Edit the Tx/Rx layout", - "Add, select, drag, nudge, delete, and auto-arrange channels. Coordinates are displayed in λ and dependent views update after each edit.", - ( - ManualSection( - "Add channels or create an array", - steps=( - "Select +TX or +RX. The new channel is placed on an unused grid position to the right and becomes selected.", - "To replace the complete layout, enter T and R counts in Auto Array.", - "Select Apply Array or press Enter in a count field. The layout is replaced and all views refresh.", - ), - bullets=( - "Tx accepts 1–16 channels and Rx accepts 1–16 channels.", - "Add, auto-array, clear, import, drag, and keyboard moves are undoable.", - "Clear returns to a usable 1T1R starter layout; it does not create a zero-channel array.", - ), - warning="Apply Array and Clear replace existing coordinates. Export Array JSON first if the current positions must be retained.", - ), - ManualSection( - "Select, drag, and nudge", - steps=( - "Click a Tx or Rx in the physical plot to select it.", - "Drag with the left mouse button. The plot can expand near an edge. On release, the point snaps to the displayed 0.5λ grid and all results recalculate.", - "With a channel selected, use the arrow keys to move 0.5λ at a time. Arrow keys still edit text when an input field has focus.", - "Press Esc during a drag to restore the pre-drag position. Otherwise Esc clears the selection or exits Delete mode.", - ), - note="Channel numbers are aligned again after a move or deletion. Import channel-named external data only after the final layout and numbering are settled.", - ), - ManualSection( - "Delete and edit history", - steps=( - "Select a channel and press Delete to remove it.", - "With nothing selected, select Delete or press Delete to enter persistent Delete mode, then click multiple channels.", - "Select Delete again or press Esc to leave Delete mode.", - "Use Edit > Undo Layout Edit and Redo Layout Edit to move through recent layout changes.", - ), - bullets=( - "At least one Tx and one Rx must remain, so the last channel of either type cannot be deleted.", - "History keeps up to 50 steps and covers layout edits only, not frequency, dictionary, or channel amplitude/phase changes.", - ), - ), - ), - ), - ManualChapter( - "virtual_overview", - "Virtual array and overview", - "Confirm that Tx/Rx combinations form the expected virtual points, find duplicates, and see which axes have usable capability.", - ( - ManualSection( - "Inspect virtual points", - steps=( - "After editing the physical array, inspect the virtual-array plot. Each point represents a Tx/Rx pair.", - "Hover a virtual point to read its channel pair and coordinates.", - "Compare unique virtual points with total virtual channels. A difference indicates overlapping points.", - ), - bullets=( - "Physical and virtual coordinates are displayed in λ; the overview also converts aperture to mm.", - "Duplicate points are not silently discarded. Utilization and duplicate notices include them.", - ), - ), - ManualSection( - "Read array metrics", - bullets=( - "Channels: current T×R size.", - "Virtual: unique points / all combinations and the resulting utilization.", - "Az/El aperture: effective spread on each axis, converted to mm at the operating frequency.", - "Az/El resolution: useful for comparing layouts; unavailable means no usable spread on that axis.", - "Capability: one usable axis keeps its 1D result; both axes are required for 2D.", - ), - note="Changing frequency changes the mm conversion but not positions displayed in λ. Use the same frequency when comparing layouts.", - ), - ManualSection( - "Read angle evaluation", - bullets=( - "No-fold range: the continuous true-angle interval available with the current settings.", - "Range error: check the maximum error against the task requirement.", - "Peak margin: use it with the command-bar criterion to judge whether the peak is clear enough.", - "Cut reason: explains why a side stops, such as a data edge, array boundary, or unreliable spectrum.", - ), - warning="Overview results depend on layout, frequency, dictionary, and channel data together. Recheck them after any of those changes.", - ), - ), - ), - ManualChapter( - "global_controls", - "Global controls and display", - "The command bar controls physical-size conversion, reliability criteria, automatic layout, and plot scaling.", - ( - ManualSection( - "Frequency", - steps=( - "Enter a positive value. A plain number, GHz suffix, or G suffix is accepted.", - "Press Enter or leave the field to apply it.", - "Check the header badge and aperture in mm to confirm the new frequency is active.", - ), - note="Blank, nonnumeric, zero, or negative input restores the most recent valid frequency and reports the recovery in the status bar.", - ), - ManualSection( - "Competing-peak margin", - steps=( - "Enter a dB value of 0 or greater.", - "Press Enter or leave the field, then inspect peak margin and cut reasons in angle evaluation.", - ), - paragraphs=( - "This is an operational acceptance criterion. A stricter value may reduce the usable interval; a looser value requires more careful inspection of competing peaks.", - ), - warning="Do not lower the margin only to enlarge the usable range. Use the project requirement or an agreed team value.", - ), - ManualSection( - "Auto Array and DBF display", - bullets=( - "Auto Array: enter T/R counts from 1 to 16 and apply a starter layout that can still be dragged and refined. The default arrangement is horizontal and normally creates azimuth aperture first; spread channels along y to enable elevation or 2D DBF.", - "dB: best for low-level regions, sidelobes, and competing peaks.", - "Magnitude: best for a quick view of the main-peak shape and heatmap boundaries.", - "Switching dB/magnitude changes display scaling only; layout, dictionary, and true angle remain unchanged.", - ), - ), - ), - ), - ManualChapter( - "dbf_1d", - "1D DBF: azimuth and elevation", - "Inspect each axis independently and use drag, play, pause, and stop to verify continuous peak tracking through the required range.", - ( - ManualSection( - "Start an inspection", - steps=( - "Open 1D DBF. Azimuth is on the left and elevation is on the right.", - "Confirm that the true-angle line, estimated-peak marker, frame, and angle text are visible.", - "Hover the spectrum to read its angle and displayed value.", - "Move near the true-angle line, hold the left mouse button, and drag to a new angle.", - ), - bullets=( - "An axis without aperture shows a capability message and disables playback; the other axis remains usable when valid.", - "Dragging pauses the scan and immediately updates that axis and its metrics.", - ), - ), - ManualSection( - "Play, pause, and stop", - steps=( - "Select Play to scan the true angle from -90° to +90°.", - "Select the same button while running to pause at the displayed angle.", - "Select it again to resume. Select Stop to end the current axis scan.", - "When switching to another axis, follow the button and status-bar state to confirm which scan is active.", - ), - note="Use playback to find jumps or competitors, then drag through the suspicious interval for a closer check.", - ), - ManualSection( - "Judge the result", - bullets=( - "The estimated peak should follow the true angle without jumping far away in the required interval.", - "Read peak-to-true-angle error together with peak margin and the cut reason.", - "Use dB to inspect near-main competing peaks, then magnitude to confirm the main-peak outline.", - ), - warning="If the curve tracks in the opposite direction, first check Ideal Reversed Phase and the imported-dictionary phase-reverse option. Do not immediately rewrite array coordinates.", - ), - ), - ), - ManualChapter( - "dbf_2d", - "2D DBF heatmap", - "When both axes are usable, inspect them together with independent playback and a draggable true-angle crosshair.", - ( - ManualSection( - "Availability and markers", - bullets=( - "The heatmap is available only when azimuth and elevation both have usable aperture.", - "The white crosshair is the current true azimuth/elevation; the peak marker is the current estimate.", - "The color bar follows the dB/magnitude selection and the lightweight badge reports current angle or peak information.", - ), - note="If a capability message appears, add spread on the missing axis. If the design is intentionally single-axis, use 1D DBF instead.", - ), - ManualSection( - "Play and drag", - steps=( - "Select Play Az to change true azimuth only, or Play El to change true elevation only.", - "Both can run together. Selecting one active button pauses only that axis.", - "Select Stop to end both scans.", - "Move near the crosshair and drag with the left mouse button to set both true angles. Dragging stops automatic playback.", - "Hover the heatmap to read azimuth, elevation, and the displayed value.", - ), - ), - ManualSection( - "Recommended 2D review", - bullets=( - "Play azimuth and elevation separately before running both together.", - "Drag to the center, edges, and corners of the required region and record whether the peak remains near the true angle.", - "If several bright regions compete, switch to dB and return to 1D to isolate the affected axis.", - ), - warning="The heatmap locates issues but does not replace range statistics in the performance report.", - ), - ), - ), - ManualChapter( - "dbf_dictionary", - "Configure the DBF dictionary", - "Choose one of four dictionary modes, preview either axis, and explicitly map imported data to physical or virtual channels.", - ( - ManualSection( - "Four modes", - bullets=( - "Ideal geometric: default for checking layout and basic interaction.", - "Ideal reversed phase: a quick check of external-data or system direction conventions.", - "Channel amp/phase dictionary: uses the currently loaded channel data; missing channels remain ideal.", - "Imported CSV/XLSX: uses external simulation, calibration, or measured tables, loaded separately for azimuth and elevation.", - ), - note="Selecting a radio option changes the preview only. Select Apply Dictionary before the main window uses it; closing the dialog does not apply an unconfirmed mode.", - ), - ManualSection( - "Import an external dictionary", - steps=( - "Choose Physical channels for Tx1, Tx2, Rx1… or Virtual channels for Tx1Rx1, Tx1Rx2… ordering.", - "Select Load Az Dictionary or Load El Dictionary and choose CSV, TSV, XLSX, or XLSM.", - "Switch the Az/El preview and verify angle rows, channel columns, file name, and target type.", - "If required, enable imported phase reversal or 0° phase calibration and inspect the preview again.", - "Load at least one axis, choose Imported CSV/XLSX, and select Apply Dictionary.", - ), - bullets=( - "The table needs a header, angle information, and channel columns. Matching channel names are preferred.", - "Plain real values are read as phase angles; complex-form values are read as complex responses.", - "One axis may be loaded alone; the unloaded axis continues with default data.", - ), - warning="Finalize channel count and numbering before import. Later T/R changes can make external column counts or names incompatible.", - ), - ManualSection( - "Preview and quality callout", - bullets=( - "The preview lists phase by angle and channel; use horizontal scrolling for wide tables.", - "The quality callout summarizes valid rows, competing peaks, zero rows, and effective rank checks.", - "Amber and red callouts request review but do not block Apply.", - "Load errors show a specific reason. Correct the source and reload without restarting the app.", - ), - note="The callout checks the imported table; it is not a project acceptance result. Recheck required angles in 1D and 2D after applying.", - ), - ), - ), - ManualChapter( - "channel_patterns", - "Configure channel amplitude/phase", - "Load horizontal/elevation amplitude and phase data for physical or virtual channels, using summary files or one channel at a time.", - ( - ManualSection( - "Targets and data slots", - bullets=( - "Physical target: Tx1… and Rx1… rows for real transmit/receive channels.", - "Virtual target: Tx1Rx1, Tx1Rx2… rows for combined channels.", - "Each target has four independent slots: amplitude-horizontal, amplitude-elevation, phase-horizontal, and phase-elevation.", - "Unloaded slots remain ideal; a complete four-slot import for every channel is not required.", - ), - note="Changing the target changes the current table and import mapping; it does not clear data already loaded for the other target.", - ), - ManualSection( - "Import a summary file", - steps=( - "Choose Physical or Virtual as the target.", - "Select the relevant Load Summary button for amplitude/phase and horizontal/elevation.", - "Choose a CSV, TSV, XLSX, or XLSM file containing an angle column and multiple data columns.", - "After import, verify the file/column shown in each row and the header channel-data badge.", - ), - bullets=( - "Physical mapping follows current Tx/Rx rules and recognizable column names.", - "Virtual mapping follows Tx1Rx1, Tx1Rx2, through the final pair; explicit channel headers take priority.", - "Common angle headers such as Theta, Angle, Azimuth, Az, and Deg are recognized.", - ), - warning="A summary with incompatible columns is rejected. Correct the target selection or source headers instead of padding the file with empty columns.", - ), - ManualSection( - "Edit one channel, clear, and apply", - steps=( - "Select a row in the channel table.", - "Select the required Set button and load a file. A single-channel import uses the first data column after the angle column.", - "Use Clear Selected Channel to reset one row, or Clear All to return every channel to ideal.", - "Return to the main window and inspect 1D/2D results and the header badge.", - ), - bullets=( - "Every import or clear recalculates immediately. Done only closes the dialog and does not roll changes back.", - "Channel amplitude/phase is not written to state.json or Array JSON. Reimport it after restarting the app.", - "To use the Channel Amp/Phase dictionary, finish these imports first, then apply that mode in the dictionary dialog.", - ), - ), - ), - ), - ManualChapter( - "files_reports", - "Array files and performance reports", - "Separate editable coordinate files, current session settings, and PDF/PNG/CSV/JSON deliverables.", - ( - ManualSection( - "Import and export Array JSON", - steps=( - "Use File > Export Array JSON and choose a location; the outputs folder is the default suggestion.", - "Use File > Import Array JSON when the coordinates need to be restored.", - "After import, verify the first Tx/Rx, coordinate range, and channel count reported by the status bar and plot.", - ), - bullets=( - "The file stores Tx/Rx coordinates and includes an evaluation snapshot for review.", - "Import restores Tx/Rx coordinates only. The evaluation snapshot does not restore frequency, DBF dictionary, or channel amplitude/phase.", - "Tx and Rx must both be nonempty, each limited to 16, with a supported version and λ unit.", - ), - warning="Array JSON is not a complete project package. Keep source dictionary/channel files and parameter notes to reproduce calibrated results.", - ), - ManualSection( - "Export a performance report", - steps=( - "Choose File > Export Reports to open the Export Reports settings dialog directly. It is unavailable when neither axis has angle capability.", - "Choose the PDF path and title. Existing files require overwrite confirmation.", - "Set the performance-focus true-angle range for each usable axis; start must not exceed stop.", - "Set the spectrum Hold range or make it follow the focus range, then choose a Hold-curve interval for each axis. At 1 deg per frame, the dialog reports both in-range frames and plotted curves and always retains both endpoints.", - "Set the angle-error threshold and dB display floor, and select at least one spectrum scale: dB or magnitude.", - "Optionally export reproducibility data (CSV/JSON), then select Export Report.", - "Selecting Export Report or Export Angle-error PNG Only keeps the settings dialog open. After an export finishes, reuse the current settings to export the other format; only Cancel or closing the window exits the dialog.", - ), - ), - ManualSection( - "Export a standalone angle-error PNG", - bullets=( - "In the Export Reports settings dialog, confirm the report output directory and angle-error limit, then select Export Angle-error PNG Only.", - "The PNG inherits that report output directory and angle-error limit; it does not require a separate save location or generate a PDF at the same time.", - "The horizontal range is capped at -90°..+90° and contracts to the largest common coverage when channel data or a custom DBF dictionary is narrower.", - "The symmetric Y-axis limit uses the larger of the absolute error peak inside the detected no-fold range and the configured angle-error limit, multiplies it by 1.5, and rounds upward to a whole degree. Folded errors outside the no-fold range do not set the scale.", - "The standalone PNG draws every angle-error sample as one ordinary blue curve. Folded samples outside the no-fold range do not set the Y-axis scale; portions beyond the resulting limits are clipped naturally by the axes.", - "The standalone PNG shows no focus/no-fold background bands, does not use red x markers to distinguish unreliable frames, and omits the scale explanation. The PDF report retains those diagnostic details, and both outputs continue to use the plot-kit visual contract.", - ), - ), - ManualSection( - "Generation and output", - bullets=( - "Generation runs in the background and reports its stage in a progress dialog.", - "Cancel waits for the current rendering step to finish safely before stopping.", - "The PDF contains a configuration summary, focus-range statistics, and selected spectrum pages; each spectrum type uses its own page.", - "The Hold interval only reduces overlay density; Max-Hold, performance metrics, and reproducibility data still use every in-range 1 deg frame.", - "When raw data is selected, a neighboring directory contains full-frame CSV files and a report-manifest JSON recording the plotted angles.", - ), - note="Page count depends on usable axes and selected vertical scales. A wider Hold range or smaller curve interval creates a denser overlay and may increase file size and rendering time.", - ), - ), - ), - ManualChapter( - "shortcuts_state", - "Shortcuts, undo, and session restore", - "Work faster with the keyboard and know what is restored automatically versus what must be saved separately.", - ( - ManualSection( - "Keyboard shortcuts", - bullets=( - "Ctrl+O: import Array JSON.", - "Ctrl+S: export Array JSON.", - "Ctrl+Z / Ctrl+Y: undo / redo layout edits; the exact redo sequence follows the operating-system standard.", - "Ctrl+R or Ctrl+G: recalculate and refresh all views.", - "Ctrl+F: focus the frequency field and select its contents.", - "Ctrl+1 / Ctrl+2 / Ctrl+3: switch Physical & Virtual, 1D DBF, and 2D DBF.", - "Arrow keys: move the selected Tx/Rx.", - "Delete: remove the selected channel, or enter Delete mode when nothing is selected.", - "Esc: leave Delete mode, cancel an active drag, or clear selection.", - ), - note="When a text field has focus, arrow and Delete keys retain their text-edit behavior and do not change the layout.", - ), - ManualSection( - "Undo and redo scope", - bullets=( - "Undoable: add, delete, drag, arrow-key move, clear, auto-array, and Array JSON import.", - "Not undoable: frequency, peak margin, language, DBF display, dictionary, and channel amplitude/phase.", - "Up to 50 steps are retained. A new layout edit clears the old redo branch.", - ), - warning="Channel-data imports apply immediately and do not enter history. Verify target and slot, and keep a source-file list when needed.", - ), - ManualSection( - "Restored after a normal close", - bullets=( - "Restored: language, recent folders, frequency, peak margin, DBF display, layout, window geometry/state, active page, and splitter sizes.", - "The dictionary mode and external dictionary paths are restored when possible; missing or unreadable sources fall back safely.", - "Not restored: channel amplitude/phase table imports. Reimport them after restart.", - "Automatic state saving occurs during normal close; the latest changes may be missing after an abnormal termination.", - ), - ), - ), - ), - ManualChapter( - "troubleshooting", - "Troubleshooting", - "Resolve capability messages, recovered inputs, import mapping errors, report failures, and locate useful diagnostics.", - ( - ManualSection( - "Blank plot or disabled controls", - bullets=( - "1T1R has no directional aperture, so neutral 1D/2D capability messages are expected.", - "With spread on one axis only, use the available 1D side; 2D directs you back to 1D.", - "To enable an axis, spread Tx/Rx along it or apply Auto Array and refine the positions.", - "If a layout changed but a view did not, press Ctrl+R or Ctrl+G and check whether the status bar restored invalid input.", - ), - ), - ManualSection( - "Unexpected peaks or jumps", - steps=( - "Confirm the dictionary and channel-data badges in the header.", - "Return to Ideal Geometric to separate a layout issue from an external-data issue.", - "Check virtual duplicates, peak margin, and cut reasons.", - "For completely reversed tracking, check reversed-phase modes and imported-dictionary phase reversal.", - "Use 1D dragging to isolate an angle, then verify it in 2D. Change only one setting at a time.", - ), - note="Recording the before/after state for one change at a time makes the source much easier to identify.", - ), - ManualSection( - "File or report failure", - bullets=( - "Array JSON: check version, unit, nonempty tx/rx lists, maximum 16 per type, and numeric coordinates.", - "Channel data: check the angle column, data columns, target, channel count/names, and close spreadsheet software that may hold the file.", - "External dictionary: load at least one axis, match the channel target to the current layout, and verify headers and parseable data.", - "Performance report: require a usable axis, ordered ranges, at least one dB/magnitude scale, and a writable output directory.", - "If cancellation still says busy, wait for the current rendering step to finish safely.", - ), - warning="Use the exact error message and the log path shown by Help > About. Include the log, Array JSON, source-file names, and reproduction steps in a support request.", - ), - ), - ), - ) - - -def _ja_chapters() -> tuple[ManualChapter, ...]: - return ( - ManualChapter( - "quick_start", - "クイックスタート", - "空の配置から再現可能な確認を完了するまでの最短手順です。初回は上から順に操作してください。", - ( - ManualSection( - "開始前の確認", - paragraphs=( - "起動時には前回終了時の配置、周波数、表示方式、選択ページ、ウィンドウ配置が復元されます。ヘッダーの周波数、DBF 辞書、チャネル振幅/位相の状態を確認してください。", - ), - bullets=( - "最初から作る場合は「物理・仮想アレイ」で「クリア」を選び、1T1R の初期配置に戻します。", - "配置ファイルがある場合は「ファイル > アレイJSONを読み込み」を使用します。読み込まれるのは TX/RX 座標だけです。", - "新規作成では下部の自動配置に T/R 数を入力し、「アレイを適用」を選びます。どちらも 1~16 です。", - ), - note="ステータスバーには直前の操作結果が表示されます。変化が見えない場合は、まずここを確認してください。", - ), - ManualSection( - "基本確認の実行", - steps=( - "TX/RX を追加、ドラッグ、または自動配置し、名称と位置を確認します。座標表示は λ です。", - "動作周波数を入力して Enter を押すかフォーカスを外し、続けて競合ピーク余裕を設定します。", - "仮想アレイの一意点と重複点を確認し、概要のチャネル数、開口、分解能を読みます。", - "「1D DBF」で真角度線をドラッグするか再生し、方位と仰角のピーク追従を確認します。", - "両軸に有効な開口がある場合は「2D DBF」で十字線を関心角度へドラッグします。", - "「ファイル > アレイJSONを書き出し」で座標を保存し、必要なら性能レポートを出力します。", - ), - ), - ManualSection( - "期待される表示", - bullets=( - "有効な軸には角度スペクトル、真角度、推定ピーク、測角指標が表示されます。", - "開口のない軸には、平坦な曲線や誤解を招くヒートマップではなく能力メッセージが表示されます。", - "仮想点の重複、境界制限、ピーク余裕不足はプロット、概要、または状態表示に示されます。", - ), - warning="1 枚の静止画だけで判断しないでください。対象角度をドラッグまたは再生し、使用中の辞書とチャネルデータ状態も確認します。", - ), - ), - ), - ManualChapter( - "workspace", - "メインウィンドウと3つの作業ページ", - "各領域とページの用途、および配置変更後に自動更新される情報を説明します。", - ( - ManualSection( - "ウィンドウの構成", - bullets=( - "メニュー:読み込み/書き出し、元に戻す/やり直し、チャネルデータ、DBF 辞書、言語、ヘルプ。", - "ヘッダー:周波数、DBF 辞書、チャネル振幅/位相のグローバル状態。", - "ページ:物理・仮想アレイ、1D DBF、2D DBF。Ctrl+1、Ctrl+2、Ctrl+3 でも切り替えられます。", - "右側概要:アレイ規模、仮想チャネル利用率、開口、分解能、測角評価。", - "下部コマンド:周波数、競合ピーク余裕、自動配置、DBF 表示方式。", - "ステータスバー:直前の読み込み、編集、再生、入力復元、レポート処理。", - ), - ), - ManualSection( - "ページの選択", - bullets=( - "物理・仮想アレイ:実際の TX/RX 位置を編集し、仮想点と概要を確認します。", - "1D DBF:方位または仰角を個別に確認します。一方だけ有効でも使用できます。", - "2D DBF:方位と仰角を同時に確認します。両軸に有効な開口が必要です。", - ), - note="2D が能力不足でも 1D の一方が有効なら、1D を使用してください。2D 表示のためだけに正しい単軸設計を変更する必要はありません。", - ), - ManualSection( - "表示領域の調整", - steps=( - "主プロットと右側概要の間のスプリッターをドラッグして幅を調整します。", - "ウィンドウ変更後は短い遅延更新が終わってからプロットを読みます。", - "省略されたファイル名や状態文字列は、ホバーして完全な tooltip を確認します。", - ), - bullets=( - "最小サイズは 1100×650 です。小さい画面では概要側を先に狭くします。", - "正常終了時にウィンドウ位置と分割比が保存され、次回は現在の画面内に復元されます。", - ), - ), - ), - ), - ManualChapter( - "layout_editing", - "TX/RX 配置の編集", - "チャネルの追加、選択、ドラッグ、キー移動、削除、自動配置を行います。座標は λ 表示で、変更後に関連表示が更新されます。", - ( - ManualSection( - "追加と自動配置", - steps=( - "「+TX」または「+RX」を選びます。新しいチャネルは同種チャネルの右側の空きグリッドに追加され、選択状態になります。", - "配置全体を作り直す場合は、自動配置に T/R 数を入力します。", - "「アレイを適用」を選ぶか、数値欄で Enter を押します。現在配置が置換され、全表示が更新されます。", - ), - bullets=( - "TX と RX はそれぞれ 1~16 チャネルです。", - "追加、自動配置、クリア、読み込み、ドラッグ、キー移動は元に戻せます。", - "「クリア」はゼロチャネルではなく、1T1R の初期配置へ戻します。", - ), - warning="「アレイを適用」と「クリア」は現在座標を置換します。残す場合は先にアレイ JSON を書き出してください。", - ), - ManualSection( - "選択、ドラッグ、微調整", - steps=( - "物理アレイ上の TX または RX をクリックして選択します。", - "左ボタンでドラッグします。端に近づくと描画範囲が広がり、離すと 0.5λ 表示グリッドに合わせて再計算されます。", - "選択後に矢印キーで 1 回につき 0.5λ 移動します。入力欄にフォーカスがある場合は文字編集が優先されます。", - "ドラッグ中に Esc を押すと開始前へ戻ります。それ以外では選択解除または削除モード終了になります。", - ), - note="移動や削除後に同種チャネル番号が整列されます。Tx1、Rx1 などの名称を使う外部データは、配置確定後に読み込んでください。", - ), - ManualSection( - "削除と履歴", - steps=( - "チャネルを選択して Delete を押すと削除できます。", - "未選択時に「削除」または Delete を使うと連続削除モードになり、複数チャネルをクリックして削除できます。", - "もう一度「削除」を選ぶか Esc で終了します。", - "「編集 > 配置編集を元に戻す/やり直す」で最近の配置を復元します。", - ), - bullets=( - "最後の TX または RX は削除できず、各種 1 チャネル以上を維持します。", - "履歴は最大 50 ステップで、配置編集だけが対象です。周波数、辞書、チャネルデータは対象外です。", - ), - ), - ), - ), - ManualChapter( - "virtual_overview", - "仮想アレイと概要", - "TX/RX の組み合わせ、仮想点の重複、各軸の利用可能性を素早く確認します。", - ( - ManualSection( - "仮想点の確認", - steps=( - "物理配置を編集した後、仮想アレイを確認します。各点は 1 組の TX/RX に対応します。", - "仮想点へカーソルを合わせ、チャネル組み合わせと座標を読みます。", - "一意仮想点数と全仮想チャネル数を比較します。差があれば重複点があります。", - ), - bullets=( - "物理/仮想座標は λ、概要の開口は mm でも表示されます。", - "重複点は無視されず、利用率と重複表示に反映されます。", - ), - ), - ManualSection( - "アレイ概要の読み方", - bullets=( - "チャネル数:現在の T×R。", - "仮想チャネル:一意点/全組み合わせ、および利用率。", - "方位/仰角開口:各軸の展開を現在周波数で mm 換算した値。", - "方位/仰角分解能:配置比較に使用します。利用不可はその軸に有効な展開がない状態です。", - "能力表示:一方だけ有効なら 1D、両方有効なら 2D が利用できます。", - ), - note="周波数変更で mm 換算は変わりますが、λ 表示の位置は変わりません。比較時は周波数を揃えてください。", - ), - ManualSection( - "測角評価の読み方", - bullets=( - "折り返しなし範囲:現在設定で連続利用できる真角度区間。", - "範囲内誤差:最大誤差がタスク要件を満たすか確認します。", - "ピーク余裕:下部の判定値と合わせ、ピークが十分明確か確認します。", - "終了理由:データ端、アレイ境界、角度スペクトル信頼性など、範囲が止まった理由です。", - ), - warning="概要は配置、周波数、辞書、チャネルデータの組み合わせ結果です。いずれかを変更した後は再確認してください。", - ), - ), - ), - ManualChapter( - "global_controls", - "共通設定と表示", - "下部コマンドは寸法換算、信頼性判定、自動配置、グラフ表示に影響します。", - ( - ManualSection( - "周波数", - steps=( - "正の数を入力します。数値だけ、GHz、または G の接尾辞を使用できます。", - "Enter を押すかフォーカスを外して適用します。", - "ヘッダーの周波数と概要の mm 開口を確認します。", - ), - note="空欄、数値以外、ゼロ、負数では直前の有効値に戻り、ステータスバーに表示されます。", - ), - ManualSection( - "競合ピーク余裕", - steps=( - "0 以上の dB 値を入力します。", - "Enter またはフォーカス移動で適用し、測角評価の余裕と終了理由を確認します。", - ), - paragraphs=( - "これは運用上の判定値です。厳しくすると利用範囲が狭くなる場合があり、緩くすると競合ピークの目視確認がより重要になります。", - ), - warning="範囲を広げるためだけに値を下げず、プロジェクト要件またはチーム合意値を使用してください。", - ), - ManualSection( - "自動配置と DBF 表示", - bullets=( - "自動配置:1~16 の T/R 数を入力し、後からドラッグ調整できる初期配置を作ります。既定は水平配置で通常は方位開口を先に作るため、仰角または 2D DBF には一部チャネルを y 方向へ広げます。", - "dB:低レベル領域、サイドローブ、競合ピークの確認向け。", - "振幅:主ピーク形状とヒートマップ境界の簡易確認向け。", - "表示切り替えは目盛だけを変更し、配置、辞書、真角度は変更しません。", - ), - ), - ), - ), - ManualChapter( - "dbf_1d", - "1D DBF:方位と仰角", - "方位と仰角を個別に確認し、ドラッグ、再生、一時停止、停止で対象範囲のピーク追従を調べます。", - ( - ManualSection( - "確認の開始", - steps=( - "「1D DBF」を開きます。左が方位、右が仰角です。", - "真角度線、推定ピーク、フレーム、角度表示を確認します。", - "曲線へカーソルを合わせ、角度と表示値を読みます。", - "真角度線付近で左ボタンを押し、目的角度へドラッグします。", - ), - bullets=( - "開口のない軸は能力メッセージと再生無効状態になり、もう一方が有効ならそのまま使用できます。", - "真角度のドラッグで再生は一時停止し、曲線と指標がすぐ更新されます。", - ), - ), - ManualSection( - "再生、一時停止、停止", - steps=( - "「再生」を選ぶと真角度が -90° から +90° まで移動します。", - "再生中に同じボタンを選ぶと現在角度で一時停止します。", - "もう一度選ぶと再開し、「停止」で現在軸の走査を終了します。", - "別軸へ移る場合はボタンとステータスバーで有効な走査を確認します。", - ), - note="まず再生でジャンプや競合を探し、異常区間をドラッグで詳しく確認してください。", - ), - ManualSection( - "結果の判断", - bullets=( - "対象範囲では推定ピークが真角度を追従し、遠い位置へ突然移動しないことを確認します。", - "誤差だけでなく、ピーク余裕と終了理由も一緒に確認します。", - "dB で競合ピーク、振幅で主ピーク形状を確認します。", - ), - warning="追従方向が逆の場合は、まず逆位相辞書と読み込み辞書の位相反転設定を確認し、すぐに座標を変更しないでください。", - ), - ), - ), - ManualChapter( - "dbf_2d", - "2D DBF ヒートマップ", - "両軸が有効な場合に、独立再生とドラッグ可能な十字線で方位と仰角を同時確認します。", - ( - ManualSection( - "利用条件と表示", - bullets=( - "方位と仰角の両方に有効な開口がある場合のみ利用できます。", - "白い十字線が現在の真方位/真仰角、ピーク記号が推定位置です。", - "カラーバーは dB/振幅に連動し、上部バッジに現在角度またはピーク情報が表示されます。", - ), - note="能力メッセージが出た場合は不足軸の配置を広げます。単軸設計なら 1D DBF を使用してください。", - ), - ManualSection( - "再生とドラッグ", - steps=( - "「方位再生」は方位だけ、「仰角再生」は仰角だけを動かします。", - "両方を同時に再生できます。再度選んだ軸だけが一時停止します。", - "「停止」は両軸の再生を終了します。", - "十字線付近を左ドラッグすると両方の真角度を設定でき、自動再生は停止します。", - "ヒートマップへカーソルを合わせ、方位、仰角、表示値を読みます。", - ), - ), - ManualSection( - "確認手順", - bullets=( - "最初に方位と仰角を別々に再生し、その後に同時再生します。", - "対象領域の中心、端、四隅へ十字線を動かし、ピークが真角度付近にあるか記録します。", - "近い明領域が複数ある場合は dB 表示へ切り替え、1D で問題軸を特定します。", - ), - warning="ヒートマップは問題位置の確認用です。範囲統計が必要な場合は性能レポートを使用してください。", - ), - ), - ), - ManualChapter( - "dbf_dictionary", - "DBF 辞書の設定", - "4 種類の辞書を選び、方位/仰角をプレビューし、外部データを物理または仮想チャネルへ明示的に割り当てます。", - ( - ManualSection( - "4つのモード", - bullets=( - "理想幾何辞書:配置と基本動作を確認する既定モード。", - "理想逆位相辞書:外部データやシステムの方向規約を確認するモード。", - "チャネル振幅/位相辞書:現在読み込まれているチャネルデータを使用し、未設定チャネルは理想状態。", - "CSV/XLSX 辞書:外部シミュレーション、校正、実測テーブルを方位/仰角別に読み込みます。", - ), - note="ラジオボタンの選択はプレビューだけを更新します。「辞書を適用」を選ぶまでメイン画面には反映されません。", - ), - ManualSection( - "外部辞書の読み込み", - steps=( - "Tx1、Tx2、Rx1…なら「物理チャネル」、Tx1Rx1、Tx1Rx2…なら「仮想チャネル」を選びます。", - "「方位辞書読込」または「仰角辞書読込」で CSV、TSV、XLSX、XLSM を選びます。", - "方位/仰角プレビューを切り替え、角度行数、チャネル列数、ファイル名、対象を確認します。", - "必要なら位相反転または 0° 位相校正を有効にし、再度プレビューします。", - "少なくとも一方を読み込み、CSV/XLSX 辞書を選んで「辞書を適用」を押します。", - ), - bullets=( - "表にはヘッダー、角度情報、チャネル列が必要で、現在チャネルと一致する列名を推奨します。", - "通常の実数値は位相角、複数形式の値は複素応答として読み込まれます。", - "一方の軸だけでも読み込み可能で、未読み込み軸は既定データを使用します。", - ), - warning="読み込み前にチャネル数と番号を確定してください。後の T/R 変更で列数や列名が一致しなくなる場合があります。", - ), - ManualSection( - "プレビューと品質表示", - bullets=( - "プレビューには角度ごとの各チャネル位相が表示され、列が多い場合は横スクロールできます。", - "品質表示には有効行、競合ピーク、ゼロ行、有効ランクなどの確認結果が示されます。", - "黄/赤の表示は確認を促しますが、適用操作自体は止めません。", - "読み込みエラーには理由が表示されます。元ファイルを修正して再読み込みできます。", - ), - note="品質表示は読み込み確認であり、プロジェクト合否ではありません。適用後に 1D/2D で対象角度を確認してください。", - ), - ), - ), - ManualChapter( - "channel_patterns", - "チャネル振幅/位相の設定", - "物理または仮想チャネルに水平/仰角の振幅と位相を、集約ファイルまたは単一チャネル単位で読み込みます。", - ( - ManualSection( - "対象とデータ枠", - bullets=( - "物理対象:実 TX/RX の Tx1…、Rx1…を表示します。", - "仮想対象:組み合わせチャネルの Tx1Rx1、Tx1Rx2…を表示します。", - "各対象には振幅-水平、振幅-仰角、位相-水平、位相-仰角の 4 枠があります。", - "未読み込み枠は理想状態で、すべてを埋める必要はありません。", - ), - note="対象切り替えは表示と読み込み割り当てだけを変更し、もう一方へ読み込んだデータは消去しません。", - ), - ManualSection( - "集約ファイルの読み込み", - steps=( - "物理または仮想対象を選びます。", - "振幅/位相と水平/仰角に対応する「集約読込」を選びます。", - "角度列と複数データ列を含む CSV、TSV、XLSX、XLSM を選びます。", - "読み込み後、各行のファイル/列名とヘッダー状態を確認します。", - ), - bullets=( - "物理対象は現在の Tx/Rx 規則と認識可能な列名で割り当てます。", - "仮想対象は Tx1Rx1、Tx1Rx2 から最後の組み合わせ順で、明示列名を優先します。", - "Theta、Angle、Azimuth、Az、Deg などの角度列名を認識します。", - ), - warning="列が対象と一致しない集約ファイルは拒否されます。空列を追加せず、対象選択または表ヘッダーを修正してください。", - ), - ManualSection( - "単一チャネル、消去、反映", - steps=( - "表でチャネルを選択します。", - "必要な「設定」ボタンからファイルを読み込みます。単一チャネルでは角度列の後の最初のデータ列を使用します。", - "1 チャネルだけ戻す場合は「選択チャネルをクリア」、全体は「すべてクリア」を使用します。", - "メイン画面へ戻り、1D/2D とヘッダー状態を確認します。", - ), - bullets=( - "読み込み/消去のたびに即時再計算されます。「完了」は閉じるだけで、変更を戻しません。", - "チャネル振幅/位相は state.json やアレイ JSON に保存されず、再起動後は再読み込みが必要です。", - "チャネル振幅/位相辞書を使う場合は、本章の設定後に辞書画面でそのモードを適用します。", - ), - ), - ), - ), - ManualChapter( - "files_reports", - "アレイファイルと性能レポート", - "再編集用座標ファイル、現在セッション設定、提出用 PDF/PNG/CSV/JSON を区別します。", - ( - ManualSection( - "アレイ JSON の読み込み/書き出し", - steps=( - "「ファイル > アレイJSONを書き出し」で保存先を選びます。既定候補は outputs です。", - "座標を戻す場合は「ファイル > アレイJSONを読み込み」を使用します。", - "読み込み後、ステータスバーの最初の TX/RX、座標範囲、プロットのチャネル数を確認します。", - ), - bullets=( - "ファイルは TX/RX 座標と、確認用の書き出し時 evaluation スナップショットを含みます。", - "再読み込みで復元されるのは TX/RX 座標だけです。evaluation から周波数、辞書、チャネルデータは復元されません。", - "TX/RX は空でなく各 16 以下、対応バージョンと λ 単位が必要です。", - ), - warning="アレイ JSON は完全なプロジェクト一式ではありません。校正結果の再現には辞書、チャネル元ファイル、設定値も保存してください。", - ), - ManualSection( - "性能レポートの出力", - steps=( - "「ファイル > レポート出力」を選ぶと、「レポート出力」設定画面が直接開きます。両軸とも利用不可の場合は実行できません。", - "PDF パスとタイトルを指定します。既存ファイルは上書き確認されます。", - "利用可能な各軸の性能評価真角度範囲を設定し、開始角度を終了角度以下にします。", - "Hold 真角度範囲を設定するか評価範囲への連動を選び、各軸の Hold 曲線間隔も指定します。現在は1°/フレームで、範囲内フレーム数と描画曲線数が表示され、両端は必ず保持されます。", - "誤差しきい値と dB 表示下限を設定し、dB/振幅の少なくとも一方を選びます。", - "必要なら再現用 CSV/JSON を選び、「レポートを出力」を押します。", - "「レポートを出力」または「測角誤差 PNG のみ出力」を選んでも設定画面は閉じません。出力完了後も現在の設定を引き継いでもう一方を出力でき、「キャンセル」または画面を閉じた場合だけ終了します。", - ), - ), - ManualSection( - "測角誤差 PNG の単独出力", - bullets=( - "「レポート出力」設定画面でレポート出力先フォルダーと測角誤差しきい値を確認し、「測角誤差 PNG のみ出力」を選びます。", - "PNG は同じ画面のレポート出力先フォルダーと測角誤差しきい値を引き継ぎます。別の保存先を選ぶ必要はなく、PDF も同時には生成されません。", - "横軸は最大 -90°..+90°で、チャネルデータまたはカスタム DBF 辞書が狭い場合は全入力に共通する最大範囲へ縮小します。", - "縦軸の対称上限は、非折り返し範囲内の測角誤差絶対値のピークと設定した誤差しきい値の大きい方を 1.5 倍し、整数へ切り上げた値です。非折り返し範囲外の折り返し誤差はスケール計算に含めません。", - "単独 PNG はすべての測角誤差サンプルを同じ通常の青い曲線として描画します。非折り返し範囲外の折り返しサンプルは縦軸スケール計算に含めず、決定した縦軸範囲を超える部分は座標軸で自然にクリップされます。", - "単独 PNG では評価範囲や非折り返し範囲の背景帯を表示せず、信頼性なしフレームを赤い × で特別表示せず、スケール説明も表示しません。PDF レポートにはこれらの診断情報を残し、両方とも plot-kit の表示規約を使用します。", - ), - ), - ManualSection( - "生成と出力内容", - bullets=( - "生成はバックグラウンドで行われ、進捗画面に処理段階が表示されます。", - "キャンセル後は現在の描画ステップが安全に終わってから停止します。", - "PDF には設定概要、評価範囲統計、選択した角度スペクトルが入り、各種類は別ページです。", - "Hold 曲線間隔は重ね合わせ密度だけを下げ、Max-Hold、性能統計、再現データは範囲内の全1°フレームを使用します。", - "生データを選ぶと、全フレーム CSV と実際の描画角度を記録したレポート一覧 JSON が隣接ディレクトリに作成されます。", - ), - note="ページ数は利用可能な軸と縦軸種類で決まります。Hold 範囲を広げるか曲線間隔を小さくすると重ね合わせが密になり、ファイルサイズと描画時間が増える場合があります。", - ), - ), - ), - ManualChapter( - "shortcuts_state", - "ショートカット、履歴、起動時復元", - "キー操作を使い、何が自動復元され、何を別保存すべきか確認します。", - ( - ManualSection( - "キーボード操作", - bullets=( - "Ctrl+O:アレイ JSON を読み込み。", - "Ctrl+S:アレイ JSON を書き出し。", - "Ctrl+Z / Ctrl+Y:配置編集を元に戻す/やり直す。やり直しは OS 標準操作に従います。", - "Ctrl+R または Ctrl+G:全表示を再計算して更新。", - "Ctrl+F:周波数欄へ移動し、現在文字列を選択。", - "Ctrl+1 / Ctrl+2 / Ctrl+3:物理・仮想、1D DBF、2D DBF を切り替え。", - "矢印キー:選択中 TX/RX を移動。", - "Delete:選択チャネルを削除。未選択時は削除モード。", - "Esc:削除モード終了、ドラッグ取消、または選択解除。", - ), - note="入力欄にフォーカスがある場合、矢印と Delete は文字編集となり、配置を変更しません。", - ), - ManualSection( - "元に戻す/やり直す範囲", - bullets=( - "対象:追加、削除、ドラッグ、矢印移動、クリア、自動配置、アレイ JSON 読み込み。", - "対象外:周波数、ピーク余裕、言語、DBF 表示、辞書、チャネル振幅/位相。", - "最大 50 ステップ。新しい配置編集後は以前のやり直し分岐が消去されます。", - ), - warning="チャネルデータは即時反映され履歴には入りません。対象とデータ枠を確認し、必要なら元ファイル一覧を残してください。", - ), - ManualSection( - "正常終了後に復元される項目", - bullets=( - "復元:言語、最近のフォルダー、周波数、ピーク余裕、DBF 表示、配置、ウィンドウ位置/状態、ページ、分割比。", - "辞書モードと外部辞書パスは復元を試み、元ファイルがない場合は安全なモードへ戻ります。", - "非復元:チャネル振幅/位相の読み込み内容。再起動後に再読み込みします。", - "状態保存は正常終了時です。異常終了では直前変更が保存されない場合があります。", - ), - ), - ), - ), - ManualChapter( - "troubleshooting", - "トラブルシューティング", - "能力表示、入力復元、ファイル割り当て、レポート失敗、ログ位置を確認します。", - ( - ManualSection( - "空のプロットまたは無効ボタン", - bullets=( - "1T1R には方向開口がないため、1D/2D の能力メッセージは正常です。", - "一方だけ展開がある場合は有効な 1D を使い、2D から 1D へ戻ります。", - "軸を有効にするには、その方向へ TX/RX を広げるか自動配置後に調整します。", - "配置変更後に更新されない場合は Ctrl+R/Ctrl+G を押し、ステータスバーで無効入力復元を確認します。", - ), - ), - ManualSection( - "ピーク異常またはジャンプ", - steps=( - "ヘッダーの辞書とチャネルデータ状態を確認します。", - "理想幾何辞書へ戻し、配置と外部データのどちらが原因か分けます。", - "仮想点重複、ピーク余裕、終了理由を確認します。", - "方向が完全に逆なら逆位相モードと読み込み位相反転を確認します。", - "1D ドラッグで角度を特定し、2D で確認します。設定は一度に 1 項目だけ変更します。", - ), - note="変更前後の状態を 1 項目ずつ記録すると、原因を早く特定できます。", - ), - ManualSection( - "ファイルまたはレポートの失敗", - bullets=( - "アレイ JSON:バージョン、単位、空でない tx/rx、各 16 以下、数値座標を確認。", - "チャネルデータ:角度列、データ列、対象、列数/名称を確認し、ファイルを使用中の表計算ソフトを閉じます。", - "外部辞書:少なくとも一軸を読み込み、対象と現在配置を一致させ、ヘッダーとデータを確認。", - "性能レポート:有効軸、範囲順序、dB/振幅の選択、書き込み可能な出力先を確認。", - "キャンセル後も処理中の場合は、現在の描画ステップが安全に終わるまで待ちます。", - ), - warning="エラー文字列と「ヘルプ > このアプリについて」のログパスを使用してください。問い合わせにはログ、アレイ JSON、元ファイル名、再現手順を添付します。", - ), - ), - ), - ) - - -_CHAPTERS_BY_LANGUAGE = { - "zh": _zh_chapters(), - "en": _en_chapters(), - "ja": _ja_chapters(), -} - - -def manual_chapters(language: str) -> tuple[ManualChapter, ...]: - """Return all chapters in stable navigation order for ``language``. - - Unsupported or malformed language values intentionally fall back to Chinese, - matching the application's existing localization behavior. - """ - - normalized = language.strip().lower() if isinstance(language, str) else "zh" - if normalized not in _SUPPORTED_LANGUAGES: - normalized = "zh" - return _CHAPTERS_BY_LANGUAGE[normalized] - - -def _escape(value: str) -> str: - return html.escape(str(value), quote=True) - - -def manual_chapter_html(chapter: ManualChapter) -> str: - """Render one chapter as a safe, self-contained HTML document. - - Every content field is escaped before insertion. The function therefore - remains safe if a future caller builds a chapter from a translated resource - or another non-code source. - """ - - parts = [ - "", - f"

{_escape(chapter.title)}

", - f"

{_escape(chapter.summary)}

", - ] - for section in chapter.sections: - parts.append(f"

{_escape(section.heading)}

") - parts.extend(f"

{_escape(paragraph)}

" for paragraph in section.paragraphs) - if section.steps: - parts.append("
    ") - parts.extend(f"
  1. {_escape(step)}
  2. " for step in section.steps) - parts.append("
") - if section.bullets: - parts.append("
    ") - parts.extend(f"
  • {_escape(bullet)}
  • " for bullet in section.bullets) - parts.append("
") - if section.note: - parts.append( - f"

{_escape(section.note)}

" - ) - if section.warning: - parts.append( - f"

{_escape(section.warning)}

" - ) - parts.append("") - return "".join(parts) - - -def manual_chapter_search_text(chapter: ManualChapter) -> str: - """Return all searchable plain text for a chapter, without HTML or markup.""" - - values = [chapter.key, chapter.title, chapter.summary] - for section in chapter.sections: - values.append(section.heading) - values.extend(section.paragraphs) - values.extend(section.steps) - values.extend(section.bullets) - if section.note: - values.append(section.note) - if section.warning: - values.append(section.warning) - return "\n".join(value.strip() for value in values if value and value.strip()) - - -__all__ = [ - "MANUAL_CHAPTER_IDS", - "ManualChapter", - "ManualSection", - "manual_chapter_html", - "manual_chapter_search_text", - "manual_chapters", -] diff --git a/src/virtual_array/version.py b/src/virtual_array/version.py index 4a013b8..17eff8e 100644 --- a/src/virtual_array/version.py +++ b/src/virtual_array/version.py @@ -1 +1 @@ -APP_VERSION = "0.2.0" +APP_VERSION = "1.0.0" diff --git a/tests/test_analysis.py b/tests/test_analysis.py index 07fd481..b5cbfef 100644 --- a/tests/test_analysis.py +++ b/tests/test_analysis.py @@ -28,12 +28,6 @@ PatternSeries, ) from virtual_array.geometry import AntennaArray -from virtual_array.gui import ( - RESPONSE_MODE_AZIMUTH, - RESPONSE_MODE_ELEVATION, - _response_cut_for_mode, - _response_sidelobe_marker, -) def test_case4_analysis_metrics_are_stable() -> None: @@ -467,59 +461,3 @@ def test_dbf_angle_metrics_treat_flat_spectrum_as_unusable() -> None: def test_estimate_resolution_uses_half_lambda_aperture_units() -> None: assert estimate_resolution(0.0) is None assert estimate_resolution(75.0) == pytest.approx(1.3537, abs=1e-4) - - -def test_response_cut_switches_between_azimuth_and_elevation() -> None: - af_db = np.array( - [ - [-30.0, -20.0, -10.0], - [-12.0, 0.0, -12.0], - [-9.0, -18.0, -27.0], - ] - ) - azimuths = np.array([-1.0, 0.0, 1.0]) - elevations = np.array([-10.0, 0.0, 10.0]) - - az_cut = _response_cut_for_mode( - af_db, azimuths, elevations, RESPONSE_MODE_AZIMUTH - ) - el_cut = _response_cut_for_mode( - af_db, azimuths, elevations, RESPONSE_MODE_ELEVATION - ) - - assert az_cut.label == "方位" - assert np.array_equal(az_cut.angles, azimuths) - assert np.array_equal(az_cut.gains_db, af_db[1, :]) - assert el_cut.label == "俯仰" - assert np.array_equal(el_cut.angles, elevations) - assert np.array_equal(el_cut.gains_db, af_db[:, 1]) - - -def test_response_sidelobe_marker_prefers_local_peak() -> None: - angles = np.array([-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0]) - gains_db = np.array([-18.0, -10.0, -12.0, -14.0, 0.0, -15.0, -13.0, -11.0, -18.0]) - - index, is_peak = _response_sidelobe_marker(angles, gains_db, guard=1.5) - - assert is_peak - assert angles[index] == -3.0 - - -def test_response_sidelobe_marker_rejects_low_clearance_peak() -> None: - angles = np.array([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0]) - gains_db = np.array([-18.0, -10.0, -10.2, 0.0, -10.2, -10.0, -18.0]) - - index, is_peak = _response_sidelobe_marker(angles, gains_db, guard=1.5) - - assert not is_peak - assert angles[index] == -2.0 - - -def test_response_sidelobe_marker_marks_fallback_when_no_peak_exists() -> None: - angles = np.array([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0]) - gains_db = np.array([-12.0, -8.0, -3.0, 0.0, -3.0, -8.0, -12.0]) - - index, is_peak = _response_sidelobe_marker(angles, gains_db, guard=1.5) - - assert not is_peak - assert angles[index] == -2.0 diff --git a/tests/test_app_state.py b/tests/test_app_state.py deleted file mode 100644 index dcb2167..0000000 --- a/tests/test_app_state.py +++ /dev/null @@ -1,26 +0,0 @@ -from __future__ import annotations - -from virtual_array.app_state import load_state, save_state - - -def test_save_and_load_state_round_trip(tmp_path) -> None: - path = tmp_path / "state.json" - state = { - "version": 1, - "last_layout_dir": str(tmp_path / "layouts"), - "last_pattern_dir": str(tmp_path / "patterns"), - "frequency_mode": "77 GHz", - "layout": { - "version": 1, - "unit": "lambda", - "tx": [{"name": "Tx1", "x": 0, "y": 0}], - "rx": [{"name": "Rx1", "x": 0, "y": 0}], - }, - } - - assert save_state(state, path) == path - assert load_state(path) == state - - -def test_load_missing_state_returns_empty_dict(tmp_path) -> None: - assert load_state(tmp_path / "missing.json") == {} diff --git a/tests/test_apple_switch.py b/tests/test_apple_switch.py deleted file mode 100644 index 8060463..0000000 --- a/tests/test_apple_switch.py +++ /dev/null @@ -1,100 +0,0 @@ -from __future__ import annotations - -import os - -import pytest - - -os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") - -QtCore = pytest.importorskip("PySide6.QtCore") -QtGui = pytest.importorskip("PySide6.QtGui") -QtTest = pytest.importorskip("PySide6.QtTest") -QtWidgets = pytest.importorskip("PySide6.QtWidgets") - -from virtual_array.qt_tk import AppleSwitch, BooleanVar, Checkbutton, _ensure_app # noqa: E402 - - -@pytest.fixture(scope="module") -def app(): - return _ensure_app() - - -def test_ttk_checkbutton_uses_accessible_apple_switch(app): - variable = BooleanVar(False) - calls: list[bool] = [] - wrapper = Checkbutton( - text="导入字典按90°相位校准", - variable=variable, - command=lambda: calls.append(variable.get()), - ) - switch = wrapper._qt - - assert isinstance(switch, AppleSwitch) - assert isinstance(switch, QtWidgets.QCheckBox) - assert switch.accessibleName() == "导入字典按90°相位校准" - assert switch.animationDuration() == 180 - assert switch.minimumSizeHint().height() >= 28 - - switch.show() - switch.setFocus() - QtTest.QTest.keyClick(switch, QtCore.Qt.Key.Key_Space) - app.processEvents() - - assert switch.isChecked() - assert variable.get() is True - assert calls == [True] - - switch.setEnabled(False) - QtTest.QTest.keyClick(switch, QtCore.Qt.Key.Key_Space) - app.processEvents() - assert switch.isChecked() - switch.close() - - -def test_switch_animation_retargets_from_live_position(app): - switch = AppleSwitch("动画开关") - switch.resize(switch.sizeHint()) - switch.show() - app.processEvents() - - if not switch._animations_enabled(): - pytest.skip("the active Qt style disables widget animation") - - switch.setChecked(True) - QtTest.QTest.qWait(60) - live_position = switch.switchPosition() - assert 0.0 < live_position < 1.0 - - switch.setChecked(False) - assert switch.switchPosition() == pytest.approx(live_position, abs=0.03) - QtTest.QTest.qWait(220) - assert switch.switchPosition() == pytest.approx(0.0, abs=0.0001) - switch.close() - - -class _NoWidgetAnimationStyle(QtWidgets.QProxyStyle): - def styleHint(self, hint, option=None, widget=None, return_data=None): # noqa: N802 - if hint == QtWidgets.QStyle.StyleHint.SH_Widget_Animate: - return 0 - return super().styleHint(hint, option, widget, return_data) - - -def test_switch_honors_qt_animation_style_hint(app): - switch = AppleSwitch("减少动画") - style = _NoWidgetAnimationStyle() - switch.setStyle(style) - switch.show() - app.processEvents() - - switch.setChecked(True) - assert switch.switchPosition() == pytest.approx(1.0) - - image = QtGui.QImage( - switch.sizeHint(), - QtGui.QImage.Format.Format_ARGB32_Premultiplied, - ) - image.fill(QtCore.Qt.GlobalColor.transparent) - switch.render(image) - assert not image.isNull() - switch.close() diff --git a/tests/test_gui_element_editing.py b/tests/test_gui_element_editing.py deleted file mode 100644 index a77667e..0000000 --- a/tests/test_gui_element_editing.py +++ /dev/null @@ -1,582 +0,0 @@ -from __future__ import annotations - -from collections import deque -from types import SimpleNamespace - -import numpy as np -import pytest -from matplotlib.figure import Figure - -from virtual_array.analysis import DBF_SCAN_GRID_SIZE -from virtual_array.gui import ( - CHANNEL_PATTERN_TARGET_PHYSICAL, - CHANNEL_PATTERN_TARGET_VIRTUAL, - DBF_DISPLAY_MAGNITUDE, - EditableElement, - MAX_HISTORY_STATES, - ResponseChart, - VirtualArrayGui, - _build_auto_layout_elements, - _default_workspace_sash_position, - _dbf_peak_index, - _drag_position_with_offset, - _format_frequency_ghz, - _format_margin_db, - _new_response_hover_annotation, - _parse_frequency_ghz, - _parse_margin_db, - _square_axis_limits, - _validate_element_count, - _validated_window_geometry, -) - - -def test_drag_position_preserves_grab_offset_without_grid_jumps() -> None: - assert _drag_position_with_offset( - 0.37, - -1.22, - (0.18, -0.08), - None, - ) == pytest.approx((0.55, -1.30)) - - -def test_drag_position_clips_after_applying_grab_offset() -> None: - assert _drag_position_with_offset( - 0.95, - -1.95, - (0.20, -0.20), - (-1.0, 1.0, -2.0, 2.0), - ) == pytest.approx((1.0, -2.0)) - - -def test_layout_import_rejects_more_than_16_tx() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - config = { - "version": 1, - "unit": "lambda", - "tx": [{"name": f"Tx{i}", "x": i, "y": 0} for i in range(17)], - "rx": [{"name": "Rx1", "x": 0, "y": 0}], - } - - with pytest.raises(ValueError, match="maximum is 16"): - app._elements_from_layout_config(config) - - -def test_layout_import_normalizes_element_names() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - config = { - "version": 1, - "unit": "lambda", - "tx": [ - {"name": "CustomA", "x": 0, "y": 0}, - {"name": "CustomB", "x": 1, "y": 0}, - ], - "rx": [{"name": "Anything", "x": 0, "y": 0}], - } - - elements = app._elements_from_layout_config(config) - - assert [element.name for element in elements] == ["Tx1", "Tx2", "Rx1"] - - -def test_renumber_elements_compacts_after_middle_delete() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.elements = [ - EditableElement(kind="tx", index=0, name="Tx1", x=0, y=0), - EditableElement(kind="tx", index=2, name="Tx3", x=2, y=0), - EditableElement(kind="rx", index=0, name="Rx1", x=0, y=-1), - EditableElement(kind="rx", index=2, name="Rx3", x=2, y=-1), - ] - app.selected_element = app.elements[1] - - app._renumber_elements() - - assert [(element.kind, element.index, element.name) for element in app.elements] == [ - ("tx", 0, "Tx1"), - ("tx", 1, "Tx2"), - ("rx", 0, "Rx1"), - ("rx", 1, "Rx2"), - ] - assert app.selected_element.name == "Tx2" - - -@pytest.mark.parametrize( - ("raw_value", "expected"), - [ - ("77", 77.0), - ("77 GHz", 77.0), - ("92.5ghz", 92.5), - ("60g", 60.0), - (79.25, 79.25), - ], -) -def test_frequency_parser_accepts_custom_ghz_values(raw_value, expected) -> None: - assert _parse_frequency_ghz(raw_value) == pytest.approx(expected) - - -@pytest.mark.parametrize("raw_value", ["", "abc", 0, -1, True, float("inf")]) -def test_frequency_parser_rejects_invalid_values(raw_value) -> None: - assert _parse_frequency_ghz(raw_value) is None - - -def test_frequency_formatter_keeps_compact_display() -> None: - assert _format_frequency_ghz(77.0) == "77" - assert _format_frequency_ghz(77.125000) == "77.125" - - -@pytest.mark.parametrize( - ("raw_value", "expected"), - [ - ("0.5", 0.5), - ("1.25 dB", 1.25), - ("2db", 2.0), - (0, 0.0), - ], -) -def test_margin_parser_accepts_non_negative_db_values(raw_value, expected) -> None: - assert _parse_margin_db(raw_value) == pytest.approx(expected) - - -@pytest.mark.parametrize("raw_value", ["", "abc", -0.1, True, float("inf")]) -def test_margin_parser_rejects_invalid_values(raw_value) -> None: - assert _parse_margin_db(raw_value) is None - - -def test_margin_formatter_keeps_compact_display() -> None: - assert _format_margin_db(1.0) == "1" - assert _format_margin_db(0.125) == "0.125" - - -def test_response_hover_tooltip_follows_cursor_without_arrow() -> None: - class DummyCanvas: - def __init__(self) -> None: - self.draw_count = 0 - - def draw_idle(self) -> None: - self.draw_count += 1 - - fig = Figure() - ax = fig.add_subplot(111) - ax.set_xlim(-90, 90) - ax.set_ylim(-40, 0) - annotation = _new_response_hover_annotation(ax) - canvas = DummyCanvas() - chart = ResponseChart(fig=fig, ax=ax, canvas=canvas, hover_annotation=annotation) - chart.hover_angles = np.array([-10.0, 0.0, 10.0]) - chart.hover_db = np.array([-12.0, -6.0, -18.0]) - app = VirtualArrayGui.__new__(VirtualArrayGui) - - app._update_response_hover( - SimpleNamespace(inaxes=ax, xdata=1.25, ydata=-8.5), - chart, - "Az", - ) - - assert annotation.arrow_patch is None - assert annotation.get_visible() - assert annotation.xy == pytest.approx((1.25, -8.5)) - assert "Az = 0.0" in annotation.get_text() - assert canvas.draw_count == 1 - - app._update_response_hover( - SimpleNamespace(inaxes=None, xdata=None, ydata=None), - chart, - "Az", - ) - - assert not annotation.get_visible() - assert canvas.draw_count == 2 - - -def test_dbf_display_values_convert_db_to_correlation_magnitude() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.dbf_display_mode = SimpleNamespace(get=lambda: DBF_DISPLAY_MAGNITUDE) - - values = app._dbf_display_values(np.array([-40.0, -6.020599913, 0.0, 3.0])) - - assert values == pytest.approx([0.01, 0.5, 1.0, 1.0]) - assert app._format_dbf_display_value(-6.020599913) == "相关系数 = 0.500" - - -def test_window_geometry_validation_accepts_tk_geometry_strings() -> None: - assert _validated_window_geometry("1440x900+20-10") == "1440x900+20-10" - assert _validated_window_geometry("1200x800") == "1200x800" - assert _validated_window_geometry("0x800+0+0") is None - assert _validated_window_geometry("not-geometry") is None - - -def test_default_workspace_sash_position_uses_half_available_width() -> None: - assert _default_workspace_sash_position(1720) == 860 - assert _default_workspace_sash_position(1280) == 640 - assert _default_workspace_sash_position(2) == 1 - assert _default_workspace_sash_position(1) is None - - -def test_layout_snapshot_restore_round_trip_preserves_selection() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.elements = [ - EditableElement(kind="tx", index=0, name="Tx1", x=0, y=0), - EditableElement(kind="rx", index=0, name="Rx1", x=1, y=-2), - ] - app.selected_element = app.elements[1] - snapshot = app._capture_layout_snapshot() - - app.elements[1].x = 9 - app.selected_element = None - app.dragging = app.elements[0] - app.drag_bounds = (0, 1, 0, 1) - app.drag_axis_limits = ((0, 1), (0, 1)) - app.drag_start_snapshot = snapshot - - app._restore_layout_snapshot(snapshot) - - assert [(element.name, element.x, element.y) for element in app.elements] == [ - ("Tx1", 0, 0), - ("Rx1", 1, -2), - ] - assert app.selected_element is app.elements[1] - assert app.dragging is None - assert app.drag_start_snapshot is None - - -def test_escape_mid_drag_restores_layout_and_releases_pointer() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.elements = [ - EditableElement(kind="tx", index=0, name="Tx1", x=0.0, y=2.0), - EditableElement(kind="rx", index=0, name="Rx1", x=0.0, y=-2.0), - ] - app.selected_element = None - snapshot = app._capture_layout_snapshot() - app.dragging = app.elements[0] - app.dragging.x = 0.55 - app.drag_bounds = (-4.0, 4.0, -4.0, 4.0) - app.drag_axis_limits = ((-2.0, 2.0), (-2.0, 2.0)) - app.drag_start_snapshot = snapshot - app.drag_grab_offset = (0.15, -0.10) - app._physical_drag_after_id = "drag-redraw" - app.delete_mode = False - - cancelled: list[str] = [] - released: list[bool] = [] - generated: list[bool] = [] - status: list[str] = [] - app.root = SimpleNamespace(after_cancel=cancelled.append) - app.phys_canvas = SimpleNamespace(release_pointer=lambda: released.append(True)) - app.generate_virtual_array = lambda: generated.append(True) - app.status = SimpleNamespace(set=status.append) - app._t = lambda key, **_kwargs: key - - assert app.on_escape_key() == "break" - assert [(element.x, element.y) for element in app.elements] == [ - (0.0, 2.0), - (0.0, -2.0), - ] - assert app.dragging is None - assert app.drag_start_snapshot is None - assert app.drag_grab_offset is None - assert app._physical_drag_after_id is None - assert cancelled == ["drag-redraw"] - assert released == [True] - assert generated == [True] - assert status == ["drag_cancel"] - - -def test_default_gui_layout_uses_clean_1t1r_starter() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - - elements = app._build_elements() - - assert [(element.name, element.x, element.y) for element in elements] == [ - ("Tx1", 0.0, 4.0), - ("Rx1", 0.0, -4.0), - ] - - -def test_auto_layout_builds_centered_tx_rx_rows() -> None: - elements = _build_auto_layout_elements(tx_count=3, rx_count=2) - - assert [(element.name, element.x, element.y) for element in elements] == [ - ("Tx1", -2.0, 4.0), - ("Tx2", 0.0, 4.0), - ("Tx3", 2.0, 4.0), - ("Rx1", -1.0, -4.0), - ("Rx2", 1.0, -4.0), - ] - - -def test_pattern_channel_names_switch_between_physical_and_virtual_targets() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.elements = _build_auto_layout_elements(tx_count=2, rx_count=3) - - assert app._pattern_channel_names(CHANNEL_PATTERN_TARGET_PHYSICAL) == [ - "Tx1", - "Tx2", - "Rx1", - "Rx2", - "Rx3", - ] - assert app._pattern_channel_names(CHANNEL_PATTERN_TARGET_VIRTUAL) == [ - "Tx1Rx1", - "Tx1Rx2", - "Tx1Rx3", - "Tx2Rx1", - "Tx2Rx2", - "Tx2Rx3", - ] - assert app._all_pattern_channel_names() == [ - "Tx1", - "Tx2", - "Rx1", - "Rx2", - "Rx3", - "Tx1Rx1", - "Tx1Rx2", - "Tx1Rx3", - "Tx2Rx1", - "Tx2Rx2", - "Tx2Rx3", - ] - - -def test_square_axis_limits_keep_physical_grid_square() -> None: - x_limits, y_limits = _square_axis_limits( - [-1.0, 1.0], - [-4.0, 4.0], - minimum_span=4.0, - padding=2.0, - ) - - assert x_limits[1] - x_limits[0] == pytest.approx(y_limits[1] - y_limits[0]) - assert x_limits[0] < -1.0 < x_limits[1] - assert y_limits[0] < -4.0 < y_limits[1] - - -@pytest.mark.parametrize( - ("raw_value", "kind", "expected"), - [ - ("1", "tx", 1), - ("16", "rx", 16), - (4, "tx", 4), - ], -) -def test_validate_element_count_accepts_valid_ranges(raw_value, kind, expected) -> None: - assert _validate_element_count(raw_value, kind) == expected - - -@pytest.mark.parametrize("raw_value", ["", "abc", "0", "17"]) -def test_validate_element_count_rejects_invalid_ranges(raw_value) -> None: - with pytest.raises(ValueError): - _validate_element_count(raw_value, "tx") - - -class _FakeStatus: - def __init__(self) -> None: - self.value = "" - - def set(self, value: str) -> None: - self.value = value - - -def test_delete_element_renumbers_by_position_without_gaps() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.elements = [ - EditableElement(kind="tx", index=0, name="Tx1", x=4, y=0), - EditableElement(kind="tx", index=1, name="Tx2", x=0, y=0), - EditableElement(kind="tx", index=2, name="Tx3", x=2, y=0), - EditableElement(kind="rx", index=0, name="Rx1", x=0, y=-2), - ] - app.selected_element = app.elements[1] - app.dragging = None - app.drag_bounds = None - app.drag_axis_limits = None - app.drag_start_snapshot = None - app.delete_mode = True - app.undo_stack = deque(maxlen=MAX_HISTORY_STATES) - app.redo_stack = deque(maxlen=MAX_HISTORY_STATES) - app.status = _FakeStatus() - app.generate_virtual_array = lambda: None - - assert app._delete_element(app.elements[1]) - - assert [(element.name, element.x) for element in app.elements if element.kind == "tx"] == [ - ("Tx1", 2), - ("Tx2", 4), - ] - assert "编号已自动对齐" in app.status.value - - -class _FakeRoot: - def __init__(self) -> None: - self.cancelled: list[str] = [] - - def after_cancel(self, after_id: str) -> None: - self.cancelled.append(after_id) - - -class _FakeLabel: - def __init__(self) -> None: - self.text = "" - - def configure(self, **kwargs) -> None: # noqa: ANN003 - self.text = kwargs["text"] - - -class _FakeCursorWidget: - def __init__(self) -> None: - self.cursor = "" - - def configure(self, **kwargs) -> None: # noqa: ANN003 - if "cursor" in kwargs: - self.cursor = kwargs["cursor"] - - -class _FakeCanvasWithWidget: - def __init__(self) -> None: - self.draw_count = 0 - self.widget = _FakeCursorWidget() - - def draw_idle(self) -> None: - self.draw_count += 1 - - def get_tk_widget(self) -> _FakeCursorWidget: - return self.widget - - -def test_dbf_true_line_drag_pauses_animation_at_selected_angle() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.root = _FakeRoot() - app.status = _FakeStatus() - app.dbf_scan_active = True - app.dbf_scan_paused = False - app.dbf_scan_mode = "azimuth" - app.dbf_scan_after_id = "pending" - app.dbf_true_angles = np.linspace(-90.0, 90.0, DBF_SCAN_GRID_SIZE) - app.dbf_scan_angles = np.linspace(-90.0, 90.0, DBF_SCAN_GRID_SIZE) - app.dbf_spectra_db = np.zeros( - (DBF_SCAN_GRID_SIZE, DBF_SCAN_GRID_SIZE), dtype=float - ) - drawn_frames: list[int] = [] - app._draw_dbf_scan_frame = lambda: drawn_frames.append(app.dbf_scan_frame) - app._update_dbf_scan_controls = lambda: None - - app._set_dbf_scan_angle("azimuth", -69.8) - - assert app.dbf_scan_active - assert app.dbf_scan_paused - assert app.dbf_scan_frame == 20 - assert app.dbf_scan_after_id is None - assert app.root.cancelled == ["pending"] - assert drawn_frames == [20] - assert "方位DBF角谱已暂停在-70.0°" in app.status.value - - -def test_dbf_angle_label_tracks_chart_mode_and_frame() -> None: - app = VirtualArrayGui.__new__(VirtualArrayGui) - progress_label = _FakeLabel() - app.az_chart = SimpleNamespace(progress_label=None) - app.el_chart = SimpleNamespace( - progress_label=progress_label, - ) - - app._set_dbf_progress("elevation", 45, 0.0) - - assert progress_label.text == "俯仰 0° (46/181)" - - -def test_response_true_angle_line_sets_hand_cursor_near_guide() -> None: - fig = Figure() - ax = fig.add_subplot(111) - ax.set_xlim(-90, 90) - ax.set_ylim(-40, 0) - canvas = _FakeCanvasWithWidget() - chart = ResponseChart(fig=fig, ax=ax, canvas=canvas, true_angle=0.0) - app = VirtualArrayGui.__new__(VirtualArrayGui) - - app._update_response_cursor( - SimpleNamespace(inaxes=ax, xdata=1.0, ydata=-10.0), - chart, - ) - - assert canvas.widget.cursor == "hand2" - - app._update_response_cursor( - SimpleNamespace(inaxes=ax, xdata=12.0, ydata=-10.0), - chart, - ) - - assert canvas.widget.cursor == "" - - -def test_dbf2d_crosshair_sets_hand_cursor_near_true_angle_guides() -> None: - fig = Figure() - ax = fig.add_subplot(111) - ax.set_xlim(-90, 90) - ax.set_ylim(-90, 90) - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.dbf2d_ax = ax - app.dbf2d_canvas = _FakeCanvasWithWidget() - app.dbf2d_az_frame = 90 - app.dbf2d_el_frame = 90 - - app._update_dbf2d_cursor(SimpleNamespace(inaxes=ax, xdata=1.0, ydata=45.0)) - - assert app.dbf2d_canvas.widget.cursor == "hand2" - - app._update_dbf2d_cursor(SimpleNamespace(inaxes=ax, xdata=20.0, ydata=45.0)) - - assert app.dbf2d_canvas.widget.cursor == "" - - -def test_dbf2d_hover_tooltip_reports_nearest_angle_and_correlation() -> None: - fig = Figure() - ax = fig.add_subplot(111) - ax.set_xlim(-1, 1) - ax.set_ylim(-2, 2) - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.dbf2d_ax = ax - app.dbf2d_canvas = _FakeCanvasWithWidget() - app.dbf2d_hover_azimuths = np.array([-1.0, 0.0, 1.0]) - app.dbf2d_hover_elevations = np.array([-2.0, 2.0]) - app.dbf2d_hover_db = np.array([[-10.0, -9.0, -8.0], [-7.0, -6.0, -5.0]]) - app.dbf2d_hover_annotation = _new_response_hover_annotation(ax) - app.dbf2d_hover_marker = ax.scatter([], []) - - app._update_dbf2d_hover(SimpleNamespace(inaxes=ax, xdata=0.2, ydata=1.9)) - - assert app.dbf2d_hover_annotation.get_visible() - assert app.dbf2d_hover_annotation.xy == pytest.approx((0.2, 1.9)) - tooltip = app.dbf2d_hover_annotation.get_text() - assert "方位 = +0.0" in tooltip - assert "俯仰 = +2.0" in tooltip - assert "相关系数 = -6.00 dB" in tooltip - assert app.dbf2d_canvas.draw_count == 1 - - -def test_dbf2d_hover_tooltip_uses_magnitude_display_mode() -> None: - fig = Figure() - ax = fig.add_subplot(111) - ax.set_xlim(-1, 1) - ax.set_ylim(-2, 2) - app = VirtualArrayGui.__new__(VirtualArrayGui) - app.dbf_display_mode = SimpleNamespace(get=lambda: DBF_DISPLAY_MAGNITUDE) - app.dbf2d_ax = ax - app.dbf2d_canvas = _FakeCanvasWithWidget() - app.dbf2d_hover_azimuths = np.array([-1.0, 0.0, 1.0]) - app.dbf2d_hover_elevations = np.array([-2.0, 2.0]) - app.dbf2d_hover_db = np.array([[-10.0, -9.0, -8.0], [-7.0, -6.0, -5.0]]) - app.dbf2d_hover_annotation = _new_response_hover_annotation(ax) - app.dbf2d_hover_marker = ax.scatter([], []) - - app._update_dbf2d_hover(SimpleNamespace(inaxes=ax, xdata=0.2, ydata=1.9)) - - tooltip = app.dbf2d_hover_annotation.get_text() - assert "方位 = +0.0" in tooltip - assert "俯仰 = +2.0" in tooltip - assert "相关系数 = 0.501" in tooltip - - -def test_dbf_peak_marker_prefers_true_angle_when_peaks_are_tied() -> None: - scan_angles = np.array([-90.0, 0.0, 90.0]) - spectrum_db = np.array([0.0, 0.0, 0.0]) - - assert _dbf_peak_index(scan_angles, spectrum_db, true_angle=0.0) == 1 diff --git a/tests/test_interactive_cursors.py b/tests/test_interactive_cursors.py deleted file mode 100644 index e65ac4b..0000000 --- a/tests/test_interactive_cursors.py +++ /dev/null @@ -1,189 +0,0 @@ -from __future__ import annotations - -import os - -import pytest - - -os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") - -QtCore = pytest.importorskip("PySide6.QtCore") -QtGui = pytest.importorskip("PySide6.QtGui") -QtWidgets = pytest.importorskip("PySide6.QtWidgets") -QtTest = pytest.importorskip("PySide6.QtTest") - -from virtual_array.native_theme import apply_native_theme # noqa: E402 -from virtual_array.qt_tk import AppleSwitch, ttk # noqa: E402 - - -HAND = QtCore.Qt.CursorShape.PointingHandCursor -ARROW = QtCore.Qt.CursorShape.ArrowCursor - - -@pytest.fixture(scope="module") -def qapp(): - app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) - apply_native_theme(app) - yield app - - -def _show(qapp, widget: QtWidgets.QWidget) -> None: - widget.show() - qapp.processEvents() - - -def test_buttons_switches_and_slider_track_enabled_state(qapp) -> None: - parent = QtWidgets.QWidget() - layout = QtWidgets.QVBoxLayout(parent) - controls = ( - QtWidgets.QPushButton("Push", parent), - QtWidgets.QToolButton(parent), - QtWidgets.QRadioButton("Radio", parent), - AppleSwitch("Switch", parent), - QtWidgets.QComboBox(parent), - QtWidgets.QSlider(QtCore.Qt.Orientation.Horizontal, parent), - ) - for control in controls: - layout.addWidget(control) - _show(qapp, parent) - - try: - for control in controls: - assert control.cursor().shape() == HAND - control.setEnabled(False) - qapp.processEvents() - assert control.cursor().shape() == ARROW - control.setEnabled(True) - qapp.processEvents() - assert control.cursor().shape() == HAND - finally: - parent.close() - parent.deleteLater() - qapp.processEvents() - - -def test_text_scroll_and_custom_cursor_surfaces_are_not_overridden(qapp) -> None: - parent = QtWidgets.QWidget() - layout = QtWidgets.QVBoxLayout(parent) - line_edit = QtWidgets.QLineEdit(parent) - text_edit = QtWidgets.QTextEdit(parent) - scroll_bar = QtWidgets.QScrollBar(parent) - custom_surface = QtWidgets.QWidget(parent) - custom_surface.setProperty("preserveCursor", True) - custom_surface.setCursor(QtGui.QCursor(QtCore.Qt.CursorShape.CrossCursor)) - for widget in (line_edit, text_edit, scroll_bar, custom_surface): - layout.addWidget(widget) - _show(qapp, parent) - - try: - assert line_edit.cursor().shape() != HAND - assert text_edit.viewport().cursor().shape() != HAND - assert scroll_bar.cursor().shape() != HAND - assert custom_surface.cursor().shape() == QtCore.Qt.CursorShape.CrossCursor - finally: - parent.close() - parent.deleteLater() - qapp.processEvents() - - -def test_tabs_and_menus_only_point_at_enabled_actions(qapp) -> None: - tabs = QtWidgets.QTabBar() - tabs.resize(320, 40) - tabs.addTab("Enabled") - tabs.addTab("Disabled") - tabs.setTabEnabled(1, False) - _show(qapp, tabs) - - menu = QtWidgets.QMenu() - - try: - QtTest.QTest.mouseMove(tabs, tabs.tabRect(0).center()) - qapp.processEvents() - assert tabs.cursor().shape() == HAND - QtTest.QTest.mouseMove(tabs, tabs.tabRect(1).center()) - qapp.processEvents() - assert tabs.cursor().shape() == ARROW - QtTest.QTest.mouseMove(tabs, QtCore.QPoint(tabs.width() - 2, tabs.height() - 2)) - qapp.processEvents() - assert tabs.cursor().shape() == ARROW - - enabled_action = menu.addAction("Enabled") - separator = menu.addSeparator() - disabled_action = menu.addAction("Disabled") - disabled_action.setEnabled(False) - _show(qapp, menu) - for action, expected in ( - (enabled_action, HAND), - (disabled_action, ARROW), - (separator, ARROW), - ): - QtTest.QTest.mouseMove(menu, menu.actionGeometry(action).center()) - qapp.processEvents() - assert menu.cursor().shape() == expected - finally: - menu.close() - tabs.close() - menu.deleteLater() - tabs.deleteLater() - qapp.processEvents() - - -def test_marked_read_only_items_point_only_over_valid_rows(qapp) -> None: - view = QtWidgets.QListWidget() - view.resize(260, 160) - view.setProperty("pointingHandItems", True) - view.addItem("Selectable") - editable = QtWidgets.QListWidgetItem("Editable") - editable.setFlags(editable.flags() | QtCore.Qt.ItemFlag.ItemIsEditable) - view.addItem(editable) - _show(qapp, view) - - try: - QtTest.QTest.mouseMove(view.viewport(), view.visualItemRect(view.item(0)).center()) - qapp.processEvents() - assert view.viewport().cursor().shape() == HAND - QtTest.QTest.mouseMove(view.viewport(), view.visualItemRect(view.item(1)).center()) - qapp.processEvents() - assert view.viewport().cursor().shape() == ARROW - QtTest.QTest.mouseMove( - view.viewport(), - QtCore.QPoint(view.viewport().width() - 2, view.viewport().height() - 2), - ) - qapp.processEvents() - assert view.viewport().cursor().shape() == ARROW - finally: - view.close() - view.deleteLater() - qapp.processEvents() - - -def test_cursor_policy_installation_is_idempotent(qapp) -> None: - policy = qapp._workbench_interactive_cursor_policy - apply_native_theme(qapp) - assert qapp._workbench_interactive_cursor_policy is policy - - -def test_compatibility_widget_rebuilds_object_scoped_qss_after_rename(qapp) -> None: - style_name = "ObjectNameSyncTest.TButton" - ttk.Style().configure( - style_name, - background="#ffffff", - foreground="#161616", - bordercolor="#8d8d8d", - relief="solid", - padding=(8, 6), - ) - parent = QtWidgets.QWidget() - button = ttk.Button(parent, text="Load", style=style_name) - original_name = button._qt.objectName() - assert f"#{original_name} {{" in button._qt.styleSheet() - - button._qt.setObjectName("renamedDialogButton") - qapp.processEvents() - - stylesheet = button._qt.styleSheet() - assert "#renamedDialogButton {" in stylesheet - assert f"#{original_name} {{" not in stylesheet - assert "border: 1px solid #8d8d8d" in stylesheet - parent.deleteLater() - qapp.processEvents() diff --git a/tests/test_layout_export.py b/tests/test_layout_export.py deleted file mode 100644 index 2832570..0000000 --- a/tests/test_layout_export.py +++ /dev/null @@ -1,46 +0,0 @@ -from __future__ import annotations - -import json - -from virtual_array.gui import _layout_config_to_json, _note_display - - -def test_layout_config_json_keeps_points_compact_and_evaluation_readable() -> None: - config = { - "version": 1, - "unit": "lambda", - "tx": [{"name": "Tx1", "x": -9, "y": -12}], - "rx": [{"name": "Rx1", "x": -9, "y": 0}], - "evaluation": { - "frequency_mode": "77 GHz", - "virtual_utilization": { - "unique_points": 1, - "virtual_channels": 1, - "ratio": 1, - "duplicate_points": 0, - }, - }, - } - - text = _layout_config_to_json(config) - - assert ' {"name": "Tx1", "x": -9, "y": -12}' in text - assert ' {"name": "Rx1", "x": -9, "y": 0}' in text - assert ' "evaluation": {' in text - assert json.loads(text) == config - - -def test_note_display_assigns_icons_and_colors() -> None: - duplicate_text, duplicate_color = _note_display("存在重复虚拟通道") - windowing_text, windowing_color = _note_display("建议加窗降低旁瓣") - high_text, high_color = _note_display("俯仰模糊风险高") - none_text, none_color = _note_display("暂无风险提示") - - assert duplicate_text.startswith("WARN ") - assert duplicate_color == "#c2410c" - assert windowing_text.startswith("TAPER ") - assert windowing_color == "#a16207" - assert high_text.startswith("RISK ") - assert high_color == "#b91c1c" - assert none_text.startswith("OK ") - assert none_color == "#15803d" diff --git a/tests/test_logging_config.py b/tests/test_logging_config.py index 36c9e4f..7730f2a 100644 --- a/tests/test_logging_config.py +++ b/tests/test_logging_config.py @@ -2,6 +2,7 @@ import logging import sys +from pathlib import Path from virtual_array.logging_config import ( LOG_FILE_NAME, @@ -13,10 +14,11 @@ def test_default_log_dir_uses_appdata(monkeypatch) -> None: - monkeypatch.setenv("APPDATA", r"C:\Users\tester\AppData\Roaming") + appdata = r"C:\Users\tester\AppData\Roaming" + monkeypatch.setenv("APPDATA", appdata) monkeypatch.delenv("ANTENNA_ARRAY_LOG_DIR", raising=False) - assert str(default_log_dir()).endswith(r"antenna-array\logs") + assert default_log_dir() == Path(appdata) / "antenna-array" / "logs" def test_env_override_controls_log_dir(monkeypatch, tmp_path) -> None: diff --git a/tests/test_performance_report_dialog.py b/tests/test_performance_report_dialog.py deleted file mode 100644 index f936805..0000000 --- a/tests/test_performance_report_dialog.py +++ /dev/null @@ -1,650 +0,0 @@ -from __future__ import annotations - -import os -import re -from pathlib import Path - -import pytest - - -os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") - -QtWidgets = pytest.importorskip("PySide6.QtWidgets") -QtCore = pytest.importorskip("PySide6.QtCore") -QtTest = pytest.importorskip("PySide6.QtTest") - -from virtual_array.native_theme import application_stylesheet # noqa: E402 -from virtual_array.performance_report_dialog import PerformanceReportDialog # noqa: E402 -from virtual_array.qt_tk import AppleSwitch # noqa: E402 - - -@pytest.fixture(scope="module") -def qapp(): - app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) - yield app - - -@pytest.fixture -def dialog(qapp, tmp_path: Path): - del qapp - widget = PerformanceReportDialog( - None, - language="zh", - initial_directory=tmp_path, - azimuth_available=True, - elevation_available=True, - ) - yield widget - widget.set_export_busy(False) - widget.close() - widget.deleteLater() - - -def test_dialog_defaults_are_complete_and_do_not_write_files( - dialog: PerformanceReportDialog, tmp_path: Path -) -> None: - assert dialog.objectName() == "performanceReportDialog" - assert dialog.property("workbenchRole") == "dialog-shell" - output_path = Path(dialog.output_path_edit.text()) - assert output_path.parent == tmp_path - assert re.fullmatch( - r"mimo_performance_report_\d{8}_\d{6}\.pdf", output_path.name - ) - assert not output_path.exists() - - assert dialog.title_edit.text() == "当前配置测角性能报告" - assert (dialog.az_focus_start.value(), dialog.az_focus_stop.value()) == (-70, 70) - assert (dialog.el_focus_start.value(), dialog.el_focus_stop.value()) == (-15, 15) - assert (dialog.az_hold_start.value(), dialog.az_hold_stop.value()) == (-70, 70) - assert (dialog.el_hold_start.value(), dialog.el_hold_stop.value()) == (-15, 15) - assert dialog.az_hold_follows_focus.isChecked() - assert dialog.el_hold_follows_focus.isChecked() - assert dialog.az_hold_curve_step.value() == 1 - assert dialog.el_hold_curve_step.value() == 1 - assert not dialog.az_hold_start.isEnabled() - assert not dialog.el_hold_start.isEnabled() - - assert "141" in dialog.az_hold_frame_count.text() - assert "1°" in dialog.az_hold_frame_count.text() - assert "31" in dialog.el_hold_frame_count.text() - assert "0°" in dialog.findChild( - QtWidgets.QLabel, "azOrthogonalPlaneNote" - ).text() - assert "0°" in dialog.findChild( - QtWidgets.QLabel, "elOrthogonalPlaneNote" - ).text() - - assert dialog.error_limit_spin.value() == pytest.approx(1.0) - assert dialog.spectrum_floor_spin.value() == pytest.approx(-40.0) - assert dialog.spectrum_floor_spin.isEnabled() - assert dialog.include_spectrum_db_checkbox.isChecked() - assert not dialog.include_spectrum_magnitude_checkbox.isChecked() - assert dialog.include_raw_checkbox.isChecked() - assert dialog.save_button.isEnabled() - assert isinstance(dialog.angle_image_button, QtWidgets.QPushButton) - assert dialog.angle_image_button.isEnabled() - assert dialog.angle_image_button.property("fluentRole") != "quiet" - spectrum_scale_label = dialog.findChild( - QtWidgets.QLabel, "reportSpectrumScaleLabel" - ) - assert spectrum_scale_label is not None - assert "可多选" in spectrum_scale_label.text() - assert "分别输出" in dialog.include_spectrum_db_checkbox.toolTip() - assert dialog.export_kind == "report" - - with pytest.raises(AttributeError): - setattr(dialog, "export_kind", "angle_image") - - -def test_range_spin_boxes_and_important_object_names_are_stable( - dialog: PerformanceReportDialog, -) -> None: - expected_spin_names = ( - "azFocusStart", - "azFocusStop", - "azHoldStart", - "azHoldStop", - "elFocusStart", - "elFocusStop", - "elHoldStart", - "elHoldStop", - ) - for object_name in expected_spin_names: - spin = dialog.findChild(QtWidgets.QSpinBox, object_name) - assert spin is not None - assert (spin.minimum(), spin.maximum(), spin.singleStep()) == (-90, 90, 1) - - expected_names_and_types = { - "reportOutputPath": QtWidgets.QLineEdit, - "reportTitle": QtWidgets.QLineEdit, - "reportBrowseButton": QtWidgets.QPushButton, - "azHoldFollowsFocus": AppleSwitch, - "elHoldFollowsFocus": AppleSwitch, - "azHoldCurveStep": QtWidgets.QSpinBox, - "elHoldCurveStep": QtWidgets.QSpinBox, - "reportErrorLimitDeg": QtWidgets.QDoubleSpinBox, - "reportSpectrumFloorDb": QtWidgets.QDoubleSpinBox, - "reportIncludeSpectrumDb": AppleSwitch, - "reportIncludeSpectrumMagnitude": AppleSwitch, - "reportIncludeRawData": AppleSwitch, - "reportValidationError": QtWidgets.QLabel, - "performanceReportButtonBox": QtWidgets.QDialogButtonBox, - } - for object_name, widget_type in expected_names_and_types.items(): - assert dialog.findChild(widget_type, object_name) is not None - - switch_names = ( - "azHoldFollowsFocus", - "elHoldFollowsFocus", - "reportIncludeSpectrumDb", - "reportIncludeSpectrumMagnitude", - "reportIncludeRawData", - ) - for object_name in switch_names: - switch = dialog.findChild(AppleSwitch, object_name) - assert isinstance(switch, QtWidgets.QCheckBox) - assert not switch.isTristate() - - expected_roles = { - "performanceReportRail": "dialog-rail", - "performanceReportRailContent": "dialog-rail", - "performanceReportContent": "dialog-content", - "reportOutputGroup": "dialog-rail", - "reportAxisTabs": "dialog-content", - "reportPerformanceSettingsGroup": "dialog-rail", - "azimuthReportGroup": "dialog-section", - "elevationReportGroup": "dialog-section", - "performanceReportButtonBox": "dialog-footer", - } - for object_name, role in expected_roles.items(): - widget = dialog.findChild(QtWidgets.QWidget, object_name) - assert widget is not None - assert widget.property("workbenchRole") == role - - for object_name in ("azHoldCurveStep", "elHoldCurveStep"): - spin = dialog.findChild(QtWidgets.QSpinBox, object_name) - assert spin is not None - assert (spin.minimum(), spin.maximum(), spin.singleStep()) == (1, 180, 1) - - -@pytest.mark.parametrize("language", ("zh", "en", "ja")) -@pytest.mark.parametrize("dialog_size", ((920, 600), (820, 540))) -def test_compact_layout_balances_configuration_rail_and_axis_panel( - qapp, tmp_path: Path, language: str, dialog_size: tuple[int, int] -) -> None: - compact_dialog = PerformanceReportDialog( - None, - language=language, - initial_directory=tmp_path, - azimuth_available=True, - elevation_available=True, - ) - compact_dialog.setStyleSheet(application_stylesheet()) - compact_dialog.resize(*dialog_size) - compact_dialog.show() - qapp.processEvents() - - try: - rail = compact_dialog.findChild( - QtWidgets.QScrollArea, "performanceReportRail" - ) - rail_content = compact_dialog.findChild( - QtWidgets.QWidget, "performanceReportRailContent" - ) - content = compact_dialog.findChild( - QtWidgets.QWidget, "performanceReportContent" - ) - output_group = compact_dialog.findChild( - QtWidgets.QGroupBox, "reportOutputGroup" - ) - settings_group = compact_dialog.findChild( - QtWidgets.QGroupBox, "reportPerformanceSettingsGroup" - ) - - assert rail is not None - assert rail_content is not None - assert content is not None - assert output_group is not None - assert settings_group is not None - assert compact_dialog.size() == QtCore.QSize(*dialog_size) - assert rail.geometry().right() < content.geometry().left() - assert output_group.parentWidget() is rail_content - assert settings_group.parentWidget() is rail_content - assert settings_group.geometry().top() > output_group.geometry().bottom() - assert compact_dialog.title_edit.isVisibleTo(compact_dialog) - assert compact_dialog.title_edit.width() >= 120 - assert output_group.contentsRect().contains( - compact_dialog.title_edit.geometry() - ) - QtTest.QTest.mouseClick( - compact_dialog.title_edit, - QtCore.Qt.MouseButton.LeftButton, - ) - assert compact_dialog.title_edit.hasFocus() - QtTest.QTest.keyClick( - compact_dialog.title_edit, - QtCore.Qt.Key.Key_A, - QtCore.Qt.KeyboardModifier.ControlModifier, - ) - QtTest.QTest.keyClicks(compact_dialog.title_edit, "Editable report title") - assert compact_dialog.title_edit.text() == "Editable report title" - assert rail.horizontalScrollBar().maximum() == 0 - assert compact_dialog.azimuth_page.horizontalScrollBar().maximum() == 0 - assert compact_dialog.button_box.geometry().bottom() <= compact_dialog.rect().bottom() - finally: - compact_dialog.close() - compact_dialog.deleteLater() - qapp.processEvents() - - -@pytest.mark.parametrize("language", ("zh", "en", "ja")) -def test_themed_angle_rows_keep_clear_vertical_separation( - qapp, tmp_path: Path, language: str -) -> None: - themed_dialog = PerformanceReportDialog( - None, - language=language, - initial_directory=tmp_path, - azimuth_available=True, - elevation_available=True, - ) - themed_dialog.setStyleSheet(application_stylesheet()) - themed_dialog.resize(780, 700) - themed_dialog.show() - qapp.processEvents() - - try: - for tab_index, (axis, group, page) in enumerate( - ( - ("az", themed_dialog.azimuth_group, themed_dialog.azimuth_page), - ("el", themed_dialog.elevation_group, themed_dialog.elevation_page), - ) - ): - themed_dialog.axis_tabs.setCurrentIndex(tab_index) - qapp.processEvents() - grid = group.layout() - assert isinstance(grid, QtWidgets.QGridLayout) - assert grid.verticalSpacing() == 8 - assert group.height() >= group.minimumSizeHint().height() - assert page.horizontalScrollBar().maximum() == 0 - - focus = getattr(themed_dialog, f"{axis}_focus_start") - hold = getattr(themed_dialog, f"{axis}_hold_start") - gap = hold.geometry().top() - (focus.geometry().bottom() + 1) - assert gap >= 6 - assert focus.height() >= 37 - assert hold.height() >= 37 - finally: - themed_dialog.close() - themed_dialog.deleteLater() - qapp.processEvents() - - -def test_hold_range_follows_focus_until_user_requests_independent_range( - dialog: PerformanceReportDialog, -) -> None: - dialog.az_focus_start.setValue(-32) - dialog.az_focus_stop.setValue(48) - assert (dialog.az_hold_start.value(), dialog.az_hold_stop.value()) == (-32, 48) - assert "81" in dialog.az_hold_frame_count.text() - - dialog.az_hold_follows_focus.setChecked(False) - assert dialog.az_hold_start.isEnabled() - assert dialog.az_hold_stop.isEnabled() - dialog.az_hold_start.setValue(-10) - dialog.az_hold_stop.setValue(12) - dialog.az_focus_start.setValue(-25) - assert (dialog.az_hold_start.value(), dialog.az_hold_stop.value()) == (-10, 12) - assert "23" in dialog.az_hold_frame_count.text() - - dialog.az_hold_follows_focus.setChecked(True) - assert not dialog.az_hold_start.isEnabled() - assert (dialog.az_hold_start.value(), dialog.az_hold_stop.value()) == (-25, 48) - - -def test_hold_curve_interval_updates_plotted_curve_preview_and_options( - dialog: PerformanceReportDialog, -) -> None: - dialog.az_focus_start.setValue(-10) - dialog.az_focus_stop.setValue(12) - dialog.az_hold_curve_step.setValue(5) - - assert "范围内 23 帧" in dialog.az_hold_frame_count.text() - assert "每 5°(5 帧)" in dialog.az_hold_frame_count.text() - assert "共 6 条" in dialog.az_hold_frame_count.text() - assert "起止角均保留" in dialog.az_hold_frame_count.text() - - dialog.el_hold_curve_step.setValue(4) - options = dialog.options() - assert options.azimuth_hold_stride_frames == 5 - assert options.elevation_hold_stride_frames == 4 - - -def test_invalid_range_shows_inline_error_and_prevents_accept( - dialog: PerformanceReportDialog, qapp, -) -> None: - requests: list[str] = [] - dialog.export_requested.connect(requests.append) - dialog.open() - qapp.processEvents() - - dialog.az_focus_start.setValue(30) - dialog.az_focus_stop.setValue(20) - - assert dialog.validation_label.isVisibleTo(dialog) - assert "起始角不能大于终止角" in dialog.validation_label.text() - dialog.save_button.click() - assert requests == [] - assert dialog.isVisible() - assert dialog.result() != QtWidgets.QDialog.DialogCode.Accepted - - dialog.az_focus_stop.setValue(40) - assert not dialog.validation_label.isVisibleTo(dialog) - dialog.save_button.click() - qapp.processEvents() - assert requests == ["report"] - assert dialog.isVisible() - assert dialog.result() != QtWidgets.QDialog.DialogCode.Accepted - - -def test_at_least_one_spectrum_vertical_scale_is_required( - dialog: PerformanceReportDialog, -) -> None: - dialog.include_spectrum_db_checkbox.setChecked(False) - - assert dialog.validation_label.isVisibleTo(dialog) - assert "至少选择一种" in dialog.validation_label.text() - assert "dB" in dialog.validation_label.text() - assert "模值" in dialog.validation_label.text() - assert not dialog.save_button.isEnabled() - assert dialog.angle_image_button.isEnabled() - assert not dialog.spectrum_floor_spin.isEnabled() - - dialog.include_spectrum_magnitude_checkbox.setChecked(True) - assert not dialog.validation_label.isVisibleTo(dialog) - assert dialog.save_button.isEnabled() - - options = dialog.options() - assert options.include_spectrum_db is False - assert options.include_spectrum_magnitude is True - - dialog.include_spectrum_db_checkbox.setChecked(True) - assert dialog.spectrum_floor_spin.isEnabled() - options = dialog.options() - assert options.include_spectrum_db is True - assert options.include_spectrum_magnitude is True - - -def test_axis_capability_disables_irrelevant_controls_and_report_action( - qapp, tmp_path: Path -) -> None: - azimuth_only = PerformanceReportDialog( - None, - language="en", - initial_directory=tmp_path, - azimuth_available=True, - elevation_available=False, - ) - try: - assert azimuth_only.azimuth_group.isEnabled() - assert not azimuth_only.elevation_group.isEnabled() - assert azimuth_only.save_button.isEnabled() - assert azimuth_only.angle_image_button.isEnabled() - - options = azimuth_only.options() - assert options.azimuth_focus.start_deg == -70 - assert options.azimuth_focus.stop_deg == 70 - assert options.elevation_focus.start_deg == -15 - assert options.elevation_focus.stop_deg == 15 - assert options.elevation_hold.start_deg == -15 - assert options.elevation_hold.stop_deg == 15 - assert options.azimuth_hold_stride_frames == 1 - assert options.elevation_hold_stride_frames == 1 - finally: - azimuth_only.close() - azimuth_only.deleteLater() - - no_axis = PerformanceReportDialog( - None, - language="ja", - initial_directory=tmp_path, - azimuth_available=False, - elevation_available=False, - ) - try: - no_axis.setStyleSheet(application_stylesheet()) - no_axis.resize(920, 600) - no_axis.show() - qapp.processEvents() - - assert not no_axis.azimuth_group.isEnabled() - assert not no_axis.elevation_group.isEnabled() - assert not no_axis.save_button.isEnabled() - assert not no_axis.angle_image_button.isEnabled() - rail = no_axis.findChild(QtWidgets.QScrollArea, "performanceReportRail") - assert rail.horizontalScrollBar().maximum() == 0 - assert rail.verticalScrollBar().maximum() == 0 - assert no_axis.validation_label.parentWidget() is no_axis - assert no_axis.validation_label.geometry().bottom() < ( - no_axis.button_box.geometry().top() - ) - finally: - no_axis.close() - no_axis.deleteLater() - - -@pytest.mark.parametrize( - ( - "language", - "title_fragment", - "save_text", - "cancel_text", - "magnitude_text", - "hold_count_fragment", - ), - ( - ("zh", "性能报告", "输出报告", "取消", "模值", "范围内 141 帧"), - ( - "en", - "Performance Report", - "Export report", - "Cancel", - "Magnitude", - "141 frames in range", - ), - ( - "ja", - "性能レポート", - "レポートを出力", - "キャンセル", - "振幅値", - "範囲内 141 フレーム", - ), - ), -) -def test_all_supported_languages_are_applied( - qapp, - tmp_path: Path, - language: str, - title_fragment: str, - save_text: str, - cancel_text: str, - magnitude_text: str, - hold_count_fragment: str, -) -> None: - del qapp - widget = PerformanceReportDialog( - None, - language=language, - initial_directory=tmp_path, - azimuth_available=True, - elevation_available=True, - ) - try: - assert title_fragment in widget.windowTitle() - assert widget.save_button.text() == save_text - assert widget.cancel_button.text() == cancel_text - assert "PNG" in widget.angle_image_button.text() - assert widget.include_spectrum_db_checkbox.text() == "dB" - assert widget.include_spectrum_magnitude_checkbox.text() == magnitude_text - assert hold_count_fragment in widget.az_hold_frame_count.text() - assert widget.options().language == language - finally: - widget.close() - widget.deleteLater() - - -def test_browse_and_report_request_normalise_pdf_suffix_without_closing( - qapp, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - selected_without_suffix = tmp_path / "custom-report" - monkeypatch.setattr( - QtWidgets.QFileDialog, - "getSaveFileName", - staticmethod(lambda *_args, **_kwargs: (str(selected_without_suffix), "")), - ) - widget = PerformanceReportDialog( - None, - language="zh", - initial_directory=tmp_path, - azimuth_available=True, - elevation_available=True, - ) - try: - requests: list[str] = [] - widget.export_requested.connect(requests.append) - widget.open() - qapp.processEvents() - - widget.browse_button.click() - expected = selected_without_suffix.with_suffix(".pdf") - assert Path(widget.output_path_edit.text()) == expected - assert not expected.exists() - - widget.save_button.click() - qapp.processEvents() - assert requests == ["report"] - assert widget.isVisible() - assert widget.result() != QtWidgets.QDialog.DialogCode.Accepted - options = widget.options() - assert options.output_path == expected - assert options.error_limit_deg == pytest.approx(1.0) - assert options.spectrum_floor_db == pytest.approx(-40.0) - assert options.include_spectrum_db is True - assert options.include_spectrum_magnitude is False - assert options.include_raw_data is True - assert options.azimuth_hold_stride_frames == 1 - assert options.elevation_hold_stride_frames == 1 - assert not expected.exists() - finally: - widget.close() - widget.deleteLater() - - -def test_report_then_angle_image_requests_keep_same_dialog_and_configuration( - qapp, - tmp_path: Path, -) -> None: - report_path = tmp_path / "delivery" / "custom-report.pdf" - expected_image_path = report_path.with_name("custom-report_angle_error.png") - widget = PerformanceReportDialog( - None, - language="en", - initial_directory=tmp_path, - azimuth_available=True, - elevation_available=False, - ) - try: - requests: list[str] = [] - widget.export_requested.connect(requests.append) - widget.open() - qapp.processEvents() - - original_identity = id(widget) - widget.output_path_edit.setText(str(report_path)) - widget.title_edit.setText("Sequential export settings") - widget.error_limit_spin.setValue(7.5) - widget.az_focus_start.setValue(-44) - widget.az_focus_stop.setValue(51) - widget.az_hold_curve_step.setValue(5) - - assert widget.save_button.isEnabled() - assert widget.angle_image_button.isEnabled() - - widget.save_button.click() - qapp.processEvents() - report_options = widget.options() - - assert requests == ["report"] - assert id(widget) == original_identity - assert widget.isVisible() - assert widget.result() != QtWidgets.QDialog.DialogCode.Accepted - assert report_options.output_path == report_path - assert report_options.title == "Sequential export settings" - assert report_options.error_limit_deg == pytest.approx(7.5) - assert report_options.azimuth_focus.start_deg == -44 - assert report_options.azimuth_focus.stop_deg == 51 - assert report_options.azimuth_hold_stride_frames == 5 - - # Model one completed worker cycle before requesting the second export. - widget.set_export_busy(True) - widget.set_export_busy(False) - widget.angle_image_button.click() - qapp.processEvents() - - assert requests == ["report", "angle_image"] - assert id(widget) == original_identity - assert widget.isVisible() - assert widget.result() != QtWidgets.QDialog.DialogCode.Accepted - assert widget.export_kind == "angle_image" - options = widget.angle_error_image_options() - assert options.output_path == expected_image_path - assert options.output_path.parent == report_path.parent - assert options.error_limit_deg == pytest.approx(7.5) - assert options.language == "en" - assert widget.options() == report_options - assert not report_path.exists() - assert not expected_image_path.exists() - finally: - widget.close() - widget.deleteLater() - - -def test_busy_state_blocks_export_and_close_then_restores_valid_actions( - dialog: PerformanceReportDialog, qapp, -) -> None: - requests: list[str] = [] - dialog.export_requested.connect(requests.append) - dialog.open() - qapp.processEvents() - - # The report is invalid without a spectrum scale, while standalone PNG - # export remains valid. Restoration must preserve that distinction. - dialog.include_spectrum_db_checkbox.setChecked(False) - dialog.include_spectrum_magnitude_checkbox.setChecked(False) - assert not dialog.save_button.isEnabled() - assert dialog.angle_image_button.isEnabled() - - dialog.set_export_busy(True) - assert not dialog.save_button.isEnabled() - assert not dialog.angle_image_button.isEnabled() - assert not dialog.cancel_button.isEnabled() - - dialog.save_button.click() - dialog.angle_image_button.click() - dialog.reject() - assert dialog.close() is False - QtTest.QTest.keyClick(dialog, QtCore.Qt.Key.Key_Escape) - qapp.processEvents() - - assert requests == [] - assert dialog.isVisible() - - dialog.set_export_busy(False) - assert not dialog.save_button.isEnabled() - assert dialog.angle_image_button.isEnabled() - assert dialog.cancel_button.isEnabled() - - dialog.cancel_button.click() - qapp.processEvents() - assert not dialog.isVisible() diff --git a/tests/test_project.py b/tests/test_project.py new file mode 100644 index 0000000..86596f3 --- /dev/null +++ b/tests/test_project.py @@ -0,0 +1,146 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pytest +from pydantic import ValidationError + +from virtual_array.examples.case4_5tx7rx_sel import build_array +from virtual_array.project import ( + Layout, + Point, + Project, + auto_layout, + default_project, + layout_from_v1, + layout_to_v1, + project_array, + project_from_document, + snap_lambda, +) + +EXAMPLES = Path(__file__).resolve().parents[1] / "examples" + + +def test_default_project_matches_case4_reference_array() -> None: + array = project_array(default_project()) + reference = build_array() + + assert np.array_equal(array.tx_xy(), reference.tx_xy()) + assert np.array_equal(array.rx_xy(), reference.rx_xy()) + assert [point.name for point in array.tx] == [point.name for point in reference.tx] + + +def test_layout_v1_example_imports_with_lambda_coordinates() -> None: + document = json.loads((EXAMPLES / "antenna_layout_config.json").read_text(encoding="utf-8")) + + layout = layout_from_v1(document) + + assert len(layout.tx) == 8 + assert layout.tx[4] == Point(x=1.5, y=-12) + assert layout.rx[6] == Point(x=9, y=5) + + +def test_layout_v1_snaps_to_half_lambda_grid_and_accepts_legacy_unit() -> None: + layout = layout_from_v1( + { + "version": 1, + "unit": "λ/2", + "tx": [{"name": "A", "x": 3, "y": -1.2}], + "rx": [{"x": 0.4, "y": 0}], + } + ) + + assert layout.tx[0] == Point(x=1.5, y=-0.5) + assert layout.rx[0] == Point(x=0.0, y=0.0) + + +@pytest.mark.parametrize( + "document, message", + [ + ({"version": 3}, "Unsupported layout version"), + ({"version": 1, "unit": "mm", "tx": [], "rx": []}, "unit"), + ({"version": 1, "unit": "lambda", "tx": [], "rx": [{"x": 0, "y": 0}]}, "non-empty"), + ( + {"version": 1, "unit": "lambda", "tx": [{"x": 0}], "rx": [{"x": 0, "y": 0}]}, + "missing coordinate", + ), + ( + { + "version": 1, + "unit": "lambda", + "tx": [{"x": i, "y": 0} for i in range(17)], + "rx": [{"x": 0, "y": 0}], + }, + "maximum is 16", + ), + ], +) +def test_layout_v1_rejects_invalid_documents(document: dict, message: str) -> None: + with pytest.raises(ValueError, match=message): + layout_from_v1(document) + + +def test_layout_v1_round_trip_preserves_coordinates_and_names() -> None: + project = default_project() + + document = layout_to_v1(project) + + assert document["unit"] == "lambda" + assert document["tx"][0] == {"name": "Tx1", "x": 0, "y": 0} + assert document["rx"][5] == {"name": "Rx6", "x": 12, "y": -7} + assert layout_from_v1(document) == project.layout + + +def test_project_from_v1_document_reads_evaluation_settings() -> None: + document = layout_to_v1(default_project()) + document["evaluation"] = {"frequency_ghz": "79", "ambiguity_margin_db": 1.5} + + project = project_from_document(document) + + assert project.frequency_ghz == 79.0 + assert project.ambiguity_margin_db == 1.5 + + +def test_project_from_v2_document_round_trips() -> None: + project = default_project().model_copy(update={"name": "demo", "frequency_ghz": 24.125}) + + restored = project_from_document(project.model_dump(mode="json")) + + assert restored == project + + +def test_auto_layout_centers_rows_on_half_lambda_grid() -> None: + layout = auto_layout(3, 4) + + assert [point.x for point in layout.tx] == [-1.0, 0.0, 1.0] + assert [point.x for point in layout.rx] == [-1.5, -0.5, 0.5, 1.5] + assert {point.y for point in layout.tx} == {2.0} + assert {point.y for point in layout.rx} == {-2.0} + with pytest.raises(ValueError): + auto_layout(0, 4) + + +def test_project_validation_rejects_bad_values() -> None: + layout = Layout(tx=[Point(x=0, y=0)], rx=[Point(x=0, y=0)]) + with pytest.raises(ValidationError): + Project(layout=layout, frequency_ghz=0) + with pytest.raises(ValidationError): + Project(layout=layout, dbf_dictionary={"mode": "custom"}) + with pytest.raises(ValidationError): + Point(x=float("nan"), y=0) + + +def test_legacy_zero_ref_dictionary_mode_is_folded_into_channel_pattern() -> None: + layout = Layout(tx=[Point(x=0, y=0)], rx=[Point(x=0, y=0)]) + + project = Project(layout=layout, dbf_dictionary={"mode": "channel_pattern_zero_ref"}) + + assert project.dbf_dictionary.mode == "channel_pattern" + + +def test_snap_lambda_avoids_negative_zero() -> None: + assert str(snap_lambda(-0.1)) == "0.0" + assert snap_lambda(0.76) == 1.0 diff --git a/tests/test_qt_gui_smoke.py b/tests/test_qt_gui_smoke.py deleted file mode 100644 index b082592..0000000 --- a/tests/test_qt_gui_smoke.py +++ /dev/null @@ -1,1424 +0,0 @@ -from __future__ import annotations - -import json -import os -from pathlib import Path -from types import SimpleNamespace - -import numpy as np -import pytest - - -# This must be selected before QApplication is created by any GUI import. -os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") - -QtWidgets = pytest.importorskip("PySide6.QtWidgets") -QtCore = pytest.importorskip("PySide6.QtCore") -QtGui = pytest.importorskip("PySide6.QtGui") -QtTest = pytest.importorskip("PySide6.QtTest") - -from scripts.capture_ui_review import ( # noqa: E402 - close_gui_session, - create_gui_session, - locate_page_navigator, - process_events, - render_widget, -) -from virtual_array.qt_tk import AppleSwitch # noqa: E402 - - -@pytest.fixture(scope="module") -def isolated_appdata(tmp_path_factory: pytest.TempPathFactory): - path = tmp_path_factory.mktemp("qt-gui-appdata") - previous = { - name: os.environ.get(name) for name in ("APPDATA", "LOCALAPPDATA") - } - os.environ["APPDATA"] = str(path) - os.environ["LOCALAPPDATA"] = str(path) - try: - yield path - finally: - for name, value in previous.items(): - if value is None: - os.environ.pop(name, None) - else: - os.environ[name] = value - - -@pytest.fixture(scope="module") -def gui_session(isolated_appdata: Path): - del isolated_appdata - session = create_gui_session() - try: - yield session - finally: - close_gui_session(session) - - -def _main_tab_labels(session) -> list[str]: - navigator = locate_page_navigator(session) - assert navigator is not None, "canonical GUI must expose its main page navigator" - tab_source = navigator.tab_widget or navigator.tab_bar - assert tab_source is not None, "main pages must expose visible tab labels" - return [ - str(tab_source.tabText(index)).replace("&&", "&") - for index in range(navigator.count) - ] - - -def _visible_dialogs(session) -> list: - return [ - widget - for widget in session.app.topLevelWidgets() - if isinstance(widget, QtWidgets.QDialog) and widget.isVisible() - ] - - -def _open_modeless_dialog(session, invocation) -> object: - baseline = {id(dialog) for dialog in _visible_dialogs(session)} - invocation() - process_events(session.app, cycles=6) - opened = [ - dialog for dialog in _visible_dialogs(session) if id(dialog) not in baseline - ] - assert opened, "dialog action must create and show a QDialog" - return opened[-1] - - -def _close_with_standard_button(session, dialog, standard_button) -> None: - boxes = dialog.findChildren(QtWidgets.QDialogButtonBox) - buttons = [box.button(standard_button) for box in boxes] - buttons = [button for button in buttons if button is not None] - assert buttons, f"dialog must expose {standard_button!r} through QDialogButtonBox" - buttons[-1].click() - process_events(session.app, cycles=5) - assert all(candidate is not dialog for candidate in _visible_dialogs(session)) - - -def _sample_element_pattern(): - from virtual_array.element_pattern import ElementPattern - - angles = np.linspace(-90.0, 90.0, 181) - horizontal = -np.minimum((angles / 27.0) ** 2 * 3.0, 35.0) - elevation = -np.minimum((angles / 34.0) ** 2 * 3.0, 35.0) - return ElementPattern( - name="Qt dialog smoke pattern", - source_path="qt-dialog-smoke.csv", - angle_column="Angle", - horizontal_column="Az Gain", - elevation_column="El Gain", - angles_deg=angles, - horizontal_gain_db=horizontal, - elevation_gain_db=elevation, - ) - - -@pytest.mark.parametrize( - "width,height", - [ - (1024, 650), - (1100, 650), - (1280, 720), - (1366, 768), - (1920, 1080), - ], -) -def test_canonical_gui_renders_at_target_sizes( - gui_session, tmp_path: Path, width: int, height: int -) -> None: - window = gui_session.window - assert isinstance(window, QtWidgets.QWidget) - - window.resize(width, height) - process_events(gui_session.app, cycles=6) - - assert window.isVisible() - assert (window.width(), window.height()) == (width, height), ( - "the resizable workspace must preserve the requested logical size; " - "layout minimums must not silently enlarge it" - ) - screenshot = render_widget(window, tmp_path / f"main-{width}x{height}.png") - assert screenshot.stat().st_size > 1_000 - - -def test_header_frequency_keeps_common_values_visible_at_compact_width( - gui_session, -) -> None: - controller = gui_session.controller - window = gui_session.window - original_language = controller.language - original_frequency = controller.current_frequency_ghz() - original_size = window.size() - - try: - window.resize(1024, 650) - for language in ("zh", "en", "ja"): - controller.set_language(language) - for frequency in (24.0, 77.0, 999.0): - controller._set_frequency_ghz(frequency) - controller._refresh_workspace_header() - process_events(gui_session.app, cycles=3) - - value_label = controller.header_chip_value_labels[ - "chip_frequency" - ]._qt - expected = f"{int(frequency)} GHz" - assert value_label.text() == expected - assert value_label.toolTip() == expected - assert value_label.fontMetrics().horizontalAdvance(expected) <= ( - value_label.width() - ) - - controller._set_frequency_ghz(12345.123456) - controller._refresh_workspace_header() - process_events(gui_session.app, cycles=3) - value_label = controller.header_chip_value_labels["chip_frequency"]._qt - assert value_label.text() != value_label.toolTip() - assert value_label.toolTip() == "12345.123456 GHz" - - chip_row = value_label.parentWidget().parentWidget() - assert controller.header_title_group._qt.geometry().right() < ( - chip_row.geometry().left() - ) - assert window.size() == QtCore.QSize(1024, 650) - finally: - controller.set_language(original_language) - controller._set_frequency_ghz(original_frequency) - controller._refresh_workspace_header() - window.resize(original_size) - process_events(gui_session.app, cycles=4) - - -def test_canonical_gui_exposes_and_switches_three_main_pages( - gui_session, tmp_path: Path -) -> None: - navigator = locate_page_navigator(gui_session) - assert navigator is not None, "canonical GUI must expose its main page navigator" - assert navigator.count >= 3 - - for index in range(3): - navigator.select(index) - process_events(gui_session.app, cycles=5) - assert navigator.current_index == index - screenshot = render_widget(gui_session.window, tmp_path / f"page-{index}.png") - assert screenshot.stat().st_size > 1_000 - - -def test_canonical_gui_keeps_key_workspace_and_dialog_controls(gui_session) -> None: - controller = gui_session.controller - window = gui_session.window - - # Plot attributes are stable across the compatibility and native Qt shells. - assert getattr(controller, "phys_canvas", None) is not None - assert getattr(controller, "virt_canvas", None) is not None - assert getattr(controller, "az_chart", None) is not None - assert getattr(controller, "el_chart", None) is not None - - assert len(window.findChildren(QtWidgets.QAbstractButton)) >= 3 - assert len(window.findChildren(QtWidgets.QLineEdit)) >= 2 - for method_name in ( - "open_dbf_dictionary_dialog", - "open_channel_patterns_dialog", - "open_performance_report_dialog", - "_show_user_manual_dialog", - ): - assert callable(getattr(controller, method_name, None)) - - -def test_native_shell_exposes_shortcuts_focus_and_splitter(gui_session) -> None: - from PySide6 import QtCore, QtGui - - controller = gui_session.controller - window = gui_session.window - - assert isinstance(controller.native_menu_bar, QtWidgets.QMenuBar) - assert isinstance(controller.native_status_bar, QtWidgets.QStatusBar) - assert isinstance(controller.workspace_splitter, QtWidgets.QSplitter) - assert controller.workspace_splitter.handleWidth() >= 6 - - for key in ( - "menu_import_layout", - "menu_export_layout", - "menu_undo", - "menu_redo", - ): - action = controller.native_actions[key] - assert isinstance(action, QtGui.QAction) - assert not action.shortcut().isEmpty() - assert "menu_export_report" in controller.native_actions - report_action = controller.native_actions["menu_export_report"] - assert isinstance(report_action, QtGui.QAction) - assert report_action in controller.native_menus["menu_file"].actions() - assert report_action.menu() is None - assert "menu_export_angle_error_image" not in controller.native_actions - assert isinstance(controller.native_manual_menu, QtWidgets.QMenu) - assert len(controller.native_manual_chapter_actions) == 12 - assert controller.native_actions["menu_user_manual_open"].shortcut() == ( - QtGui.QKeySequence(QtGui.QKeySequence.StandardKey.HelpContents) - ) - - assert controller.auto_apply_button._qt.property("fluentRole") == "primary" - focusable = window.findChildren(QtWidgets.QLineEdit) + window.findChildren( - QtWidgets.QAbstractButton - ) - assert focusable - assert all( - widget.focusPolicy() != QtCore.Qt.FocusPolicy.NoFocus - for widget in focusable - if widget.isEnabled() and widget.isVisible() - ) - assert controller.main_notebook._qt.tabBar().accessibleName() - - -def test_report_dialog_reuses_one_instance_for_sequential_report_and_png_exports( - gui_session, - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, -) -> None: - from virtual_array.performance_report import ( - generate_angle_error_image, - generate_performance_report, - ) - - controller = gui_session.controller - report_dir = tmp_path / "reports" - report_dir.mkdir() - report_path = report_dir / "custom-report.pdf" - report_path.write_bytes(b"existing report placeholder") - image_path = report_dir / "custom-report_angle_error.png" - captured: list[dict[str, object]] = [] - overwrite_parents: list[QtWidgets.QWidget] = [] - busy_observations: list[bool] = [] - snapshot = object() - - monkeypatch.setattr(controller, "last_report_dir", report_dir) - monkeypatch.setattr(controller, "last_report_error_limit_deg", 7.5) - monkeypatch.setattr( - controller, - "current_metrics", - SimpleNamespace( - x_aperture=1.0, - azimuth_resolution=1.0, - y_aperture=0.0, - elevation_resolution=None, - ), - ) - monkeypatch.setattr(controller, "_performance_report_snapshot", lambda: snapshot) - - def start_export(generator, frozen_snapshot, options, *, export_kind="report"): - export_parent = controller._performance_export_parent - assert export_parent is controller._performance_report_dialog - busy_observations.append( - not export_parent.save_button.isEnabled() - and not export_parent.angle_image_button.isEnabled() - and not export_parent.cancel_button.isEnabled() - ) - captured.append( - { - "generator": generator, - "snapshot": frozen_snapshot, - "options": options, - "export_kind": export_kind, - } - ) - # Stand in for thread.finished so this test can issue the next request. - export_parent.set_export_busy(False) - controller._performance_export_parent = None - - def confirm_overwrite(parent, *_args, **_kwargs): - overwrite_parents.append(parent) - return QtWidgets.QMessageBox.StandardButton.Yes - - monkeypatch.setattr(QtWidgets.QMessageBox, "question", confirm_overwrite) - monkeypatch.setattr( - gui_session.gui_module, - "fit_dialog_to_parent", - lambda *_args, **_kwargs: None, - ) - monkeypatch.setattr(controller, "_start_performance_report_export", start_export) - - dialog = None - try: - controller.open_performance_report_dialog() - process_events(gui_session.app, cycles=5) - dialog = controller._performance_report_dialog - assert isinstance(dialog, QtWidgets.QDialog) - assert dialog.isVisible() - assert dialog.error_limit_spin.value() == pytest.approx(7.5) - - # Invoking the menu again raises the existing form instead of resetting it. - original_identity = id(dialog) - controller.open_performance_report_dialog() - process_events(gui_session.app, cycles=2) - assert controller._performance_report_dialog is dialog - assert id(controller._performance_report_dialog) == original_identity - - dialog.output_path_edit.setText(str(report_path)) - dialog.title_edit.setText("Keep these settings") - dialog.error_limit_spin.setValue(7.5) - dialog.az_focus_start.setValue(-43) - dialog.az_focus_stop.setValue(52) - - dialog.save_button.click() - process_events(gui_session.app, cycles=3) - assert dialog.isVisible() - assert dialog.save_button.isEnabled() - - dialog.angle_image_button.click() - process_events(gui_session.app, cycles=3) - - assert dialog.isVisible() - assert controller._performance_report_dialog is dialog - assert [item["export_kind"] for item in captured] == [ - "report", - "angle_image", - ] - assert [item["generator"] for item in captured] == [ - generate_performance_report, - generate_angle_error_image, - ] - assert all(item["snapshot"] is snapshot for item in captured) - assert busy_observations == [True, True] - assert overwrite_parents == [dialog] - - report_options = captured[0]["options"] - image_options = captured[1]["options"] - assert report_options.output_path == report_path - assert report_options.title == "Keep these settings" - assert report_options.error_limit_deg == pytest.approx(7.5) - assert report_options.azimuth_focus.start_deg == -43 - assert report_options.azimuth_focus.stop_deg == 52 - assert image_options.output_path == image_path - assert image_options.output_path.parent == report_dir - assert image_options.error_limit_deg == pytest.approx(7.5) - assert dialog.title_edit.text() == "Keep these settings" - assert (dialog.az_focus_start.value(), dialog.az_focus_stop.value()) == ( - -43, - 52, - ) - assert controller.last_report_dir == report_dir - assert controller.last_report_error_limit_deg == pytest.approx(7.5) - finally: - if dialog is not None: - dialog.set_export_busy(False) - dialog.reject() - process_events(gui_session.app, cycles=4) - controller._performance_export_parent = None - gui_session.window.activateWindow() - process_events(gui_session.app, cycles=3) - - -def test_carbon_workbench_theme_and_primary_interactions_are_explicit(gui_session) -> None: - from PySide6 import QtGui - - from virtual_array.native_theme import ( - AppleTokens, - TOKENS, - WorkbenchTokens, - application_stylesheet, - ) - - controller = gui_session.controller - stylesheet = application_stylesheet() - - assert isinstance(TOKENS, WorkbenchTokens) - assert AppleTokens is WorkbenchTokens # backwards-compatible public alias - assert TOKENS.canvas == "#f4f4f4" - assert TOKENS.accent == "#0f62fe" - assert TOKENS.primary_fill == "#0f62fe" - assert TOKENS.radius <= 4 - assert TOKENS.card_radius <= 4 - assert "QPushButton:focus" in stylesheet - assert "QScrollBar:vertical" in stylesheet - assert "QTabBar::tab:selected" in stylesheet - assert f"border: 1px solid {TOKENS.control_border}" in stylesheet - - def contrast_ratio(first: str, second: str) -> float: - def luminance(value: str) -> float: - color = QtGui.QColor(value) - channels = [] - for channel in (color.redF(), color.greenF(), color.blueF()): - channels.append( - channel / 12.92 - if channel <= 0.04045 - else ((channel + 0.055) / 1.055) ** 2.4 - ) - return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2] - - lighter, darker = sorted((luminance(first), luminance(second)), reverse=True) - return (lighter + 0.05) / (darker + 0.05) - - assert contrast_ratio(TOKENS.control_border, TOKENS.surface) >= 3.0 - assert contrast_ratio(TOKENS.primary_fill, "#ffffff") >= 4.5 - assert f"background: {TOKENS.primary_fill}" in stylesheet - - assert controller.auto_apply_button._qt.isDefault() - assert controller.physical_action_buttons["physical_delete"]._qt.isCheckable() - assert controller.az_chart.play_button._qt.isCheckable() - assert controller.el_chart.play_button._qt.isCheckable() - assert controller.dbf2d_az_button._qt.isCheckable() - assert controller.dbf2d_el_button._qt.isCheckable() - assert callable(controller.phys_canvas.grab_pointer) - assert callable(controller.phys_canvas.release_pointer) - - cancelled_events = [] - callback_id = controller.phys_canvas.mpl_connect( - "pointer_cancel_event", cancelled_events.append - ) - controller.phys_canvas._captured_axis = controller.physical_ax - try: - controller.phys_canvas.eventFilter( - controller.phys_canvas, - QtCore.QEvent(QtCore.QEvent.Type.UngrabMouse), - ) - assert len(cancelled_events) == 1 - assert cancelled_events[0].inaxes is controller.physical_ax - assert controller.phys_canvas._captured_axis is None - finally: - controller.phys_canvas.mpl_disconnect(callback_id) - - original_delete_mode = controller.delete_mode - try: - controller.delete_mode = True - controller._update_delete_button_state() - delete_stylesheet = controller.physical_action_buttons[ - "physical_delete" - ]._qt.styleSheet() - assert TOKENS.danger_fill in delete_stylesheet - assert TOKENS.danger in delete_stylesheet - finally: - controller.delete_mode = original_delete_mode - controller._update_delete_button_state() - - -def test_callout_role_updates_do_not_grow_local_stylesheets(gui_session) -> None: - from virtual_array.native_theme import mark_callout - - label = QtWidgets.QLabel("Quality") - label.setStyleSheet("QLabel { color: black; }") - lengths = [] - for _cycle in range(5): - for role in ("neutral", "success", "warning", "danger"): - mark_callout(label, role) - lengths.append(len(label.styleSheet())) - assert len(set(lengths[4:])) <= 4 - assert max(lengths) < 500 - label.deleteLater() - process_events(gui_session.app, cycles=2) - - -def test_toolbar_selectors_and_evaluation_metrics_use_continuous_surfaces( - gui_session, -) -> None: - from virtual_array.gui import THEME - - controller = gui_session.controller - process_events(gui_session.app, cycles=2) - - assert THEME["metric_bg"] == THEME["card_bg"] - for radio in ( - controller.dbf_display_db_radio, - controller.dbf_display_mag_radio, - ): - assert radio is not None - stylesheet = radio._qt.styleSheet() - assert f"background-color: {THEME['status_bar_bg']}" in stylesheet - assert "background-color: transparent" not in stylesheet - assert "border:" not in stylesheet - assert radio.cget("style") == "Toolbar.TRadiobutton" - assert ( - radio._qt.cursor().shape() - == QtCore.Qt.CursorShape.PointingHandCursor - ) - - unselected_radio = next( - radio._qt - for radio in ( - controller.dbf_display_db_radio, - controller.dbf_display_mag_radio, - ) - if not radio._qt.isChecked() - ) - option = QtWidgets.QStyleOptionButton() - unselected_radio.initStyleOption(option) - indicator = unselected_radio.style().subElementRect( - QtWidgets.QStyle.SubElement.SE_RadioButtonIndicator, - option, - unselected_radio, - ) - image = QtGui.QImage( - unselected_radio.size(), - QtGui.QImage.Format.Format_ARGB32_Premultiplied, - ) - image.fill(QtGui.QColor(THEME["status_bar_bg"])) - unselected_radio.render(image) - visible_indicator_pixels = sum( - 1 - for y in range(indicator.top(), indicator.bottom() + 1) - for x in range(indicator.left(), indicator.right() + 1) - if image.pixelColor(x, y).lightness() < 235 - ) - assert visible_indicator_pixels >= 8 - - metric_labels = ( - *controller.primary_name_labels.values(), - *controller.primary_value_labels.values(), - *controller.secondary_name_labels.values(), - *controller.secondary_value_labels.values(), - ) - assert metric_labels - assert all(THEME["card_bg"] in label._qt.styleSheet() for label in metric_labels) - - -def test_escape_interrupts_captured_dbf_drags(gui_session) -> None: - controller = gui_session.controller - - controller.dbf_drag_mode = "azimuth" - assert controller.on_escape_key() == "break" - assert controller.dbf_drag_mode is None - - controller.dbf2d_dragging = True - assert controller.on_escape_key() == "break" - assert controller.dbf2d_dragging is False - - -def test_workspace_tabs_support_keyboard_navigation(gui_session) -> None: - controller = gui_session.controller - tab_widget = controller.main_notebook._qt - tab_bar = tab_widget.tabBar() - original_index = tab_widget.currentIndex() - - try: - tab_widget.setCurrentIndex(0) - tab_bar.setFocus() - QtTest.QTest.keyClick( - tab_widget, - QtCore.Qt.Key.Key_Tab, - QtCore.Qt.KeyboardModifier.ControlModifier, - ) - process_events(gui_session.app, cycles=4) - assert tab_widget.currentIndex() == 1 - assert tab_bar.hasFocus() - finally: - tab_widget.setCurrentIndex(original_index) - process_events(gui_session.app, cycles=3) - - -def test_performance_report_worker_runs_off_the_gui_thread( - gui_session, monkeypatch: pytest.MonkeyPatch -) -> None: - from virtual_array.performance_report_dialog import PerformanceReportDialog - - controller = gui_session.controller - app = gui_session.app - events: list[tuple[str, object, bool]] = [] - worker_thread_checks: list[bool] = [] - cancel_requests: list[bool] = [] - progress_canceled: list[bool] = [] - information_parents: list[QtWidgets.QWidget] = [] - application_exit_signals: list[str] = [] - on_about_to_quit = lambda: application_exit_signals.append("aboutToQuit") - on_last_window_closed = lambda: application_exit_signals.append( - "lastWindowClosed" - ) - original_success = controller._on_performance_report_succeeded - original_failure = controller._on_performance_report_failed - original_progress = controller._on_performance_report_progress - original_cancel = controller._cancel_performance_report_export - - app.aboutToQuit.connect(on_about_to_quit) - app.lastWindowClosed.connect(on_last_window_closed) - - report_dialog = PerformanceReportDialog( - gui_session.window, - language="zh", - initial_directory=Path.cwd(), - azimuth_available=True, - elevation_available=True, - ) - report_dialog.open() - process_events(app, cycles=4) - - def capture_information(parent, *_args, **_kwargs): - information_parents.append(parent) - return QtWidgets.QMessageBox.StandardButton.Ok - - monkeypatch.setattr( - QtWidgets.QMessageBox, - "information", - capture_information, - ) - - def in_gui_thread() -> bool: - # Do not cache QApplication.thread(): PySide can invalidate that wrapper - # while short-lived QThread wrappers are deleted between exports. - return QtCore.QThread.currentThread() is app.thread() - - def fake_generator(_snapshot, _options, progress_callback): - worker_thread_checks.append(in_gui_thread()) - progress_callback(5, "start") - progress_callback(100, "done") - return SimpleNamespace(pdf_path=Path("report.pdf"), data_directory=None) - - def capture_progress(percent: int, message: str) -> None: - events.append( - ( - "progress", - (percent, message), - in_gui_thread(), - ) - ) - original_progress(percent, message) - - def capture_success(artifacts) -> None: # noqa: ANN001 - events.append( - ( - "success", - artifacts.pdf_path, - in_gui_thread(), - ) - ) - original_success(artifacts) - - controller._on_performance_report_progress = capture_progress - controller._on_performance_report_succeeded = capture_success - controller._on_performance_report_failed = lambda message: events.append( - ( - "failure", - message, - in_gui_thread(), - ) - ) - controller._cancel_performance_report_export = lambda: cancel_requests.append( - in_gui_thread() - ) - try: - for _run_index in range(2): - report_dialog.set_export_busy(True) - controller._performance_export_parent = report_dialog - assert not report_dialog.save_button.isEnabled() - assert not report_dialog.angle_image_button.isEnabled() - assert not report_dialog.cancel_button.isEnabled() - - controller._start_performance_report_export( - fake_generator, - object(), - object(), - ) - thread = controller._performance_report_thread - worker = controller._performance_report_worker - bridge = controller._performance_report_bridge - progress = controller._performance_report_progress - assert isinstance(thread, QtCore.QThread) - assert worker is not None - assert bridge is not None - assert progress is not None - assert bridge.thread() is app.thread() - assert progress.parentWidget() is report_dialog - assert ( - progress.windowModality() - == QtCore.Qt.WindowModality.WindowModal - ) - assert progress.minimumWidth() >= 480 - assert progress.minimumHeight() >= 160 - assert progress.property("workbenchRole") == "progress-dialog" - progress_label = progress.findChild(QtWidgets.QLabel) - assert progress_label is not None and progress_label.wordWrap() - assert progress_label.objectName() == "performanceReportProgressLabel" - assert progress_label.property("workbenchRole") == "progress-status" - assert progress_label.alignment() & QtCore.Qt.AlignmentFlag.AlignCenter - assert "0%" in progress_label.text() - progress_bar = progress.findChild( - QtWidgets.QProgressBar, "performanceReportProgressBar" - ) - assert progress_bar is not None - assert progress_bar.property("workbenchRole") == "report-progress" - assert not progress_bar.isTextVisible() - assert progress_bar.accessibleName() - assert progress_bar.height() >= 12 - original_progress(65, "正在绘制逐帧 Hold: 方位") - assert progress_bar.value() == 65 - assert progress_label.text() == "正在绘制逐帧 Hold: 方位 · 65%" - progress.canceled.connect(lambda: progress_canceled.append(True)) - - loop = QtCore.QEventLoop() - thread.finished.connect(loop.quit) - watchdog = QtCore.QTimer() - watchdog.setSingleShot(True) - watchdog.timeout.connect(loop.quit) - watchdog.start(3_000) - loop.exec() - finished_in_time = watchdog.isActive() - watchdog.stop() - process_events(app, cycles=8) - assert finished_in_time, "report worker did not finish before timeout" - assert controller._performance_report_thread is None - assert controller._performance_report_worker is None - assert controller._performance_report_bridge is None - assert controller._performance_report_progress is None - assert controller._performance_export_parent is None - assert report_dialog.save_button.isEnabled() - assert report_dialog.angle_image_button.isEnabled() - assert report_dialog.cancel_button.isEnabled() - assert report_dialog.isVisible() - assert gui_session.window.isVisible() - - assert worker_thread_checks == [False, False] - assert events == [ - ("progress", (5, "start"), True), - ("progress", (100, "done"), True), - ("success", Path("report.pdf"), True), - ("progress", (5, "start"), True), - ("progress", (100, "done"), True), - ("success", Path("report.pdf"), True), - ] - assert cancel_requests == [] - assert progress_canceled == [] - assert information_parents == [report_dialog, report_dialog] - assert application_exit_signals == [] - finally: - app.aboutToQuit.disconnect(on_about_to_quit) - app.lastWindowClosed.disconnect(on_last_window_closed) - controller._on_performance_report_progress = original_progress - controller._on_performance_report_succeeded = original_success - controller._on_performance_report_failed = original_failure - controller._cancel_performance_report_export = original_cancel - progress = controller._performance_report_progress - if progress is not None: - progress.blockSignals(True) - progress.close() - controller._performance_report_progress = None - controller._performance_export_parent = None - report_dialog.set_export_busy(False) - report_dialog.close() - report_dialog.deleteLater() - process_events(app, cycles=3) - - -def test_configuration_and_manual_dialogs_use_native_qt_controls(gui_session) -> None: - controller = gui_session.controller - dialog_specs = ( - ( - controller.open_dbf_dictionary_dialog, - True, - False, - QtWidgets.QDialogButtonBox.StandardButton.Cancel, - ), - ( - controller.open_channel_patterns_dialog, - True, - False, - QtWidgets.QDialogButtonBox.StandardButton.Close, - ), - ( - controller._show_user_manual_dialog, - False, - True, - QtWidgets.QDialogButtonBox.StandardButton.Close, - ), - ) - - for invocation, expects_table, expects_text_browser, close_button_kind in dialog_specs: - dialog = _open_modeless_dialog(gui_session, invocation) - closed = False - try: - assert dialog.windowTitle() - assert dialog.property("workbenchRole") == "dialog-shell" - assert dialog.width() <= gui_session.window.width() - assert dialog.height() <= gui_session.window.height() - button_boxes = dialog.findChildren(QtWidgets.QDialogButtonBox) - assert button_boxes, "custom dialogs must use QDialogButtonBox" - if expects_table: - tables = dialog.findChildren(QtWidgets.QTableView) - assert tables, "DBF and channel dialogs must expose a native QTableView" - assert all( - isinstance(table.model(), QtCore.QAbstractTableModel) - for table in tables - ) - assert all(table.model().columnCount() > 0 for table in tables) - if dialog.objectName() == "channelPatternsDialog": - source_panel = dialog.findChild( - QtWidgets.QWidget, "channelPatternSourcePanel" - ) - table_panel = dialog.findChild( - QtWidgets.QWidget, "channelPatternTablePanel" - ) - action_bar = dialog.findChild( - QtWidgets.QWidget, "channelPatternActionBar" - ) - assert source_panel.property("workbenchRole") == "dialog-rail" - assert table_panel.property("workbenchRole") == "dialog-content" - assert action_bar.property("workbenchRole") == "dialog-footer" - for button in dialog.findChildren(QtWidgets.QAbstractButton): - if not button.isVisible() or not button.text(): - continue - text_width = button.fontMetrics().horizontalAdvance(button.text()) - assert text_width + 12 <= button.width(), button.text() - elif dialog.objectName() == "dbfDictionaryDialog": - mode_panel = dialog.findChild( - QtWidgets.QWidget, "dbfModePanel" - ) - custom_panel = dialog.findChild( - QtWidgets.QWidget, "dbfCustomImportPanel" - ) - custom_scroll = dialog.findChild( - QtWidgets.QScrollArea, "dbfCustomImportScroll" - ) - import_disclosure = dialog.findChild( - QtWidgets.QPushButton, "dbfImportDisclosure" - ) - toolbar = dialog.findChild(QtWidgets.QWidget, "dbfPreviewToolbar") - az_button = dialog.findChild( - QtWidgets.QAbstractButton, "dbfPreviewAzButton" - ) - el_button = dialog.findChild( - QtWidgets.QAbstractButton, "dbfPreviewElButton" - ) - preview_table = dialog.findChild( - QtWidgets.QTableView, "dbfPreviewTable" - ) - preview_panel = dialog.findChild( - QtWidgets.QWidget, "dbfPreviewPanel" - ) - preview_header = dialog.findChild( - QtWidgets.QWidget, "dbfPreviewHeader" - ) - action_bar = dialog.findChild( - QtWidgets.QWidget, "dbfDictionaryActionBar" - ) - phase_reverse_toggle = dialog.findChild( - AppleSwitch, "dbfPhaseReverseToggle" - ) - zero_calibrate_toggle = dialog.findChild( - AppleSwitch, "dbfZeroCalibrateToggle" - ) - custom_mode = dialog.findChild( - QtWidgets.QRadioButton, "dbfMode_custom" - ) - ideal_mode = dialog.findChild( - QtWidgets.QRadioButton, "dbfMode_ideal" - ) - az_load_button = dialog.findChild( - QtWidgets.QPushButton, "dbfLoadAzButton" - ) - az_clear_button = dialog.findChild( - QtWidgets.QPushButton, "dbfClearAzButton" - ) - el_load_button = dialog.findChild( - QtWidgets.QPushButton, "dbfLoadElButton" - ) - el_clear_button = dialog.findChild( - QtWidgets.QPushButton, "dbfClearElButton" - ) - fit_columns_button = dialog.findChild( - QtWidgets.QPushButton, "dbfFitColumnsButton" - ) - calibration_separator = dialog.findChild( - QtWidgets.QFrame, "dbfCalibrationSeparator" - ) - button_box = button_boxes[0] - apply_button = button_box.button( - QtWidgets.QDialogButtonBox.StandardButton.Apply - ) - assert all( - widget is not None - for widget in ( - mode_panel, - custom_panel, - custom_scroll, - toolbar, - az_button, - el_button, - preview_table, - preview_panel, - preview_header, - action_bar, - phase_reverse_toggle, - zero_calibrate_toggle, - custom_mode, - ideal_mode, - az_load_button, - az_clear_button, - el_load_button, - el_clear_button, - fit_columns_button, - calibration_separator, - apply_button, - ) - ) - assert mode_panel.property("workbenchRole") == "dialog-rail" - assert custom_panel.property("workbenchRole") == "dialog-rail" - assert preview_panel.property("workbenchRole") == "dialog-content" - assert preview_header.property("workbenchRole") == "dialog-header" - assert action_bar.property("workbenchRole") == "dialog-footer" - for toggle in (phase_reverse_toggle, zero_calibrate_toggle): - assert isinstance(toggle, QtWidgets.QCheckBox) - assert not toggle.isTristate() - assert not custom_panel.isVisible() - assert not custom_scroll.isVisible() - assert import_disclosure is None - assert az_button.isChecked() and not el_button.isChecked() - custom_mode.click() - process_events(gui_session.app, cycles=3) - assert custom_panel.isVisible() - assert custom_scroll.isVisible() - assert not apply_button.isEnabled() - for button in ( - az_load_button, - az_clear_button, - el_load_button, - el_clear_button, - ): - stylesheet = button.styleSheet() - assert f"#{button.objectName()} {{" in stylesheet - assert "border: 1px solid" in stylesheet - assert fit_columns_button.toolTip() - fit_columns_button.click() - process_events(gui_session.app, cycles=2) - header = preview_table.horizontalHeader() - for section in range(preview_table.model().columnCount()): - assert header.sectionResizeMode(section) == ( - QtWidgets.QHeaderView.ResizeMode.Interactive - ) - assert 68 <= preview_table.columnWidth(0) <= 86 - for section in range(1, preview_table.model().columnCount()): - assert 64 <= preview_table.columnWidth(section) <= 96 - dialog.resize(820, 540) - process_events(gui_session.app, cycles=4) - assert custom_scroll.horizontalScrollBar().maximum() == 0 - assert custom_scroll.verticalScrollBar().maximum() > 0 - assert custom_panel.height() >= custom_panel.minimumSizeHint().height() - assert calibration_separator.geometry().top() > max( - el_load_button.geometry().bottom(), - el_clear_button.geometry().bottom(), - ) - dialog.resize(1240, 780) - process_events(gui_session.app, cycles=4) - assert custom_scroll.verticalScrollBar().maximum() == 0 - ideal_mode.click() - process_events(gui_session.app, cycles=3) - assert not custom_panel.isVisible() - assert not custom_scroll.isVisible() - assert apply_button.isEnabled() - if expects_text_browser: - from virtual_array.user_manual import manual_chapters - - browsers = dialog.findChildren(QtWidgets.QTextBrowser) - assert len(browsers) == 1 - assert browsers[0].toPlainText().strip() - search = dialog.findChild(QtWidgets.QLineEdit, "manualSearch") - assert search is not None - assert search.placeholderText() - assert search.isClearButtonEnabled() - chapter_list = dialog.findChild( - QtWidgets.QListWidget, "manualChapterList" - ) - assert chapter_list is not None - assert chapter_list.count() == len(manual_chapters(controller.language)) - assert chapter_list.accessibleName() - splitter = dialog.findChild( - QtWidgets.QSplitter, "manualContentSplitter" - ) - assert splitter is not None - assert " None: - controller = gui_session.controller - original_language = controller.language - controller.set_language("zh") - dialog = _open_modeless_dialog(gui_session, controller._show_user_manual_dialog) - closed = False - try: - chapter_list = dialog.findChild(QtWidgets.QListWidget, "manualChapterList") - browser = dialog.findChild(QtWidgets.QTextBrowser, "manualBrowser") - search = dialog.findChild(QtWidgets.QLineEdit, "manualSearch") - result_count = dialog.findChild(QtWidgets.QLabel, "manualSearchResultCount") - assert chapter_list is not None - assert browser is not None - assert search is not None - assert result_count is not None - assert chapter_list.count() == 12 - - chapter_list.setCurrentRow(chapter_list.count() - 1) - process_events(gui_session.app, cycles=3) - assert chapter_list.currentItem().text() in browser.toPlainText() - - QtTest.QTest.keyClick( - dialog, - QtCore.Qt.Key.Key_F, - QtCore.Qt.KeyboardModifier.ControlModifier, - ) - process_events(gui_session.app, cycles=2) - assert search.hasFocus() - - search.setText("Ctrl+Shift+Z") - process_events(gui_session.app, cycles=3) - visible_rows = [ - row - for row in range(chapter_list.count()) - if not chapter_list.item(row).isHidden() - ] - assert visible_rows - assert len(visible_rows) < chapter_list.count() - assert result_count.text() - - QtTest.QTest.keyClick(search, QtCore.Qt.Key.Key_Return) - process_events(gui_session.app, cycles=2) - assert dialog.isVisible(), "Enter in manual search must not close the dialog" - - search.setText("__definitely_not_a_manual_term__") - process_events(gui_session.app, cycles=2) - assert chapter_list.currentRow() == -1 - assert "未找到" in browser.toPlainText() - - search.clear() - process_events(gui_session.app, cycles=2) - assert all( - not chapter_list.item(row).isHidden() - for row in range(chapter_list.count()) - ) - - _close_with_standard_button( - gui_session, - dialog, - QtWidgets.QDialogButtonBox.StandardButton.Close, - ) - closed = True - finally: - controller.set_language(original_language) - if not closed: - try: - dialog.reject() - except RuntimeError: - pass - - -def test_help_menu_chapter_action_opens_the_requested_section(gui_session) -> None: - controller = gui_session.controller - original_language = controller.language - controller.set_language("zh") - requested_key = "files_reports" - action = controller.native_manual_chapter_actions[requested_key] - dialog = _open_modeless_dialog(gui_session, action.trigger) - closed = False - try: - chapter_list = dialog.findChild(QtWidgets.QListWidget, "manualChapterList") - assert chapter_list is not None - current = chapter_list.currentItem() - assert current is not None - assert current.data(QtCore.Qt.ItemDataRole.UserRole) == requested_key - assert current.text() in dialog.findChild( - QtWidgets.QTextBrowser, "manualBrowser" - ).toPlainText() - _close_with_standard_button( - gui_session, - dialog, - QtWidgets.QDialogButtonBox.StandardButton.Close, - ) - closed = True - finally: - controller.set_language(original_language) - if not closed: - try: - dialog.reject() - except RuntimeError: - pass - - -def test_element_pattern_confirmation_dialog_can_be_cancelled_modally( - gui_session, -) -> None: - controller = gui_session.controller - baseline = {id(dialog) for dialog in _visible_dialogs(gui_session)} - observation: dict[str, object] = {} - attempts = 0 - watchdog = QtCore.QTimer() - watchdog.setSingleShot(True) - - def abort_modal_wait() -> None: - observation.setdefault( - "error", TimeoutError("element-pattern confirmation did not close") - ) - active = gui_session.app.activeModalWidget() - if isinstance(active, QtWidgets.QDialog): - active.reject() - - watchdog.timeout.connect(abort_modal_wait) - - def cancel_confirmation() -> None: - nonlocal attempts - attempts += 1 - opened = [ - dialog - for dialog in _visible_dialogs(gui_session) - if id(dialog) not in baseline - ] - if not opened and attempts < 100: - QtCore.QTimer.singleShot(10, cancel_confirmation) - return - if not opened: - observation["error"] = AssertionError( - "element-pattern confirmation did not show a modal QDialog" - ) - return - - dialog = opened[-1] - try: - observation["modal"] = dialog.isModal() - observation["size"] = (dialog.width(), dialog.height()) - observation["shell_role"] = dialog.property("workbenchRole") - action_bar = dialog.findChild( - QtWidgets.QWidget, "elementPatternActionBar" - ) - observation["footer_role"] = ( - action_bar.property("workbenchRole") if action_bar is not None else None - ) - boxes = dialog.findChildren(QtWidgets.QDialogButtonBox) - observation["button_box_count"] = len(boxes) - cancel_buttons = [ - box.button(QtWidgets.QDialogButtonBox.StandardButton.Cancel) - for box in boxes - ] - cancel_buttons = [button for button in cancel_buttons if button is not None] - observation["has_cancel"] = bool(cancel_buttons) - if cancel_buttons: - cancel_buttons[-1].click() - else: - dialog.reject() - except BaseException as exc: - observation["error"] = exc - dialog.reject() - - QtCore.QTimer.singleShot(0, cancel_confirmation) - watchdog.start(3_000) - try: - result = controller._confirm_element_pattern_import(_sample_element_pattern()) - finally: - watchdog.stop() - process_events(gui_session.app, cycles=4) - - error = observation.get("error") - if isinstance(error, BaseException): - raise error - assert result is None - assert observation.get("modal") is True - assert observation.get("shell_role") == "dialog-shell" - assert observation.get("footer_role") == "dialog-footer" - assert observation.get("button_box_count", 0) >= 1 - assert observation.get("has_cancel") is True - width, height = observation["size"] - assert width <= gui_session.window.width() - assert height <= gui_session.window.height() - assert not [ - dialog - for dialog in _visible_dialogs(gui_session) - if id(dialog) not in baseline - ] - - -def test_main_page_labels_are_localized_in_all_supported_languages(gui_session) -> None: - controller = gui_session.controller - expected = { - "zh": ["物理与虚拟阵列", "1D DBF", "2D DBF"], - "en": ["Physical & Virtual", "1D DBF", "2D DBF"], - "ja": ["物理・仮想アレイ", "1D DBF", "2D DBF"], - } - expected_dynamic = { - "zh": ("不可用", "边界受限"), - "en": ("Unavailable", "At boundary"), - "ja": ("利用不可", "境界制限"), - } - expected_accessible = { - "zh": ("工作区页面", "应用状态"), - "en": ("Workspace pages", "Application status"), - "ja": ("ワークスペースページ", "アプリケーション状態"), - } - original_language = controller.language - - try: - for language, labels in expected.items(): - controller.set_language(language) - process_events(gui_session.app, cycles=5) - assert controller.language == language - assert _main_tab_labels(gui_session)[:3] == labels - margin, cut_reason = expected_dynamic[language] - assert controller.secondary_value_labels["row_az_margin"]._qt.text() == margin - assert controller.secondary_value_labels["row_az_cut"]._qt.text() == cut_reason - workspace_name, status_name = expected_accessible[language] - assert controller.main_notebook._qt.tabBar().accessibleName() == workspace_name - assert controller.native_status_bar.accessibleName() == status_name - for overlay in ( - controller.az_chart.empty_overlay, - controller.el_chart.empty_overlay, - controller.dbf2d_empty_overlay, - ): - assert overlay is not None - assert overlay.accessibleName() - assert ( - controller.auto_apply_button._qt.accessibleName() - == controller.auto_apply_button._qt.text() - ) - assert ( - controller.az_chart.play_button._qt.accessibleName() - == controller.az_chart.play_button._qt.text() - ) - if language == "en": - for label in ( - controller.header_title_label._qt, - controller.header_subtitle_label._qt, - ): - assert ( - label.fontMetrics().horizontalAdvance(label.text()) - <= label.width() - ) - assert controller.header_subtitle_label._qt.toolTip().startswith( - "Array layout" - ) - finally: - controller.set_language(original_language) - process_events(gui_session.app, cycles=5) - - -def test_initial_1t1r_uses_neutral_capability_empty_states(gui_session) -> None: - controller = gui_session.controller - navigator = locate_page_navigator(gui_session) - assert navigator is not None - original_index = navigator.current_index - - kinds = [element.kind for element in controller.elements] - assert kinds.count("tx") == 1 - assert kinds.count("rx") == 1 - metrics = controller.current_metrics - assert metrics is not None - assert metrics.x_aperture == 0.0 - assert metrics.y_aperture == 0.0 - assert metrics.azimuth_resolution is None - assert metrics.elevation_resolution is None - - try: - navigator.select(1) - process_events(gui_session.app, cycles=5) - expected_1d_titles = ( - "当前阵列没有方位孔径", - "当前阵列没有俯仰孔径", - ) - for chart, expected_title in zip( - (controller.az_chart, controller.el_chart), - expected_1d_titles, - ): - overlay = chart.empty_overlay - assert overlay is not None and overlay.isVisible() - assert overlay.title_label.text() == expected_title - assert overlay.body_label.text() - assert overlay.action_button.isVisible() - assert overlay.action_button.text() - assert not chart.footer_widget._qt.isVisible() - assert not chart.play_button._qt.isEnabled() - - navigator.select(2) - process_events(gui_session.app, cycles=5) - overlay_2d = controller.dbf2d_empty_overlay - assert overlay_2d is not None and overlay_2d.isVisible() - assert overlay_2d.title_label.text() == "当前阵列不具备完整 2D 测角能力" - assert overlay_2d.body_label.text() - assert overlay_2d.action_button.isVisible() - assert not controller.dbf2d_controls_widget._qt.isVisible() - assert controller.dbf2d_hover_db.size == 0 - assert not controller.dbf2d_az_button._qt.isEnabled() - assert not controller.dbf2d_el_button._qt.isEnabled() - finally: - navigator.select(original_index) - process_events(gui_session.app, cycles=3) - - -def test_v1_state_round_trips_active_tab_and_splitter_sizes( - isolated_appdata: Path, -) -> None: - from virtual_array.app_state import state_path - - target = state_path() - assert target.parent.parent.resolve() == isolated_appdata.resolve() - previous_state = target.read_bytes() if target.exists() else None - sessions = [] - - try: - target.parent.mkdir(parents=True, exist_ok=True) - # A pre-feature v1 state omits both optional window fields. It must - # still load with the default page and a usable splitter. - target.write_text( - json.dumps( - { - "version": 1, - "language": "zh", - "window": {"state": "normal"}, - } - ), - encoding="utf-8", - ) - first = create_gui_session((1366, 768)) - sessions.append(first) - first_navigator = locate_page_navigator(first) - assert first_navigator is not None - assert first_navigator.current_index == 0 - default_sizes = first.controller.workspace_splitter.sizes() - assert len(default_sizes) == 2 and all(size > 0 for size in default_sizes) - - first_navigator.select(2) - first.controller.workspace_splitter.setSizes([900, 320]) - process_events(first.app, cycles=6) - saved_sizes = [ - int(size) for size in first.controller.workspace_splitter.sizes() - ] - first.controller._save_local_state() - - persisted = json.loads(target.read_text(encoding="utf-8")) - assert persisted["version"] == 1 - assert persisted["window"]["active_tab"] == 2 - assert persisted["window"]["splitter_sizes"] == saved_sizes - - # Geometry restoration is deliberately excluded from this assertion: - # an offscreen platform may expose a smaller synthetic screen and clamp - # it. Keep the same logical test width so Qt can apply the two saved - # pane sizes without unrelated screen-geometry scaling. - persisted["window"].pop("geometry", None) - target.write_text(json.dumps(persisted), encoding="utf-8") - close_gui_session(first) - sessions.pop() - restored = create_gui_session((1366, 768)) - sessions.append(restored) - process_events(restored.app, cycles=8) - restored_navigator = locate_page_navigator(restored) - assert restored_navigator is not None - assert restored_navigator.current_index == 2 - assert restored.controller.workspace_splitter.sizes() == saved_sizes - finally: - for session in reversed(sessions): - close_gui_session(session) - if previous_state is None: - target.unlink(missing_ok=True) - else: - target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(previous_state) diff --git a/tests/test_server.py b/tests/test_server.py new file mode 100644 index 0000000..230b344 --- /dev/null +++ b/tests/test_server.py @@ -0,0 +1,398 @@ +from __future__ import annotations + +import base64 +import io +import time +import zipfile +from pathlib import Path + +import numpy as np +import pytest +from fastapi.testclient import TestClient + +from virtual_array.analysis import ( + Dbf2dScanner, + dbf_2d_spectrum, + dbf_azimuth_spectrum_bank, +) +from virtual_array.element_pattern import ( + PATTERN_KIND_PHASE, + PATTERN_PLANE_HORIZONTAL, + ChannelPatternSet, + PatternSeries, +) +from virtual_array.examples.case4_5tx7rx_sel import build_array +from virtual_array.geometry import AntennaArray +from virtual_array.project import default_project +from virtual_array.server import create_app + +EXAMPLES = Path(__file__).resolve().parents[1] / "examples" +PATTERN_CSV = EXAMPLES / "A8H_8horn_Realized Gain EH plane.csv" + + +@pytest.fixture() +def client(tmp_path) -> TestClient: + return TestClient(create_app(data_dir=tmp_path / "data", static_dir=tmp_path / "web")) + + +@pytest.fixture() +def project() -> dict: + return default_project().model_dump(mode="json") + + +def small_project() -> dict: + project = default_project().model_dump(mode="json") + project["layout"] = { + "tx": [{"x": 0, "y": 0}, {"x": 2, "y": 0}], + "rx": [{"x": 0, "y": -2}, {"x": 0.5, "y": -2}, {"x": 1, "y": -1.5}], + } + return project + + +def decode(payload: dict) -> np.ndarray: + data = base64.b64decode(payload["data"]) + return np.frombuffer(data, dtype=payload["dtype"]).reshape(payload["shape"]) + + +def upload(client: TestClient, name: str, content: bytes) -> str: + response = client.post("/api/assets", files={"file": (name, content, "text/csv")}) + assert response.status_code == 200, response.text + return response.json()["id"] + + +def wait_for_job(client: TestClient, job: dict, timeout: float = 120.0) -> dict: + deadline = time.time() + timeout + while time.time() < deadline: + status = client.get(f"/api/jobs/{job['id']}").json() + if status["status"] in {"succeeded", "failed", "cancelled"}: + return status + time.sleep(0.2) + raise AssertionError("export job timed out") + + +# ── Core: reusable 2D scanner ──────────────────────────────────────── + + +def test_dbf_2d_scanner_reuse_matches_fresh_spectrum_with_channel_phase() -> None: + array = AntennaArray.from_xy(tx_x=[0, 3], tx_y=[0, 0], rx_x=[0, 1, 2], rx_y=[0, 2, 0]) + angles = np.array([-60.0, 0.0, 60.0]) + patterns = ChannelPatternSet() + for index, name in enumerate(["Tx1", "Rx2"]): + patterns.set_series( + name, + PATTERN_KIND_PHASE, + PATTERN_PLANE_HORIZONTAL, + PatternSeries( + name="phase.csv", + source_path="phase.csv", + angle_column="Theta", + value_column=f"ch{index}", + value_kind=PATTERN_KIND_PHASE, + angles_deg=angles, + values=angles * (index + 1), + ), + ) + scanner = Dbf2dScanner(array, channel_patterns=patterns) + + for true_az, true_el in [(0.0, 0.0), (20.0, -10.0), (-45.0, 30.0)]: + _az, _el, expected = dbf_2d_spectrum( + array, true_az, true_el, channel_patterns=patterns + ) + assert np.array_equal(scanner.spectrum_db(true_az, true_el), expected) + + +# ── API ────────────────────────────────────────────────────────────── + + +def test_health_and_config(client: TestClient) -> None: + assert client.get("/api/health").json()["status"] == "ok" + config = client.get("/api/config").json() + assert config["limits"]["max_tx"] == 16 + assert config["default_project"]["version"] == 2 + + +def test_root_explains_missing_web_client(client: TestClient) -> None: + response = client.get("/") + assert response.status_code == 200 + assert "npm run build" in response.text + + +def test_static_client_is_served_with_spa_fallback(tmp_path) -> None: + web = tmp_path / "web" + (web / "assets").mkdir(parents=True) + (web / "index.html").write_text("app", encoding="utf-8") + (web / "assets" / "app.js").write_text("console.log(1)", encoding="utf-8") + client = TestClient(create_app(data_dir=tmp_path / "data", static_dir=web)) + + assert client.get("/").text == "app" + assert client.get("/projects/123").text == "app" + assert client.get("/assets/app.js").text == "console.log(1)" + assert client.get("/api/nope").status_code == 404 + + +def test_evaluate_reports_metrics_capability_and_virtual_points(client, project) -> None: + response = client.post("/api/evaluate", json={"project": project}) + + assert response.status_code == 200 + result = response.json() + assert result["summary"]["virtual_count"] == 64 + assert result["summary"]["x_aperture_lambda"] == pytest.approx(37.5) + assert result["capability"] == {"azimuth": True, "elevation": True, "two_d": True} + assert len(result["virtual_points"]) == result["summary"]["unique_count"] + assert result["angle"]["azimuth"]["no_fold_width"] > 0 + assert result["pattern_status"] == {"amplitude": "ideal", "phase": "ideal"} + assert result["wavelength_mm"] == pytest.approx(299.792458 / 77.0) + + +def test_evaluate_marks_missing_elevation_aperture(client) -> None: + project = default_project().model_dump(mode="json") + project["layout"] = {"tx": [{"x": 0, "y": 0}], "rx": [{"x": 0, "y": 0}, {"x": 1, "y": 0}]} + + result = client.post("/api/evaluate", json={"project": project}).json() + + assert result["capability"] == {"azimuth": True, "elevation": False, "two_d": False} + assert result["angle"]["elevation"] is None + + +def test_evaluate_rejects_invalid_project(client, project) -> None: + project["frequency_ghz"] = -1 + + response = client.post("/api/evaluate", json={"project": project}) + + assert response.status_code == 422 + assert "frequency_ghz" in response.json()["detail"] + + +def test_dbf_bank_matches_core_computation(client, project) -> None: + result = client.post("/api/dbf/bank", json={"project": project, "axis": "azimuth"}).json() + + _true, _scan, expected = dbf_azimuth_spectrum_bank(build_array()) + spectra = decode(result["spectra_db"]) + assert spectra.shape == (181, 181) + assert np.allclose(spectra, expected, atol=1e-4) + assert len(result["frames"]["errors"]) == 181 + assert result["frames"]["quality"][90] == "normal" + + +def test_dbf_2d_returns_frames(client, project) -> None: + response = client.post( + "/api/dbf/2d", + json={"project": project, "frames": [{"azimuth": 10, "elevation": 0}]}, + ) + + assert response.status_code == 200 + frame = response.json()["frames"][0] + assert decode(frame["spectrum_db"]).shape == (181, 181) + assert frame["peak_azimuth"] == pytest.approx(10.0) + + +def test_auto_layout_endpoint(client) -> None: + layout = client.post("/api/layout/auto", json={"tx_count": 2, "rx_count": 4}).json() + assert len(layout["tx"]) == 2 and len(layout["rx"]) == 4 + assert client.post("/api/layout/auto", json={"tx_count": 17, "rx_count": 4}).status_code == 422 + + +def test_element_pattern_upload_preview_and_evaluate(client, project) -> None: + asset = upload(client, PATTERN_CSV.name, PATTERN_CSV.read_bytes()) + + preview = client.post("/api/element-pattern/preview", json={"asset": asset}).json() + swapped = client.post( + "/api/element-pattern/preview", json={"asset": asset, "swap_axes": True} + ).json() + + assert preview["name"] == PATTERN_CSV.name + assert preview["elevation_column"] is not None + assert swapped["horizontal_column"] == preview["elevation_column"] + project["element_pattern"] = {"asset": asset} + result = client.post("/api/evaluate", json={"project": project}).json() + assert result["pattern_status"]["amplitude"] == "imported" + + +def test_asset_upload_rejects_unsupported_files(client) -> None: + response = client.post("/api/assets", files={"file": ("a.exe", b"x", "application/octet-stream")}) + assert response.status_code == 422 + assert client.get("/api/assets/" + "0" * 64).status_code == 404 + + +def test_channel_pattern_summary_resolves_to_physical_channels(client) -> None: + project = small_project() + content = ( + '"Theta [deg]","cang_deg(a) [deg]","cang_deg(b) [deg]","cang_deg(c) [deg]",' + '"cang_deg(d) [deg]","cang_deg(e) [deg]"\n' + "-30,1,2,3,4,5\n0,2,3,4,5,6\n30,3,4,5,6,7\n" + ).encode() + asset = upload(client, "phase-summary.csv", content) + + bindings = client.post( + "/api/channel-patterns/resolve", + json={ + "project": project, + "asset": asset, + "kind": "phase", + "plane": "horizontal", + "target": "physical", + }, + ).json() + + assert [binding["channel"] for binding in bindings] == ["Tx1", "Tx2", "Rx1", "Rx2", "Rx3"] + assert [binding["column_index"] for binding in bindings] == [0, 1, 2, 3, 4] + project["channel_patterns"] = bindings + result = client.post("/api/evaluate", json={"project": project}).json() + assert result["pattern_status"] == {"amplitude": "ideal", "phase": "imported"} + + +def test_channel_pattern_single_channel_and_count_mismatch(client) -> None: + project = small_project() + asset = upload(client, "one.csv", b"Theta,gain\n-10,-3\n0,0\n10,-3\n") + + single = client.post( + "/api/channel-patterns/resolve", + json={ + "project": project, + "asset": asset, + "kind": "amplitude", + "plane": "elevation", + "channel": "Rx2", + }, + ).json() + mismatch = client.post( + "/api/channel-patterns/resolve", + json={"project": project, "asset": asset, "kind": "amplitude", "plane": "horizontal"}, + ) + + assert single == [ + { + "channel": "Rx2", + "kind": "amplitude", + "plane": "elevation", + "asset": asset, + "column_index": 0, + "column": "gain", + } + ] + assert mismatch.status_code == 422 + project["channel_patterns"] = single + status = client.post("/api/evaluate", json={"project": project}).json()["pattern_status"] + assert status["amplitude"] == "mixed" + + +def test_custom_dictionary_preview_and_mismatch_error(client) -> None: + project = small_project() + header = "Angle," + ",".join(f"V{index}" for index in range(1, 7)) + rows = [f"{angle}," + ",".join("0" for _ in range(6)) for angle in (-90, 0, 90)] + asset = upload(client, "dict.csv", ("\n".join([header, *rows]) + "\n").encode()) + project["dbf_dictionary"] = {"mode": "custom", "azimuth_asset": asset} + + preview = client.post( + "/api/dictionary/preview", json={"project": project, "axis": "azimuth"} + ).json() + project["layout"]["rx"].pop() + mismatch = client.post("/api/dbf/bank", json={"project": project, "axis": "azimuth"}) + + assert preview["channel_count"] == 6 + assert preview["tables"]["azimuth"]["channel_mode"] == "virtual" + assert decode(preview["phase_deg"]).shape == (181, 6) + assert mismatch.status_code == 422 + assert "virtual channel" in mismatch.json()["detail"] + + +def test_missing_asset_reference_is_reported(client, project) -> None: + project["element_pattern"] = {"asset": "a" * 64} + + response = client.post("/api/evaluate", json={"project": project}) + + assert response.status_code == 422 + assert "missing" in response.json()["detail"] + + +def test_import_document_accepts_desktop_layout(client) -> None: + document = (EXAMPLES / "ti.json").read_text(encoding="utf-8") + import json + + response = client.post("/api/import/document", json={"document": json.loads(document)}) + + assert response.status_code == 200 + assert len(response.json()["project"]["layout"]["tx"]) == 8 + bad = client.post("/api/import/document", json={"document": {"version": 9}}) + assert bad.status_code == 422 + + +def test_export_layout_contains_desktop_evaluation_block(client, project) -> None: + document = client.post("/api/export/layout", json={"project": project}).json() + + assert document["version"] == 1 + assert document["evaluation"]["frequency_ghz"] == 77 + assert document["evaluation"]["virtual_utilization"]["virtual_channels"] == 64 + + +def test_project_library_crud(client, project) -> None: + created = client.post("/api/projects", json={"project": project}).json() + project["name"] = "renamed" + updated = client.put(f"/api/projects/{created['id']}", json={"project": project}).json() + listing = client.get("/api/projects").json() + + assert updated["project"]["name"] == "renamed" + assert listing[0]["id"] == created["id"] + assert listing[0]["tx_count"] == 8 + assert client.delete(f"/api/projects/{created['id']}").status_code == 204 + assert client.get(f"/api/projects/{created['id']}").status_code == 404 + assert client.get("/api/projects/not-an-id").status_code == 404 + + +def test_bundle_round_trip_restores_assets(tmp_path, project) -> None: + source = TestClient(create_app(data_dir=tmp_path / "a", static_dir=tmp_path / "web")) + target = TestClient(create_app(data_dir=tmp_path / "b", static_dir=tmp_path / "web")) + asset = upload(source, PATTERN_CSV.name, PATTERN_CSV.read_bytes()) + project["element_pattern"] = {"asset": asset, "swap_axes": True} + + bundle = source.post("/api/export/bundle", json={"project": project}) + with zipfile.ZipFile(io.BytesIO(bundle.content)) as archive: + names = archive.namelist() + restored = target.post( + "/api/import/bundle", + files={"file": ("p.mimo.zip", bundle.content, "application/zip")}, + ).json() + + assert "project.json" in names + assert restored["missing_assets"] == [] + assert restored["project"]["element_pattern"] == {"asset": asset, "swap_axes": True} + assert target.post("/api/evaluate", json={"project": restored["project"]}).status_code == 200 + + +def test_angle_error_image_job_produces_png(client) -> None: + job = client.post("/api/angle-error-image", json={"project": small_project()}).json() + + status = wait_for_job(client, job) + download = client.get(f"/api/jobs/{job['id']}/download") + + assert status["status"] == "succeeded", status + assert download.content[:8] == b"\x89PNG\r\n\x1a\n" + + +def test_report_job_produces_zip_with_pdf_and_data(client) -> None: + job = client.post( + "/api/reports", + json={"project": small_project(), "options": {"title": "测试报告"}}, + ).json() + + status = wait_for_job(client, job) + download = client.get(f"/api/jobs/{job['id']}/download") + + assert status["status"] == "succeeded", status + with zipfile.ZipFile(io.BytesIO(download.content)) as archive: + names = archive.namelist() + assert "测试报告.pdf" in names + assert any(name.endswith(".csv") for name in names) + + +def test_report_rejects_invalid_options(client) -> None: + response = client.post( + "/api/reports", + json={ + "project": small_project(), + "options": {"include_spectrum_db": False, "include_spectrum_magnitude": False}, + }, + ) + + assert response.status_code == 422 + assert client.get("/api/jobs/" + "f" * 32).status_code == 404 diff --git a/tests/test_toplevel_first_frame.py b/tests/test_toplevel_first_frame.py deleted file mode 100644 index dd2ca9e..0000000 --- a/tests/test_toplevel_first_frame.py +++ /dev/null @@ -1,70 +0,0 @@ -from __future__ import annotations - -import os - -import pytest - - -os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") - -QtCore = pytest.importorskip("PySide6.QtCore") -QtWidgets = pytest.importorskip("PySide6.QtWidgets") - -from virtual_array.qt_tk import Label, Toplevel, _ensure_app # noqa: E402 - - -@pytest.fixture(scope="module") -def app(): - return _ensure_app() - - -class _FirstShowProbe(QtCore.QObject): - def __init__(self, dialog: QtWidgets.QDialog) -> None: - super().__init__(dialog) - self.dialog = dialog - self.snapshots: list[tuple[str, str, int, QtCore.QSize]] = [] - - def eventFilter(self, watched, event): # noqa: N802 - dialog = getattr(self, "dialog", None) - if watched is dialog and event.type() == QtCore.QEvent.Type.Show: - self.snapshots.append( - ( - dialog.objectName(), - dialog.windowTitle(), - len(dialog.findChildren(QtWidgets.QLabel)), - dialog.size(), - ) - ) - return super().eventFilter(watched, event) - - -def test_toplevel_first_visible_frame_is_built_and_sized(app) -> None: - top = Toplevel() - probe = _FirstShowProbe(top._qt) - top._qt.installEventFilter(probe) - - assert not top._qt.isVisible() - top._qt.setObjectName("readyDialog") - top.title("Ready") - Label(top, text="Complete content").pack() - top.geometry("720x520+20+30") - - assert not top._qt.isVisible() - app.processEvents() - - assert top._qt.isVisible() - assert probe.snapshots == [ - ("readyDialog", "Ready", 1, QtCore.QSize(720, 520)) - ] - - top.destroy() - app.processEvents() - - -def test_destroyed_toplevel_is_not_reshown_by_deferred_timer(app) -> None: - top = Toplevel() - top.destroy() - - app.processEvents() - - assert not top._qt.isVisible() diff --git a/tests/test_user_manual.py b/tests/test_user_manual.py deleted file mode 100644 index ed10bd9..0000000 --- a/tests/test_user_manual.py +++ /dev/null @@ -1,92 +0,0 @@ -from __future__ import annotations - -from virtual_array.user_manual import ( - ManualChapter, - ManualSection, - manual_chapter_html, - manual_chapter_search_text, - manual_chapters, -) - - -EXPECTED_CHAPTER_KEYS = ( - "quick_start", - "workspace", - "layout_editing", - "virtual_overview", - "global_controls", - "dbf_1d", - "dbf_2d", - "dbf_dictionary", - "channel_patterns", - "files_reports", - "shortcuts_state", - "troubleshooting", -) - - -def test_manual_has_matching_detailed_chapters_in_all_languages() -> None: - for language in ("zh", "en", "ja"): - chapters = manual_chapters(language) - assert tuple(chapter.key for chapter in chapters) == EXPECTED_CHAPTER_KEYS - assert len({chapter.key for chapter in chapters}) == len(chapters) - for chapter in chapters: - assert chapter.title.strip() - assert chapter.summary.strip() - assert len(chapter.sections) >= 2 - search_text = manual_chapter_search_text(chapter) - assert len(search_text) >= 400, (language, chapter.key) - rendered = manual_chapter_html(chapter).lower() - assert " None: - chinese = "\n".join( - manual_chapter_search_text(chapter) for chapter in manual_chapters("zh") - ) - for required in ( - "1T1R", - "0.5λ", - "1~16", - "50", - "Ctrl+Shift+Z", - "CSV/XLSX", - "应用字典", - "state.json", - "不会恢复", - "立即生效", - ): - assert required in chinese - - -def test_manual_renderer_escapes_all_content_fields() -> None: - chapter = ManualChapter( - key="escape_check", - title="", - summary="<summary>", - sections=( - ManualSection( - heading="<heading>", - paragraphs=("<paragraph>",), - steps=("<step>",), - bullets=("<bullet>",), - note="<note>", - warning="<warning>", - ), - ), - ) - rendered = manual_chapter_html(chapter) - for raw in ( - "<title>", - "<summary>", - "<heading>", - "<paragraph>", - "<step>", - "<bullet>", - "<note>", - "<warning>", - ): - assert raw not in rendered - assert "<title>" in rendered From cd51866901d891cadfeb5a092ba8ec7a6bed9308 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Tue, 20 Oct 2026 11:53:19 +0000 Subject: [PATCH 2/5] =?UTF-8?q?=E9=87=8D=E6=9E=84=EF=BC=9A=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20Web=20=E5=89=8D=E7=AB=AF=E4=B8=8E=E6=9C=AC=E5=9C=B0?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=99=A8=E9=83=A8=E7=BD=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 界面(web/,React + TypeScript + Vite) - 阵列布局:SVG 拖拽编辑、λ/2 吸附、缩放平移、方向键微调、删除模式、撤销/重做、坐标表、自动排阵,虚拟阵列实时预览与通道关联高亮 - 1D DBF 角谱播放(整库一次请求、浏览器端播放)、2D DBF 热图(点击设真实角、分轴扫描、批量预取) - 新增测角性能视图(逐帧误差与竞争峰裕量) - DBF 字典、通道幅相/单元方向图、性能报告、项目库、使用说明对话框 - 中/英/日三语、浅色/深色主题、手机宽度适配 功能 - 服务器端项目库与项目包(.mimo.zip)导入导出,兼容桌面版阵面 JSON - 报告后台任务(进度、取消、下载),中文文件名下载兼容 - ruff 配置更新并修复全部告警 部署 - Dockerfile(内置 CJK 字体)+ docker-compose、Linux/Windows 安装与启动脚本、systemd 单元、CI Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TgRQxvYJLtrCkPBUDGPWAw --- .dockerignore | 13 + .gitattributes | 6 +- .github/workflows/ci.yml | 34 + .gitignore | 5 + .opencode/skills/mimo-project/SKILL.md | 61 +- CLAUDE.md | 92 +- CONTRIBUTING.md | 35 +- Dockerfile | 40 + README.md | 513 +--- deploy/mimo-array.service | 20 + docker-compose.yml | 15 + pyproject.toml | 6 +- pyrightconfig.json | 5 +- scripts/build_web.sh | 9 + scripts/run_server.ps1 | 11 + scripts/setup_server.ps1 | 21 + scripts/setup_server.sh | 14 + src/virtual_array/__init__.py | 2 +- src/virtual_array/analysis.py | 1 - src/virtual_array/dbf_dictionary.py | 1 - src/virtual_array/element_pattern.py | 7 +- src/virtual_array/engine.py | 2 +- .../examples/case4_5tx7rx_sel.py | 1 - src/virtual_array/geometry.py | 8 +- src/virtual_array/logging_config.py | 1 - src/virtual_array/performance_report.py | 4 +- src/virtual_array/server/app.py | 10 +- src/virtual_array/table_io.py | 1 - tests/test_analysis.py | 6 +- tests/test_app_logo_assets.py | 1 - tests/test_dbf_dictionary.py | 4 +- tests/test_element_pattern.py | 2 +- tests/test_geometry.py | 2 +- tests/test_performance_report.py | 2 +- tests/test_server.py | 8 +- web/index.html | 14 + web/package-lock.json | 2362 +++++++++++++++++ web/package.json | 29 + web/public/favicon.png | Bin 0 -> 2505 bytes web/src/App.tsx | 177 ++ web/src/api/client.ts | 137 + web/src/api/types.ts | 280 ++ web/src/charts/Plot.tsx | 107 + web/src/charts/plotly.d.ts | 5 + web/src/charts/theme.ts | 98 + web/src/components/Chrome.tsx | 291 ++ web/src/components/Overview.tsx | 212 ++ web/src/components/ui.tsx | 331 +++ web/src/dialogs/DictionaryDialog.tsx | 298 +++ web/src/dialogs/HelpDialog.tsx | 73 + web/src/dialogs/PatternsDialog.tsx | 398 +++ web/src/dialogs/ProjectsDialog.tsx | 114 + web/src/dialogs/ReportDialog.tsx | 239 ++ web/src/dialogs/useAssetNames.ts | 33 + web/src/i18n/__tests__/messages.test.ts | 21 + web/src/i18n/help.ts | 300 +++ web/src/i18n/index.ts | 24 + web/src/i18n/messages.ts | 1060 ++++++++ web/src/lib/__tests__/lib.test.ts | 80 + web/src/lib/encoding.ts | 36 + web/src/lib/format.ts | 62 + web/src/lib/geometry.ts | 101 + web/src/main.tsx | 11 + web/src/state/actions.ts | 120 + web/src/state/compute.ts | 93 + web/src/state/jobs.ts | 81 + web/src/state/store.ts | 250 ++ web/src/styles/global.css | 1343 ++++++++++ web/src/styles/views.css | 611 +++++ web/src/views/AngleView.tsx | 175 ++ web/src/views/ArrayView.tsx | 351 +++ web/src/views/Dbf2dView.tsx | 394 +++ web/src/views/DbfView.tsx | 237 ++ web/src/views/EmptyCapability.tsx | 29 + web/src/views/PhysicalEditor.tsx | 325 +++ web/src/views/VirtualPlot.tsx | 111 + web/src/views/plane.tsx | 224 ++ web/src/views/usePlayback.ts | 59 + web/tsconfig.json | 19 + web/vite.config.ts | 26 + 80 files changed, 11748 insertions(+), 556 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/workflows/ci.yml create mode 100644 Dockerfile create mode 100644 deploy/mimo-array.service create mode 100644 docker-compose.yml create mode 100755 scripts/build_web.sh create mode 100644 scripts/run_server.ps1 create mode 100644 scripts/setup_server.ps1 create mode 100755 scripts/setup_server.sh create mode 100644 web/index.html create mode 100644 web/package-lock.json create mode 100644 web/package.json create mode 100644 web/public/favicon.png create mode 100644 web/src/App.tsx create mode 100644 web/src/api/client.ts create mode 100644 web/src/api/types.ts create mode 100644 web/src/charts/Plot.tsx create mode 100644 web/src/charts/plotly.d.ts create mode 100644 web/src/charts/theme.ts create mode 100644 web/src/components/Chrome.tsx create mode 100644 web/src/components/Overview.tsx create mode 100644 web/src/components/ui.tsx create mode 100644 web/src/dialogs/DictionaryDialog.tsx create mode 100644 web/src/dialogs/HelpDialog.tsx create mode 100644 web/src/dialogs/PatternsDialog.tsx create mode 100644 web/src/dialogs/ProjectsDialog.tsx create mode 100644 web/src/dialogs/ReportDialog.tsx create mode 100644 web/src/dialogs/useAssetNames.ts create mode 100644 web/src/i18n/__tests__/messages.test.ts create mode 100644 web/src/i18n/help.ts create mode 100644 web/src/i18n/index.ts create mode 100644 web/src/i18n/messages.ts create mode 100644 web/src/lib/__tests__/lib.test.ts create mode 100644 web/src/lib/encoding.ts create mode 100644 web/src/lib/format.ts create mode 100644 web/src/lib/geometry.ts create mode 100644 web/src/main.tsx create mode 100644 web/src/state/actions.ts create mode 100644 web/src/state/compute.ts create mode 100644 web/src/state/jobs.ts create mode 100644 web/src/state/store.ts create mode 100644 web/src/styles/global.css create mode 100644 web/src/styles/views.css create mode 100644 web/src/views/AngleView.tsx create mode 100644 web/src/views/ArrayView.tsx create mode 100644 web/src/views/Dbf2dView.tsx create mode 100644 web/src/views/DbfView.tsx create mode 100644 web/src/views/EmptyCapability.tsx create mode 100644 web/src/views/PhysicalEditor.tsx create mode 100644 web/src/views/VirtualPlot.tsx create mode 100644 web/src/views/plane.tsx create mode 100644 web/src/views/usePlayback.ts create mode 100644 web/tsconfig.json create mode 100644 web/vite.config.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..94a22e7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +.git +.venv +**/__pycache__ +**/*.pyc +.pytest_cache +data +outputs +build +dist +*.egg-info +web/node_modules +web/dist +src/virtual_array/server/static diff --git a/.gitattributes b/.gitattributes index 926f80a..aa3052a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,6 +4,10 @@ *.md text eol=lf *.toml text eol=lf *.json text eol=lf -*.spec text eol=lf +*.ts text eol=lf +*.tsx text eol=lf +*.css text eol=lf +*.sh text eol=lf +*.yml text eol=lf *.ps1 text eol=crlf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6655886 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + python: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: pip install -e ".[dev]" ruff + - run: ruff check src tests + - run: pytest -q + + web: + runs-on: ubuntu-latest + defaults: + run: + working-directory: web + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: web/package-lock.json + - run: npm ci --no-audit --no-fund + - run: npm test + - run: npm run build diff --git a/.gitignore b/.gitignore index 36a715e..b6b8b21 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,8 @@ dist/ *.egg-info/ *.log .claude/ +node_modules/ +web/dist/ +src/virtual_array/server/static/ +data/ +*.tsbuildinfo diff --git a/.opencode/skills/mimo-project/SKILL.md b/.opencode/skills/mimo-project/SKILL.md index e976e8b..9e42d44 100644 --- a/.opencode/skills/mimo-project/SKILL.md +++ b/.opencode/skills/mimo-project/SKILL.md @@ -1,53 +1,36 @@ --- name: mimo-project -description: MIMO Array Visualizer project conventions - file structure, test commands, naming, data flow +description: MIMO Array Visualizer project conventions - web architecture, units, test commands, data flow --- ## Project layout ``` -GUI.py → 启动器 (import virtual_array.gui.main) -GUI_mod.py → 启动器 (import virtual_array.gui_mod.main) — 重构版 -src/virtual_array/ - gui.py → 原版 GUI (~7700 行) - gui_mod.py → 重构版 GUI (1200×800 固定窗口,三子页 Notebook) - geometry.py → ArrayPoint, VirtualPoint, AntennaArray - analysis.py → calculate_metrics_and_psf, dbf_*_spectrum - element_pattern.py → ElementPattern, ChannelPatternSet - dbf_dictionary.py → DBF 字典配置 - app_state.py → JSON 持久化到 ~/Library/Application Support/antenna-array/ - logging_config.py → 日志配置 - grid.py → GRID_STEP=1.0, snap_to_grid() - version.py → APP_VERSION +src/virtual_array/ Python package + geometry.py, analysis.py, dbf_dictionary.py, element_pattern.py, + table_io.py, performance_report.py → 计算核心(无 UI 依赖,单位 λ/2) + project.py → v2 项目文档(Pydantic,单位 λ),兼容 v1 阵面 JSON + assets.py → 导入文件按 SHA-256 存储 + engine.py → Project → 核心对象,带 LRU 缓存的计算服务 + server/ → FastAPI:app.py(API + 静态前端)、store.py、jobs.py、cli.py +web/ React + TypeScript + Vite 前端(构建到 server/static) ``` ## 运行命令 ```bash -python GUI.py # 原版 -python GUI_mod.py # 重构版 -pytest tests/ -x -q # 测试 +pip install -e ".[dev]" # 后端依赖 +cd web && npm ci && npm run build # 前端构建 +mimo-array-server --port 8000 # 启动服务 +cd web && npm run dev # 前端开发(/api 代理到 :8000) +pytest -q && (cd web && npm test) # 测试 +ruff check src tests ``` -## 重构版 (gui_mod.py) 关键布局 +## 关键约定 -- 窗口:1366×768,`resizable(False, False)` -- 主布局:`main_panel` grid 4:1 (notebook : overview) -- Notebook 三个子页(Tab 1 Physical&Virtual 1:1, Tab 2 1D DBF 1:1, Tab 3 2D DBF) -- Overview 面板在右侧,primary 指标左右排列(name col 0, value col 1, padx=2) -- angle 指标 az/el 上下堆叠单列 -- 字体:matplotlib 优先链 macOS→Windows→Linux,Tkinter `TkDefaultFont`/`TkFixedFont` -- `_load_local_state()` 会从 state.json 覆盖 geometry,`main()` 里需要二次 `root.geometry()` 确保覆盖 - -## Tab 3 (2D DBF) 通过 `_build_dbf2d_widget()` 创建 - -- 返回 dbf2d_frame,由调用方 `pack(fill=BOTH, expand=True)` 放置 -- 创建 Figure、canvas、play/stop 按钮、status label -- 不要设置 canvas 固定宽高 - -## 修改注意事项 - -- 所有坐标用 λ (wavelength) 单位,显示时乘 DISPLAY_SCALE_LAMBDA -- 修改 figure 尺寸后同步调整 `subplots_adjust` 参数 -- `_build_response_chart` 方法签名是 `(parent, row, col, padding, mode)`,frame.grid 里不要额外 padx -- `_build_evaluation_panel(parent)` 创建 eval_frame 并用 grid 填充 parent -- 修改布局后检查 `_refresh_language_texts` 和 `generate_virtual_array` 里的引用 +- 项目文档与 API 坐标单位是 λ,编辑网格 0.5 λ;核心计算单位是 λ/2,只在 `project_array()` 中换算。 +- 通道名由列表顺序决定(Tx1…、Rx1…);前端每次编辑后按 (x, y) 重新排序编号。 +- 导入文件通过 asset ID 引用,项目文档不含本地路径;`engine.py` 按依赖字段的 JSON 摘要做缓存键。 +- 大矩阵用 base64 float32 传输(`encode_array`),±inf 以字符串 "Infinity"/"-Infinity" 传输。 +- UI 文案在 `web/src/i18n/messages.ts`,zh 为基准,en/ja 必须同 key、同占位符(有单元测试校验)。 +- 修改计算核心时保持现有测试的数值结果不变。 diff --git a/CLAUDE.md b/CLAUDE.md index 5f5f7ba..befd04a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,71 +4,81 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -MIMO Array Visualizer — a Python desktop application (PySide6 + pyqtgraph) for interactively editing and evaluating MIMO Tx/Rx antenna array layouts. Computes virtual array geometry, 2D array factor, and radar-performance metrics (PSL, beamwidth, ISLR, grating lobes, elevation ambiguity). +MIMO Array Visualizer — a web workbench for interactively editing and evaluating MIMO Tx/Rx antenna array layouts. A Python FastAPI server runs the computation core (virtual array geometry, 2D array factor, DBF dictionary spectra, angle-estimation metrics, PDF reports); a React + TypeScript client provides the UI. It is deployed on a local server and used from a browser. ## Commands ```bash -# Setup (PowerShell) -.\scripts\setup.ps1 +# Backend setup +python -m venv .venv && .venv/bin/pip install -e ".[dev]" -# Run GUI -.\.venv\Scripts\python.exe GUI.py -# or -.\.venv\Scripts\python.exe -m virtual_array.gui +# Web client (builds into src/virtual_array/server/static) +cd web && npm ci && npm run build -# Run tests -.\.venv\Scripts\python.exe -m pytest tests/ -x -q +# Run server (serves API + built client) +.venv/bin/mimo-array-server --host 0.0.0.0 --port 8000 --data-dir ./data -# Run a single test file -.\.venv\Scripts\python.exe -m pytest tests/test_analysis.py -x -q +# Frontend dev server with hot reload (proxies /api to :8000) +cd web && npm run dev -# Build Windows EXE -.\scripts\build_exe.ps1 -# or -.\.venv\Scripts\pyinstaller.exe MIMOArrayVisualizer.spec --noconfirm +# Tests +.venv/bin/python -m pytest -q +.venv/bin/python -m pytest tests/test_server.py -q +cd web && npm test && npx tsc -b + +# Lint +.venv/bin/ruff check src tests + +# Docker +docker compose up -d --build ``` ## Architecture -**`src/` layout** — all source lives under `src/virtual_array/`. `GUI.py` at the repo root is a thin launcher that adds `src/` to `sys.path` and calls `virtual_array.gui:main()`. - -### Core Modules +### Computation core (`src/virtual_array/`, no UI dependencies) -- **`geometry.py`** — Frozen dataclasses `ArrayPoint(name, x, y)`, `VirtualPoint(tx_name, rx_name, x, y)`, and `AntennaArray`. All coordinates are in λ units. `AntennaArray` owns tuples of Tx/Rx points and provides `virtual_points()`, `unique_virtual_xy()` (with multiplicity counting). +- **`geometry.py`** — `ArrayPoint`, `VirtualPoint`, `AntennaArray`. Core coordinates are in **λ/2 units**. +- **`analysis.py`** — `calculate_metrics_and_psf()` (2D array factor + `ArrayMetrics`), DBF spectrum banks (`dbf_azimuth_spectrum_bank` / `dbf_elevation_spectrum_bank`, 181 true × 181 scan angles), `dbf_angle_metrics_from_spectra()` (no-fold range, errors, peak margin, cut reasons), and `Dbf2dScanner` (reuses the 2D scan dictionary across true angles; `dbf_2d_spectrum` wraps it). +- **`dbf_dictionary.py`** — `DbfDictionaryConfig` (ideal / ideal_reversed / channel_pattern / custom) and CSV/XLSX dictionary tables. +- **`element_pattern.py`** — element patterns and per-channel HFSS amplitude/phase series (`ChannelPatternSet`). +- **`performance_report.py`** — multi-page PDF report, angle-error PNG, CSV/JSON data package (matplotlib). +- **`phasor.py`** — fast `exp(1j*phase)` helper used in hot loops. -- **`analysis.py`** — All signal processing. Central entry: `calculate_metrics_and_psf(array, ...)` → `(af_db, azimuths, elevations, ArrayMetrics)`. Computes 2D array factor via `exp(j*phase)` summation, optional element-pattern weighting (Tx×Rx). `ArrayMetrics` has 30+ fields (aperture, resolution, beamwidth, PSL, ISLR, grating lobe, front-radar grading, elevation ambiguity, warnings). +### Service layer -- **`element_pattern.py`** — `ElementPattern` frozen dataclass for antenna radiation patterns loaded from CSV/TSV. Auto-detects delimiter, angle column (theta/angle/azimuth/az/deg), and gain columns (gain/db/dbi/realized). Provides interpolated gain lookup and H/V axis swap. +- **`project.py`** — Pydantic `Project` document (schema version 2, coordinates in **λ**, grid 0.5 λ). Imported files are referenced by asset ID. Converts to the core array via `project_array()` (λ → λ/2). Reads/writes the desktop-era v1 layout JSON (`layout_from_v1`, `layout_to_v1`). +- **`assets.py`** — content-addressed store (`<data>/assets/<sha256>/<original name>`). +- **`engine.py`** — `Engine` turns a project into core objects and returns JSON-ready payloads (`evaluate`, `dbf_bank`, `dbf_2d`, `dictionary_preview`, `resolve_channel_patterns`, `layout_document`, `report_snapshot`). LRU caches are keyed by the JSON digest of only the fields each result depends on. -- **`gui.py`** — `VirtualArrayGui` class. Layout: 2×2 Matplotlib figure grid (Physical, Virtual, Az Response, El Response) + Qt-compatible evaluation panel + controls bar. Uses `ResponseChart` dataclass to encapsulate per-axis chart state. Interactive: drag elements with snap-to-grid, add/delete Tx/Rx (max 16 each), hover tooltips, element-pattern preview dialog, JSON layout I/O. -- **`qt_tk.py`** — PySide6 compatibility layer that preserves the old `tk`/`ttk` surface while backing widgets, timers, dialogs, and file dialogs with Qt. -- **`qt_plot.py`** — pyqtgraph-backed plotting compatibility layer for the GUI's former Matplotlib-style plotting calls. +### Server (`src/virtual_array/server/`) -- **`plotting.py`** — Standalone matplotlib functions for CLI PNG export (not used by GUI). +- **`app.py`** — `create_app(data_dir, static_dir)`; all routes under `/api` (OpenAPI docs at `/api/docs`); serves the built SPA with index fallback. +- **`store.py`** — file-backed project library (`<data>/projects/*.json`). +- **`jobs.py`** — background export jobs (PDF report / angle-error PNG) with progress, cancel, download. +- **`cli.py`** — `mimo-array-server` entry point (`--host`, `--port`, `--data-dir`; env `MIMO_DATA_DIR`). -### Supporting Modules +### Web client (`web/src/`) -- **`app_state.py`** — JSON persistence to `%APPDATA%/antenna-array/state.json` (atomic write via temp+rename). -- **`logging_config.py`** — Rotating file handler (1 MB, 5 backups) to `%APPDATA%/antenna-array/logs/`. Env override: `ANTENNA_ARRAY_LOG_DIR`. -- **`grid.py`** — `GRID_STEP = 1.0`, `snap_to_grid()`. -- **`examples/case4_5tx7rx_sel.py`** — Reference 8Tx/8Rx array. `build_array()` is the default GUI starting layout and primary test fixture. +- `api/` typed client + payload types (mirror `project.py` / `engine.py`). +- `state/store.ts` (zustand: project, undo/redo of layout edits, selection, UI prefs; persisted to localStorage), `state/compute.ts` (debounced evaluation, DBF bank cache), `state/actions.ts` (save/open/import/export), `state/jobs.ts`. +- `views/` — `ArrayView` (SVG `PhysicalEditor` with drag/snap/zoom + `VirtualPlot`), `DbfView` (1D playback, client-side from one bank request), `Dbf2dView` (heatmap, prefetching frame batches), `AngleView`. +- `dialogs/` — DBF dictionary, channel amp/phase + element pattern, report, project library, help. +- `i18n/messages.ts` — zh/en/ja strings (zh is the reference; a unit test checks keys and placeholders match). +- `charts/` — lazily loaded Plotly wrapper and theme tokens. ### Data Flow ``` -AntennaArray → calculate_metrics_and_psf() → (af_db, azimuths, elevations, ArrayMetrics) - ↓ - _draw_physical_array / _draw_virtual_array / _draw_response - ↓ - _update_evaluation_panel (Qt-compatible widgets) +Browser edits Project ──POST /api/evaluate──▶ Engine.evaluate ─▶ ArrayMetrics + DBF angle metrics + ──POST /api/dbf/bank──▶ 181×181 spectra (base64 float32) → 1D playback in browser + ──POST /api/dbf/2d────▶ batched 2D frames (Dbf2dScanner) + ──POST /api/reports───▶ background job → PDF/zip download ``` ## Conventions -- All antenna coordinates stored in λ (wavelength) units internally; converted to mm for display via `wavelength_mm()`. -- Layout JSON schema: `{"version": 1, "unit": "lambda", "tx": [...], "rx": [...], "evaluation": {...}}`. -- `ArrayMetrics.front_radar_status` grades: "Good" / "Acceptable" / "Risky" / "Bad" — color-coded in the UI. -- GUI theme constants are centralized in the `THEME` dict at the top of `gui.py`. -- Matplotlib figures use `draw_idle()` (not `draw()`) for non-blocking UI updates. -- Tests use the `build_array()` fixture from `examples/case4_5tx7rx_sel.py` as the standard reference layout. +- Project/API coordinates are λ; the core uses λ/2. Convert only in `project_array()`. +- Channel names derive from list order (`Tx1…`, `Rx1…`); the client renumbers by (x, y) after every edit, like the desktop tool. +- 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/CONTRIBUTING.md b/CONTRIBUTING.md index 532e0ca..1015e1a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,29 +1,32 @@ -# Contributing +# 参与贡献 -Thanks for helping improve MIMO Array Visualizer. +感谢参与改进 MIMO Array Visualizer。 -## Development setup +## 开发环境 ```bash python3 -m venv .venv -source .venv/bin/activate -pip install -e ".[dev]" +.venv/bin/pip install -e ".[dev]" +cd web && npm ci ``` -Before opening a pull request, run: +后端:`.venv/bin/mimo-array-server --port 8000`;前端热更新:`cd web && npm run dev`。 + +提交 PR 前请运行: ```bash -pytest tests/ -x -q -ruff check . -pyright +.venv/bin/python -m pytest -q +.venv/bin/ruff check src tests +cd web && npm test && npx tsc -b && npm run build ``` -## Pull requests +## Pull Request -- Keep changes focused and explain the user or engineering problem they solve. -- Add or update tests for behavior changes. -- For GUI changes, describe the affected platform and include a screenshot when it helps review. -- Do not commit local state, generated `outputs/`, `build/`, or `dist/` files. -- Preserve the existing layout JSON format and the public console entry points unless the change explicitly updates them. +- 改动保持聚焦,说明它解决的用户或工程问题。 +- 行为变化需要补充或更新测试;修改计算核心时,不得改变现有测试锁定的数值结果。 +- 界面改动请附截图,并说明在哪些浏览器/宽度下验证过。 +- 新增 UI 文案时,`web/src/i18n/messages.ts` 中 zh/en/ja 三种语言都要补齐(有单元测试校验)。 +- 不要提交本地数据(`data/`)、构建产物(`src/virtual_array/server/static/`、`web/node_modules/`)。 +- 保持 v1 阵面 JSON 格式和 `/api` 接口兼容,除非改动明确是要升级它们。 -For larger changes, open an issue first so the scope and intended behavior can be discussed. +较大的改动请先开 issue,讨论范围和预期行为。 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7cf249c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,40 @@ +# syntax=docker/dockerfile:1 + +# ── Stage 1: build the web client ──────────────────────────────────── +FROM node:22-bookworm-slim AS web +WORKDIR /build/web +COPY web/package.json web/package-lock.json ./ +RUN npm ci --no-audit --no-fund +COPY web/ ./ +RUN npx tsc -b && npx vite build --outDir /build/static --emptyOutDir + +# ── Stage 2: Python server ─────────────────────────────────────────── +FROM python:3.12-slim-bookworm + +ENV PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + MPLBACKEND=Agg \ + MIMO_DATA_DIR=/data + +# CJK fonts are required for Chinese/Japanese PDF reports. They must be +# installed before matplotlib builds its font cache. +RUN apt-get update \ + && apt-get install -y --no-install-recommends fonts-noto-cjk \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +COPY pyproject.toml README.md LICENSE ./ +COPY src ./src +COPY --from=web /build/static ./src/virtual_array/server/static +RUN pip install . \ + && useradd --create-home --uid 1000 mimo \ + && mkdir -p /data \ + && chown mimo:mimo /data + +USER mimo +VOLUME ["/data"] +EXPOSE 8000 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/health', timeout=4)" +CMD ["mimo-array-server", "--host", "0.0.0.0", "--port", "8000", "--data-dir", "/data"] diff --git a/README.md b/README.md index 3bea9e1..0b56ad1 100644 --- a/README.md +++ b/README.md @@ -1,483 +1,148 @@ # MIMO Array Visualizer -**English** | [中文](#中文) | [日本語](#日本語) +**中文** | [English](#english) -Desktop tool for interactively editing and evaluating MIMO Tx/Rx antenna array -layouts. Computes virtual array geometry, 2D array factor, and radar-performance -metrics (PSL, beamwidth, ISLR, grating lobes, elevation ambiguity). +MIMO 阵列工作台:在浏览器中交互式编辑、评估 MIMO 雷达 Tx/Rx 天线阵列布局。部署在本地服务器上,局域网内用浏览器即可使用,无需在每台电脑上安装软件。 -The desktop UI is a native **PySide6 / pyqtgraph** application with a -Carbon-led engineering-workbench appearance and Apple-inspired interaction: -dense neutral surfaces, system typography, clear focus states, and restrained motion. It intentionally -does **not** imitate a macOS shell; the application keeps native Qt controls and -platform behavior. It has one maintained implementation, `virtual_array.gui`, -and a resizable three-page workspace. `GUI.py`, `GUI_mod.py`, and the installed -console command all start this same interface; `GUI_mod.py` remains only as a -compatibility alias for existing shortcuts. +可计算虚拟阵列几何、2D 阵列因子与方向图指标(PSL、ISLR、3 dB 波束宽度、栅瓣),以及基于 DBF 字典的测角性能(不模糊范围、测角误差、竞争峰裕量、截断原因),并输出多页 PDF 性能报告。 --- -## Features - -### Core Engine - -- Interactive Tx/Rx layout editor with add, delete-mode, clear, - auto-place by Tx/Rx count, drag, and snap-to-grid. -- Undo/redo for layout edits, plus keyboard shortcuts for common actions. -- Virtual-array visualization with duplicate-channel statistics. -- Array evaluation: aperture, resolution, 3 dB beamwidth, PSL, ISLR, - grating-lobe and elevation-ambiguity indicators. -- Custom frequency input with GHz suffix parsing, plus configurable DBF - competitor-peak margin threshold. -- DBF dictionary spectrum animation for azimuth and elevation, with draggable - true-angle lines over 181 angles from −90° to +90° in 1° steps. -- 2D DBF heatmap with independent azimuth/elevation playback controls. -- Configurable DBF dictionary modes: ideal, phase-reversed, channel-pattern - calibrated, and imported CSV/XLSX dictionary matrices with tabular preview. -- HFSS channel-pattern CSV/XLSX import for per-channel amplitude and phase. -- Header **Channel Amp/Phase** status reports amplitude and phase separately - as ideal, imported, or mixed; imported element patterns count as imported - amplitude. -- Polished channel-pattern UI: centered channel table values, top-layer hover - tooltips, compact transparent Tx/Rx legend, and aligned bottom toolbar inputs. -- Readable JSON layout import/export with optional evaluation metadata. -- Current-configuration performance report export to a multi-page PDF, with - selectable Az/El focus and frame-hold ranges, independent dB/magnitude - spectrum pages, and optional CSV/JSON audit data. -- Local state persistence (last paths, frequency, window geometry, layout). -- PyInstaller onedir packaging for Windows. - -### Carbon-Led Native Desktop Interface - -- Resizable window: **1366 × 768** default, **1024 × 650 logical px** minimum - (**1100 × 650** recommended), clamped to the available screen area when restored. -- Three localized tab pages: - - **Physical & Virtual** — Physical and virtual array side by side (1:1). - - **1D DBF** — Azimuth and elevation response spectra side by side (1:1). - - **2D DBF** — Full-tab 2D heatmap with playback controls. -- Draggable workspace/overview splitter, with the side panel kept in a readable - 280–360 px range: - - Channel count, virtual channels, aperture, resolution. - - Angle evaluation: no-fold range, max error, peak margin, cut reason. -- Native Qt menus, dialogs, tables, status bar, keyboard focus, and standard - action icons, styled through one Carbon-led token/QSS theme. -- Direct array manipulation preserves the pointer-to-element grab offset, - captures the pointer for uninterrupted dragging, coalesces drag redraws to - about 16 ms, and snaps to the grid only on release. This removes cursor jumps - and grid-step jitter without changing stored layout geometry. -- Subtle hover/pressed feedback and visible keyboard focus provide responsive - state changes without decorative bounce or data-obscuring animation. -- Neutral capability guidance replaces misleading flat spectra or heatmaps when - an array has no usable aperture in one or both axes. -- Cross-platform Chinese font support (macOS / Windows / Linux). -- OpenCode skills and ruff/pyright tooling preconfigured. +## 功能 ---- +### 界面 -## Quick Start +- **阵列布局**:SVG 编辑器,可拖拽 Tx/Rx,松开后吸附到 λ/2 网格;支持滚轮缩放、平移、方向键微调、删除模式、撤销/重做(50 步)、自动排阵(T/R 数量),坐标表可批量精确编辑(同时显示 mm)。拖动时虚拟阵列实时预览;选中物理通道时,与之相关的虚拟点会高亮。 +- **1D DBF**:方位/俯仰字典角谱,共 181 帧真实角(−90°~+90°)。播放、拖动、点击图上任意位置都可跳转;实时显示峰值、误差、竞争峰裕量和峰质量。 +- **2D DBF**:方位 × 俯仰相关热图。点击热图设定真实角;方位、俯仰可分别或同时扫描,服务器端预取后续帧。 +- **测角性能**:逐帧测角误差和竞争峰裕量曲线,标注不模糊范围和裕量阈值,可导出出版级 PNG。 +- **阵列概览**:通道数、虚拟通道利用率、口径(mm/λ)、分辨率、测角评估、方向图指标和提示。 +- 中文 / English / 日本語界面,浅色 / 深色 / 跟随系统主题,桌面和手机宽度均可用。 -### Setup +### 功能 -```powershell -# Windows (PowerShell) -.\scripts\setup.ps1 -``` +- **DBF 字典**:理想几何、理想反向相位、通道幅相校准、导入 CSV/XLSX 字典(方位/俯仰分别导入,支持虚拟或物理通道列,可选相位取反和 0° 校准);附相位矩阵预览和质量提示。 +- **通道幅相**:导入 HFSS 汇总文件(物理或虚拟通道),或为单个通道导入幅度/相位 × 水平/俯仰;支持 dB、度数、复数(`1+2j`、`2∠40`)。 +- **单元方向图**:导入 CSV/TSV,可预览 H/V 切面并交换。 +- **项目库**:项目保存在服务器数据目录,同一服务器的用户共享;浏览器会自动保留当前草稿。 +- **导入导出**:阵面 JSON 与桌面版兼容(version 1,单位 λ,含评估信息);项目包 `.mimo.zip` 包含配置和全部导入数据,可在服务器之间迁移。 +- **性能报告**:服务器后台生成多页 PDF,可选附带 CSV/JSON 可复现数据包,显示进度、可取消,完成后自动下载。 +- **HTTP API**:全部功能均可通过 REST API 调用,方便脚本批量评估。接口文档见 `/api/docs`。 -**macOS / Linux**: +--- -```bash -python3 -m venv .venv -source .venv/bin/activate -pip install -e ".[dev]" -``` +## 部署 -### Run +### 方式一:Docker(推荐) ```bash -# Canonical launcher -python GUI.py - -# Compatibility alias; opens the same interface -python GUI_mod.py - -# Installed console entry point -mimo-array-visualizer +git clone https://github.com/rex991460774/mimo-array-visualizer.git +cd mimo-array-visualizer +docker compose up -d --build ``` -Windows: +浏览器打开 `http://<服务器IP>:8000/`。数据(项目库、导入文件、报告任务、日志)保存在 Docker 卷 `mimo-data` 中,升级镜像不会丢失。 -```powershell -.\scripts\run_gui.ps1 -``` +- 改端口:编辑 `docker-compose.yml` 中的 `"8000:8000"`,例如改为 `"8080:8000"`。 +- 升级:`git pull && docker compose up -d --build`。 +- 备份:`docker run --rm -v mimo-array-visualizer_mimo-data:/data -v "$PWD":/backup alpine tar czf /backup/mimo-data.tgz -C /data .` -If PowerShell blocks execution: - -```powershell -Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -``` - ---- - -## Keyboard Shortcuts - -| Shortcut | Action | -| --- | --- | -| `Ctrl+Z` | Undo layout edit | -| `Ctrl+Y` / `Ctrl+Shift+Z` | Redo layout edit | -| `Ctrl+S` | Export layout JSON | -| `Ctrl+O` | Import layout JSON | -| `Ctrl+G` / `Ctrl+R` | Refresh analysis | -| `Ctrl+F` | Focus frequency input | -| `Delete` | Delete selected element / enter delete mode | -| `Escape` | Clear selection / exit delete mode / cancel drag | - ---- +镜像已内置 Noto CJK 字体,中文/日文 PDF 报告可直接生成。 -## DBF Angle Spectra +### 方式二:Linux 裸机 -Each 1D DBF plot has 181 frames simulating true incoming angles from −90° to -+90° in 1° steps. Use the compact **Play** button under each plot. **Pause** -freezes the current spectrum; click again to **Resume**. Drag the true-angle -line to jump to a specific angle. +需要 Python 3.10+ 和 Node.js 20+(仅构建前端时需要)。 -The toolbar **Peak margin (dB)** input controls the competitor-peak margin -threshold for no-fold ambiguity evaluation. - -### DBF Dictionary - -Use **Edit → Configure DBF Dictionary** to choose the beamforming dictionary: - -| Mode | Description | -| --- | --- | -| Ideal geometric | Phase-only steering from array geometry | -| Ideal reversed phase | Sign-check variant | -| Channel amp/phase | Uses imported HFSS channel data with 0° phase reference | -| Imported CSV/XLSX | External dictionary loaded per-axis (Az/El) | - -### 2D DBF Heatmap - -The 2D DBF panel shows a correlation heatmap over azimuth and elevation. -Each axis can play/pause independently — one axis stays fixed while the -other scans, or both axes scan simultaneously. - -### Current-Configuration Performance Report - -Use **File → Export Current Performance Report…** to choose the PDF path, -the Az/El performance focus ranges, and the true-angle frame ranges included -in the spectrum hold plots. Each axis also has a configurable Hold-curve -interval; the current 1° grid means an interval of 5° plots every fifth frame, -while both range endpoints are always retained. The report can include dB -plots, normalized correlation-magnitude plots, or both. Each axis/unit -combination gets a full page containing one spectrum chart. Curve sampling -only reduces overlay density: the Max-Hold envelope and reproducibility data -still use every selected 1° frame. Both units come from the same per-frame signal-to-1D-dictionary -normalized correlation (`magnitude = 10^(dB/20)`); they are display forms of -one calculation rather than separate DBF algorithms. An optional data package -exports the exact configuration plus per-frame and spectrum CSV files. - -Angle-error pages scale their vertical axes from finite errors inside the -selected performance focus range, following the HFSS report plotting rule. -Folded errors outside that range may be visually clipped so useful small-error -detail remains readable; the complete values remain in the exported CSV data. +```bash +scripts/setup_server.sh # 创建 .venv、安装依赖、构建前端 +.venv/bin/mimo-array-server --host 0.0.0.0 --port 8000 --data-dir ./data +``` -For a 2D-capable array, these Az/El pages are explicitly reported as orthogonal -main-plane diagnostics: the azimuth sweep fixes true elevation at 0°, and the -elevation sweep fixes true azimuth at 0°. They are not presented as a full -joint 2D error-volume validation. +开机自启可参考 `deploy/mimo-array.service`(systemd)。中文报告需要系统安装 CJK 字体(如 `apt install fonts-noto-cjk`)。 ---- +### 方式三:Windows 服务器 -## Layout Editing - -Use the Physical Array toolbar to add Tx/Rx elements, clear the layout to -1T1R, or enter delete mode. In delete mode each clicked element is removed -and remaining channels are renumbered by position. - -The auto-layout inputs (`T` / `R` count) and **Apply Array** button generate -centered Tx and Rx rows for quick-start configurations. - -### Layout JSON - -```json -{ - "version": 1, - "unit": "lambda", - "tx": [ - {"name": "Tx1", "x": -9, "y": -12} - ], - "rx": [ - {"name": "Rx1", "x": -9, "y": 0} - ], - "evaluation": { - "frequency_mode": "77 GHz" - } -} +```powershell +.\scripts\setup_server.ps1 # 需要 Python 3.10+ 与 Node.js 20+ +.\scripts\run_server.ps1 # 默认 0.0.0.0:8000,数据目录 .\data ``` ---- - -## Channel Pattern Import +其他电脑访问前,需要在 Windows 防火墙中放行该端口。 -Use **Edit → Configure Channel Amp/Phase** to load HFSS amplitude/phase data -for physical or virtual channels. Summary CSV/XLSX files map columns -left-to-right by channel order. Loaded patterns are applied as complex -physical-channel weights (Tx × Rx for each virtual channel). +### 安全说明 -Amplitude and phase imports both accept rectangular complex values such as -`1+2j` / `1+2i` and polar values such as `2∠40`. For an amplitude import, the -complex magnitude is converted to dB with `20*log10(abs(value))`; existing real -values remain interpreted as dB. For a phase import, the complex angle is used -and calibrated to the 0° row as before. Complex amplitude values must be nonzero. +服务没有内置登录鉴权,适合在可信的实验室局域网内使用。命令行方式默认只监听 `127.0.0.1`;需要局域网访问时显式指定 `--host 0.0.0.0`。如需暴露到更大范围,请在前面加一层带认证的反向代理(如 Nginx Basic Auth)。上传文件限制为 CSV/TSV/TXT/XLSX/XLSM,单个不超过 32 MB。 --- -## Development - -See [CONTRIBUTING.md](CONTRIBUTING.md) for the development and pull-request workflow. +## 开发 ```bash -# Run tests -pytest tests/ -x -q +python -m venv .venv && .venv/bin/pip install -e ".[dev]" +.venv/bin/mimo-array-server --port 8000 # 后端 -# Lint & format -ruff check . -ruff format . - -# Build Windows EXE -.\scripts\build_exe.ps1 +cd web && npm ci && npm run dev # 前端热更新:http://localhost:5173(/api 代理到 :8000) ``` -Repeatable visual review (isolated state, three pages plus four dialogs): - ```bash -python scripts/capture_ui_review.py --output-dir outputs/ui-review -python scripts/capture_ui_review.py --output-dir outputs/ui-review-8t8r --skip-dialogs --auto-tx 8 --auto-rx 8 +.venv/bin/python -m pytest -q # 后端测试(计算核心 + API) +.venv/bin/ruff check src tests # Python lint +cd web && npm test && npx tsc -b # 前端单元测试 + 类型检查 +cd web && npm run build # 构建到 src/virtual_array/server/static ``` -Entry points: +### 架构 -```bash -mimo-array-visualizer -mimo-array-case4 ``` - ---- - -## Project Structure - -``` -GUI.py → Canonical launcher for virtual_array.gui -GUI_mod.py → Compatibility alias for the same interface -src/virtual_array/ - gui.py → Single native PySide6 GUI (resizable, three-page layout) - geometry.py → ArrayPoint, VirtualPoint, AntennaArray - analysis.py → Metrics, PSF, DBF spectra - performance_report.py → PDF report, focus statistics, Hold data package - performance_report_dialog.py → Native report configuration dialog - element_pattern.py → ElementPattern, ChannelPatternSet - dbf_dictionary.py → DBF dictionary configuration - app_state.py → JSON persistence - grid.py → Grid snap helpers - version.py → APP_VERSION - examples/ → Reference array fixtures -tests/ → pytest suite -.opencode/ → OpenCode skills & tooling config -``` - -## License - -This project is licensed under the MIT License. See [LICENSE](LICENSE). - ---- - -# 中文 - -MIMO 阵列可视化工具 — 用于交互式编辑和评估 MIMO 发射/接收天线阵列布局的桌面应用。可计算虚拟阵列几何、2D 阵列因子以及雷达性能指标(旁瓣电平、波束宽度、ISLR、栅瓣、俯仰模糊)。 - -桌面端采用原生 **PySide6 / pyqtgraph** 与 Carbon-led 工程工作台视觉,并保留 -Apple-inspired 的直接操控与即时反馈:紧凑中性色表面、系统字体、清晰焦点和低干扰动效。它不会伪装成 -macOS 外壳,而是保留 Qt 原生控件与平台行为。项目只维护 -`virtual_array.gui` 一套实现;`GUI.py`、`GUI_mod.py` 与安装后的控制台命令 -均打开同一个三页界面,`GUI_mod.py` 仅用于兼容已有快捷方式。 - -## 功能特性 - -### 核心引擎 - -- 交互式 Tx/Rx 布局编辑器:添加、删除模式、清空、按 T/R 数量自动排阵、拖拽、吸附网格。 -- 编辑操作的撤销/重做,常用快捷键。 -- 虚拟阵列可视化(含重复通道统计)。 -- 阵列评估:口径尺寸、分辨率、3 dB 波束宽度、PSL、ISLR、栅瓣和俯仰模糊指标。 -- 自定义频率输入(支持 GHz 后缀解析),可配置 DBF 竞争峰裕量阈值。 -- 方位/俯仰 DBF 字典角谱动画,181 个真实角(−90° 到 +90°,步进 1°)。 -- 2D DBF 热图,方位/俯仰轴独立播放控制。 -- 可配置 DBF 字典模式:理想几何、反向相位、通道幅相校准、导入 CSV/XLSX 字典。 -- HFSS 通道方向图 CSV/XLSX 导入(幅度/相位)。 -- 顶部 **通道幅相** 状态分别显示幅度、相位为理想、导入或混合;导入单元方向图时幅度视为导入。 -- 通道方向图界面细节优化:通道表内容居中、悬停信息置顶、Tx/Rx 图例紧凑透明、底部工具条输入框对齐。 -- 可读的 JSON 布局导入/导出(含评估元数据)。 -- 当前配置性能报告:可选方位/俯仰关注范围、逐帧 Hold 真实角范围以及 - dB/归一化模值角谱,输出多页 PDF 及可选 CSV/JSON 可复现数据包。 -- 本地状态持久化(最近路径、频率、窗口几何、布局)。 -- PyInstaller onedir Windows 打包。 - -### Carbon-led 原生桌面界面 - -- 可缩放窗口:默认 **1366 × 768**,最小 **1024 × 650 逻辑像素**(推荐 **1100 × 650**);恢复窗口时自动限制在屏幕可用区域内。 -- 三个已本地化的子页面: - - **Physical & Virtual** — 物理阵列与虚拟阵列左右并排(1:1)。 - - **1D DBF** — 方位与俯仰响应曲线左右并排(1:1)。 - - **2D DBF** — 全页 2D 热图及播放控件。 -- 主工作区与右侧 **Overview** 通过可拖动分隔条布局,侧栏保持 280–360 px 的可读宽度: - - 通道数、虚拟通道、口径、分辨率。 - - 测角评估:不模糊范围、最大误差、竞争峰裕量、截断原因。 -- 原生 Qt 菜单、弹窗、表格、状态栏、键盘焦点和标准操作图标,统一由 Carbon-led token/QSS 主题控制。 -- 阵元拖拽保留指针与阵元的抓取偏移,拖动期间捕获指针并以约 16 ms 合并重绘,松开时才吸附网格;因此不会出现阵元跳到指针中心或逐格抖动。 -- hover、pressed 与键盘焦点反馈即时但克制,不加入装饰性弹跳,也不让动画干扰工程数据阅读。 -- 阵列在某方向无有效孔径时显示中性能力提示,不再显示误导性的平直角谱或整片热图。 -- 跨平台中文字体(macOS / Windows / Linux)。 -- 预配置 OpenCode 技能和 ruff/pyright 工具。 - -### 当前配置性能报告 - -从 **文件 → 输出当前配置性能报告…** 进入配置对话框,可选报告路径、 -方位/俯仰测角性能关注范围、角谱 Hold 的真实角范围与曲线间隔,以及 dB、 -归一化模值两种纵坐标(可单选或同时输出)。当前真实角网格为 1°/帧, -例如间隔设为 5° 即每 5 帧绘制一条,并始终保留范围起止帧。每个“维度 × -纵坐标”组合独占一整页且只放一张角谱图;抽稀只降低叠加曲线密度, -Max-Hold 包络和可复现数据仍使用 Hold 范围内全部 1° 帧。 -dB 与模值来自同一套逐帧“信号—1D DBF 字典”归一化相关结果,模值按 -`10^(dB/20)` 转换,并不是另一套测角算法。 - -测角误差页按所选“性能关注范围”内的有限误差自适应纵轴,遵循 HFSS 报告 -绘图口径;关注范围外的折返误差可能在图上被裁切,以保留小误差细节, -完整原始值仍保存在可选 CSV 数据包中。 - -对于具备二维孔径的阵列,报告中两个 1D DBF 页明确定义为正交主平面诊断: -方位扫描时真实俯仰固定为 0°,俯仰扫描时真实方位固定为 0°; -它们不会被表述为完整的联合二维误差体验证。 - -## 快速开始 - -### 环境配置 - -**Windows (PowerShell)**: - -```powershell -.\scripts\setup.ps1 +浏览器(React + TypeScript) + │ 项目文档 JSON(坐标单位 λ) + ▼ +FastAPI 服务(virtual_array.server) + ├─ project.py 项目模型、v1 阵面 JSON 兼容 + ├─ engine.py 项目 → 计算核心,按依赖字段做 LRU 缓存 + ├─ assets.py 导入文件按 SHA-256 存储 + └─ jobs.py 报告后台任务 + ▼ +计算核心(无 UI 依赖,坐标单位 λ/2) + geometry · analysis · dbf_dictionary · element_pattern · performance_report ``` -**macOS / Linux**: - -```bash -python3 -m venv .venv -source .venv/bin/activate -pip install -e ".[dev]" -``` +- 1D DBF 一次请求返回完整的 181 × 181 角谱(base64 float32),播放全部在浏览器中完成,不需要逐帧请求。 +- 2D DBF 使用 `Dbf2dScanner` 复用扫描字典,单帧约 30 ms,前端按批预取。 +- 阵列因子计算改为矩阵乘法后约快 2 倍,数值结果与原实现一致(测试锁定)。 -### 运行 +### 项目结构 -```bash -python GUI.py # 正式入口 -python GUI_mod.py # 兼容别名,打开同一界面 -mimo-array-visualizer ``` - -## 快捷键 - -| 快捷键 | 操作 | -| --- | --- | -| `Ctrl+Z` | 撤销布局编辑 | -| `Ctrl+Y` / `Ctrl+Shift+Z` | 重做布局编辑 | -| `Ctrl+S` | 导出布局 JSON | -| `Ctrl+O` | 导入布局 JSON | -| `Ctrl+G` / `Ctrl+R` | 刷新分析 | -| `Ctrl+F` | 聚焦频率输入框 | -| `Delete` | 删除选中通道 / 进入删除模式 | -| `Escape` | 清除选择 / 退出删除模式 / 取消拖拽 | - -## 开发 - -```bash -pytest tests/ -x -q # 运行测试 -ruff check . # 代码检查 -ruff format . # 代码格式化 +src/virtual_array/ + geometry.py, analysis.py, dbf_dictionary.py, element_pattern.py, + table_io.py, performance_report.py, phasor.py 计算核心 + project.py, assets.py, engine.py 服务层 + server/ FastAPI 应用、项目库、任务、CLI + examples/ 参考阵列(case4 8T8R) +web/ React 前端 +tests/ pytest +deploy/, scripts/, Dockerfile, docker-compose.yml 部署 ``` -可重复视觉验收(隔离状态,批量生成三页和四个弹窗): +### 从桌面版迁移 -```bash -python scripts/capture_ui_review.py --output-dir outputs/ui-review -python scripts/capture_ui_review.py --output-dir outputs/ui-review-8t8r --skip-dialogs --auto-tx 8 --auto-rx 8 -``` +桌面版(PySide6)已由 Web 版取代,代码保留在 git 历史中。桌面版导出的阵面 JSON 可直接通过「导入 → 导入阵面 JSON」打开,频率和裕量设置会一并读取。桌面版中按本地路径引用的字典和方向图文件,需要在 Web 版中重新上传一次;之后会保存在服务器上,也可以随项目包一起迁移。 --- -# 日本語 - -MIMOアレイ可視化ツール — MIMO送信/受信アンテナアレイ配置を対話的に編集・評価するデスクトップアプリです。仮想アレイ形状、2Dアレイファクタ、レーダ性能指標(PSL、ビーム幅、ISLR、グレーティングローブ、仰角曖昧性)を計算します。 - -デスクトップ UI はネイティブ **PySide6 / pyqtgraph** と Carbon-led のエンジニアリングワークベンチ外観を採用し、Apple-inspired の直接操作と即時フィードバックを維持します。コンパクトなニュートラル面、システム書体、明瞭なフォーカス、控えめなモーションを使いますが、macOS の外殻を模倣するものではなく、Qt ネイティブの部品とプラットフォーム動作を維持します。保守する実装は `virtual_array.gui` の 1 つだけです。`GUI.py`、`GUI_mod.py`、インストール済みコンソールコマンドはすべて同じ 3 ページ画面を起動し、`GUI_mod.py` は既存ショートカット用の互換エイリアスです。 - -## 機能 - -### コアエンジン - -- インタラクティブな Tx/Rx 配置編集(追加、削除モード、クリア、自動配置、ドラッグ、グリッドスナップ) -- アンドゥ/リドゥ、キーボードショートカット -- 仮想アレイ表示(重複チャネル統計付き) -- アレイ評価:開口サイズ、分解能、3 dB ビーム幅、PSL、ISLR、グレーティングローブ、仰角曖昧性指標 -- カスタム周波数入力(GHz サフィックス対応)、DBF 競合ピークマージン設定 -- 方位/仰角 DBF 辞書角度スペクトルアニメーション(181 フレーム、−90° 〜 +90°、1° ステップ) -- 2D DBF ヒートマップ(方位/仰角の独立再生) -- 設定可能な DBF 辞書モード(理想幾何、逆位相、チャネル振幅/位相校正、CSV/XLSX 辞書読み込み) -- HFSS チャネルパターン CSV/XLSX 読み込み(振幅/位相) -- ヘッダーの **チャネル振幅/位相** ステータスで、振幅と位相をそれぞれ理想・読込・混在として表示。要素パターン読み込み時は振幅を読込扱いにします。 -- チャネルパターン UI を調整:表の値を中央揃え、ホバー情報を最前面表示、Tx/Rx 凡例を小さく透明化、下部ツールバー入力欄を整列。 -- 可読 JSON 配置の読み込み/書き出し(評価メタデータ付き) -- 現在設定の性能レポート(Az/El 評価範囲、両端を保持する軸別 Hold 曲線間隔、 - 範囲内全フレームによる Max-Hold と CSV、 - 複数ページ PDF、任意の CSV/JSON 再現データ) -- ローカル状態の永続化 -- PyInstaller onedir Windows パッケージ - -### Carbon-led ネイティブデスクトップ UI - -- リサイズ可能:既定 **1366 × 768**、最小 **1024 × 650 論理 px**(推奨 **1100 × 650**)。復元時は利用可能な画面領域内に収めます。 -- ローカライズ済みの 3 ページ: - - **Physical & Virtual** — 物理/仮想アレイ左右 1:1 - - **1D DBF** — 方位/仰角応答スペクトル左右 1:1 - - **2D DBF** — タブ全体の 2D ヒートマップ -- メイン領域と右側 **Overview** はドラッグ可能なスプリッターで構成し、側面パネルは 280–360 px の読みやすい幅を維持 -- ネイティブ Qt のメニュー、ダイアログ、テーブル、ステータスバー、キーボードフォーカス、標準アクションアイコンを単一の Carbon-led token/QSS テーマで統一 -- 配置ドラッグはポインターと素子の相対位置を保持し、ドラッグ中はポインターをキャプチャして約 16 ms 単位で再描画をまとめ、リリース時だけグリッドへスナップします。カーソル中心へのジャンプや段階的な揺れを防ぎます。 -- hover、pressed、キーボードフォーカスは即時かつ控えめに示し、装飾的なバウンドやデータを邪魔するアニメーションは使いません。 -- 有効な開口がない軸では、誤解を招く平坦スペクトルやヒートマップの代わりに中立的な案内を表示 -- クロスプラットフォーム中国語フォント対応 -- OpenCode スキル・ruff/pyright ツール設定済み - -## クイックスタート +## English -```bash -python3 -m venv .venv -source .venv/bin/activate -pip install -e ".[dev]" -python GUI.py # 正式エントリ -python GUI_mod.py # 同じ画面を開く互換エイリアス -mimo-array-visualizer -``` +MIMO Array Visualizer is a web workbench for editing and evaluating MIMO radar Tx/Rx antenna layouts. Run it on a local server and use it from any browser on the LAN. -## 開発 +- **UI**: drag-and-snap SVG array editor with undo/redo, live virtual-array preview, 1D DBF spectrum playback, 2D DBF heatmap, angle-error/peak-margin view, overview panel; Chinese/English/Japanese; light/dark themes. +- **Analysis**: virtual geometry, 2D array factor metrics (PSL, ISLR, beamwidth, grating lobes), DBF-dictionary angle evaluation (no-fold range, error, peak margin, cut reasons) with ideal, reversed, channel-calibrated or imported CSV/XLSX dictionaries, HFSS channel amp/phase and element patterns. +- **Workflow**: shared server-side project library, desktop-compatible layout JSON, portable `.mimo.zip` bundles, background PDF reports with CSV/JSON data packages, REST API at `/api/docs`. -```bash -pytest tests/ -x -q # テスト実行 -ruff check . # リント -ruff format . # フォーマット -``` +**Deploy with Docker**: `docker compose up -d --build`, then open `http://<server>:8000/`. +**Bare metal**: `scripts/setup_server.sh` (or `scripts\setup_server.ps1` on Windows), then `mimo-array-server --host 0.0.0.0 --port 8000 --data-dir ./data`. +The server has no built-in authentication; use it on a trusted network or behind an authenticating reverse proxy. -再現可能なビジュアル確認(状態を分離し、3 ページと 4 ダイアログを一括生成): +## License -```bash -python scripts/capture_ui_review.py --output-dir outputs/ui-review -python scripts/capture_ui_review.py --output-dir outputs/ui-review-8t8r --skip-dialogs --auto-tx 8 --auto-rx 8 -``` +MIT, see [LICENSE](LICENSE). diff --git a/deploy/mimo-array.service b/deploy/mimo-array.service new file mode 100644 index 0000000..c4736e3 --- /dev/null +++ b/deploy/mimo-array.service @@ -0,0 +1,20 @@ +# systemd unit for a bare-metal Linux deployment. +# Install: sudo cp deploy/mimo-array.service /etc/systemd/system/ +# sudo systemctl daemon-reload && sudo systemctl enable --now mimo-array +# Adjust User, WorkingDirectory and paths to the checkout location. +[Unit] +Description=MIMO Array Visualizer web workbench +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=mimo +WorkingDirectory=/opt/mimo-array-visualizer +ExecStart=/opt/mimo-array-visualizer/.venv/bin/mimo-array-server --host 0.0.0.0 --port 8000 --data-dir /var/lib/mimo-array +Restart=on-failure +RestartSec=3 +Environment=MPLBACKEND=Agg + +[Install] +WantedBy=multi-user.target diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..96b1951 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,15 @@ +services: + mimo-array: + build: . + image: mimo-array-visualizer:1.0.0 + container_name: mimo-array + ports: + # Change the left side to use another host port, e.g. "8080:8000". + - "8000:8000" + volumes: + # Projects, uploaded pattern/dictionary files, export jobs and logs. + - mimo-data:/data + restart: unless-stopped + +volumes: + mimo-data: diff --git a/pyproject.toml b/pyproject.toml index f6a92d3..7ec9cc6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,11 @@ extend-exclude = ["web"] [tool.ruff.lint] select = ["E", "F", "W", "I", "N", "UP", "B", "SIM"] -ignore = ["E501"] +# B905: zip(strict=) is not used to avoid changing long-standing core behavior. +ignore = ["E501", "B905"] + +[tool.ruff.lint.flake8-bugbear] +extend-immutable-calls = ["fastapi.File"] [tool.ruff.format] quote-style = "double" diff --git a/pyrightconfig.json b/pyrightconfig.json index c7b4ffa..ba4019a 100644 --- a/pyrightconfig.json +++ b/pyrightconfig.json @@ -1,7 +1,8 @@ { "venvPath": ".", "venv": ".venv", - "include": ["src", "tests", "GUI.py"], + "include": ["src", "tests"], + "exclude": ["web", "src/virtual_array/server/static"], "extraPaths": ["src"], - "pythonVersion": "3.14" + "pythonVersion": "3.10" } diff --git a/scripts/build_web.sh b/scripts/build_web.sh new file mode 100755 index 0000000..e97441a --- /dev/null +++ b/scripts/build_web.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Build the web client into src/virtual_array/server/static (served by the API server). +set -euo pipefail +cd "$(dirname "$0")/../web" +if [ ! -d node_modules ]; then + npm ci --no-audit --no-fund +fi +npm run build +echo "Web client built into src/virtual_array/server/static" diff --git a/scripts/run_server.ps1 b/scripts/run_server.ps1 new file mode 100644 index 0000000..e37cf75 --- /dev/null +++ b/scripts/run_server.ps1 @@ -0,0 +1,11 @@ +# Start the web workbench on this Windows machine. +# Other machines on the LAN can open http://<this-host>:8000/ when -Host 0.0.0.0 +# is used and the Windows firewall allows the port. +param( + [string]$BindHost = "0.0.0.0", + [int]$Port = 8000, + [string]$DataDir = (Join-Path (Join-Path $PSScriptRoot "..") "data") +) +$ErrorActionPreference = "Stop" +Set-Location (Join-Path $PSScriptRoot "..") +.\.venv\Scripts\mimo-array-server.exe --host $BindHost --port $Port --data-dir $DataDir diff --git a/scripts/setup_server.ps1 b/scripts/setup_server.ps1 new file mode 100644 index 0000000..0e1dc79 --- /dev/null +++ b/scripts/setup_server.ps1 @@ -0,0 +1,21 @@ +# One-time setup on a Windows server: Python venv, dependencies, web client. +# Requires Python 3.10+ and Node.js 20+ on PATH. +$ErrorActionPreference = "Stop" +Set-Location (Join-Path $PSScriptRoot "..") + +if (-not (Test-Path ".venv")) { + py -3 -m venv .venv +} +.\.venv\Scripts\python.exe -m pip install --upgrade pip +.\.venv\Scripts\python.exe -m pip install -e ".[dev]" + +Push-Location web +if (-not (Test-Path "node_modules")) { + npm ci --no-audit --no-fund +} +npm run build +Pop-Location + +Write-Host "" +Write-Host "Done. Start the server with:" +Write-Host " .\scripts\run_server.ps1" diff --git a/scripts/setup_server.sh b/scripts/setup_server.sh new file mode 100755 index 0000000..e064bab --- /dev/null +++ b/scripts/setup_server.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# One-time setup on a Linux/macOS server: Python venv, dependencies, web client. +set -euo pipefail +cd "$(dirname "$0")/.." +PYTHON="${PYTHON:-python3}" +if [ ! -d .venv ]; then + "$PYTHON" -m venv .venv +fi +.venv/bin/python -m pip install --upgrade pip +.venv/bin/python -m pip install -e ".[dev]" +scripts/build_web.sh +echo +echo "Done. Start the server with:" +echo " .venv/bin/mimo-array-server --host 0.0.0.0 --port 8000 --data-dir ./data" diff --git a/src/virtual_array/__init__.py b/src/virtual_array/__init__.py index 2e4a440..8ae8d8e 100644 --- a/src/virtual_array/__init__.py +++ b/src/virtual_array/__init__.py @@ -1,5 +1,5 @@ -from .version import APP_VERSION from .geometry import AntennaArray, ArrayPoint, VirtualPoint +from .version import APP_VERSION __version__ = APP_VERSION diff --git a/src/virtual_array/analysis.py b/src/virtual_array/analysis.py index 6bc692d..dec5cbf 100644 --- a/src/virtual_array/analysis.py +++ b/src/virtual_array/analysis.py @@ -10,7 +10,6 @@ from .geometry import AntennaArray from .phasor import unit_phasor - AZIMUTH_FOV = (-75.0, 75.0) ELEVATION_FOV = (-15.0, 15.0) AF_GRID_SIZE = 181 diff --git a/src/virtual_array/dbf_dictionary.py b/src/virtual_array/dbf_dictionary.py index f91e892..90aefb7 100644 --- a/src/virtual_array/dbf_dictionary.py +++ b/src/virtual_array/dbf_dictionary.py @@ -12,7 +12,6 @@ from .phasor import unit_phasor from .table_io import read_xlsx_rows - DBF_DICT_IDEAL = "ideal" DBF_DICT_IDEAL_REVERSED = "ideal_reversed" DBF_DICT_CHANNEL_PATTERN = "channel_pattern" diff --git a/src/virtual_array/element_pattern.py b/src/virtual_array/element_pattern.py index 70cce02..fb9c099 100644 --- a/src/virtual_array/element_pattern.py +++ b/src/virtual_array/element_pattern.py @@ -1,15 +1,14 @@ from __future__ import annotations import csv +from collections.abc import Iterable from dataclasses import dataclass from pathlib import Path -from typing import Iterable import numpy as np from .table_io import read_xlsx_rows - ANGLE_HEADER_KEYWORDS = ("theta", "angle", "azimuth", "az", "deg") GAIN_HEADER_KEYWORDS = ("gain", "db", "dbi", "realized") PATTERN_KIND_AMPLITUDE = "amplitude" @@ -80,7 +79,7 @@ def display_name(self) -> str: return f"{self.name} ({self.horizontal_column})" return f"{self.name} (H: {self.horizontal_column}; V: {self.elevation_column})" - def swapped_axes(self) -> "ElementPattern": + def swapped_axes(self) -> ElementPattern: if self.elevation_column is None or self.elevation_gain_db is None: return self return ElementPattern( @@ -148,7 +147,7 @@ def with_series( kind: str, plane: str, series: PatternSeries | None, - ) -> "ChannelPattern": + ) -> ChannelPattern: values = { "amplitude_horizontal": self.amplitude_horizontal, "amplitude_elevation": self.amplitude_elevation, diff --git a/src/virtual_array/engine.py b/src/virtual_array/engine.py index 79d4293..3c46fd3 100644 --- a/src/virtual_array/engine.py +++ b/src/virtual_array/engine.py @@ -33,8 +33,8 @@ DBF_SCAN_FOV, DBF_SCAN_GRID_SIZE, ArrayMetrics, - DbfAngleMetrics, Dbf2dScanner, + DbfAngleMetrics, calculate_metrics_and_psf, dbf_angle_frame_series_from_spectra, dbf_angle_metrics_from_spectra, diff --git a/src/virtual_array/examples/case4_5tx7rx_sel.py b/src/virtual_array/examples/case4_5tx7rx_sel.py index 015065d..5ea3741 100644 --- a/src/virtual_array/examples/case4_5tx7rx_sel.py +++ b/src/virtual_array/examples/case4_5tx7rx_sel.py @@ -4,7 +4,6 @@ from virtual_array.geometry import AntennaArray - RX_X = [0, 5, 10, 14, 19, 24, 31, 35] RX_Y = [-10, -10, -10, -10, -10, -14, -10, -10] TX_X = [0, 7, 13, 20, 24, 28, 32, 40] diff --git a/src/virtual_array/geometry.py b/src/virtual_array/geometry.py index df0e4b7..aa61206 100644 --- a/src/virtual_array/geometry.py +++ b/src/virtual_array/geometry.py @@ -1,7 +1,7 @@ from __future__ import annotations +from collections.abc import Iterable from dataclasses import dataclass -from typing import Iterable import numpy as np @@ -41,7 +41,7 @@ def from_xy( tx_y: Iterable[float], rx_x: Iterable[float], rx_y: Iterable[float], - ) -> "AntennaArray": + ) -> AntennaArray: tx_x_values = tuple(tx_x) tx_y_values = tuple(tx_y) rx_x_values = tuple(rx_x) @@ -66,12 +66,12 @@ def subset( self, tx_indices: Iterable[int] | None = None, rx_indices: Iterable[int] | None = None, - ) -> "AntennaArray": + ) -> AntennaArray: tx = self.tx if tx_indices is None else tuple(self.tx[i] for i in tx_indices) rx = self.rx if rx_indices is None else tuple(self.rx[i] for i in rx_indices) return AntennaArray(tx=tx, rx=rx) - def horizontal_subset(self, tx_y: float = 0.0, rx_y: float = -10.0) -> "AntennaArray": + def horizontal_subset(self, tx_y: float = 0.0, rx_y: float = -10.0) -> AntennaArray: tx = tuple(point for point in self.tx if point.y == tx_y) rx = tuple(point for point in self.rx if point.y == rx_y) return AntennaArray(tx=tx, rx=rx) diff --git a/src/virtual_array/logging_config.py b/src/virtual_array/logging_config.py index 2581507..88de99d 100644 --- a/src/virtual_array/logging_config.py +++ b/src/virtual_array/logging_config.py @@ -8,7 +8,6 @@ from pathlib import Path from types import TracebackType - APP_DIR_NAME = "antenna-array" LOG_FILE_NAME = "antenna-array.log" LOG_DIR_ENV = "ANTENNA_ARRAY_LOG_DIR" diff --git a/src/virtual_array/performance_report.py b/src/virtual_array/performance_report.py index 9b4d773..6bd682a 100644 --- a/src/virtual_array/performance_report.py +++ b/src/virtual_array/performance_report.py @@ -8,10 +8,11 @@ import os import textwrap import uuid +from collections.abc import Callable from dataclasses import dataclass from datetime import datetime from pathlib import Path -from typing import Any, Callable +from typing import Any import numpy as np from matplotlib import colormaps, colors, rc_context @@ -39,7 +40,6 @@ from .element_pattern import ChannelPatternSet, ElementPattern, virtual_channel_names from .geometry import AntennaArray - REPORT_SCHEMA_VERSION = 1 LIGHT_SPEED_MM_PER_NS = 299.792458 DISPLAY_SCALE_LAMBDA = 0.5 diff --git a/src/virtual_array/server/app.py b/src/virtual_array/server/app.py index 426b404..b85dc95 100644 --- a/src/virtual_array/server/app.py +++ b/src/virtual_array/server/app.py @@ -467,7 +467,10 @@ def job_download(job_id: str) -> FileResponse: raise HTTPException(status_code=404, detail="Job not found.") from exc if job.status != "succeeded" or job.download_path is None: raise HTTPException(status_code=409, detail="The export is not ready.") - return FileResponse(job.download_path, filename=job.download_name) + return FileResponse( + job.download_path, + headers={"Content-Disposition": _content_disposition(job.download_name or "export")}, + ) @app.api_route("/api/{path:path}", methods=["GET", "POST", "PUT", "DELETE"]) def api_not_found(path: str) -> None: @@ -507,7 +510,10 @@ def web_client(path: str) -> FileResponse: def _content_disposition(filename: str) -> str: from urllib.parse import quote - ascii_name = filename.encode("ascii", "ignore").decode() or "project.mimo.zip" + suffix = ".mimo.zip" if filename.endswith(".mimo.zip") else Path(filename).suffix + stem = filename[: len(filename) - len(suffix)] if suffix else filename + ascii_stem = stem.encode("ascii", "ignore").decode().strip(" ._") or "export" + ascii_name = ascii_stem + suffix return f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(filename)}" diff --git a/src/virtual_array/table_io.py b/src/virtual_array/table_io.py index 391b561..d997ed9 100644 --- a/src/virtual_array/table_io.py +++ b/src/virtual_array/table_io.py @@ -6,7 +6,6 @@ from pathlib import Path from xml.etree import ElementTree - NS_MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main" NS_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" NS_PACKAGE_REL = "http://schemas.openxmlformats.org/package/2006/relationships" diff --git a/tests/test_analysis.py b/tests/test_analysis.py index b5cbfef..ca44954 100644 --- a/tests/test_analysis.py +++ b/tests/test_analysis.py @@ -8,10 +8,10 @@ DBF_QUALITY_OK, DBF_SCAN_GRID_SIZE, calculate_metrics_and_psf, + dbf_2d_normalization_reference, + dbf_2d_spectrum, dbf_angle_frame_series_from_spectra, dbf_angle_metrics_from_spectra, - dbf_2d_spectrum, - dbf_2d_normalization_reference, dbf_azimuth_angle_metrics, dbf_azimuth_spectrum, dbf_azimuth_spectrum_bank, @@ -20,13 +20,13 @@ dbf_peak_index, estimate_resolution, ) -from virtual_array.examples.case4_5tx7rx_sel import build_array from virtual_array.element_pattern import ( PATTERN_KIND_AMPLITUDE, PATTERN_PLANE_HORIZONTAL, ChannelPatternSet, PatternSeries, ) +from virtual_array.examples.case4_5tx7rx_sel import build_array from virtual_array.geometry import AntennaArray diff --git a/tests/test_app_logo_assets.py b/tests/test_app_logo_assets.py index ae84d6e..41cbaf8 100644 --- a/tests/test_app_logo_assets.py +++ b/tests/test_app_logo_assets.py @@ -2,7 +2,6 @@ from PIL import Image - ASSET_DIR = Path(__file__).resolve().parents[1] / "src" / "virtual_array" / "assets" PNG_SIZES = (16, 24, 32, 48, 64, 128, 256, 512, 1024) diff --git a/tests/test_dbf_dictionary.py b/tests/test_dbf_dictionary.py index 8afe342..4fd6ad0 100644 --- a/tests/test_dbf_dictionary.py +++ b/tests/test_dbf_dictionary.py @@ -10,10 +10,10 @@ from virtual_array.dbf_dictionary import ( CHANNEL_MODE_PHYSICAL, CHANNEL_MODE_VIRTUAL, - DBF_DICTIONARY_QUALITY_DANGER, - DBF_DICTIONARY_QUALITY_OK, DBF_DICT_CHANNEL_PATTERN, DBF_DICT_CUSTOM, + DBF_DICTIONARY_QUALITY_DANGER, + DBF_DICTIONARY_QUALITY_OK, DbfDictionaryConfig, dictionary_quality_report, load_dbf_dictionary_table, diff --git a/tests/test_element_pattern.py b/tests/test_element_pattern.py index 8873bda..81e132b 100644 --- a/tests/test_element_pattern.py +++ b/tests/test_element_pattern.py @@ -15,9 +15,9 @@ ElementPattern, PatternSeries, format_pattern_cut_metrics, + load_element_pattern, load_hfss_pattern_series, load_hfss_summary_pattern, - load_element_pattern, pattern_cut_metrics, virtual_channel_names, ) diff --git a/tests/test_geometry.py b/tests/test_geometry.py index 8239766..27549c4 100644 --- a/tests/test_geometry.py +++ b/tests/test_geometry.py @@ -1,8 +1,8 @@ import numpy as np import pytest -from virtual_array.geometry import AntennaArray from virtual_array.examples.case4_5tx7rx_sel import build_array +from virtual_array.geometry import AntennaArray from virtual_array.grid import snap_to_grid diff --git a/tests/test_performance_report.py b/tests/test_performance_report.py index 5ed6619..24954c6 100644 --- a/tests/test_performance_report.py +++ b/tests/test_performance_report.py @@ -105,7 +105,7 @@ def _angle_error_plot_axis_data() -> SimpleNamespace: def _figure_legend_labels(figure: object) -> list[str]: return [ text.get_text() - for legend in getattr(figure, "legends") + for legend in figure.legends for text in legend.get_texts() ] diff --git a/tests/test_server.py b/tests/test_server.py index 230b344..fc709e8 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -217,10 +217,10 @@ def test_asset_upload_rejects_unsupported_files(client) -> None: def test_channel_pattern_summary_resolves_to_physical_channels(client) -> None: project = small_project() content = ( - '"Theta [deg]","cang_deg(a) [deg]","cang_deg(b) [deg]","cang_deg(c) [deg]",' - '"cang_deg(d) [deg]","cang_deg(e) [deg]"\n' - "-30,1,2,3,4,5\n0,2,3,4,5,6\n30,3,4,5,6,7\n" - ).encode() + b'"Theta [deg]","cang_deg(a) [deg]","cang_deg(b) [deg]","cang_deg(c) [deg]",' + b'"cang_deg(d) [deg]","cang_deg(e) [deg]"\n' + b"-30,1,2,3,4,5\n0,2,3,4,5,6\n30,3,4,5,6,7\n" + ) asset = upload(client, "phase-summary.csv", content) bindings = client.post( diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..e0b5eec --- /dev/null +++ b/web/index.html @@ -0,0 +1,14 @@ +<!doctype html> +<html lang="zh-CN"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <meta name="color-scheme" content="light dark" /> + <link rel="icon" type="image/png" href="/favicon.png" /> + <title>MIMO 阵列工作台 + + +
+ + + diff --git a/web/package-lock.json b/web/package-lock.json new file mode 100644 index 0000000..eb08414 --- /dev/null +++ b/web/package-lock.json @@ -0,0 +1,2362 @@ +{ + "name": "mimo-array-visualizer-web", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "mimo-array-visualizer-web", + "version": "1.0.0", + "dependencies": { + "lucide-react": "1.60.0", + "plotly.js-cartesian-dist-min": "3.7.0", + "react": "19.3.1", + "react-dom": "19.3.1", + "zustand": "5.0.15" + }, + "devDependencies": { + "@types/node": "22.20.5", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "5.2.0", + "typescript": "5.9.3", + "vite": "7.3.7", + "vitest": "3.2.7" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", + "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@babel/types": "^7.29.8", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.10.tgz", + "integrity": "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", + "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.10.tgz", + "integrity": "sha512-B3lYAs2nkKskbgQ1nfy8Ma9ao9Q1rntTAQHrzzyDuj+TSO+X3le6PfWwqDvodsb+OumE10eMFfuMCTQSQ5iuIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.9", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.3", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz", + "integrity": "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.12.tgz", + "integrity": "sha512-Z8lz+5UOiCJLonjeqwJlhUtHA/Sr6R1AidkccQxdWF0nigNzP81aLoU+udgOaGfL5s1uzFXzcux/pCwGAMu0lw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.12.tgz", + "integrity": "sha512-+tKxNa2psFmiTb0KfXlXs4Yj7vkEhzAvZ0DrQ5+0gWHQJM10jSleQ3l1FIVm5uvD53YM8lHfM4mgCLDDN9f1Gg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.12.tgz", + "integrity": "sha512-iiripdfvyRBugV55/Dk7GplNXQtN/PG85OcKeveU1z2UkTg0MofbBF1qk//qgPWiqJbVvQcXAVCfE56oDGO4EQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.12.tgz", + "integrity": "sha512-BmATib8swSMAagWNIfDZMnb+k34RXR4bbGOUfZgK8lLlniuMyVoSDDXCOGkdhtUmBXL4aygDh7bhjQ+TmhTvIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.12.tgz", + "integrity": "sha512-GzrO0CiUq8vcAI/hYJuIcp6wNm3T3YhOpumYtf9Z3Fz+cfN1VESCVfy7EPcM3/m2K8l+Gn2U+4XtNZjwhUXctQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.12.tgz", + "integrity": "sha512-Dpta6gigm4o6SYioXtTkZBlGLA/Sl6OpzgLqY+51uafJE2blPejAtR1w82CVLPN+F9cvo1+/em92x/zcOgY0uQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.12.tgz", + "integrity": "sha512-YpeDwQ5uFaogRvytNC8RK0keDO65kI5wNEhGSs+4GiJc3KHhxj4j5cnQh2nCu9ybJj6RP0/ycB6bkN0yFJ9I+w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.12.tgz", + "integrity": "sha512-LQrB3/sImIr1ycrlEyaApOLH1rAy8JV4/dH4eoK817aWATdcs4fESXz53/w72NwDnwPM5zEUpoL7socH4ZDnwA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.12.tgz", + "integrity": "sha512-iAF2iYu9S4SBfNsb4k0ewNBjO83WxHEltIuKQBGMzEKFgrYfmJn+gatBDXR2t/0zJN0UW0kzR4rfvQ1UHzkZ1A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.12.tgz", + "integrity": "sha512-0MQdRtdbirJCXPIVeW/hd/LXLR8Qz96pc+2EBptuuV5q/zSGOzND7SZt8gBTE58NC9cUG/8UxcUXQiKRZ2WzzA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.12.tgz", + "integrity": "sha512-yGDEwn0AGnrY/KCz2oY8R9KKNiQnTcwNuCWXeSXF0VLxXzlqoCgaS5QHsf1lbQvKWwPuN2Czkjk1wXRCBONTOQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.12.tgz", + "integrity": "sha512-AjlbD0efZEhHaJ3bsNjxSFDoguNq6VZvC+FKGJGBCA+ZN7BrZq2TuuSWFa6AI8IpOeuvhp2LoYcP7jiZwmtU0Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.12.tgz", + "integrity": "sha512-sDW0CiPoUCEEUV25uBG5sJ2gKe75DJqLpj91m1eK1vKffywyY7v4i6q1450ZuR6QW4NArXg7JpbMGgKU8di3HQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.12.tgz", + "integrity": "sha512-VTQYUhMjl8kv999VuYqScgv7P9cR9KuxI/6bkUsEa3bsswqG0+otFjuLZmJ1U+ffEP4IAz0jxOeV0DX6NRBhjg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.12.tgz", + "integrity": "sha512-ppsKwpSjNrzJ8hge3Z3uiCcoRgAAQk2tU7auy3MFF348ffWRldFPnWIT/a/enK7huijlTfnwn4DYpDoapEb45A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.12.tgz", + "integrity": "sha512-Gc3cVRC1trFH+GFWWTsJz6YuD4u75fzr/q99jqQGimonN/zvN6Wecck5WGzllOHj+XYXHcq0Ibor0tanGjfI6A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.12.tgz", + "integrity": "sha512-pjmDTFStvwFE3shTeUDvSDiSp8/qAf5bQXejcEUDDavWz4jEhTIpCdpS06G0PEwSCSNK0Lngjz2v9l4hk3Z74A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.12.tgz", + "integrity": "sha512-mkbjxPqpR91u1JD7xY4aLZhr/Mqka4/RqGcG4WNGgN/lC1o7TzyCyqJoSJXp9qVVxMwpJGFlEF1VlERb+Ghw1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.12.tgz", + "integrity": "sha512-vIeut2LkuVc3gcsawLJPahNAzvzBcFRhu2O+yVb//BuQKz7PIItMF0piXRbN/lIDO3d68TSDd368Vg6YwgTybw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.12.tgz", + "integrity": "sha512-3Sx+D3r9oPkTdNUcPrIRM2Am+vzEV6VGWoImHG4ZVK2jJeOW+eDjLeTm6nvu/z/m0fiX2YmGLXIypblc336MXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.12.tgz", + "integrity": "sha512-Nn2xh0teFnl71EiiUrKvECWcdGXtWF8q0uGclYwXGVw6QClGAcME0/bJSGdK+xIvd6MLEKYmjkTUvCBV+7m5Kw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.12.tgz", + "integrity": "sha512-n1/0H9TS+kBa4xp6n9aV7yiynBNfmerjkj2nAMIfY0ZHv1zShWRXnsAuAPAH0sfEK4ZSMK+z24q2RjAPFLCN1w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.12.tgz", + "integrity": "sha512-AdlDbQpsLfGlsHr1NfLZFtdnvxCKNp9TwlYVYExs8JJLWjLafUQEKJk0r9zUbmU57mw9nglMEvzqPHuLWYmaKw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.12.tgz", + "integrity": "sha512-u5SSUJBHod51UamjkigSr+JPre6xMy5vaWTTV2K0SnFG4RuKyYpf66dTSLFKX2cwaldpwyBurXPUCxq8riQMEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.12.tgz", + "integrity": "sha512-j5rXD4R/4DM5+V991AA9xOnG2Rwu2g3p5TPgu1Eu7apju0NUrLl+Bn/KpWc6wYJtlXqzwz1r+LNV1JeBU4VGvw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz", + "integrity": "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.29.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-rc.3", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.18.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/@vitest/expect": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz", + "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz", + "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.7", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz", + "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.7", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz", + "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz", + "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz", + "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.30", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.30.tgz", + "integrity": "sha512-YJs6Pz17RMNv8HoyKREtCY38E3BV1nPkWVmIb+XN1uHC1Vqt3KZCH/uJH9ZKRoiKb/icZ6tvehyee6RZNbFfRA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.4.tgz", + "integrity": "sha512-2TcbbiwXEq+N0kD36tykpCfyyQigUXmuwNQbnPp4Xk4PX9JOqVIKjJlIDjpH7uY6tmRGoAd+apeT1p60T8wsdA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.29", + "caniuse-lite": "^1.0.30001816", + "electron-to-chromium": "^1.5.459", + "node-releases": "^2.0.59", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001817", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001817.tgz", + "integrity": "sha512-uZ1JG80BwhtMalIAGPxPfmNhHyd/B/nTdr3hITWlRamSyAdUStP1Gop01e7SD5q6J90ixJvWDbvmiFVfDgn4bw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.461", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.461.tgz", + "integrity": "sha512-3WZFARz1By+/rYcqQ0OLj4UcEdhd6tz2LEcDtKBUq7ey77EeJ1OtetY/5hjSUxw7dC5r5mA7FfkhRbqO9vnTCg==", + "dev": true, + "license": "ISC" + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lucide-react": { + "version": "1.60.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.60.0.tgz", + "integrity": "sha512-UqxOW0FgAfDyb9VmjKb6/BkOzW6yfhf/QNboKtS2NDsscnNRW2CDzlyhbMKBQ1ontmcxuIDqHJ2AVgFR3NI+GA==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.59", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.59.tgz", + "integrity": "sha512-5qr2okC4ItAI0hG5SaV0HoYMpnM/Y6+Oqr7AmPYy/2uEoGvS+GbSKLeRxSS1uAdu59yz0ouzcuXievSgg///WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/plotly.js-cartesian-dist-min": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/plotly.js-cartesian-dist-min/-/plotly.js-cartesian-dist-min-3.7.0.tgz", + "integrity": "sha512-kfQjcAXXByRlskP8JsrlGYRPOvB+kOehZk/qBNewgr9SOMEnBN5nwEnUGOAQ0EEgYdQX51z3VZ81aBnDgSr9Bw==", + "license": "MIT" + }, + "node_modules/postcss": { + "version": "8.5.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", + "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz", + "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.64.12", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.12.tgz", + "integrity": "sha512-GhAu8ZglZ61VWSX/ZW3K/qkazgURBIQL0/Yy51QsS8DPyebR5Cf/Z2PANJFpTU0aVZ9byJcyqR6xvBbkXhdGYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.12", + "@rollup/rollup-android-arm64": "4.64.12", + "@rollup/rollup-darwin-arm64": "4.64.12", + "@rollup/rollup-darwin-x64": "4.64.12", + "@rollup/rollup-freebsd-arm64": "4.64.12", + "@rollup/rollup-freebsd-x64": "4.64.12", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.12", + "@rollup/rollup-linux-arm-musleabihf": "4.64.12", + "@rollup/rollup-linux-arm64-gnu": "4.64.12", + "@rollup/rollup-linux-arm64-musl": "4.64.12", + "@rollup/rollup-linux-loong64-gnu": "4.64.12", + "@rollup/rollup-linux-loong64-musl": "4.64.12", + "@rollup/rollup-linux-ppc64-gnu": "4.64.12", + "@rollup/rollup-linux-ppc64-musl": "4.64.12", + "@rollup/rollup-linux-riscv64-gnu": "4.64.12", + "@rollup/rollup-linux-riscv64-musl": "4.64.12", + "@rollup/rollup-linux-s390x-gnu": "4.64.12", + "@rollup/rollup-linux-x64-gnu": "4.64.12", + "@rollup/rollup-linux-x64-musl": "4.64.12", + "@rollup/rollup-openbsd-x64": "4.64.12", + "@rollup/rollup-openharmony-arm64": "4.64.12", + "@rollup/rollup-win32-arm64-msvc": "4.64.12", + "@rollup/rollup-win32-ia32-msvc": "4.64.12", + "@rollup/rollup-win32-x64-gnu": "4.64.12", + "@rollup/rollup-win32-x64-msvc": "4.64.12", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/strip-literal/node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.6.tgz", + "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "7.3.7", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.7.tgz", + "integrity": "sha512-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0 || ^0.28.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz", + "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.7", + "@vitest/mocker": "3.2.7", + "@vitest/pretty-format": "^3.2.7", + "@vitest/runner": "3.2.7", + "@vitest/snapshot": "3.2.7", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.7", + "@vitest/ui": "3.2.7", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/zustand": { + "version": "5.0.15", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.15.tgz", + "integrity": "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==", + "license": "MIT", + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "immer": ">=9.0.6", + "react": ">=18.0.0", + "use-sync-external-store": ">=1.2.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + }, + "use-sync-external-store": { + "optional": true + } + } + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..d90f56c --- /dev/null +++ b/web/package.json @@ -0,0 +1,29 @@ +{ + "name": "mimo-array-visualizer-web", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "typecheck": "tsc -b", + "test": "vitest run", + "preview": "vite preview" + }, + "dependencies": { + "lucide-react": "1.60.0", + "plotly.js-cartesian-dist-min": "3.7.0", + "react": "19.3.1", + "react-dom": "19.3.1", + "zustand": "5.0.15" + }, + "devDependencies": { + "@types/node": "22.20.5", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "5.2.0", + "typescript": "5.9.3", + "vite": "7.3.7", + "vitest": "3.2.7" + } +} diff --git a/web/public/favicon.png b/web/public/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..88b711cfe8ad840354d79ee6df6578a470aece0b GIT binary patch literal 2505 zcmV;)2{!hLP)AEZxveg208)~sxi}539d=p8CU_tEzLSm#L=#z;}lm`=^ls9~`0ZqUM zBPn2fxxxbvm!=_6Kw~Z8qvC?5twgQujkXr^ zB-D`uzzx*Fzs<83%+(3aeynJe@O(` zmIPP;m&=dTgkKn^3Fu)1`)RCSFf*i2`2oM2Q1;Eqp;O-#8!vY`x0oJ?2{&2pp zd^Jh9Z8tUlx6~k@K|q6m1_2EM7ILyGI!Pg*l&aXkb=~SGkxD^`@^HfQJdn{NIVmNi ztj<44c%E0a@6z&mF!;U?-}i4$0Lhv_tEE~KDm%TbFq!{V-?xInDrJo%QmGWSZrvK0 ztX{>BKmHiDZCC7U`}XZ8B_?(S|p`|PvuJP(#-MaGg+ z;_B6_IC}J`>0`%^9cXE3f#-QpN@03>8lQdkS;dtniO$YW^!D}|$@6_5BO@ai85x0; zvW)yBfUHuA0Q{bw9#%_jZEciNQV2l+6hcr+$#^`@nVFf2Z612)Ap)S3l9pvrDaHQ& ze%4B(qoZtUYNAq#LJ0o)>#vdWAAkIju~>{!%E-Q7DMcwI`}+FI`rNZ;j}L&BWn}}* zm5t!s+#Fojg>Bn#T^FwFqF5}#aU2W`48Zq&qmP=+y?gg!>C&Yr7K?CQ7mnjZp1Q8< zx@c=_!@KXk8z~RxLZN`}?ryyN^2C-xdi827TC@lx@y$2im@+9P;_*1r=`<3FL>aKo&Q2^}zTBvsQVKIO zGq`Z!f>DvuloUc_1CjQB`st^d;yF1vX;c6JFJ8P@vwnAXw^0`WoS2wkz3GW3o*)1| z_0&@p%QtM;5D|R*BGQy12r)*0i~2NND~ti zNF);GZ!K<`ZEZA#5P0N~M=(7-4cB!cgg`!@$N2a-u3ftZDJ52|T7}luR*;005|2Lm zD9)ch58JkJ_Uu_B1$r)Xb90bVnpIUw;rs8uM(?U|iy6r} zbm$Orxtv)Y&-2jN*N0>>X<~)%zWWYee)%O*sT7`m`f0Sbwwkd#&%+mAe1WmCF)UiN z2%9%=Mtgg^nU8LN>eMN?u3KFK!ZzTy-+rr0KVN(8wYus(_Sj9UoY znwpB#85|rW0LEf54h;>J^>OgvK>}cFYim_IA%vh(s!ReZ5^(wQWs;kKKOuN zef1Sd((^o$r0@I2H|uv_fBiKN9y~~rEEbC-$xlE1l<|0+D^{%F@bGY?K1pUW8J;_L zj_1#xH&5Nx^E~>#&rBx6haY~J0Jvq#7S7Jj((^o%uUxspHEY&z*REZrjUMCV$&*~Z ze7TNY>QjNaxjE!=IoP(1SS*H2CWB8t`2@qm!ypNz6r_~6=bn2oJ3DJc{q@&hM^8@= za=9D|g#zO7I3_12Q79C!Y}qobTel9mTrQ$6U0q#es*}&>Q79B3gn;Y1=FH@?vsok(32fQ2#ke*t5o2Rxn4Fx%0}niabUF>s z^U&1PgsG`1jE;_C{rdGLXwd;mb8~aq>d(#1!M5#+ySd}XkDGqCZQF)?J|EdFl7#R3 zW(>!1aN@*?x;9V71}LTcQX_Qq=uyVwaS9>0a^*^9v)M93^W1aKv8}C*Cr_R%GnCIi z|Gcp$;nd&X&z(DW@|9O!;j6E{%AGrR^5>s_u4+u*eDh68DVa{EIX*sqQ{(&5M;}oL zQBwlS2ms)Zjg8TDT^5T)x~|I`H*T<{rNxNZfddE3d)IY&`SN7~;MT2MNs{?|p04Zi zmtTG%01gfgn)i<5&~;t@_19k&#ed_*jqLC5=ia@0>3JR<$6=vRpyzoynj-+d^Ugbw zv2@n`lVp2)dqiC;5g@|{6adiM+l#igHe)bIBA3fWqAI175jE|*g%Gf98;;|c_cw0b zKsueq)rhal~RVSe6B)6qHgJ8XCffAAX3z!NEv0>NpNksT5v# z;ROgGFg!eLqC4HEo(oAFIdTN~e7NlSo~lF4K;63;*RfykoxaIfll>eMMCvG2eCK2oWa=`*}v z(L29-Pm*qFFHq`w=G9)H+F@llh|sQ2yD(i=>bmqwRytsCg zrwuEKR<(o3e{#TD&s=WxptSLSfd&B$0vZG~2xt({AfO@vI#OCF$>7xlT*KctEiliC z(AfSAFhhSU?BVZgCR_jnFu>~RZ-sR*{qH;MX4pR^Km=ILm!k{*b9n}8@E-sJfm*op zaP{2)+dzOda<6c~Uzu6(m!=xm<`(M3$pwFPcEMks#w}c*S9g%hQ=u#WHPe3qj{OJD TdHY+*00000NkvXXu0mjfM8MOD literal 0 HcmV?d00001 diff --git a/web/src/App.tsx b/web/src/App.tsx new file mode 100644 index 0000000..1a3a8b6 --- /dev/null +++ b/web/src/App.tsx @@ -0,0 +1,177 @@ +import { RefreshCw } from "lucide-react"; +import { lazy, Suspense, useCallback, useEffect, useState } from "react"; +import { api } from "./api/client"; +import { ControlBar, StatusBar, TopBar } from "./components/Chrome"; +import { Overview } from "./components/Overview"; +import { Button, Spinner, useFilePicker } from "./components/ui"; +import { translate, useT } from "./i18n"; +import { exportLayout, importFile, saveProject } from "./state/actions"; +import { useEvaluationSync } from "./state/compute"; +import { type ThemeMode, useStore, type ViewId } from "./state/store"; +import { ArrayView } from "./views/ArrayView"; + +const DbfView = lazy(() => import("./views/DbfView").then((m) => ({ default: m.DbfView }))); +const Dbf2dView = lazy(() => import("./views/Dbf2dView").then((m) => ({ default: m.Dbf2dView }))); +const AngleView = lazy(() => import("./views/AngleView").then((m) => ({ default: m.AngleView }))); +const DictionaryDialog = lazy(() => import("./dialogs/DictionaryDialog").then((m) => ({ default: m.DictionaryDialog }))); +const PatternsDialog = lazy(() => import("./dialogs/PatternsDialog").then((m) => ({ default: m.PatternsDialog }))); +const ReportDialog = lazy(() => import("./dialogs/ReportDialog").then((m) => ({ default: m.ReportDialog }))); +const ProjectsDialog = lazy(() => import("./dialogs/ProjectsDialog").then((m) => ({ default: m.ProjectsDialog }))); +const HelpDialog = lazy(() => import("./dialogs/HelpDialog").then((m) => ({ default: m.HelpDialog }))); + +const VIEW_KEYS: Record = { "1": "array", "2": "dbf1d", "3": "dbf2d", "4": "angle" }; + +function useThemeAttribute(theme: ThemeMode) { + useEffect(() => { + const root = document.documentElement; + if (theme === "system") root.removeAttribute("data-theme"); + else root.setAttribute("data-theme", theme); + }, [theme]); +} + +function isTextInput(target: EventTarget | null): boolean { + const element = target as HTMLElement | null; + if (!element) return false; + const tag = element.tagName; + return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || element.isContentEditable; +} + +function useShortcuts(pickImport: () => void) { + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + const state = useStore.getState(); + if (state.dialog) return; + const mod = event.ctrlKey || event.metaKey; + const key = event.key.toLowerCase(); + if (mod && key === "s") { + event.preventDefault(); + saveProject(); + return; + } + if (mod && key === "o") { + event.preventDefault(); + pickImport(); + return; + } + if (mod && key === "e") { + event.preventDefault(); + exportLayout(); + return; + } + if (isTextInput(event.target)) return; + if (mod && key === "z" && !event.shiftKey) { + event.preventDefault(); + state.undo(); + } else if (mod && (key === "y" || (key === "z" && event.shiftKey))) { + event.preventDefault(); + state.redo(); + } else if (!mod && !event.altKey && VIEW_KEYS[event.key]) { + state.setView(VIEW_KEYS[event.key]); + } else if ((event.key === "Delete" || event.key === "Backspace") && state.view === "array") { + const { selection, project } = state; + if (!selection || !project) { + if (event.key === "Delete") state.setDeleteMode(!state.deleteMode); + return; + } + if (project.layout[selection.kind].length <= 1) { + state.setStatus("physical.lastElement", "error", { kind: selection.kind === "tx" ? "Tx" : "Rx" }); + return; + } + const name = `${selection.kind === "tx" ? "Tx" : "Rx"}${selection.index + 1}`; + state.commitLayout( + { ...project.layout, [selection.kind]: project.layout[selection.kind].filter((_, i) => i !== selection.index) }, + null, + ); + state.setStatus("status.deleted", "success", { name }); + } else if (event.key === "Escape") { + if (state.deleteMode) state.setDeleteMode(false); + else if (state.selection) state.select(null); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [pickImport]); +} + +function Boot({ onReady }: { onReady: () => void }) { + const language = useStore((state) => state.language); + const [failed, setFailed] = useState(false); + const load = useCallback(() => { + setFailed(false); + api.config().then( + (config) => { + useStore.getState().initialize(config); + onReady(); + }, + () => setFailed(true), + ); + }, [onReady]); + useEffect(load, [load]); + return ( +
+ {failed ? ( + <> +

{translate(language, "app.offline")}

+ + + ) : ( + <> + +

{translate(language, "app.loading")}

+ + )} +
+ ); +} + +function Workbench() { + const t = useT(); + const view = useStore((state) => state.view); + const dialog = useStore((state) => state.dialog); + const openDialog = useStore((state) => state.openDialog); + const language = useStore((state) => state.language); + const pickImport = useFilePicker(".json,.zip,application/json,application/zip", importFile); + useEvaluationSync(); + useShortcuts(pickImport); + useEffect(() => { + document.documentElement.lang = language === "zh" ? "zh-CN" : language; + document.title = t("app.name"); + }, [language, t]); + const close = useCallback(() => openDialog(null), [openDialog]); + + return ( +
+ + +
+
+ }> + {view === "array" && } + {view === "dbf1d" && } + {view === "dbf2d" && } + {view === "angle" && } + +
+ +
+ + + {dialog === "dictionary" && } + {dialog === "patterns" && } + {dialog === "report" && } + {dialog === "projects" && } + {dialog === "help" && } + +
+ ); +} + +export function App() { + const theme = useStore((state) => state.theme); + const [ready, setReady] = useState(false); + useThemeAttribute(theme); + const onReady = useCallback(() => setReady(true), []); + return ready ? : ; +} diff --git a/web/src/api/client.ts b/web/src/api/client.ts new file mode 100644 index 0000000..017fd6e --- /dev/null +++ b/web/src/api/client.ts @@ -0,0 +1,137 @@ +import type { + AssetInfo, + Axis, + ChannelPatternBinding, + Dbf2dResult, + DbfBank, + DictionaryPreview, + ElementPatternPreview, + Evaluation, + ImportResult, + Job, + Layout, + PatternKind, + PatternPlane, + Project, + ProjectRecord, + ProjectSummary, + ReportOptions, + ServerConfig, +} from "./types"; + +export class ApiError extends Error { + constructor( + message: string, + readonly status: number, + ) { + super(message); + } +} + +async function request(path: string, init: RequestInit = {}): Promise { + let response: Response; + try { + response = await fetch(path, init); + } catch (error) { + if ((error as Error).name === "AbortError") throw error; + throw new ApiError("network", 0); + } + if (!response.ok) { + let detail = response.statusText; + try { + const body = await response.json(); + if (typeof body?.detail === "string") detail = body.detail; + } catch { + // keep status text + } + throw new ApiError(detail || `HTTP ${response.status}`, response.status); + } + if (response.status === 204) return undefined as T; + return (await response.json()) as T; +} + +function post(path: string, body: unknown, signal?: AbortSignal): Promise { + return request(path, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal, + }); +} + +async function postForBlob(path: string, body: unknown): Promise { + const response = await fetch(path, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + if (!response.ok) { + let detail = response.statusText; + try { + detail = (await response.json()).detail ?? detail; + } catch { + // keep status text + } + throw new ApiError(detail, response.status); + } + return response.blob(); +} + +function upload(path: string, file: File): Promise { + const form = new FormData(); + form.append("file", file, file.name); + return request(path, { method: "POST", body: form }); +} + +export const api = { + config: () => request("/api/config"), + autoLayout: (tx_count: number, rx_count: number) => + post("/api/layout/auto", { tx_count, rx_count }), + evaluate: (project: Project, signal?: AbortSignal) => + post("/api/evaluate", { project }, signal), + dbfBank: (project: Project, axis: Axis, signal?: AbortSignal) => + post("/api/dbf/bank", { project, axis }, signal), + dbf2d: (project: Project, frames: { azimuth: number; elevation: number }[], signal?: AbortSignal) => + post("/api/dbf/2d", { project, frames }, signal), + uploadAsset: (file: File) => upload("/api/assets", file), + assetInfo: (id: string) => request(`/api/assets/${id}`), + elementPatternPreview: (asset: string, swap_axes: boolean) => + post("/api/element-pattern/preview", { asset, swap_axes }), + resolveChannelPatterns: (body: { + project: Project; + asset: string; + kind: PatternKind; + plane: PatternPlane; + target: "physical" | "virtual"; + channel?: string | null; + }) => post("/api/channel-patterns/resolve", body), + dictionaryPreview: (project: Project, axis: Axis, signal?: AbortSignal) => + post("/api/dictionary/preview", { project, axis }, signal), + importDocument: (document: unknown) => post("/api/import/document", { document }), + importBundle: (file: File) => upload("/api/import/bundle", file), + exportLayout: (project: Project) => post>("/api/export/layout", { project }), + exportBundle: (project: Project) => postForBlob("/api/export/bundle", { project }), + listProjects: () => request("/api/projects"), + getProject: (id: string) => request(`/api/projects/${id}`), + createProject: (project: Project) => post("/api/projects", { project }), + updateProject: (id: string, project: Project) => + request(`/api/projects/${id}`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ project }), + }), + deleteProject: (id: string) => request(`/api/projects/${id}`, { method: "DELETE" }), + createReport: (project: Project, options: ReportOptions) => + post("/api/reports", { project, options }), + createAngleErrorImage: (project: Project, error_limit_deg: number, language: string) => + post("/api/angle-error-image", { project, error_limit_deg, language }), + job: (id: string) => request(`/api/jobs/${id}`), + cancelJob: (id: string) => post(`/api/jobs/${id}/cancel`, {}), + jobDownloadUrl: (id: string) => `/api/jobs/${id}/download`, +}; + +export function errorMessage(error: unknown): string { + if (error instanceof ApiError) return error.message; + if (error instanceof Error) return error.message; + return String(error); +} diff --git a/web/src/api/types.ts b/web/src/api/types.ts new file mode 100644 index 0000000..91087e7 --- /dev/null +++ b/web/src/api/types.ts @@ -0,0 +1,280 @@ +// Mirrors src/virtual_array/project.py and engine.py payloads. + +export type ElementKind = "tx" | "rx"; +export type Axis = "azimuth" | "elevation"; +export type DictionaryMode = "ideal" | "ideal_reversed" | "channel_pattern" | "custom"; +export type ChannelMode = "virtual" | "physical"; +export type PatternKind = "amplitude" | "phase"; +export type PatternPlane = "horizontal" | "elevation"; + +export interface Point { + x: number; + y: number; +} + +export interface Layout { + tx: Point[]; + rx: Point[]; +} + +export interface DictionarySettings { + mode: DictionaryMode; + azimuth_asset: string | null; + elevation_asset: string | null; + channel_mode: ChannelMode; + phase_reversed: boolean; + zero_phase_calibrated: boolean; +} + +export interface ElementPatternSettings { + asset: string; + swap_axes: boolean; +} + +export interface ChannelPatternBinding { + channel: string; + kind: PatternKind; + plane: PatternPlane; + asset: string; + column_index: number; + column: string; +} + +export interface Project { + version: 2; + name: string; + frequency_ghz: number; + ambiguity_margin_db: number; + layout: Layout; + dbf_dictionary: DictionarySettings; + element_pattern: ElementPatternSettings | null; + channel_patterns: ChannelPatternBinding[]; +} + +/** JSON-safe number from the server: ±Infinity arrive as strings. */ +export type WireNumber = number | "Infinity" | "-Infinity" | null; + +export interface EncodedArray { + dtype: "float32" | "float64"; + shape: number[]; + data: string; +} + +export type CutReason = + | "competitor" + | "error_jump" + | "boundary_limited" + | "unreliable" + | "data_boundary" + | "normal" + | null; + +export interface AngleMetrics { + no_fold_left: WireNumber; + no_fold_right: WireNumber; + no_fold_width: WireNumber; + no_fold_max_abs_error: WireNumber; + focus_max_abs_error: WireNumber; + center_error: WireNumber; + min_peak_margin_db: WireNumber; + center_peak_margin_db: WireNumber; + negative_cut_reason: CutReason; + positive_cut_reason: CutReason; +} + +export interface ArrayMetrics { + tx_count: number; + rx_count: number; + virtual_count: number; + unique_count: number; + azimuth_resolution: WireNumber; + elevation_resolution: WireNumber; + azimuth_3db_beamwidth: WireNumber; + azimuth_null_beamwidth: WireNumber; + azimuth_islr_db: WireNumber; + azimuth_first_sidelobe_db: WireNumber; + azimuth_first_sidelobe_angle: WireNumber; + azimuth_grating_lobe_db: WireNumber; + azimuth_grating_lobe_angle: WireNumber; + elevation_3db_beamwidth: WireNumber; + psl_db: WireNumber; + azimuth_psl_db: WireNumber; + elevation_psl_db: WireNumber; + sidelobe_azimuth: WireNumber; + sidelobe_elevation: WireNumber; + front_radar_status: "Good" | "Acceptable" | "Risky" | "Bad" | string; + elevation_ambiguity_level: "High" | "Medium" | "Low" | string; + psl_grade: string; + warning_messages: string[]; +} + +export interface VirtualPointGroup { + x: number; + y: number; + count: number; + pairs: string[]; +} + +export type AmpPhaseState = "ideal" | "imported" | "mixed"; + +export interface Evaluation { + wavelength_mm: number; + half_wavelength_mm: number; + summary: { + tx_count: number; + rx_count: number; + virtual_count: number; + unique_count: number; + duplicate_locations: number; + duplicate_excess: number; + utilization: number; + x_aperture_lambda: number; + y_aperture_lambda: number; + x_aperture_mm: number; + y_aperture_mm: number; + }; + metrics: ArrayMetrics; + capability: { azimuth: boolean; elevation: boolean; two_d: boolean }; + virtual_points: VirtualPointGroup[]; + angle: Record; + pattern_status: { amplitude: AmpPhaseState; phase: AmpPhaseState }; + notes: string[]; +} + +export interface DbfBank { + axis: Axis; + true_angles: number[]; + scan_angles: number[]; + spectra_db: EncodedArray; + frames: { + estimated: number[]; + errors: number[]; + main_peak_db: number[]; + competitor_peak_db: WireNumber[]; + margins_db: WireNumber[]; + quality: CutReason[]; + }; + metrics: AngleMetrics; +} + +export interface Dbf2dFrame { + true_azimuth: number; + true_elevation: number; + peak_azimuth: number; + peak_elevation: number; + peak_db: number; + spectrum_db: EncodedArray; +} + +export interface Dbf2dResult { + scan_azimuths: number[]; + scan_elevations: number[]; + frames: Dbf2dFrame[]; +} + +export interface AssetInfo { + id: string; + filename: string; + size: number; + uploaded_at: string; +} + +export interface PatternCutMetrics { + peak_angle_deg: number; + peak_gain_dbi: number; + beamwidth_3db_deg: number | null; + beamwidth_6db_deg: number | null; +} + +export interface ElementPatternPreview { + name: string; + angle_column: string; + horizontal_column: string; + elevation_column: string | null; + angles: number[]; + horizontal_gain_db: number[]; + elevation_gain_db: number[] | null; + horizontal_metrics: PatternCutMetrics; + elevation_metrics: PatternCutMetrics | null; +} + +export interface DictionaryPreview { + axis: Axis; + angles: number[]; + phase_deg: EncodedArray; + channel_count: number; + quality: { + severity: "ok" | "warning" | "danger"; + row_count: number; + channel_count: number; + zero_norm_rows: number; + competitor_ambiguous_rows: number; + non_neighbor_effective_rank: number; + non_neighbor_rank_rows: number; + }; + tables: Record< + Axis, + { channel_mode: ChannelMode; value_format: string; rows: number; columns: string[]; is_2d: boolean } | null + >; +} + +export interface ProjectSummary { + id: string; + name: string; + created_at: string; + updated_at: string; + tx_count: number; + rx_count: number; + frequency_ghz: number | null; +} + +export interface ProjectRecord { + id: string; + created_at: string; + updated_at: string; + project: Project; +} + +export interface ImportResult { + project: Project; + missing_assets: string[]; +} + +export interface Job { + id: string; + kind: "report" | "angle_image"; + status: "queued" | "running" | "succeeded" | "failed" | "cancelled"; + progress: number; + message: string; + error: string | null; + download_name: string | null; +} + +export interface ReportOptions { + title: string; + azimuth_focus: { start: number; stop: number }; + elevation_focus: { start: number; stop: number }; + azimuth_hold: { start: number; stop: number }; + elevation_hold: { start: number; stop: number }; + azimuth_hold_stride_frames: number; + elevation_hold_stride_frames: number; + error_limit_deg: number; + spectrum_floor_db: number; + include_raw_data: boolean; + include_spectrum_db: boolean; + include_spectrum_magnitude: boolean; + language: "zh" | "en" | "ja"; +} + +export interface ServerConfig { + version: string; + default_project: Project; + limits: { + max_tx: number; + max_rx: number; + grid_step_lambda: number; + max_asset_bytes: number; + max_2d_frames_per_request: number; + }; + dbf: { scan_fov: [number, number]; scan_step_deg: number; scan_grid_size: number }; +} diff --git a/web/src/charts/Plot.tsx b/web/src/charts/Plot.tsx new file mode 100644 index 0000000..e358c98 --- /dev/null +++ b/web/src/charts/Plot.tsx @@ -0,0 +1,107 @@ +import { useEffect, useRef } from "react"; + +// Plotly is large; load it on first use so the array editor opens instantly. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let plotlyPromise: Promise | null = null; +function loadPlotly() { + plotlyPromise ??= import("plotly.js-cartesian-dist-min").then((module) => module.default ?? module); + return plotlyPromise; +} + +export interface PlotPoint { + x: number; + y: number; + z?: number; + curveNumber: number; + pointIndex: number; +} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +export function Plot({ + data, + layout, + config, + onClick, + className, + style, + ariaLabel, +}: { + data: any[]; + layout: Record; + config?: Record; + onClick?: (point: PlotPoint) => void; + className?: string; + style?: React.CSSProperties; + ariaLabel?: string; +}) { + const container = useRef(null); + const clickHandler = useRef(onClick); + clickHandler.current = onClick; + const ready = useRef(false); + + useEffect(() => { + let cancelled = false; + const element = container.current; + if (!element) return; + loadPlotly().then((Plotly) => { + if (cancelled || !element) return; + Plotly.react(element, data, layout, { + displaylogo: false, + responsive: false, + displayModeBar: false, + doubleClick: "reset", + ...config, + }); + if (!ready.current) { + ready.current = true; + (element as any).on?.("plotly_click", (event: any) => { + const point = event?.points?.[0]; + if (point && clickHandler.current) { + clickHandler.current({ + x: Number(point.x), + y: Number(point.y), + z: point.z === undefined ? undefined : Number(point.z), + curveNumber: point.curveNumber, + pointIndex: Array.isArray(point.pointIndex) ? point.pointIndex[0] : point.pointIndex, + }); + } + }); + } + }); + return () => { + cancelled = true; + }; + }, [data, layout, config]); + + useEffect(() => { + const element = container.current; + if (!element) return; + let frame = 0; + const observer = new ResizeObserver(() => { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => { + loadPlotly().then((Plotly) => { + if (ready.current && element.isConnected) Plotly.Plots.resize(element); + }); + }); + }); + observer.observe(element); + return () => { + observer.disconnect(); + cancelAnimationFrame(frame); + loadPlotly().then((Plotly) => Plotly.purge(element)); + ready.current = false; + }; + }, []); + + return ( +
+ ); +} +/* eslint-enable @typescript-eslint/no-explicit-any */ diff --git a/web/src/charts/plotly.d.ts b/web/src/charts/plotly.d.ts new file mode 100644 index 0000000..03ef9fa --- /dev/null +++ b/web/src/charts/plotly.d.ts @@ -0,0 +1,5 @@ +declare module "plotly.js-cartesian-dist-min" { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const Plotly: any; + export default Plotly; +} diff --git a/web/src/charts/theme.ts b/web/src/charts/theme.ts new file mode 100644 index 0000000..95a0d95 --- /dev/null +++ b/web/src/charts/theme.ts @@ -0,0 +1,98 @@ +import { useEffect, useState } from "react"; + +export interface ChartTheme { + text: string; + textSecondary: string; + grid: string; + zero: string; + surface: string; + line: string; + secondary: string; + trueAngle: string; + peak: string; + band: string; + tx: string; + rx: string; + accent: string; + danger: string; + warning: string; + success: string; + dark: boolean; + font: string; +} + +function readTheme(): ChartTheme { + const style = getComputedStyle(document.documentElement); + const value = (name: string) => style.getPropertyValue(name).trim(); + return { + text: value("--text"), + textSecondary: value("--text-secondary"), + grid: value("--chart-grid"), + zero: value("--chart-zero"), + surface: value("--surface"), + line: value("--chart-line"), + secondary: value("--chart-secondary"), + trueAngle: value("--chart-true"), + peak: value("--chart-peak"), + band: value("--chart-band"), + tx: value("--tx"), + rx: value("--rx"), + accent: value("--accent"), + danger: value("--danger"), + warning: value("--warning"), + success: value("--success"), + dark: style.getPropertyValue("color-scheme").trim() === "dark", + font: value("--font-sans"), + }; +} + +/** Re-reads CSS tokens whenever the theme attribute or OS scheme changes. */ +export function useChartTheme(): ChartTheme { + const [theme, setTheme] = useState(() => readTheme()); + useEffect(() => { + const refresh = () => setTheme(readTheme()); + const observer = new MutationObserver(refresh); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] }); + const media = window.matchMedia("(prefers-color-scheme: dark)"); + media.addEventListener("change", refresh); + return () => { + observer.disconnect(); + media.removeEventListener("change", refresh); + }; + }, []); + return theme; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function baseLayout(theme: ChartTheme, overrides: Record = {}): Record { + const axis = { + gridcolor: theme.grid, + zerolinecolor: theme.zero, + linecolor: theme.zero, + tickcolor: theme.zero, + ticks: "outside", + ticklen: 4, + showline: true, + mirror: false, + tickfont: { size: 11, color: theme.textSecondary }, + title: { font: { size: 12, color: theme.textSecondary }, standoff: 6 }, + automargin: true, + }; + return { + paper_bgcolor: "rgba(0,0,0,0)", + plot_bgcolor: "rgba(0,0,0,0)", + font: { family: theme.font, size: 12, color: theme.text }, + margin: { l: 56, r: 16, t: 12, b: 44 }, + showlegend: false, + hovermode: "x", + hoverlabel: { + bgcolor: theme.surface, + bordercolor: theme.zero, + font: { family: theme.font, size: 12, color: theme.text }, + }, + dragmode: false, + ...overrides, + xaxis: { ...axis, ...(overrides.xaxis ?? {}) }, + yaxis: { ...axis, ...(overrides.yaxis ?? {}) }, + }; +} diff --git a/web/src/components/Chrome.tsx b/web/src/components/Chrome.tsx new file mode 100644 index 0000000..980a5bd --- /dev/null +++ b/web/src/components/Chrome.tsx @@ -0,0 +1,291 @@ +import { + Activity, + Check, + ChevronDown, + Download, + FileDown, + FilePlus2, + FileText, + FolderOpen, + Grid3x3, + HelpCircle, + Languages, + LineChart, + Map as MapIcon, + Monitor, + Moon, + MoreHorizontal, + Package, + Radar, + Save, + Sun, + Target, + Upload, +} from "lucide-react"; +import type { ReactNode } from "react"; +import { LANGUAGE_LABELS, useT } from "../i18n"; +import { fmt, parseNumber, trimNumber } from "../lib/format"; +import { exportBundle, exportLayout, importFile, newProject, saveProject } from "../state/actions"; +import { type Language, type ThemeMode, useIsDirty, useStore, type ViewId } from "../state/store"; +import { Button, Menu, MenuItem, NumberInput, Segmented, Spinner, useFilePicker } from "./ui"; + +export function TopBar() { + const t = useT(); + const project = useStore((state) => state.project)!; + const projectId = useStore((state) => state.projectId); + const language = useStore((state) => state.language); + const theme = useStore((state) => state.theme); + const { updateProject, openDialog, setLanguage, setTheme } = useStore.getState(); + const dirty = useIsDirty(); + const pickImport = useFilePicker(".json,.zip,application/json,application/zip", importFile); + + return ( +
+
+ + {t("app.name")} + +
+
+ updateProject({ name: event.target.value })} + onBlur={(event) => !event.target.value.trim() && updateProject({ name: t("project.untitled") })} + /> + + + + {!projectId ? t("project.local") : dirty ? t("project.unsaved") : t("project.saved")} + + +
+
+
+ + + ( + + )} + > + {(close) => ( + <> + } onSelect={() => { close(); pickImport(); }}> + {t("menu.importLayout")} + + } onSelect={() => { close(); pickImport(); }}> + {t("menu.importBundle")} + + + )} + + ( + + )} + > + {(close) => ( + <> + } onSelect={() => { close(); exportLayout(); }}> + {t("menu.exportLayout")} + + } onSelect={() => { close(); exportBundle(); }}> + {t("menu.exportBundle")} + + + )} + + + ( + +
+
+ ); +} + +const VIEWS: { id: ViewId; icon: ReactNode; key: "view.array" | "view.dbf1d" | "view.dbf2d" | "view.angle" }[] = [ + { id: "array", icon: , key: "view.array" }, + { id: "dbf1d", icon: , key: "view.dbf1d" }, + { id: "dbf2d", icon: , key: "view.dbf2d" }, + { id: "angle", icon: , key: "view.angle" }, +]; + +export function ControlBar() { + const t = useT(); + const project = useStore((state) => state.project)!; + const view = useStore((state) => state.view); + const display = useStore((state) => state.display); + const evaluation = useStore((state) => state.evaluation); + const { setView, updateProject, setDisplay, openDialog } = useStore.getState(); + const dictMode = project.dbf_dictionary.mode; + const pattern = evaluation?.pattern_status; + const patternActive = pattern && (pattern.amplitude !== "ideal" || pattern.phase !== "ideal"); + + return ( + + ); +} + +export function StatusBar() { + const t = useT(); + const status = useStore((state) => state.status); + const evaluating = useStore((state) => state.evaluating); + const config = useStore((state) => state.config); + const evaluation = useStore((state) => state.evaluation); + const project = useStore((state) => state.project); + const language = useStore((state) => state.language); + const separator = language === "en" ? ": " : ":"; + const text = status + ? `${t(status.key, status.params)}${status.detail ? `${separator}${status.detail}` : ""}` + : t("status.ready"); + return ( +
+ + {status?.tone === "success" && } + {text} + + {evaluating && ( + + {t("status.computing")} + + )} + {project && evaluation && ( + + λ = {fmt(evaluation.wavelength_mm, 3)} mm @ {trimNumber(project.frequency_ghz, 3)} GHz + + )} + {config && v{config.version}} +
+ ); +} diff --git a/web/src/components/Overview.tsx b/web/src/components/Overview.tsx new file mode 100644 index 0000000..8cd65eb --- /dev/null +++ b/web/src/components/Overview.tsx @@ -0,0 +1,212 @@ +import { AlertTriangle, ChevronRight } from "lucide-react"; +import type { AngleMetrics, Axis, CutReason, Evaluation } from "../api/types"; +import { type Translate, useT } from "../i18n"; +import { wire } from "../lib/encoding"; +import { fmt, fmtSigned } from "../lib/format"; +import { useStore } from "../state/store"; +import { Callout, Spinner } from "./ui"; + +function cutReason(reason: CutReason, t: Translate): string { + return reason ? t(`cut.${reason}` as const) : "—"; +} + +export function cutSummary(metrics: AngleMetrics, t: Translate): string { + const negative = cutReason(metrics.negative_cut_reason, t); + const positive = cutReason(metrics.positive_cut_reason, t); + return negative === positive ? negative : t("cut.pair", { negative, positive }); +} + +function noFoldText(metrics: AngleMetrics): string { + const left = wire(metrics.no_fold_left); + const right = wire(metrics.no_fold_right); + const width = wire(metrics.no_fold_width); + if (left === null || right === null || !Number.isFinite(left) || !Number.isFinite(right)) return "—"; + return `${fmtSigned(left)} ~ ${fmtSigned(right)} (${fmt(width, 0, "°")})`; +} + +function marginText(metrics: AngleMetrics, t: Translate): string { + const width = wire(metrics.no_fold_width) ?? 0; + const limited = ["boundary_limited", "unreliable"]; + if ( + width <= 0 && + (limited.includes(metrics.negative_cut_reason ?? "") || limited.includes(metrics.positive_cut_reason ?? "")) + ) { + return t("overview.unavailable"); + } + const margin = wire(metrics.min_peak_margin_db); + if (margin === Number.POSITIVE_INFINITY) return t("overview.noCompetitor"); + return fmt(margin, 1, " dB"); +} + +function gradeTone(grade: string): string { + if (grade === "Good") return "ok"; + if (grade === "Acceptable") return ""; + if (grade === "Risky") return "warn"; + return "bad"; +} + +export function Overview() { + const t = useT(); + const evaluation = useStore((state) => state.evaluation); + const evaluating = useStore((state) => state.evaluating); + const error = useStore((state) => state.evaluationError); + return ( + + ); +} + +function Kpis({ evaluation }: { evaluation: Evaluation }) { + const t = useT(); + const { summary, metrics } = evaluation; + const utilization = Math.round(summary.utilization * 100); + return ( +
+ + + + + + +
+ ); +} + +function Kpi({ label, value, sub, tone }: { label: string; value: string; sub?: string; tone?: "warn" }) { + return ( +
+ + {label} + + {value} + {sub && {sub}} +
+ ); +} + +function AngleCard({ axis, evaluation }: { axis: Axis; evaluation: Evaluation }) { + const t = useT(); + const result = evaluation.angle[axis]; + const title = t(axis === "azimuth" ? "axis.azimuth" : "axis.elevation"); + return ( +
+
+ {title} + {!evaluation.capability[axis] && {t("overview.noAperture")}} +
+ {result && "error" in result ? ( + {result.error} + ) : result ? ( +
+
{t("overview.noFold")}
+
{noFoldText(result)}
+
{t("overview.maxError")}
+
{fmt(wire(result.no_fold_max_abs_error), 1, "°")}
+
{t("overview.peakMargin")}
+
{marginText(result, t)}
+
{t("overview.cutReason")}
+
{cutSummary(result, t)}
+
+ ) : null} +
+ ); +} + +function PatternMetrics({ evaluation }: { evaluation: Evaluation }) { + const t = useT(); + const m = evaluation.metrics; + const at = (value: number | null, angle: number | null, prefix = "") => + value === null || !Number.isFinite(value) ? "—" : `${fmt(value, 1, " dB")}${angle === null ? "" : ` @ ${prefix}${fmtSigned(angle, 1)}`}`; + return ( +
+
+ + +

{t("overview.patternTitle")}

+
+
+
{t("overview.az3db")}
+
{fmt(wire(m.azimuth_3db_beamwidth), 2, "°")}
+
{t("overview.el3db")}
+
{fmt(wire(m.elevation_3db_beamwidth), 2, "°")}
+
{t("overview.azPsl")}
+
{fmt(wire(m.azimuth_psl_db), 2, " dB")}
+
{t("overview.elPsl")}
+
{fmt(wire(m.elevation_psl_db), 2, " dB")}
+
{t("overview.psl2d")}
+
+ {fmt(wire(m.psl_db), 2, " dB")} +
+
{t("overview.islr")}
+
{fmt(wire(m.azimuth_islr_db), 2, " dB")}
+
{t("overview.firstSidelobe")}
+
{at(wire(m.azimuth_first_sidelobe_db), wire(m.azimuth_first_sidelobe_angle))}
+
{t("overview.grating")}
+
{at(wire(m.azimuth_grating_lobe_db), wire(m.azimuth_grating_lobe_angle))}
+
{t("overview.frontRadar")}
+
+ + {t(`grade.${m.front_radar_status}` as never)} + +
+
{t("overview.ambiguity")}
+
+ + {t(`level.${m.elevation_ambiguity_level}` as never)} + +
+
+
+
+ ); +} diff --git a/web/src/components/ui.tsx b/web/src/components/ui.tsx new file mode 100644 index 0000000..41997ad --- /dev/null +++ b/web/src/components/ui.tsx @@ -0,0 +1,331 @@ +import { AlertTriangle, CheckCircle2, Info, X, XCircle } from "lucide-react"; +import { + type ButtonHTMLAttributes, + type ReactNode, + useCallback, + useEffect, + useId, + useRef, + useState, +} from "react"; +import { createPortal } from "react-dom"; + +type ButtonVariant = "default" | "primary" | "ghost" | "danger"; + +export function Button({ + variant = "default", + size, + icon, + active, + className = "", + children, + ...rest +}: ButtonHTMLAttributes & { + variant?: ButtonVariant; + size?: "sm"; + icon?: ReactNode; + active?: boolean; +}) { + const iconOnly = !children; + const classes = [ + "btn", + variant !== "default" ? variant : "", + size ?? "", + iconOnly ? "icon" : "", + active ? "active" : "", + className, + ] + .filter(Boolean) + .join(" "); + return ( + + ); +} + +export function Segmented({ + value, + options, + onChange, + label, +}: { + value: T; + options: { value: T; label: ReactNode; title?: string }[]; + onChange: (value: T) => void; + label?: string; +}) { + return ( +
+ {options.map((option) => ( + + ))} +
+ ); +} + +/** + * Numeric input that commits on Enter/blur and reverts invalid text, + * matching the desktop tool's "restore last valid value" behaviour. + */ +export function NumberInput({ + value, + onCommit, + parse, + format = (v) => String(v), + className = "input num", + invalidTitle, + ...rest +}: { + value: number; + onCommit: (value: number) => void; + parse: (text: string) => number | null; + format?: (value: number) => string; + className?: string; + invalidTitle?: string; +} & Omit, "value" | "onChange">) { + const [text, setText] = useState(format(value)); + const [invalid, setInvalid] = useState(false); + const focused = useRef(false); + + useEffect(() => { + if (!focused.current) setText(format(value)); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [value]); + + const commit = () => { + const parsed = parse(text); + if (parsed === null) { + setText(format(value)); + setInvalid(false); + return; + } + setInvalid(false); + if (parsed !== value) onCommit(parsed); + setText(format(parsed)); + }; + + return ( + { + focused.current = true; + event.currentTarget.select(); + }} + onChange={(event) => { + setText(event.target.value); + setInvalid(parse(event.target.value) === null); + }} + onBlur={() => { + focused.current = false; + commit(); + }} + onKeyDown={(event) => { + if (event.key === "Enter") { + commit(); + (event.target as HTMLInputElement).blur(); + } else if (event.key === "Escape") { + setText(format(value)); + setInvalid(false); + (event.target as HTMLInputElement).blur(); + } + event.stopPropagation(); + }} + /> + ); +} + +export function Callout({ + tone = "neutral", + title, + children, +}: { + tone?: "neutral" | "info" | "success" | "warning" | "danger"; + title?: ReactNode; + children?: ReactNode; +}) { + const icon = + tone === "success" ? ( + + ) : tone === "warning" ? ( + + ) : tone === "danger" ? ( + + ) : ( + + ); + return ( +
+ {icon} +
+ {title &&
{title}
} + {children} +
+
+ ); +} + +export function Dialog({ + title, + onClose, + children, + footer, + size, +}: { + title: ReactNode; + onClose: () => void; + children: ReactNode; + footer?: ReactNode; + size?: "wide" | "medium"; +}) { + const titleId = useId(); + const panel = useRef(null); + useEffect(() => { + const previous = document.activeElement as HTMLElement | null; + panel.current?.focus(); + const onKey = (event: KeyboardEvent) => { + if (event.key === "Escape") { + event.stopPropagation(); + onClose(); + } + }; + window.addEventListener("keydown", onKey, true); + return () => { + window.removeEventListener("keydown", onKey, true); + previous?.focus?.(); + }; + }, [onClose]); + + return createPortal( +
{ + if (event.target === event.currentTarget) onClose(); + }} + > +
+
+

{title}

+ +
+
{children}
+ {footer &&
{footer}
} +
+
, + document.body, + ); +} + +export function Menu({ + trigger, + children, + align = "right", +}: { + trigger: (props: { open: boolean; toggle: () => void }) => ReactNode; + children: (close: () => void) => ReactNode; + align?: "left" | "right"; +}) { + const [open, setOpen] = useState(false); + const anchor = useRef(null); + const close = useCallback(() => setOpen(false), []); + useEffect(() => { + if (!open) return; + const onDown = (event: MouseEvent) => { + if (!anchor.current?.contains(event.target as Node)) setOpen(false); + }; + const onKey = (event: KeyboardEvent) => event.key === "Escape" && setOpen(false); + document.addEventListener("mousedown", onDown); + document.addEventListener("keydown", onKey); + return () => { + document.removeEventListener("mousedown", onDown); + document.removeEventListener("keydown", onKey); + }; + }, [open]); + return ( +
+ {trigger({ open, toggle: () => setOpen((value) => !value) })} + {open && ( +
+ {children(close)} +
+ )} +
+ ); +} + +export function MenuItem({ + icon, + children, + onSelect, + checked, + disabled, +}: { + icon?: ReactNode; + children: ReactNode; + onSelect: () => void; + checked?: boolean; + disabled?: boolean; +}) { + return ( + + ); +} + +/** Hidden file input driven by a callback. */ +export function useFilePicker(accept: string, onFile: (file: File) => void) { + const input = useRef(null); + const callback = useRef(onFile); + callback.current = onFile; + useEffect(() => { + const element = document.createElement("input"); + element.type = "file"; + element.accept = accept; + element.style.display = "none"; + element.addEventListener("change", () => { + const file = element.files?.[0]; + element.value = ""; + if (file) callback.current(file); + }); + document.body.appendChild(element); + input.current = element; + return () => element.remove(); + }, [accept]); + return useCallback(() => input.current?.click(), []); +} + +export function Spinner() { + return
+ {error && {error}} +
+ + + + + {SLOTS.map((slot) => ( + + ))} + + + + + + + {physical.map(renderRow)} + setShowVirtual((value) => !value)}> + + + {showVirtual && virtual.map(renderRow)} + +
{t("patternDialog.channel")}{t(slotKey(slot.kind, slot.plane))} +
{t("patternDialog.groupPhysical")}
+ {showVirtual ? "▾" : "▸"} {t("patternDialog.groupVirtual")} ({virtual.length}) +
+
+ + ); +} + +function ElementPatternSection() { + const t = useT(); + const project = useStore((state) => state.project)!; + const { updateProject, setStatus } = useStore.getState(); + const settings = project.element_pattern; + const [preview, setPreview] = useState(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + if (!settings) { + setPreview(null); + return; + } + let cancelled = false; + api.elementPatternPreview(settings.asset, settings.swap_axes).then( + (result) => !cancelled && (setPreview(result), setError(null)), + (reason) => !cancelled && setError(errorMessage(reason)), + ); + return () => { + cancelled = true; + }; + }, [settings]); + + const pick = useFilePicker(PATTERN_ACCEPT, async (file) => { + setBusy(true); + setError(null); + try { + const info = await api.uploadAsset(file); + rememberAssetName(info.id, info.filename); + const result = await api.elementPatternPreview(info.id, false); + updateProject({ element_pattern: { asset: info.id, swap_axes: false } }); + setPreview(result); + setStatus("status.elementLoaded", "success", { name: result.name }); + } catch (reason) { + setError(errorMessage(reason)); + } finally { + setBusy(false); + } + }); + + const describe = (metrics: ElementPatternPreview["horizontal_metrics"] | null) => + metrics + ? t("patternDialog.metrics", { + peak: fmt(metrics.peak_gain_dbi, 2), + angle: fmt(metrics.peak_angle_deg, 1), + bw3: fmt(metrics.beamwidth_3db_deg, 1, "°"), + bw6: fmt(metrics.beamwidth_6db_deg, 1, "°"), + }) + : ""; + + return ( +
+
+

+ {t("patternDialog.elementSection")} +

+ {busy && } + {settings && ( + + )} + + {settings && ( + + )} +
+

+ {t("patternDialog.elementHint")} +

+ {error && {error}} + {!settings && {t("patternDialog.isotropic")}} + {settings && preview && ( + <> +
+ {preview.name} · θ: {preview.angle_column} · H: {preview.horizontal_column} + {preview.elevation_column ? ` · V: ${preview.elevation_column}` : ""} +
+ {!preview.elevation_column && {t("patternDialog.reuse")}} +
+ + +
+ + )} +
+ ); +} + +function PatternCut({ title, angles, gains, caption }: { title: string; angles: number[]; gains: number[]; caption: string }) { + const t = useT(); + const theme = useChartTheme(); + const data = useMemo( + () => [ + { + type: "scatter", + mode: "lines", + x: angles, + y: gains, + line: { color: theme.line, width: 2 }, + hovertemplate: "%{x:.0f}° %{y:.2f} dB", + }, + ], + [angles, gains, theme], + ); + const layout = useMemo( + () => + baseLayout(theme, { + margin: { l: 50, r: 10, t: 8, b: 40 }, + xaxis: { title: { text: t("axis.angle") }, dtick: 60 }, + yaxis: { title: { text: t("axis.gain") } }, + }), + [theme, t], + ); + return ( +
+
{title}
+
+ {caption} +
+
+
+ +
+
+
+ ); +} diff --git a/web/src/dialogs/ProjectsDialog.tsx b/web/src/dialogs/ProjectsDialog.tsx new file mode 100644 index 0000000..9825492 --- /dev/null +++ b/web/src/dialogs/ProjectsDialog.tsx @@ -0,0 +1,114 @@ +import { FolderOpen, Save, Trash2 } from "lucide-react"; +import { useCallback, useEffect, useState } from "react"; +import { api, errorMessage } from "../api/client"; +import type { ProjectSummary } from "../api/types"; +import { Button, Callout, Dialog, Spinner } from "../components/ui"; +import { useT } from "../i18n"; +import { openProject, saveProject } from "../state/actions"; +import { useIsDirty, useStore } from "../state/store"; + +export function ProjectsDialog({ onClose }: { onClose: () => void }) { + const t = useT(); + const language = useStore((state) => state.language); + const projectId = useStore((state) => state.projectId); + const dirty = useIsDirty(); + const [items, setItems] = useState(null); + const [error, setError] = useState(null); + + const refresh = useCallback(() => { + api.listProjects().then( + (result) => { + setItems(result); + setError(null); + }, + (reason) => setError(errorMessage(reason)), + ); + }, []); + useEffect(refresh, [refresh]); + + const format = (iso: string) => { + try { + return new Date(iso).toLocaleString(language === "zh" ? "zh-CN" : language === "ja" ? "ja-JP" : "en-US"); + } catch { + return iso; + } + }; + + return ( + + + {t("projectsDialog.hint")} + + + + + } + > + {error && {error}} + {dirty && projectId && ( +
+ {t("projectsDialog.discard")} +
+ )} + {!items && !error && } + {items && items.length === 0 &&

{t("projectsDialog.empty")}

} +
+ {items?.map((item) => ( +
+
+
+ {item.name || t("project.untitled")}{" "} + {item.id === projectId && {t("projectsDialog.current")}} +
+
+ {item.tx_count}T{item.rx_count}R · {item.frequency_ghz ?? "—"} GHz ·{" "} + {t("projectsDialog.updated", { time: format(item.updated_at) })} +
+
+ +
+ ))} +
+
+ ); +} diff --git a/web/src/dialogs/ReportDialog.tsx b/web/src/dialogs/ReportDialog.tsx new file mode 100644 index 0000000..65aea48 --- /dev/null +++ b/web/src/dialogs/ReportDialog.tsx @@ -0,0 +1,239 @@ +import { Download, FileText, ImageDown } from "lucide-react"; +import { useState } from "react"; +import { api } from "../api/client"; +import type { Job, ReportOptions } from "../api/types"; +import { Button, Callout, Dialog, NumberInput, Segmented } from "../components/ui"; +import { LANGUAGE_LABELS, translate, useT } from "../i18n"; +import { parseNumber, trimNumber } from "../lib/format"; +import { useExportJob } from "../state/jobs"; +import { type Language, useStore } from "../state/store"; + +type RangeKey = "azimuth_focus" | "elevation_focus" | "azimuth_hold" | "elevation_hold"; + +function angleParser(text: string) { + const value = parseNumber(text, ["°"]); + return value !== null && value >= -90 && value <= 90 ? value : null; +} + +export function ReportDialog({ onClose }: { onClose: () => void }) { + const t = useT(); + const project = useStore((state) => state.project)!; + const language = useStore((state) => state.language); + const capability = useStore((state) => state.evaluation?.capability) ?? { azimuth: true, elevation: true, two_d: true }; + const [options, setOptions] = useState(() => ({ + title: translate(language, "reportDialog.defaultTitle"), + azimuth_focus: { start: -70, stop: 70 }, + elevation_focus: { start: -15, stop: 15 }, + azimuth_hold: { start: -70, stop: 70 }, + elevation_hold: { start: -15, stop: 15 }, + azimuth_hold_stride_frames: 1, + elevation_hold_stride_frames: 1, + error_limit_deg: 1, + spectrum_floor_db: -40, + include_raw_data: true, + include_spectrum_db: true, + include_spectrum_magnitude: false, + language, + })); + const report = useExportJob(); + const image = useExportJob(); + const set = (key: K, value: ReportOptions[K]) => + setOptions((current) => ({ ...current, [key]: value })); + const setRange = (key: RangeKey, edge: "start" | "stop", value: number) => + setOptions((current) => { + const range = { ...current[key], [edge]: value }; + if (range.start > range.stop) { + if (edge === "start") range.stop = range.start; + else range.start = range.stop; + } + return { ...current, [key]: range }; + }); + const noOutput = !options.include_spectrum_db && !options.include_spectrum_magnitude; + + const rangeRow = (key: RangeKey, label: string) => ( + <> + + + trimNumber(v, 1)} onCommit={(v) => setRange(key, "start", v)} aria-label={`${label} ${t("reportDialog.start")}`} /> + ~ + trimNumber(v, 1)} onCommit={(v) => setRange(key, "stop", v)} aria-label={`${label} ${t("reportDialog.stop")}`} /> + ° + + + ); + + const strideRow = (key: "azimuth_hold_stride_frames" | "elevation_hold_stride_frames") => ( + <> + + { + const value = parseNumber(text); + return value !== null && Number.isInteger(value) && value >= 1 && value <= 180 ? value : null; + }} + onCommit={(value) => set(key, value)} + /> + + ); + + return ( + + + {t("reportDialog.note")} + + + + + + } + > +
+
+ + set("title", event.target.value)} + /> + + ({ value: code, label: LANGUAGE_LABELS[code] }))} + onChange={(value) => set("language", value)} + /> +
+
+ +
+ {(["azimuth", "elevation"] as const).map((axis) => ( +
+
{t(axis === "azimuth" ? "axis.azimuth" : "axis.elevation")}
+ {capability[axis] ? ( +
+ {rangeRow(`${axis}_focus`, t("reportDialog.focus"))} + {rangeRow(`${axis}_hold`, t("reportDialog.hold"))} + {strideRow(`${axis}_hold_stride_frames`)} +
+ ) : ( +

+ {t("reportDialog.unavailableAxis")} +

+ )} +
+ ))} +
+ +
+
+ + { + const value = parseNumber(text, ["°"]); + return value !== null && value > 0 && value <= 30 ? value : null; + }} + format={(v) => trimNumber(v, 2)} + onCommit={(value) => set("error_limit_deg", value)} + /> + + + { + const value = parseNumber(text, ["db"]); + return value !== null && value >= -120 && value <= -10 ? value : null; + }} + onCommit={(value) => set("spectrum_floor_db", value)} + /> + dB + +
+ + + + {noOutput && {t("reportDialog.needOutput")}} + +
+ +
+

{t("reportDialog.imageTitle")}

+
+ + {t("reportDialog.imageHint")} + + +
+ +
+
+ ); +} + +function JobStatus({ + state, +}: { + state: { job: Job | null; error: string | null; running: boolean; cancel: () => void; download: () => void }; +}) { + const t = useT(); + const { job, error } = state; + if (error) return {error}; + if (!job) return null; + if (job.status === "failed") return {job.error}; + if (job.status === "cancelled") return {t("reportDialog.cancelled")}; + if (job.status === "succeeded") { + return ( + + {job.download_name}{" "} + + + ); + } + return ( +
+
+ + {job.message || t("reportDialog.generating")} · {job.progress}% + + +
+
+
+
+
+ ); +} diff --git a/web/src/dialogs/useAssetNames.ts b/web/src/dialogs/useAssetNames.ts new file mode 100644 index 0000000..6964b75 --- /dev/null +++ b/web/src/dialogs/useAssetNames.ts @@ -0,0 +1,33 @@ +import { useEffect, useState } from "react"; +import { api } from "../api/client"; + +const names = new Map(); + +export function rememberAssetName(id: string, filename: string): void { + names.set(id, filename); +} + +/** Resolve asset IDs to their original filenames (cached for the session). */ +export function useAssetNames(ids: (string | null | undefined)[]): Record { + const wanted = [...new Set(ids.filter((id): id is string => Boolean(id)))]; + const key = wanted.join(","); + const [, setVersion] = useState(0); + useEffect(() => { + let cancelled = false; + const missing = wanted.filter((id) => !names.has(id)); + if (missing.length === 0) return; + Promise.all( + missing.map((id) => + api.assetInfo(id).then( + (info) => names.set(id, info.filename), + () => names.set(id, id.slice(0, 12)), + ), + ), + ).then(() => !cancelled && setVersion((value) => value + 1)); + return () => { + cancelled = true; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + return Object.fromEntries(wanted.map((id) => [id, names.get(id) ?? "…"])); +} diff --git a/web/src/i18n/__tests__/messages.test.ts b/web/src/i18n/__tests__/messages.test.ts new file mode 100644 index 0000000..4f93ac1 --- /dev/null +++ b/web/src/i18n/__tests__/messages.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vitest"; +import { HELP } from "../help"; +import { en, ja, zh } from "../messages"; + +describe("i18n catalogues", () => { + it("define the same keys and placeholders in every language", () => { + const placeholders = (text: string) => [...text.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort(); + for (const catalog of [en, ja]) { + expect(Object.keys(catalog).sort()).toEqual(Object.keys(zh).sort()); + for (const key of Object.keys(zh) as (keyof typeof zh)[]) { + expect(placeholders(catalog[key]), key).toEqual(placeholders(zh[key])); + } + } + }); + + it("help sections line up across languages", () => { + const ids = (language: keyof typeof HELP) => HELP[language].map((section) => section.id); + expect(ids("en")).toEqual(ids("zh")); + expect(ids("ja")).toEqual(ids("zh")); + }); +}); diff --git a/web/src/i18n/help.ts b/web/src/i18n/help.ts new file mode 100644 index 0000000..590e972 --- /dev/null +++ b/web/src/i18n/help.ts @@ -0,0 +1,300 @@ +import type { Language } from "../state/store"; + +export interface HelpSection { + id: string; + title: string; + paragraphs?: string[]; + steps?: string[]; + bullets?: string[]; +} + +export const SHORTCUTS: { keys: string[]; zh: string; en: string; ja: string }[] = [ + { keys: ["Ctrl", "Z"], zh: "撤销阵列编辑", en: "Undo layout edit", ja: "配置編集を元に戻す" }, + { keys: ["Ctrl", "Y"], zh: "重做阵列编辑(也可 Ctrl+Shift+Z)", en: "Redo layout edit (or Ctrl+Shift+Z)", ja: "配置編集をやり直す(Ctrl+Shift+Z も可)" }, + { keys: ["Ctrl", "S"], zh: "保存到项目库", en: "Save to the project library", ja: "プロジェクトライブラリに保存" }, + { keys: ["Ctrl", "O"], zh: "导入阵面 JSON / 项目包", en: "Import array JSON / bundle", ja: "配置 JSON / パッケージを読み込む" }, + { keys: ["Ctrl", "E"], zh: "导出阵面 JSON", en: "Export array JSON", ja: "配置 JSON を書き出す" }, + { keys: ["1", "–", "4"], zh: "切换视图(阵列 / 1D / 2D / 测角)", en: "Switch view (array / 1D / 2D / angle)", ja: "表示切替(配置 / 1D / 2D / 測角)" }, + { keys: ["Delete"], zh: "删除选中通道", en: "Delete the selected channel", ja: "選択チャネルを削除" }, + { keys: ["←", "→", "↑", "↓"], zh: "微调选中通道 0.5 λ(Shift:2.5 λ)", en: "Nudge selection by 0.5 λ (Shift: 2.5 λ)", ja: "選択を 0.5 λ 移動(Shift:2.5 λ)" }, + { keys: ["Esc"], zh: "取消拖动 / 退出删除模式 / 清除选择", en: "Cancel drag / exit delete mode / clear selection", ja: "ドラッグ取消 / 削除モード終了 / 選択解除" }, +]; + +const zh: HelpSection[] = [ + { + id: "start", + title: "快速开始", + steps: [ + "在「阵列布局」中添加、拖动或用「自动排阵」生成 Tx/Rx,坐标统一以 λ 表示,松开后吸附到 λ/2 网格。", + "在顶部输入工作频率(GHz)和竞争峰裕量(dB),按 Enter 或移出输入框生效。", + "右侧「阵列概览」实时显示通道数、虚拟通道利用率、口径和分辨率,以及方位/俯仰的测角评估。", + "切换到「1D DBF」播放或拖动真实角,确认峰值是否连续跟随;「测角性能」给出逐帧误差和竞争峰裕量。", + "满意后点击「保存」存入项目库,或「导出」为阵面 JSON / 项目包,再用「性能报告」生成 PDF。", + ], + }, + { + id: "layout", + title: "阵列编辑", + bullets: [ + "▲ 红色为 Tx,● 蓝色为 Rx。拖动时保持抓取偏移,虚拟阵列同步预览,松开才吸附网格并刷新计算。", + "删除模式下点击通道即删除;每种通道至少保留 1 个,最多 16 个。编辑后通道按 (x, y) 自动重新编号。", + "选中通道后可在面板底部精确输入 X/Y,或打开「坐标表」批量编辑并查看 mm 值(随频率换算)。", + "滚轮缩放、拖动空白处平移,「适配视图」恢复自动缩放。撤销/重做最多保留 50 步。", + ], + }, + { + id: "virtual", + title: "虚拟阵列与概览", + bullets: [ + "虚拟位置 = Tx 位置 + Rx 位置。黄色为重复点(数字为重合数量),悬停查看 Tx-Rx 组合。", + "选中某个物理通道时,与其相关的虚拟点高亮,其余变暗,便于检查单个通道的贡献。", + "「阵列方向图指标」折叠区给出 PSL、ISLR、3 dB 波束宽度、栅瓣等指标;导入单元方向图后按方向图加权。", + ], + }, + { + id: "dbf1d", + title: "1D DBF 角谱", + paragraphs: [ + "每个方向有 181 帧,模拟真实角 −90°~+90°(1° 步进)的信号与 DBF 字典的归一化相关。", + ], + bullets: [ + "「播放」从当前帧开始,播放到 +90° 自动停止;拖动滑条或点击图中任意位置跳转到该真实角。", + "黄色竖线为真实角,红色 × 为峰值角;底部读数给出误差、竞争峰裕量和峰质量标记。", + "顶部「角谱显示」可在 dB 与相关系数模值之间切换,两者是同一计算结果的不同显示形式。", + ], + }, + { + id: "dbf2d", + title: "2D DBF 热图", + bullets: [ + "点击热图设定真实方位/俯仰;两个方向可分别扫描,也可同时扫描。", + "白色十字为真实角,蓝色 × 为峰值;顶部读数给出峰值位置与偏差。", + "2D 计算在服务器端完成并预取后续帧,首次进入或修改阵列后需要短暂计算。", + ], + }, + { + id: "angle", + title: "测角性能", + bullets: [ + "误差图按「不模糊范围」(浅蓝底色)内的误差自适应纵轴;范围外的折返误差可能被裁切。", + "裕量图中红色虚线为竞争峰裕量阈值;无竞争峰的帧画在图顶部。", + "「导出误差图 PNG」生成与报告一致的出版级图片。", + ], + }, + { + id: "dictionary", + title: "DBF 字典", + bullets: [ + "理想几何:按阵列几何生成导向矢量并自动选择相位符号;理想反向相位用于核对相位约定。", + "通道幅相校准:使用已导入的通道幅相数据,并以 0° 方向为相位参考。", + "导入字典:上传 CSV/XLSX,可分别指定方位与俯仰;列可对应虚拟通道(Tx×Rx)或物理通道(Tx + Rx)。值可以是相位(度)或复数(1+2j、2∠40)。", + "预览区显示字典相位矩阵和质量提示(竞争峰模糊行、零范数行、非近邻有效秩),仅供参考。", + ], + }, + { + id: "patterns", + title: "通道幅相与单元方向图", + bullets: [ + "汇总文件:HFSS 导出的 CSV/TSV/XLSX,角度列之后的数据列按通道顺序从左到右对应;列名包含通道名时按名称匹配。", + "也可以在表格中为单个通道导入某一项(幅度/相位 × 水平/俯仰)。相位以 0° 行做校准。", + "幅度支持 dB 实数或复数(按 20·log10|z| 换算);相位支持度数或复数(取相角)。", + "单元方向图用于阵列方向图指标,可交换 H/V;没有独立俯仰列时俯仰面复用水平面。", + ], + }, + { + id: "files", + title: "文件、报告与项目库", + bullets: [ + "阵面 JSON 与桌面版格式兼容(version 1,单位 λ),导出时附带评估信息。", + "项目包(.mimo.zip)包含项目配置和全部导入的数据文件,适合在不同服务器之间迁移。", + "项目库保存在服务器数据目录,同一服务器的用户都能看到;浏览器也会自动保留当前草稿。", + "性能报告在服务器端生成多页 PDF,可选附带 CSV/JSON 可复现数据包,生成期间可以继续编辑。", + ], + }, +]; + +const en: HelpSection[] = [ + { + id: "start", + title: "Quick start", + steps: [ + "In Array layout, add or drag Tx/Rx channels or use Auto layout. Coordinates are in λ and snap to the λ/2 grid on release.", + "Enter the frequency (GHz) and the competitor-peak margin (dB) in the top bar; press Enter or leave the field to apply.", + "The Overview on the right shows channel counts, virtual utilization, aperture, resolution and the azimuth/elevation angle evaluation.", + "Open 1D DBF to play or drag the true angle and check that the peak follows; Angle performance shows per-frame error and margin.", + "Save to the project library, export array JSON or a project bundle, and use Report to generate a PDF.", + ], + }, + { + id: "layout", + title: "Editing the array", + bullets: [ + "Red ▲ marks Tx, blue ● marks Rx. Dragging keeps the grab offset and previews the virtual array; it snaps and recomputes on release.", + "In delete mode, click a channel to remove it. Each kind needs 1 to 16 channels. Channels are renumbered by (x, y) after edits.", + "Edit X/Y of the selection in the panel footer, or open Coordinates for a table with mm values (from the frequency).", + "Scroll to zoom, drag the background to pan, Fit view restores auto-zoom. Undo/redo keeps 50 steps.", + ], + }, + { + id: "virtual", + title: "Virtual array and overview", + bullets: [ + "Virtual position = Tx + Rx. Amber points are duplicates (the number is the multiplicity); hover to see the Tx-Rx pairs.", + "Selecting a physical channel highlights the virtual points it forms and dims the rest.", + "The Array pattern metrics section lists PSL, ISLR, 3 dB beamwidth and grating lobes; an imported element pattern weights them.", + ], + }, + { + id: "dbf1d", + title: "1D DBF spectra", + paragraphs: [ + "Each axis has 181 frames simulating true angles from −90° to +90° (1° steps), correlated with the DBF dictionary.", + ], + bullets: [ + "Play starts from the current frame and stops at +90°. Drag the slider or click anywhere in the chart to jump.", + "The amber line is the true angle and the red × is the peak; the readout shows error, peak margin and peak-quality flags.", + "Spectrum display switches between dB and correlation magnitude; both are views of the same calculation.", + ], + }, + { + id: "dbf2d", + title: "2D DBF heatmap", + bullets: [ + "Click the heatmap to set the true azimuth/elevation; scan the axes separately or together.", + "The white cross is the true angle, the blue × the peak; the header shows peak position and offset.", + "2D spectra are computed on the server and prefetched during playback.", + ], + }, + { + id: "angle", + title: "Angle performance", + bullets: [ + "The error chart scales to errors inside the no-fold range (shaded); folded errors outside it may clip.", + "The red dashed line in the margin chart is the margin threshold; frames without a competitor are drawn at the top.", + "Export error PNG renders the publication-quality image used in reports.", + ], + }, + { + id: "dictionary", + title: "DBF dictionary", + bullets: [ + "Ideal geometric builds steering vectors from the geometry with automatic sign selection; Ideal reversed phase checks conventions.", + "Channel amp/phase uses the imported channel data, phase-referenced to 0°.", + "Imported loads CSV/XLSX for azimuth and/or elevation; columns map to virtual (Tx×Rx) or physical (Tx + Rx) channels. Values may be phase in degrees or complex (1+2j, 2∠40).", + "The preview shows the dictionary phase matrix and an advisory quality note.", + ], + }, + { + id: "patterns", + title: "Channel amp/phase and element pattern", + bullets: [ + "Summary files are HFSS CSV/TSV/XLSX exports; data columns after the angle column map to channels left to right, or by name.", + "You can also import one slot (amplitude/phase × horizontal/elevation) for a single channel. Phase is calibrated to the 0° row.", + "Amplitude accepts dB or complex values (20·log10|z|); phase accepts degrees or complex values (angle).", + "The element pattern weights the array-pattern metrics; swap H/V if needed. Without an elevation column the horizontal cut is reused.", + ], + }, + { + id: "files", + title: "Files, reports and the library", + bullets: [ + "Array JSON is compatible with the desktop tool (version 1, unit λ) and includes an evaluation block on export.", + "A project bundle (.mimo.zip) contains the project and all imported data files, for moving between servers.", + "The project library lives in the server data directory and is shared by its users; the browser also keeps your draft.", + "Reports are rendered on the server as multi-page PDFs with an optional CSV/JSON reproducibility package.", + ], + }, +]; + +const ja: HelpSection[] = [ + { + id: "start", + title: "クイックスタート", + steps: [ + "「アレイ配置」で Tx/Rx を追加・ドラッグするか自動配置を使います。座標は λ 単位で、離すと λ/2 グリッドにスナップします。", + "上部で周波数(GHz)と競合ピークマージン(dB)を入力し、Enter またはフォーカス移動で確定します。", + "右側の「アレイ概要」にチャネル数、仮想チャネル利用率、開口、分解能、方位/仰角の測角評価が表示されます。", + "「1D DBF」で真の角度を再生・ドラッグしてピーク追従を確認し、「測角性能」でフレームごとの誤差とマージンを確認します。", + "プロジェクトライブラリに保存するか、配置 JSON / パッケージを書き出し、「性能レポート」で PDF を生成します。", + ], + }, + { + id: "layout", + title: "アレイ編集", + bullets: [ + "赤 ▲ が Tx、青 ● が Rx です。ドラッグ中はつかみ位置を保ったまま仮想アレイをプレビューし、離すとスナップして再計算します。", + "削除モードではチャネルをクリックで削除します。各種 1〜16 個。編集後は (x, y) 順に番号が振り直されます。", + "選択チャネルの X/Y はパネル下部で直接入力でき、「座標表」では mm 値(周波数から換算)も確認できます。", + "ホイールでズーム、背景ドラッグでパン、「全体表示」で自動ズームに戻ります。元に戻す/やり直しは 50 手まで。", + ], + }, + { + id: "virtual", + title: "仮想アレイと概要", + bullets: [ + "仮想位置 = Tx + Rx。黄色は重複点(数字は重なり数)で、ホバーで Tx-Rx の組を確認できます。", + "物理チャネルを選択すると、そのチャネルが作る仮想点が強調表示されます。", + "「アレイパターン指標」に PSL、ISLR、3 dB ビーム幅、グレーティングローブを表示します。素子パターン読込時は重み付けされます。", + ], + }, + { + id: "dbf1d", + title: "1D DBF スペクトル", + paragraphs: ["各軸 181 フレームで、真の角度 −90°〜+90°(1° 刻み)の信号と DBF 辞書の正規化相関を示します。"], + bullets: [ + "再生は現在のフレームから始まり +90° で停止します。スライダーまたはグラフのクリックで移動できます。", + "黄色の線が真の角度、赤い × がピークです。下部に誤差、競合ピークマージン、ピーク品質を表示します。", + "スペクトル表示で dB と相関係数の振幅を切り替えられます。どちらも同じ計算結果の表示形式です。", + ], + }, + { + id: "dbf2d", + title: "2D DBF ヒートマップ", + bullets: [ + "ヒートマップをクリックして真の方位/仰角を設定します。方位・仰角は個別または同時にスキャンできます。", + "白い十字が真の角度、青い × がピークです。上部にピーク位置とずれを表示します。", + "2D スペクトルはサーバーで計算し、再生中は先読みします。", + ], + }, + { + id: "angle", + title: "測角性能", + bullets: [ + "誤差グラフは折り返しなし範囲(網掛け)内の誤差に合わせて縦軸を調整します。範囲外の折り返し誤差は切れることがあります。", + "マージングラフの赤い破線がしきい値です。競合ピークのないフレームは上端に描画します。", + "「誤差図 PNG を書き出す」でレポートと同じ品質の画像を出力します。", + ], + }, + { + id: "dictionary", + title: "DBF 辞書", + bullets: [ + "理想幾何は形状からステアリングベクトルを生成し位相符号を自動選択します。理想逆位相は規約確認用です。", + "チャネル振幅/位相校正は読み込んだチャネルデータを 0° 基準で使用します。", + "読込辞書は CSV/XLSX を方位・仰角ごとに読み込みます。列は仮想(Tx×Rx)または物理(Tx + Rx)チャネルに対応します。値は位相(度)または複素数(1+2j、2∠40)です。", + "プレビューに辞書位相行列と参考用の品質表示を示します。", + ], + }, + { + id: "patterns", + title: "チャネル振幅/位相と素子パターン", + bullets: [ + "サマリーファイルは HFSS の CSV/TSV/XLSX 出力です。角度列以降の列を左から順に、または名前でチャネルに対応させます。", + "表から単一チャネルの 1 項目(振幅/位相 × 水平/仰角)も読み込めます。位相は 0° 行で校正されます。", + "振幅は dB または複素数(20·log10|z|)、位相は度または複素数(偏角)に対応します。", + "素子パターンはアレイパターン指標の重み付けに使われ、H/V を入れ替えられます。", + ], + }, + { + id: "files", + title: "ファイル、レポート、ライブラリ", + bullets: [ + "配置 JSON はデスクトップ版と互換(version 1、単位 λ)で、書き出し時に評価情報を含みます。", + "プロジェクトパッケージ(.mimo.zip)は設定と読み込んだデータファイルをすべて含み、サーバー間の移行に使えます。", + "プロジェクトライブラリはサーバーのデータディレクトリに保存され、利用者間で共有されます。ブラウザも下書きを保持します。", + "レポートはサーバーで複数ページの PDF として生成され、CSV/JSON の再現用データを含められます。", + ], + }, +]; + +export const HELP: Record = { zh, en, ja }; diff --git a/web/src/i18n/index.ts b/web/src/i18n/index.ts new file mode 100644 index 0000000..f9aa71d --- /dev/null +++ b/web/src/i18n/index.ts @@ -0,0 +1,24 @@ +import { useCallback } from "react"; +import { useStore, type Language } from "../state/store"; +import { en, ja, type MessageKey, zh } from "./messages"; + +const catalogs: Record> = { zh, en, ja }; + +export type Translate = (key: MessageKey, params?: Record) => string; + +export function translate(language: Language, key: MessageKey, params?: Record): string { + const template = catalogs[language]?.[key] ?? zh[key] ?? key; + if (!params) return template; + return template.replace(/\{(\w+)\}/g, (match, name: string) => + name in params ? String(params[name]) : match, + ); +} + +export function useT(): Translate { + const language = useStore((state) => state.language); + return useCallback((key, params) => translate(language, key, params), [language]); +} + +export const LANGUAGE_LABELS: Record = { zh: "中文", en: "English", ja: "日本語" }; + +export type { MessageKey }; diff --git a/web/src/i18n/messages.ts b/web/src/i18n/messages.ts new file mode 100644 index 0000000..4484b8a --- /dev/null +++ b/web/src/i18n/messages.ts @@ -0,0 +1,1060 @@ +// UI strings. `zh` is the reference: en/ja must define exactly the same keys. + +export const zh = { + "app.name": "MIMO 阵列工作台", + "app.tagline": "阵列布局 · 虚拟孔径 · DBF 测角评估", + "app.loading": "正在连接服务器…", + "app.offline": "无法连接到服务器。请确认 mimo-array-server 正在运行。", + "app.retry": "重试", + + "project.untitled": "未命名阵列", + "project.name": "项目名称", + "project.saved": "已保存", + "project.unsaved": "未保存的更改", + "project.local": "未存入项目库", + + "top.frequency": "频率", + "top.margin": "裕量", + "top.marginTitle": "竞争峰裕量阈值(不模糊判定)", + "top.dictionary": "DBF 字典", + "top.ampPhase": "通道幅相", + "top.ampPhaseValue": "幅 {amplitude} · 相 {phase}", + "top.display": "角谱显示", + "top.invalidFrequency": "频率需为正数(GHz)", + "top.invalidMargin": "裕量需为非负数(dB)", + + "state.ideal": "理想", + "state.imported": "导入", + "state.mixed": "混合", + + "dict.ideal": "理想几何", + "dict.ideal_reversed": "理想反向相位", + "dict.channel_pattern": "通道幅相校准", + "dict.custom": "导入字典", + "dict.ideal.desc": "按阵列几何生成相位导向矢量,自动选择相位符号。", + "dict.ideal_reversed.desc": "相位符号取反的理想字典,用于核对相位约定。", + "dict.channel_pattern.desc": "使用已导入的通道幅相数据,按 0° 方向做相位参考。", + "dict.custom.desc": "加载外部 CSV/XLSX 字典矩阵,可分别指定方位与俯仰。", + + "menu.projects": "项目库", + "menu.save": "保存", + "menu.saveAs": "另存为新项目", + "menu.new": "新建", + "menu.import": "导入", + "menu.importLayout": "导入阵面 JSON…", + "menu.importBundle": "导入项目包(.zip)…", + "menu.export": "导出", + "menu.exportLayout": "导出阵面 JSON", + "menu.exportBundle": "导出项目包(含数据文件)", + "menu.report": "性能报告", + "menu.help": "使用说明", + "menu.language": "语言", + "menu.theme": "主题", + "menu.more": "更多", + "theme.light": "浅色", + "theme.dark": "深色", + "theme.system": "跟随系统", + + "display.db": "dB", + "display.magnitude": "模值", + + "view.array": "阵列布局", + "view.dbf1d": "1D DBF", + "view.dbf2d": "2D DBF", + "view.angle": "测角性能", + + "axis.azimuth": "方位", + "axis.elevation": "俯仰", + "axis.azShort": "Az", + "axis.elShort": "El", + "axis.azAngle": "方位角 (°)", + "axis.elAngle": "俯仰角 (°)", + "axis.trueAngle": "真实角 (°)", + "axis.correlationDb": "相关系数 (dB)", + "axis.correlationMag": "相关系数模值", + "axis.error": "测角误差 (°)", + "axis.margin": "竞争峰裕量 (dB)", + "axis.gain": "增益 (dB)", + "axis.angle": "角度 (°)", + "axis.channel": "通道", + "axis.phase": "相位 (°)", + + "physical.title": "物理阵列", + "physical.subtitle": "拖动调整位置,松开后吸附到 λ/2 网格", + "physical.addTx": "Tx", + "physical.addRx": "Rx", + "physical.addTxTitle": "添加发射通道", + "physical.addRxTitle": "添加接收通道", + "physical.deleteMode": "删除模式", + "physical.deleteSelected": "删除所选", + "physical.clear": "清空为 1T1R", + "physical.undo": "撤销", + "physical.redo": "重做", + "physical.fit": "适配视图", + "physical.table": "坐标表", + "physical.auto": "自动排阵", + "physical.autoApply": "应用", + "physical.autoTitle": "生成居中的 Tx/Rx 两行布局", + "physical.deleteHint": "删除模式:点击通道即可删除,按 Esc 退出", + "physical.dragHint": "拖动通道调整位置 · 方向键微调 · Delete 删除", + "physical.limit": "{kind} 数量已达上限({max})", + "physical.lastElement": "至少需要保留一个 {kind} 通道", + "physical.selected": "已选中 {name}", + "physical.legendTx": "Tx 发射", + "physical.legendRx": "Rx 接收", + + "inspector.title": "通道坐标", + "inspector.none": "点击通道以查看和精确编辑坐标", + "inspector.x": "X", + "inspector.y": "Y", + + "table.channel": "通道", + "table.x": "X (λ)", + "table.y": "Y (λ)", + "table.xmm": "X (mm)", + "table.ymm": "Y (mm)", + "table.close": "收起", + + "virtual.title": "虚拟阵列", + "virtual.subtitle": "虚拟位置 = Tx + Rx", + "virtual.unique": "唯一点", + "virtual.duplicate": "重复点", + "virtual.info": "唯一 {unique}/{total} · 重复 {duplicate}", + "virtual.multiplicity": "重合 {count}", + + "overview.title": "阵列概览", + "overview.channels": "通道数", + "overview.virtual": "虚拟通道", + "overview.azAperture": "方位口径", + "overview.elAperture": "俯仰口径", + "overview.azResolution": "方位分辨率", + "overview.elResolution": "俯仰分辨率", + "overview.angleTitle": "测角评估", + "overview.noFold": "不模糊范围", + "overview.maxError": "范围内最大误差", + "overview.peakMargin": "竞争峰裕量", + "overview.cutReason": "截断原因", + "overview.noCompetitor": "无竞争峰", + "overview.unavailable": "不可用", + "overview.noAperture": "无有效孔径", + "overview.patternTitle": "阵列方向图指标", + "overview.az3db": "方位 3 dB 波束宽度", + "overview.el3db": "俯仰 3 dB 波束宽度", + "overview.azPsl": "方位 PSL", + "overview.elPsl": "俯仰 PSL", + "overview.psl2d": "2D 最差 PSL", + "overview.islr": "方位 ISLR", + "overview.firstSidelobe": "方位第一旁瓣", + "overview.grating": "方位栅瓣", + "overview.frontRadar": "前向雷达评级", + "overview.ambiguity": "俯仰模糊风险", + "overview.notes": "提示", + "overview.computing": "计算中…", + "overview.error": "计算失败", + + "cut.competitor": "竞争峰模糊", + "cut.error_jump": "误差跳变", + "cut.boundary_limited": "边界受限", + "cut.unreliable": "谱不可靠", + "cut.data_boundary": "到达数据边界", + "cut.normal": "正常", + "cut.pair": "负 {negative} / 正 {positive}", + + "grade.Good": "良好", + "grade.Acceptable": "可用", + "grade.Risky": "有风险", + "grade.Bad": "较差", + "level.High": "高", + "level.Medium": "中", + "level.Low": "低", + + "note.duplicate_virtual": "存在重复虚拟通道,虚拟孔径利用率下降", + "note.windowing": "方位旁瓣偏高,建议加窗", + "note.ambiguity_high": "俯仰模糊风险高", + "note.ambiguity_medium": "俯仰模糊风险中", + + "empty.azimuth": "当前阵列没有方位孔径", + "empty.elevation": "当前阵列没有俯仰孔径", + "empty.twoD": "当前阵列不具备完整的 2D 测角能力", + "empty.body": "增加 Tx/Rx 通道或拉开阵元间距,也可以使用自动排阵。", + "empty.twoDBody": "方位和俯仰都需要有效孔径;只有一个方向可用时,请查看 1D DBF。", + "empty.editArray": "调整阵列", + "empty.view1d": "查看 1D DBF", + + "dbf.title": "{axis} DBF 字典角谱", + "dbf.play": "播放", + "dbf.pause": "暂停", + "dbf.resume": "继续", + "dbf.stop": "回到 0°", + "dbf.speed": "速度", + "dbf.true": "真实角", + "dbf.peak": "峰值角", + "dbf.error": "误差", + "dbf.margin": "竞争峰裕量", + "dbf.frame": "帧 {frame}/{total}", + "dbf.loading": "正在计算角谱…", + "dbf.legendSpectrum": "角谱", + "dbf.legendTrue": "真实角", + "dbf.legendPeak": "峰值", + "dbf.sliderLabel": "{axis}真实角", + "dbf.quality": "峰质量", + + "dbf2d.title": "2D DBF 角谱", + "dbf2d.playAz": "扫描方位", + "dbf2d.pauseAz": "暂停方位", + "dbf2d.playEl": "扫描俯仰", + "dbf2d.pauseEl": "暂停俯仰", + "dbf2d.reset": "回到 0°", + "dbf2d.trueAz": "真实方位", + "dbf2d.trueEl": "真实俯仰", + "dbf2d.peak": "峰值", + "dbf2d.delta": "峰值偏差", + "dbf2d.hint": "点击热图设定真实角;方位、俯仰可分别或同时扫描。", + "dbf2d.loading": "正在计算 2D 角谱…", + + "angle.title": "测角误差与竞争峰裕量", + "angle.subtitle": "逐帧真实角 −90°~+90°(1° 步进)", + "angle.errorChart": "{axis}测角误差", + "angle.marginChart": "{axis}竞争峰裕量", + "angle.noFold": "不模糊范围", + "angle.threshold": "裕量阈值", + "angle.errorSeries": "误差", + "angle.marginSeries": "裕量", + "angle.exportPng": "导出误差图 PNG", + "angle.clipped": "无竞争峰的帧按图上限显示", + + "dictDialog.title": "DBF 字典配置", + "dictDialog.mode": "字典模式", + "dictDialog.files": "导入字典文件", + "dictDialog.azFile": "方位字典", + "dictDialog.elFile": "俯仰字典", + "dictDialog.upload": "选择文件", + "dictDialog.replace": "更换", + "dictDialog.clear": "清除", + "dictDialog.notLoaded": "未加载", + "dictDialog.channelMode": "列对应", + "dictDialog.virtual": "虚拟通道(Tx×Rx)", + "dictDialog.physical": "物理通道(Tx + Rx)", + "dictDialog.phaseReversed": "导入字典相位取反", + "dictDialog.zeroCalibrated": "按 0° 行做相位校准", + "dictDialog.preview": "字典预览", + "dictDialog.previewAxis": "预览轴", + "dictDialog.phaseMatrix": "字典相位矩阵({rows} 角度 × {cols} 通道)", + "dictDialog.qualityOk": "质量正常", + "dictDialog.qualityWarning": "需注意", + "dictDialog.qualityDanger": "存在风险", + "dictDialog.qualityDetail": "竞争峰模糊行 {ambiguous} · 零范数行 {zeros} · 非近邻有效秩 {rank}/{rankRows}", + "dictDialog.qualityNote": "质量提示仅供参考,不影响应用。", + "dictDialog.needFile": "导入字典模式至少需要加载方位或俯仰其中一个文件。", + "dictDialog.tableInfo": "{rows} 行 · {cols} 列 · {format}", + "dictDialog.apply": "应用字典", + + "patternDialog.title": "通道幅相与单元方向图", + "patternDialog.channelSection": "通道幅相(HFSS 导出)", + "patternDialog.target": "汇总文件对应", + "patternDialog.physical": "物理通道", + "patternDialog.virtual": "虚拟通道", + "patternDialog.summaryHint": "汇总文件中角度列之后的数据列按通道顺序从左到右对应;列名包含通道名时按名称匹配。", + "patternDialog.loadSummary": "导入{slot}汇总", + "patternDialog.slot.amplitude.horizontal": "幅度·水平", + "patternDialog.slot.amplitude.elevation": "幅度·俯仰", + "patternDialog.slot.phase.horizontal": "相位·水平", + "patternDialog.slot.phase.elevation": "相位·俯仰", + "patternDialog.channel": "通道", + "patternDialog.setSingle": "为 {channel} 导入{slot}", + "patternDialog.clearChannel": "清空该通道", + "patternDialog.clearAll": "全部清空", + "patternDialog.groupPhysical": "物理通道", + "patternDialog.groupVirtual": "虚拟通道", + "patternDialog.loaded": "已导入 {count} 个通道的{slot}", + "patternDialog.elementSection": "单元方向图", + "patternDialog.elementHint": "CSV/TSV:角度列 + 增益列。有两列增益时默认第二列为水平面、第一列为俯仰面(HFSS 导出习惯),可用「交换 H/V」调整。用于阵列方向图指标计算。", + "patternDialog.elementUpload": "导入方向图", + "patternDialog.elementClear": "恢复各向同性", + "patternDialog.swap": "交换 H/V", + "patternDialog.isotropic": "当前使用理想各向同性单元", + "patternDialog.horizontal": "水平面", + "patternDialog.elevationPlane": "俯仰面", + "patternDialog.reuse": "未检测到独立俯仰列,俯仰面复用水平面。", + "patternDialog.metrics": "峰值 {peak} dBi @ {angle}° · 3 dB 宽 {bw3} · 6 dB 宽 {bw6}", + "patternDialog.done": "完成", + + "reportDialog.title": "当前配置性能报告", + "reportDialog.reportTitle": "报告标题", + "reportDialog.defaultTitle": "当前配置测角性能报告", + "reportDialog.focus": "性能关注范围", + "reportDialog.hold": "角谱 Hold 范围", + "reportDialog.stride": "Hold 曲线间隔(帧)", + "reportDialog.unavailableAxis": "当前阵列在该方向无孔径,报告将跳过此轴。", + "reportDialog.errorLimit": "误差门限 (°)", + "reportDialog.floor": "dB 显示下限", + "reportDialog.outputDb": "输出 dB 角谱页", + "reportDialog.outputMag": "输出归一化模值角谱页", + "reportDialog.rawData": "附带可复现数据包(CSV/JSON,打包为 zip)", + "reportDialog.language": "报告语言", + "reportDialog.generate": "生成 PDF 报告", + "reportDialog.generating": "正在生成…", + "reportDialog.download": "下载", + "reportDialog.done": "报告已生成", + "reportDialog.failed": "生成失败", + "reportDialog.cancelled": "已取消", + "reportDialog.cancel": "取消生成", + "reportDialog.close": "关闭", + "reportDialog.imageTitle": "测角误差图", + "reportDialog.imageHint": "单张 PNG:±90° 方位/俯仰测角误差曲线。", + "reportDialog.generateImage": "生成 PNG", + "reportDialog.needOutput": "请至少选择一种角谱输出", + "reportDialog.start": "起", + "reportDialog.stop": "止", + "reportDialog.note": "报告基于当前项目快照在服务器端生成,生成期间可继续编辑。", + + "projectsDialog.title": "项目库", + "projectsDialog.hint": "项目保存在服务器的数据目录中,同一服务器的所有用户可见。", + "projectsDialog.saveCurrent": "保存当前项目", + "projectsDialog.empty": "项目库为空。保存当前项目后会出现在这里。", + "projectsDialog.open": "打开", + "projectsDialog.delete": "删除", + "projectsDialog.confirmDelete": "确定删除项目「{name}」?此操作不可撤销。", + "projectsDialog.updated": "更新于 {time}", + "projectsDialog.current": "当前", + "projectsDialog.discard": "当前项目有未保存的更改,继续打开将丢弃这些更改。", + + "help.title": "使用说明", + "help.shortcuts": "快捷键", + + "common.cancel": "取消", + "common.close": "关闭", + "common.apply": "应用", + "common.loading": "加载中…", + "common.error": "错误", + + "status.ready": "就绪", + "status.computing": "计算中", + "status.saved": "已保存到项目库", + "status.imported": "已导入:{name}", + "status.importFailed": "导入失败:{message}", + "status.missingAssets": "项目引用的 {count} 个数据文件不在本服务器上,相关配置已移除。", + "status.exported": "已导出:{name}", + "status.undo": "已撤销", + "status.redo": "已重做", + "status.nothingToUndo": "没有可撤销的操作", + "status.nothingToRedo": "没有可重做的操作", + "status.autoLayout": "已应用自动排阵:{tx}T{rx}R", + "status.cleared": "已清空为 1T1R", + "status.deleted": "已删除 {name},编号已按位置重排", + "status.added": "已添加 {name}", + "status.moved": "{name} → ({x}, {y}) λ", + "status.dictApplied": "已应用 DBF 字典:{mode}", + "status.elementLoaded": "已加载单元方向图:{name}", + "status.elementCleared": "已恢复各向同性单元", + "status.newProject": "已新建项目", + "status.opened": "已打开:{name}", + "status.uploadFailed": "上传失败:{message}", +} as const; + +export type MessageKey = keyof typeof zh; +type Messages = Record; + +export const en: Messages = { + "app.name": "MIMO Array Workbench", + "app.tagline": "Array layout · virtual aperture · DBF angle evaluation", + "app.loading": "Connecting to server…", + "app.offline": "Cannot reach the server. Make sure mimo-array-server is running.", + "app.retry": "Retry", + + "project.untitled": "Untitled array", + "project.name": "Project name", + "project.saved": "Saved", + "project.unsaved": "Unsaved changes", + "project.local": "Not in library", + + "top.frequency": "Freq", + "top.margin": "Margin", + "top.marginTitle": "Competitor-peak margin threshold (no-fold test)", + "top.dictionary": "DBF dictionary", + "top.ampPhase": "Channel amp/phase", + "top.ampPhaseValue": "Amp {amplitude} · Phase {phase}", + "top.display": "Spectrum", + "top.invalidFrequency": "Frequency must be positive (GHz)", + "top.invalidMargin": "Margin must be non-negative (dB)", + + "state.ideal": "ideal", + "state.imported": "imported", + "state.mixed": "mixed", + + "dict.ideal": "Ideal geometric", + "dict.ideal_reversed": "Ideal reversed phase", + "dict.channel_pattern": "Channel amp/phase", + "dict.custom": "Imported", + "dict.ideal.desc": "Phase steering vectors from the array geometry with automatic sign selection.", + "dict.ideal_reversed.desc": "Ideal dictionary with the phase sign flipped, for checking conventions.", + "dict.channel_pattern.desc": "Uses the imported channel amp/phase data, phase-referenced to 0°.", + "dict.custom.desc": "Loads external CSV/XLSX dictionary matrices for azimuth and/or elevation.", + + "menu.projects": "Projects", + "menu.save": "Save", + "menu.saveAs": "Save as new project", + "menu.new": "New", + "menu.import": "Import", + "menu.importLayout": "Import array JSON…", + "menu.importBundle": "Import project bundle (.zip)…", + "menu.export": "Export", + "menu.exportLayout": "Export array JSON", + "menu.exportBundle": "Export project bundle (with data files)", + "menu.report": "Report", + "menu.help": "User guide", + "menu.language": "Language", + "menu.theme": "Theme", + "menu.more": "More", + "theme.light": "Light", + "theme.dark": "Dark", + "theme.system": "System", + + "display.db": "dB", + "display.magnitude": "Mag.", + + "view.array": "Array layout", + "view.dbf1d": "1D DBF", + "view.dbf2d": "2D DBF", + "view.angle": "Angle performance", + + "axis.azimuth": "Azimuth", + "axis.elevation": "Elevation", + "axis.azShort": "Az", + "axis.elShort": "El", + "axis.azAngle": "Azimuth (°)", + "axis.elAngle": "Elevation (°)", + "axis.trueAngle": "True angle (°)", + "axis.correlationDb": "Correlation (dB)", + "axis.correlationMag": "Correlation magnitude", + "axis.error": "Angle error (°)", + "axis.margin": "Peak margin (dB)", + "axis.gain": "Gain (dB)", + "axis.angle": "Angle (°)", + "axis.channel": "Channel", + "axis.phase": "Phase (°)", + + "physical.title": "Physical array", + "physical.subtitle": "Drag to move; snaps to the λ/2 grid on release", + "physical.addTx": "Tx", + "physical.addRx": "Rx", + "physical.addTxTitle": "Add transmit channel", + "physical.addRxTitle": "Add receive channel", + "physical.deleteMode": "Delete mode", + "physical.deleteSelected": "Delete selected", + "physical.clear": "Reset to 1T1R", + "physical.undo": "Undo", + "physical.redo": "Redo", + "physical.fit": "Fit view", + "physical.table": "Coordinates", + "physical.auto": "Auto layout", + "physical.autoApply": "Apply", + "physical.autoTitle": "Generate centered Tx and Rx rows", + "physical.deleteHint": "Delete mode: click a channel to remove it, Esc to exit", + "physical.dragHint": "Drag to move · arrow keys nudge · Delete removes", + "physical.limit": "{kind} limit reached ({max})", + "physical.lastElement": "At least one {kind} channel is required", + "physical.selected": "Selected {name}", + "physical.legendTx": "Tx transmit", + "physical.legendRx": "Rx receive", + + "inspector.title": "Channel position", + "inspector.none": "Click a channel to inspect and edit its position", + "inspector.x": "X", + "inspector.y": "Y", + + "table.channel": "Channel", + "table.x": "X (λ)", + "table.y": "Y (λ)", + "table.xmm": "X (mm)", + "table.ymm": "Y (mm)", + "table.close": "Hide", + + "virtual.title": "Virtual array", + "virtual.subtitle": "virtual position = Tx + Rx", + "virtual.unique": "unique", + "virtual.duplicate": "duplicate", + "virtual.info": "Unique {unique}/{total} · duplicate {duplicate}", + "virtual.multiplicity": "Multiplicity {count}", + + "overview.title": "Overview", + "overview.channels": "Channels", + "overview.virtual": "Virtual channels", + "overview.azAperture": "Az aperture", + "overview.elAperture": "El aperture", + "overview.azResolution": "Az resolution", + "overview.elResolution": "El resolution", + "overview.angleTitle": "Angle evaluation", + "overview.noFold": "No-fold range", + "overview.maxError": "Max error in range", + "overview.peakMargin": "Peak margin", + "overview.cutReason": "Cut reason", + "overview.noCompetitor": "No competitor", + "overview.unavailable": "Unavailable", + "overview.noAperture": "No aperture", + "overview.patternTitle": "Array pattern metrics", + "overview.az3db": "Az 3 dB beamwidth", + "overview.el3db": "El 3 dB beamwidth", + "overview.azPsl": "Az PSL", + "overview.elPsl": "El PSL", + "overview.psl2d": "2D worst PSL", + "overview.islr": "Az ISLR", + "overview.firstSidelobe": "Az first sidelobe", + "overview.grating": "Az grating lobe", + "overview.frontRadar": "Front-radar grade", + "overview.ambiguity": "Elevation ambiguity", + "overview.notes": "Notes", + "overview.computing": "Computing…", + "overview.error": "Computation failed", + + "cut.competitor": "Competitor peak", + "cut.error_jump": "Error jump", + "cut.boundary_limited": "At boundary", + "cut.unreliable": "Unreliable spectrum", + "cut.data_boundary": "Data edge", + "cut.normal": "Normal", + "cut.pair": "Neg {negative} / Pos {positive}", + + "grade.Good": "Good", + "grade.Acceptable": "Acceptable", + "grade.Risky": "Risky", + "grade.Bad": "Bad", + "level.High": "High", + "level.Medium": "Medium", + "level.Low": "Low", + + "note.duplicate_virtual": "Duplicate virtual channels reduce aperture utilization", + "note.windowing": "High azimuth sidelobes; windowing recommended", + "note.ambiguity_high": "High elevation ambiguity risk", + "note.ambiguity_medium": "Medium elevation ambiguity risk", + + "empty.azimuth": "No azimuth aperture in the current array", + "empty.elevation": "No elevation aperture in the current array", + "empty.twoD": "The current array has no complete 2D angle capability", + "empty.body": "Add Tx/Rx channels or spread the elements, or use Auto layout.", + "empty.twoDBody": "Both axes need aperture. If only one axis is available, use 1D DBF.", + "empty.editArray": "Edit array", + "empty.view1d": "Open 1D DBF", + + "dbf.title": "{axis} DBF dictionary spectrum", + "dbf.play": "Play", + "dbf.pause": "Pause", + "dbf.resume": "Resume", + "dbf.stop": "Back to 0°", + "dbf.speed": "Speed", + "dbf.true": "True", + "dbf.peak": "Peak", + "dbf.error": "Error", + "dbf.margin": "Peak margin", + "dbf.frame": "Frame {frame}/{total}", + "dbf.loading": "Computing spectra…", + "dbf.legendSpectrum": "Spectrum", + "dbf.legendTrue": "True angle", + "dbf.legendPeak": "Peak", + "dbf.sliderLabel": "{axis} true angle", + "dbf.quality": "Peak quality", + + "dbf2d.title": "2D DBF spectrum", + "dbf2d.playAz": "Scan Az", + "dbf2d.pauseAz": "Pause Az", + "dbf2d.playEl": "Scan El", + "dbf2d.pauseEl": "Pause El", + "dbf2d.reset": "Back to 0°", + "dbf2d.trueAz": "True Az", + "dbf2d.trueEl": "True El", + "dbf2d.peak": "Peak", + "dbf2d.delta": "Peak offset", + "dbf2d.hint": "Click the heatmap to set the true angle; scan Az and El separately or together.", + "dbf2d.loading": "Computing 2D spectrum…", + + "angle.title": "Angle error and peak margin", + "angle.subtitle": "Per-frame true angle −90° to +90° (1° steps)", + "angle.errorChart": "{axis} angle error", + "angle.marginChart": "{axis} peak margin", + "angle.noFold": "No-fold range", + "angle.threshold": "Margin threshold", + "angle.errorSeries": "Error", + "angle.marginSeries": "Margin", + "angle.exportPng": "Export error PNG", + "angle.clipped": "Frames without a competitor are drawn at the top of the axis", + + "dictDialog.title": "DBF dictionary", + "dictDialog.mode": "Dictionary mode", + "dictDialog.files": "Imported dictionary files", + "dictDialog.azFile": "Azimuth dictionary", + "dictDialog.elFile": "Elevation dictionary", + "dictDialog.upload": "Choose file", + "dictDialog.replace": "Replace", + "dictDialog.clear": "Clear", + "dictDialog.notLoaded": "not loaded", + "dictDialog.channelMode": "Columns map to", + "dictDialog.virtual": "Virtual channels (Tx×Rx)", + "dictDialog.physical": "Physical channels (Tx + Rx)", + "dictDialog.phaseReversed": "Reverse imported phase", + "dictDialog.zeroCalibrated": "Phase-calibrate to the 0° row", + "dictDialog.preview": "Preview", + "dictDialog.previewAxis": "Preview axis", + "dictDialog.phaseMatrix": "Dictionary phase matrix ({rows} angles × {cols} channels)", + "dictDialog.qualityOk": "Quality OK", + "dictDialog.qualityWarning": "Watch", + "dictDialog.qualityDanger": "Risk", + "dictDialog.qualityDetail": "Competitor-ambiguous rows {ambiguous} · zero-norm rows {zeros} · non-neighbor rank {rank}/{rankRows}", + "dictDialog.qualityNote": "The quality note is advisory and does not block applying.", + "dictDialog.needFile": "Imported mode needs at least an azimuth or an elevation file.", + "dictDialog.tableInfo": "{rows} rows · {cols} columns · {format}", + "dictDialog.apply": "Apply dictionary", + + "patternDialog.title": "Channel amp/phase and element pattern", + "patternDialog.channelSection": "Channel amp/phase (HFSS export)", + "patternDialog.target": "Summary columns map to", + "patternDialog.physical": "Physical channels", + "patternDialog.virtual": "Virtual channels", + "patternDialog.summaryHint": "Data columns after the angle column map to channels left to right; columns whose names contain a channel name are matched by name.", + "patternDialog.loadSummary": "Import {slot} summary", + "patternDialog.slot.amplitude.horizontal": "Amp · H", + "patternDialog.slot.amplitude.elevation": "Amp · E", + "patternDialog.slot.phase.horizontal": "Phase · H", + "patternDialog.slot.phase.elevation": "Phase · E", + "patternDialog.channel": "Channel", + "patternDialog.setSingle": "Import {slot} for {channel}", + "patternDialog.clearChannel": "Clear channel", + "patternDialog.clearAll": "Clear all", + "patternDialog.groupPhysical": "Physical channels", + "patternDialog.groupVirtual": "Virtual channels", + "patternDialog.loaded": "Imported {slot} for {count} channels", + "patternDialog.elementSection": "Element pattern", + "patternDialog.elementHint": "CSV/TSV: angle column + gain columns. With two gain columns the second is taken as horizontal and the first as elevation (HFSS export order); use Swap H/V to change. Used for the array-pattern metrics.", + "patternDialog.elementUpload": "Import pattern", + "patternDialog.elementClear": "Use isotropic", + "patternDialog.swap": "Swap H/V", + "patternDialog.isotropic": "Using ideal isotropic elements", + "patternDialog.horizontal": "Horizontal", + "patternDialog.elevationPlane": "Elevation", + "patternDialog.reuse": "No separate elevation column; the horizontal cut is reused.", + "patternDialog.metrics": "Peak {peak} dBi @ {angle}° · 3 dB BW {bw3} · 6 dB BW {bw6}", + "patternDialog.done": "Done", + + "reportDialog.title": "Current configuration report", + "reportDialog.reportTitle": "Report title", + "reportDialog.defaultTitle": "Current Configuration Angle Performance Report", + "reportDialog.focus": "Performance focus range", + "reportDialog.hold": "Spectrum hold range", + "reportDialog.stride": "Hold curve interval (frames)", + "reportDialog.unavailableAxis": "No aperture on this axis; the report skips it.", + "reportDialog.errorLimit": "Error limit (°)", + "reportDialog.floor": "dB display floor", + "reportDialog.outputDb": "dB spectrum pages", + "reportDialog.outputMag": "Normalized magnitude spectrum pages", + "reportDialog.rawData": "Include reproducibility data (CSV/JSON, zipped)", + "reportDialog.language": "Report language", + "reportDialog.generate": "Generate PDF report", + "reportDialog.generating": "Generating…", + "reportDialog.download": "Download", + "reportDialog.done": "Report ready", + "reportDialog.failed": "Generation failed", + "reportDialog.cancelled": "Cancelled", + "reportDialog.cancel": "Cancel", + "reportDialog.close": "Close", + "reportDialog.imageTitle": "Angle-error image", + "reportDialog.imageHint": "One PNG with ±90° azimuth/elevation angle-error curves.", + "reportDialog.generateImage": "Generate PNG", + "reportDialog.needOutput": "Select at least one spectrum output", + "reportDialog.start": "from", + "reportDialog.stop": "to", + "reportDialog.note": "Reports are rendered on the server from a snapshot of the current project; you can keep editing.", + + "projectsDialog.title": "Project library", + "projectsDialog.hint": "Projects are stored in the server data directory and visible to everyone using this server.", + "projectsDialog.saveCurrent": "Save current project", + "projectsDialog.empty": "The library is empty. Saved projects appear here.", + "projectsDialog.open": "Open", + "projectsDialog.delete": "Delete", + "projectsDialog.confirmDelete": "Delete project “{name}”? This cannot be undone.", + "projectsDialog.updated": "Updated {time}", + "projectsDialog.current": "Current", + "projectsDialog.discard": "The current project has unsaved changes; opening another project discards them.", + + "help.title": "User guide", + "help.shortcuts": "Keyboard shortcuts", + + "common.cancel": "Cancel", + "common.close": "Close", + "common.apply": "Apply", + "common.loading": "Loading…", + "common.error": "Error", + + "status.ready": "Ready", + "status.computing": "Computing", + "status.saved": "Saved to the project library", + "status.imported": "Imported: {name}", + "status.importFailed": "Import failed: {message}", + "status.missingAssets": "{count} referenced data file(s) are not on this server; the related settings were removed.", + "status.exported": "Exported: {name}", + "status.undo": "Undone", + "status.redo": "Redone", + "status.nothingToUndo": "Nothing to undo", + "status.nothingToRedo": "Nothing to redo", + "status.autoLayout": "Auto layout applied: {tx}T{rx}R", + "status.cleared": "Reset to 1T1R", + "status.deleted": "Deleted {name}; channels renumbered by position", + "status.added": "Added {name}", + "status.moved": "{name} → ({x}, {y}) λ", + "status.dictApplied": "DBF dictionary applied: {mode}", + "status.elementLoaded": "Element pattern loaded: {name}", + "status.elementCleared": "Using isotropic elements", + "status.newProject": "New project created", + "status.opened": "Opened: {name}", + "status.uploadFailed": "Upload failed: {message}", +}; + +export const ja: Messages = { + "app.name": "MIMOアレイ ワークベンチ", + "app.tagline": "アレイ配置 · 仮想開口 · DBF 測角評価", + "app.loading": "サーバーに接続しています…", + "app.offline": "サーバーに接続できません。mimo-array-server が起動しているか確認してください。", + "app.retry": "再試行", + + "project.untitled": "無題のアレイ", + "project.name": "プロジェクト名", + "project.saved": "保存済み", + "project.unsaved": "未保存の変更", + "project.local": "ライブラリ未登録", + + "top.frequency": "周波数", + "top.margin": "マージン", + "top.marginTitle": "競合ピークマージンしきい値(折り返し判定)", + "top.dictionary": "DBF 辞書", + "top.ampPhase": "チャネル振幅/位相", + "top.ampPhaseValue": "振幅 {amplitude} · 位相 {phase}", + "top.display": "スペクトル表示", + "top.invalidFrequency": "周波数は正の値(GHz)で入力してください", + "top.invalidMargin": "マージンは 0 以上(dB)で入力してください", + + "state.ideal": "理想", + "state.imported": "読込", + "state.mixed": "混在", + + "dict.ideal": "理想幾何", + "dict.ideal_reversed": "理想逆位相", + "dict.channel_pattern": "チャネル振幅/位相校正", + "dict.custom": "読込辞書", + "dict.ideal.desc": "アレイ形状から位相ステアリングベクトルを生成し、位相符号を自動選択します。", + "dict.ideal_reversed.desc": "位相符号を反転した理想辞書。位相規約の確認用です。", + "dict.channel_pattern.desc": "読み込んだチャネル振幅/位相データを使い、0° 方向を位相基準にします。", + "dict.custom.desc": "外部 CSV/XLSX 辞書行列を読み込みます。方位と仰角を個別に指定できます。", + + "menu.projects": "プロジェクト", + "menu.save": "保存", + "menu.saveAs": "新規プロジェクトとして保存", + "menu.new": "新規", + "menu.import": "読み込み", + "menu.importLayout": "配置 JSON を読み込む…", + "menu.importBundle": "プロジェクトパッケージ(.zip)を読み込む…", + "menu.export": "書き出し", + "menu.exportLayout": "配置 JSON を書き出す", + "menu.exportBundle": "プロジェクトパッケージを書き出す(データ含む)", + "menu.report": "性能レポート", + "menu.help": "使い方", + "menu.language": "言語", + "menu.theme": "テーマ", + "menu.more": "その他", + "theme.light": "ライト", + "theme.dark": "ダーク", + "theme.system": "システムに合わせる", + + "display.db": "dB", + "display.magnitude": "振幅", + + "view.array": "アレイ配置", + "view.dbf1d": "1D DBF", + "view.dbf2d": "2D DBF", + "view.angle": "測角性能", + + "axis.azimuth": "方位", + "axis.elevation": "仰角", + "axis.azShort": "Az", + "axis.elShort": "El", + "axis.azAngle": "方位角 (°)", + "axis.elAngle": "仰角 (°)", + "axis.trueAngle": "真の角度 (°)", + "axis.correlationDb": "相関係数 (dB)", + "axis.correlationMag": "相関係数の振幅", + "axis.error": "測角誤差 (°)", + "axis.margin": "競合ピークマージン (dB)", + "axis.gain": "利得 (dB)", + "axis.angle": "角度 (°)", + "axis.channel": "チャネル", + "axis.phase": "位相 (°)", + + "physical.title": "物理アレイ", + "physical.subtitle": "ドラッグで移動し、離すと λ/2 グリッドにスナップします", + "physical.addTx": "Tx", + "physical.addRx": "Rx", + "physical.addTxTitle": "送信チャネルを追加", + "physical.addRxTitle": "受信チャネルを追加", + "physical.deleteMode": "削除モード", + "physical.deleteSelected": "選択を削除", + "physical.clear": "1T1R にリセット", + "physical.undo": "元に戻す", + "physical.redo": "やり直す", + "physical.fit": "全体表示", + "physical.table": "座標表", + "physical.auto": "自動配置", + "physical.autoApply": "適用", + "physical.autoTitle": "中央揃えの Tx/Rx 2 行配置を生成", + "physical.deleteHint": "削除モード:チャネルをクリックで削除、Esc で終了", + "physical.dragHint": "ドラッグで移動 · 矢印キーで微調整 · Delete で削除", + "physical.limit": "{kind} の上限({max})に達しました", + "physical.lastElement": "{kind} チャネルは少なくとも 1 つ必要です", + "physical.selected": "{name} を選択", + "physical.legendTx": "Tx 送信", + "physical.legendRx": "Rx 受信", + + "inspector.title": "チャネル座標", + "inspector.none": "チャネルをクリックすると座標を確認・編集できます", + "inspector.x": "X", + "inspector.y": "Y", + + "table.channel": "チャネル", + "table.x": "X (λ)", + "table.y": "Y (λ)", + "table.xmm": "X (mm)", + "table.ymm": "Y (mm)", + "table.close": "閉じる", + + "virtual.title": "仮想アレイ", + "virtual.subtitle": "仮想位置 = Tx + Rx", + "virtual.unique": "一意点", + "virtual.duplicate": "重複点", + "virtual.info": "一意 {unique}/{total} · 重複 {duplicate}", + "virtual.multiplicity": "重なり {count}", + + "overview.title": "アレイ概要", + "overview.channels": "チャネル数", + "overview.virtual": "仮想チャネル", + "overview.azAperture": "方位開口", + "overview.elAperture": "仰角開口", + "overview.azResolution": "方位分解能", + "overview.elResolution": "仰角分解能", + "overview.angleTitle": "測角評価", + "overview.noFold": "折り返しなし範囲", + "overview.maxError": "範囲内最大誤差", + "overview.peakMargin": "競合ピークマージン", + "overview.cutReason": "打ち切り理由", + "overview.noCompetitor": "競合ピークなし", + "overview.unavailable": "利用不可", + "overview.noAperture": "有効開口なし", + "overview.patternTitle": "アレイパターン指標", + "overview.az3db": "方位 3 dB ビーム幅", + "overview.el3db": "仰角 3 dB ビーム幅", + "overview.azPsl": "方位 PSL", + "overview.elPsl": "仰角 PSL", + "overview.psl2d": "2D 最悪 PSL", + "overview.islr": "方位 ISLR", + "overview.firstSidelobe": "方位第 1 サイドローブ", + "overview.grating": "方位グレーティングローブ", + "overview.frontRadar": "前方レーダ評価", + "overview.ambiguity": "仰角曖昧性リスク", + "overview.notes": "注意", + "overview.computing": "計算中…", + "overview.error": "計算に失敗しました", + + "cut.competitor": "競合ピーク", + "cut.error_jump": "誤差ジャンプ", + "cut.boundary_limited": "境界制限", + "cut.unreliable": "スペクトル不良", + "cut.data_boundary": "データ端", + "cut.normal": "正常", + "cut.pair": "負 {negative} / 正 {positive}", + + "grade.Good": "良好", + "grade.Acceptable": "使用可", + "grade.Risky": "リスクあり", + "grade.Bad": "不良", + "level.High": "高", + "level.Medium": "中", + "level.Low": "低", + + "note.duplicate_virtual": "重複した仮想チャネルがあり、開口利用率が下がっています", + "note.windowing": "方位サイドローブが高いため、窓関数を推奨します", + "note.ambiguity_high": "仰角曖昧性リスク:高", + "note.ambiguity_medium": "仰角曖昧性リスク:中", + + "empty.azimuth": "現在のアレイには方位開口がありません", + "empty.elevation": "現在のアレイには仰角開口がありません", + "empty.twoD": "現在のアレイは完全な 2D 測角能力を持ちません", + "empty.body": "Tx/Rx チャネルを追加するか素子間隔を広げてください。自動配置も使えます。", + "empty.twoDBody": "方位と仰角の両方に開口が必要です。片方のみの場合は 1D DBF を使用してください。", + "empty.editArray": "アレイを編集", + "empty.view1d": "1D DBF を開く", + + "dbf.title": "{axis} DBF 辞書スペクトル", + "dbf.play": "再生", + "dbf.pause": "一時停止", + "dbf.resume": "再開", + "dbf.stop": "0° に戻す", + "dbf.speed": "速度", + "dbf.true": "真の角度", + "dbf.peak": "ピーク角", + "dbf.error": "誤差", + "dbf.margin": "競合ピークマージン", + "dbf.frame": "フレーム {frame}/{total}", + "dbf.loading": "スペクトルを計算しています…", + "dbf.legendSpectrum": "スペクトル", + "dbf.legendTrue": "真の角度", + "dbf.legendPeak": "ピーク", + "dbf.sliderLabel": "{axis}の真の角度", + "dbf.quality": "ピーク品質", + + "dbf2d.title": "2D DBF スペクトル", + "dbf2d.playAz": "方位スキャン", + "dbf2d.pauseAz": "方位を停止", + "dbf2d.playEl": "仰角スキャン", + "dbf2d.pauseEl": "仰角を停止", + "dbf2d.reset": "0° に戻す", + "dbf2d.trueAz": "真の方位", + "dbf2d.trueEl": "真の仰角", + "dbf2d.peak": "ピーク", + "dbf2d.delta": "ピークずれ", + "dbf2d.hint": "ヒートマップをクリックして真の角度を設定。方位・仰角は個別または同時にスキャンできます。", + "dbf2d.loading": "2D スペクトルを計算しています…", + + "angle.title": "測角誤差と競合ピークマージン", + "angle.subtitle": "フレームごとの真の角度 −90°〜+90°(1° 刻み)", + "angle.errorChart": "{axis}測角誤差", + "angle.marginChart": "{axis}競合ピークマージン", + "angle.noFold": "折り返しなし範囲", + "angle.threshold": "マージンしきい値", + "angle.errorSeries": "誤差", + "angle.marginSeries": "マージン", + "angle.exportPng": "誤差図 PNG を書き出す", + "angle.clipped": "競合ピークのないフレームは軸の上端に表示します", + + "dictDialog.title": "DBF 辞書設定", + "dictDialog.mode": "辞書モード", + "dictDialog.files": "読込辞書ファイル", + "dictDialog.azFile": "方位辞書", + "dictDialog.elFile": "仰角辞書", + "dictDialog.upload": "ファイルを選択", + "dictDialog.replace": "差し替え", + "dictDialog.clear": "クリア", + "dictDialog.notLoaded": "未読込", + "dictDialog.channelMode": "列の対応", + "dictDialog.virtual": "仮想チャネル(Tx×Rx)", + "dictDialog.physical": "物理チャネル(Tx + Rx)", + "dictDialog.phaseReversed": "読込辞書の位相を反転", + "dictDialog.zeroCalibrated": "0° 行で位相校正", + "dictDialog.preview": "プレビュー", + "dictDialog.previewAxis": "プレビュー軸", + "dictDialog.phaseMatrix": "辞書位相行列({rows} 角度 × {cols} チャネル)", + "dictDialog.qualityOk": "品質良好", + "dictDialog.qualityWarning": "注意", + "dictDialog.qualityDanger": "リスクあり", + "dictDialog.qualityDetail": "競合曖昧行 {ambiguous} · ゼロノルム行 {zeros} · 非近傍有効ランク {rank}/{rankRows}", + "dictDialog.qualityNote": "品質表示は参考情報であり、適用を妨げません。", + "dictDialog.needFile": "読込辞書モードには方位または仰角のファイルが少なくとも 1 つ必要です。", + "dictDialog.tableInfo": "{rows} 行 · {cols} 列 · {format}", + "dictDialog.apply": "辞書を適用", + + "patternDialog.title": "チャネル振幅/位相と素子パターン", + "patternDialog.channelSection": "チャネル振幅/位相(HFSS 出力)", + "patternDialog.target": "サマリー列の対応", + "patternDialog.physical": "物理チャネル", + "patternDialog.virtual": "仮想チャネル", + "patternDialog.summaryHint": "角度列以降のデータ列を左から順にチャネルへ対応させます。列名にチャネル名を含む場合は名前で照合します。", + "patternDialog.loadSummary": "{slot}サマリーを読み込む", + "patternDialog.slot.amplitude.horizontal": "振幅·水平", + "patternDialog.slot.amplitude.elevation": "振幅·仰角", + "patternDialog.slot.phase.horizontal": "位相·水平", + "patternDialog.slot.phase.elevation": "位相·仰角", + "patternDialog.channel": "チャネル", + "patternDialog.setSingle": "{channel} の{slot}を読み込む", + "patternDialog.clearChannel": "チャネルをクリア", + "patternDialog.clearAll": "すべてクリア", + "patternDialog.groupPhysical": "物理チャネル", + "patternDialog.groupVirtual": "仮想チャネル", + "patternDialog.loaded": "{count} チャネルの{slot}を読み込みました", + "patternDialog.elementSection": "素子パターン", + "patternDialog.elementHint": "CSV/TSV:角度列 + 利得列。利得列が 2 つある場合は 2 列目を水平面、1 列目を仰角面とします(HFSS 出力の慣例)。「H/V 入れ替え」で変更できます。アレイパターン指標の計算に使用します。", + "patternDialog.elementUpload": "パターンを読み込む", + "patternDialog.elementClear": "等方性に戻す", + "patternDialog.swap": "H/V 入れ替え", + "patternDialog.isotropic": "理想等方性素子を使用中", + "patternDialog.horizontal": "水平面", + "patternDialog.elevationPlane": "仰角面", + "patternDialog.reuse": "独立した仰角列がないため、仰角面は水平面を流用します。", + "patternDialog.metrics": "ピーク {peak} dBi @ {angle}° · 3 dB 幅 {bw3} · 6 dB 幅 {bw6}", + "patternDialog.done": "完了", + + "reportDialog.title": "現在構成の性能レポート", + "reportDialog.reportTitle": "レポートタイトル", + "reportDialog.defaultTitle": "現在構成の測角性能レポート", + "reportDialog.focus": "性能評価範囲", + "reportDialog.hold": "スペクトル Hold 範囲", + "reportDialog.stride": "Hold 曲線間隔(フレーム)", + "reportDialog.unavailableAxis": "この軸には開口がないため、レポートでは省略されます。", + "reportDialog.errorLimit": "誤差しきい値 (°)", + "reportDialog.floor": "dB 表示下限", + "reportDialog.outputDb": "dB スペクトルページ", + "reportDialog.outputMag": "正規化振幅スペクトルページ", + "reportDialog.rawData": "再現用データ(CSV/JSON、zip)を含める", + "reportDialog.language": "レポート言語", + "reportDialog.generate": "PDF レポートを生成", + "reportDialog.generating": "生成中…", + "reportDialog.download": "ダウンロード", + "reportDialog.done": "レポートを生成しました", + "reportDialog.failed": "生成に失敗しました", + "reportDialog.cancelled": "キャンセルしました", + "reportDialog.cancel": "キャンセル", + "reportDialog.close": "閉じる", + "reportDialog.imageTitle": "測角誤差図", + "reportDialog.imageHint": "±90° の方位/仰角測角誤差曲線を 1 枚の PNG に出力します。", + "reportDialog.generateImage": "PNG を生成", + "reportDialog.needOutput": "スペクトル出力を少なくとも 1 つ選択してください", + "reportDialog.start": "開始", + "reportDialog.stop": "終了", + "reportDialog.note": "レポートは現在のプロジェクトのスナップショットからサーバーで生成されます。生成中も編集できます。", + + "projectsDialog.title": "プロジェクトライブラリ", + "projectsDialog.hint": "プロジェクトはサーバーのデータディレクトリに保存され、同じサーバーの全ユーザーが参照できます。", + "projectsDialog.saveCurrent": "現在のプロジェクトを保存", + "projectsDialog.empty": "ライブラリは空です。保存したプロジェクトがここに表示されます。", + "projectsDialog.open": "開く", + "projectsDialog.delete": "削除", + "projectsDialog.confirmDelete": "プロジェクト「{name}」を削除しますか?元に戻せません。", + "projectsDialog.updated": "更新 {time}", + "projectsDialog.current": "現在", + "projectsDialog.discard": "現在のプロジェクトに未保存の変更があります。別のプロジェクトを開くと破棄されます。", + + "help.title": "使い方", + "help.shortcuts": "キーボードショートカット", + + "common.cancel": "キャンセル", + "common.close": "閉じる", + "common.apply": "適用", + "common.loading": "読み込み中…", + "common.error": "エラー", + + "status.ready": "準備完了", + "status.computing": "計算中", + "status.saved": "プロジェクトライブラリに保存しました", + "status.imported": "読み込みました:{name}", + "status.importFailed": "読み込みに失敗しました:{message}", + "status.missingAssets": "参照されている {count} 個のデータファイルがこのサーバーにないため、関連設定を削除しました。", + "status.exported": "書き出しました:{name}", + "status.undo": "元に戻しました", + "status.redo": "やり直しました", + "status.nothingToUndo": "元に戻す操作はありません", + "status.nothingToRedo": "やり直す操作はありません", + "status.autoLayout": "自動配置を適用しました:{tx}T{rx}R", + "status.cleared": "1T1R にリセットしました", + "status.deleted": "{name} を削除し、位置順に番号を振り直しました", + "status.added": "{name} を追加しました", + "status.moved": "{name} → ({x}, {y}) λ", + "status.dictApplied": "DBF 辞書を適用しました:{mode}", + "status.elementLoaded": "素子パターンを読み込みました:{name}", + "status.elementCleared": "等方性素子に戻しました", + "status.newProject": "新規プロジェクトを作成しました", + "status.opened": "開きました:{name}", + "status.uploadFailed": "アップロードに失敗しました:{message}", +}; diff --git a/web/src/lib/__tests__/lib.test.ts b/web/src/lib/__tests__/lib.test.ts new file mode 100644 index 0000000..711b5f2 --- /dev/null +++ b/web/src/lib/__tests__/lib.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from "vitest"; +import { decodeMatrix, matrixRow, wire } from "../encoding"; +import { dbToMagnitude, fmtSigned, parseNumber, trimNumber } from "../format"; +import { layoutsEqual, nextElementPosition, renumber, snap, virtualGroups } from "../geometry"; + +describe("geometry", () => { + it("snaps to the λ/2 grid without negative zero", () => { + expect(snap(0.74)).toBe(0.5); + expect(snap(0.76)).toBe(1); + expect(Object.is(snap(-0.1), -0)).toBe(false); + }); + + it("renumbers by position and follows the selected element", () => { + const layout = { tx: [{ x: 5, y: 0 }, { x: 1, y: 0 }], rx: [{ x: 0, y: -1 }] }; + const result = renumber(layout, { kind: "tx", index: 0 }); + expect(result.layout.tx).toEqual([{ x: 1, y: 0 }, { x: 5, y: 0 }]); + expect(result.follow).toEqual({ kind: "tx", index: 1 }); + }); + + it("groups duplicate virtual positions with their Tx-Rx pairs", () => { + const layout = { tx: [{ x: 0, y: 0 }, { x: 1, y: 0 }], rx: [{ x: 0, y: 0 }, { x: 1, y: 0 }] }; + const groups = virtualGroups(layout); + expect(groups).toHaveLength(3); + const middle = groups.find((group) => group.x === 1)!; + expect(middle.count).toBe(2); + expect(middle.pairs).toEqual(["Tx1-Rx2", "Tx2-Rx1"]); + }); + + it("places new elements 1 λ to the right of the anchor, skipping occupied cells", () => { + const layout = { tx: [{ x: 0, y: 0 }, { x: 1, y: 0 }], rx: [{ x: 2, y: 0 }] }; + expect(nextElementPosition(layout, "tx", { kind: "tx", index: 0 })).toEqual({ x: 3, y: 0 }); + expect(nextElementPosition({ tx: [], rx: [] }, "rx", null)).toEqual({ x: 0, y: -5 }); + }); + + it("compares layouts by value", () => { + const a = { tx: [{ x: 0, y: 0 }], rx: [{ x: 1, y: 0 }] }; + expect(layoutsEqual(a, structuredClone(a))).toBe(true); + expect(layoutsEqual(a, { ...a, rx: [{ x: 1.5, y: 0 }] })).toBe(false); + }); +}); + +describe("format", () => { + it("parses numbers with optional unit suffixes and decimal commas", () => { + expect(parseNumber("77 GHz", ["ghz", "g"])).toBe(77); + expect(parseNumber("24,125g", ["ghz", "g"])).toBe(24.125); + expect(parseNumber("abc")).toBeNull(); + expect(parseNumber(" ")).toBeNull(); + }); + + it("formats signed angles and trims trailing zeros", () => { + expect(fmtSigned(12)).toBe("+12°"); + expect(fmtSigned(-0.2)).toBe("0°"); + expect(fmtSigned(null)).toBe("—"); + expect(trimNumber(1.5)).toBe("1.5"); + expect(trimNumber(2)).toBe("2"); + }); + + it("converts dB to clipped correlation magnitude", () => { + expect(dbToMagnitude(0)).toBe(1); + expect(dbToMagnitude(-20)).toBeCloseTo(0.1); + expect(dbToMagnitude(3)).toBe(1); + }); +}); + +describe("encoding", () => { + it("decodes base64 float32 matrices", () => { + const values = new Float32Array([1, 2, 3, 4, 5, 6]); + const data = Buffer.from(values.buffer).toString("base64"); + const matrix = decodeMatrix({ dtype: "float32", shape: [2, 3], data }); + expect(matrix.rows).toBe(2); + expect(matrixRow(matrix, 1)).toEqual([4, 5, 6]); + }); + + it("maps wire infinities", () => { + expect(wire("Infinity")).toBe(Number.POSITIVE_INFINITY); + expect(wire("-Infinity")).toBe(Number.NEGATIVE_INFINITY); + expect(wire(null)).toBeNull(); + expect(wire(1.5)).toBe(1.5); + }); +}); diff --git a/web/src/lib/encoding.ts b/web/src/lib/encoding.ts new file mode 100644 index 0000000..e63bb5e --- /dev/null +++ b/web/src/lib/encoding.ts @@ -0,0 +1,36 @@ +import type { EncodedArray, WireNumber } from "../api/types"; + +export interface Matrix { + rows: number; + cols: number; + data: Float32Array | Float64Array; +} + +export function decodeMatrix(encoded: EncodedArray): Matrix { + const binary = atob(encoded.data); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i); + const data = + encoded.dtype === "float64" ? new Float64Array(bytes.buffer) : new Float32Array(bytes.buffer); + const [rows, cols = 1] = encoded.shape; + return { rows, cols, data }; +} + +export function matrixRow(matrix: Matrix, row: number): number[] { + const start = row * matrix.cols; + return Array.from(matrix.data.subarray(start, start + matrix.cols)); +} + +export function matrixRows(matrix: Matrix): number[][] { + const rows: number[][] = []; + for (let r = 0; r < matrix.rows; r += 1) rows.push(matrixRow(matrix, r)); + return rows; +} + +/** Server numbers may be ±Infinity strings or null (NaN). */ +export function wire(value: WireNumber | undefined): number | null { + if (value === null || value === undefined) return null; + if (value === "Infinity") return Number.POSITIVE_INFINITY; + if (value === "-Infinity") return Number.NEGATIVE_INFINITY; + return value; +} diff --git a/web/src/lib/format.ts b/web/src/lib/format.ts new file mode 100644 index 0000000..55baf13 --- /dev/null +++ b/web/src/lib/format.ts @@ -0,0 +1,62 @@ +export function fmt(value: number | null | undefined, digits = 1, suffix = ""): string { + if (value === null || value === undefined || !Number.isFinite(value)) return "—"; + return `${value.toFixed(digits)}${suffix}`; +} + +export function fmtSigned(value: number | null | undefined, digits = 0, suffix = "°"): string { + if (value === null || value === undefined || !Number.isFinite(value)) return "—"; + if (Math.abs(value) < 0.5 * 10 ** -digits) return `0${suffix}`; + return `${value > 0 ? "+" : ""}${value.toFixed(digits)}${suffix}`; +} + +export function fmtLambda(value: number): string { + return `${trimNumber(value)} λ`; +} + +export function trimNumber(value: number, digits = 3): string { + if (!Number.isFinite(value)) return "—"; + const text = value.toFixed(digits); + return text.includes(".") ? text.replace(/0+$/, "").replace(/\.$/, "") : text; +} + +export function parseNumber(text: string, suffixes: string[] = []): number | null { + let value = text.trim().toLowerCase().replace(",", "."); + for (const suffix of suffixes) { + if (value.endsWith(suffix)) { + value = value.slice(0, -suffix.length).trim(); + break; + } + } + if (!value) return null; + const number = Number(value); + return Number.isFinite(number) ? number : null; +} + +export function dbToMagnitude(db: number): number { + return Math.min(1, Math.max(0, 10 ** (Math.min(db, 0) / 20))); +} + +export function downloadBlob(blob: Blob, filename: string): void { + const url = URL.createObjectURL(blob); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = filename; + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +export function downloadJson(data: unknown, filename: string): void { + downloadBlob(new Blob([JSON.stringify(data, null, 2) + "\n"], { type: "application/json" }), filename); +} + +export function safeFilename(name: string): string { + return name.replace(/[\\/:*?"<>|\x00-\x1f]/g, "_").trim() || "project"; +} + +export function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} diff --git a/web/src/lib/geometry.ts b/web/src/lib/geometry.ts new file mode 100644 index 0000000..62e4b81 --- /dev/null +++ b/web/src/lib/geometry.ts @@ -0,0 +1,101 @@ +import type { ElementKind, Layout, Point } from "../api/types"; + +export const GRID_STEP = 0.5; + +export interface ElementRef { + kind: ElementKind; + index: number; +} + +export function snap(value: number, step = GRID_STEP): number { + const snapped = Math.round(value / step) * step; + return Object.is(snapped, -0) ? 0 : snapped; +} + +export function elementName(kind: ElementKind, index: number): string { + return `${kind === "tx" ? "Tx" : "Rx"}${index + 1}`; +} + +/** + * Sort each kind by (x, y) so channel numbers follow position, as the desktop + * tool did after every edit. Returns the new index of `follow` if given. + */ +export function renumber(layout: Layout, follow?: ElementRef | null): { layout: Layout; follow: ElementRef | null } { + let followed: ElementRef | null = null; + const sortKind = (kind: ElementKind): Point[] => { + const indexed = layout[kind].map((point, index) => ({ point, index })); + indexed.sort((a, b) => a.point.x - b.point.x || a.point.y - b.point.y || a.index - b.index); + if (follow && follow.kind === kind) { + const newIndex = indexed.findIndex((item) => item.index === follow.index); + if (newIndex >= 0) followed = { kind, index: newIndex }; + } + return indexed.map((item) => item.point); + }; + return { layout: { tx: sortKind("tx"), rx: sortKind("rx") }, follow: followed }; +} + +export interface VirtualGroup { + x: number; + y: number; + count: number; + pairs: string[]; +} + +/** Virtual positions are Tx + Rx (λ); computed locally for instant drag feedback. */ +export function virtualGroups(layout: Layout): VirtualGroup[] { + const groups = new Map(); + layout.tx.forEach((tx, ti) => { + layout.rx.forEach((rx, ri) => { + const x = round9(tx.x + rx.x); + const y = round9(tx.y + rx.y); + const key = `${x},${y}`; + const pair = `${elementName("tx", ti)}-${elementName("rx", ri)}`; + const group = groups.get(key); + if (group) { + group.count += 1; + group.pairs.push(pair); + } else { + groups.set(key, { x, y, count: 1, pairs: [pair] }); + } + }); + }); + return [...groups.values()]; +} + +function round9(value: number): number { + return Math.round(value * 1e9) / 1e9; +} + +export function nextElementPosition(layout: Layout, kind: ElementKind, selected: ElementRef | null): Point { + const same = layout[kind]; + if (same.length === 0) return { x: 0, y: kind === "tx" ? 0 : -5 }; + const anchor = + selected && selected.kind === kind && same[selected.index] + ? same[selected.index] + : same.reduce((best, point) => (point.x > best.x || (point.x === best.x && point.y > best.y) ? point : best)); + const occupied = new Set([...layout.tx, ...layout.rx].map((point) => `${point.x},${point.y}`)); + let x = snap(anchor.x + 1); + const y = snap(anchor.y); + while (occupied.has(`${x},${y}`)) x = snap(x + 1); + return { x, y }; +} + +export function layoutBounds(points: Point[], pad = 1): { minX: number; maxX: number; minY: number; maxY: number } { + if (points.length === 0) return { minX: -5, maxX: 5, minY: -5, maxY: 5 }; + let minX = Infinity; + let maxX = -Infinity; + let minY = Infinity; + let maxY = -Infinity; + for (const point of points) { + minX = Math.min(minX, point.x); + maxX = Math.max(maxX, point.x); + minY = Math.min(minY, point.y); + maxY = Math.max(maxY, point.y); + } + return { minX: minX - pad, maxX: maxX + pad, minY: minY - pad, maxY: maxY + pad }; +} + +export function layoutsEqual(a: Layout, b: Layout): boolean { + const same = (p: Point[], q: Point[]) => p.length === q.length && p.every((point, i) => point.x === q[i].x && point.y === q[i].y); + return same(a.tx, b.tx) && same(a.rx, b.rx); +} diff --git a/web/src/main.tsx b/web/src/main.tsx new file mode 100644 index 0000000..63f00a0 --- /dev/null +++ b/web/src/main.tsx @@ -0,0 +1,11 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { App } from "./App"; +import "./styles/global.css"; +import "./styles/views.css"; + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/web/src/state/actions.ts b/web/src/state/actions.ts new file mode 100644 index 0000000..d2955aa --- /dev/null +++ b/web/src/state/actions.ts @@ -0,0 +1,120 @@ +import { ApiError, api, errorMessage } from "../api/client"; +import type { ImportResult, Project } from "../api/types"; +import { downloadBlob, downloadJson, safeFilename } from "../lib/format"; +import { useStore } from "./store"; + +function store() { + return useStore.getState(); +} + +export async function saveProject(asNew = false): Promise { + const { project, projectId, markSaved, setStatus } = store(); + if (!project) return; + try { + let record; + if (projectId && !asNew) { + try { + record = await api.updateProject(projectId, project); + } catch (error) { + if (!(error instanceof ApiError && error.status === 404)) throw error; + record = await api.createProject(project); + } + } else { + record = await api.createProject(project); + } + markSaved(record.id, project); + setStatus("status.saved", "success"); + } catch (error) { + setStatus("overview.error", "error", undefined, errorMessage(error)); + } +} + +export function newProject(): void { + const { config, replaceProject, setStatus } = store(); + if (!config) return; + replaceProject(structuredClone(config.default_project), null, false); + setStatus("status.newProject"); +} + +export async function openProject(id: string): Promise { + const { replaceProject, setStatus } = store(); + try { + const record = await api.getProject(id); + replaceProject(record.project, record.id, true); + setStatus("status.opened", "success", { name: record.project.name }); + } catch (error) { + setStatus("overview.error", "error", undefined, errorMessage(error)); + } +} + +/** Drop references to data files the server does not have. */ +export function withoutMissingAssets(project: Project, missing: string[]): Project { + if (missing.length === 0) return project; + const gone = new Set(missing); + const dictionary = { ...project.dbf_dictionary }; + if (dictionary.azimuth_asset && gone.has(dictionary.azimuth_asset)) dictionary.azimuth_asset = null; + if (dictionary.elevation_asset && gone.has(dictionary.elevation_asset)) dictionary.elevation_asset = null; + if (dictionary.mode === "custom" && !dictionary.azimuth_asset && !dictionary.elevation_asset) dictionary.mode = "ideal"; + return { + ...project, + dbf_dictionary: dictionary, + element_pattern: project.element_pattern && gone.has(project.element_pattern.asset) ? null : project.element_pattern, + channel_patterns: project.channel_patterns.filter((binding) => !gone.has(binding.asset)), + }; +} + +export async function importFile(file: File): Promise { + const { replaceProject, setStatus } = store(); + try { + let result: ImportResult; + if (file.name.toLowerCase().endsWith(".zip")) { + result = await api.importBundle(file); + } else { + let document: unknown; + try { + document = JSON.parse(await file.text()); + } catch { + throw new Error("JSON parse error"); + } + result = await api.importDocument(document); + } + const project = withoutMissingAssets(result.project, result.missing_assets); + if (!project.name || project.name === "未命名阵列") { + project.name = file.name.replace(/\.(mimo\.zip|zip|json)$/i, ""); + } + replaceProject(project, null, false); + if (result.missing_assets.length > 0) { + setStatus("status.missingAssets", "error", { count: result.missing_assets.length }); + } else { + setStatus("status.imported", "success", { name: file.name }); + } + } catch (error) { + setStatus("status.importFailed", "error", { message: errorMessage(error) }); + } +} + +export async function exportLayout(): Promise { + const { project, setStatus } = store(); + if (!project) return; + try { + const document = await api.exportLayout(project); + const filename = `${safeFilename(project.name)}.json`; + downloadJson(document, filename); + setStatus("status.exported", "success", { name: filename }); + } catch (error) { + setStatus("overview.error", "error", undefined, errorMessage(error)); + } +} + +export async function exportBundle(): Promise { + const { project, setStatus } = store(); + if (!project) return; + try { + const blob = await api.exportBundle(project); + const filename = `${safeFilename(project.name)}.mimo.zip`; + downloadBlob(blob, filename); + setStatus("status.exported", "success", { name: filename }); + } catch (error) { + setStatus("overview.error", "error", undefined, errorMessage(error)); + } +} diff --git a/web/src/state/compute.ts b/web/src/state/compute.ts new file mode 100644 index 0000000..ac81056 --- /dev/null +++ b/web/src/state/compute.ts @@ -0,0 +1,93 @@ +import { useEffect, useState } from "react"; +import { api, errorMessage } from "../api/client"; +import type { Axis, DbfBank, Project } from "../api/types"; +import { useStore } from "./store"; + +const EVALUATE_DEBOUNCE_MS = 120; + +/** Fields that affect analysis results (the project name does not). */ +export function evaluationKey(project: Project): string { + const { name: _name, ...rest } = project; + return JSON.stringify(rest); +} + +/** Fields that affect DBF spectra (frequency, margin and element pattern do not). */ +export function dbfKey(project: Project): string { + return JSON.stringify([project.layout, project.channel_patterns, project.dbf_dictionary]); +} + +export function useEvaluationSync(): void { + const project = useStore((state) => state.project); + const key = project ? evaluationKey(project) : ""; + useEffect(() => { + if (!project) return; + const controller = new AbortController(); + const { setEvaluating, setEvaluation } = useStore.getState(); + const timer = window.setTimeout(async () => { + setEvaluating(true); + try { + const result = await api.evaluate(project, controller.signal); + setEvaluation(result, null); + } catch (error) { + if ((error as Error).name === "AbortError") return; + setEvaluation(useStore.getState().evaluation, errorMessage(error)); + } finally { + if (!controller.signal.aborted) setEvaluating(false); + } + }, EVALUATE_DEBOUNCE_MS); + return () => { + window.clearTimeout(timer); + controller.abort(); + }; + // `key` captures every result-relevant field of `project`. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); +} + +const bankCache = new Map>(); +const BANK_CACHE_LIMIT = 8; + +export function fetchBank(project: Project, axis: Axis): Promise { + const key = `${axis}|${dbfKey(project)}`; + let pending = bankCache.get(key); + if (!pending) { + pending = api.dbfBank(project, axis); + pending.catch(() => bankCache.delete(key)); + bankCache.set(key, pending); + while (bankCache.size > BANK_CACHE_LIMIT) { + const oldest = bankCache.keys().next().value; + if (oldest === undefined) break; + bankCache.delete(oldest); + } + } + return pending; +} + +export interface AsyncState { + data: T | null; + error: string | null; + loading: boolean; +} + +export function useDbfBank(axis: Axis, enabled: boolean): AsyncState { + const project = useStore((state) => state.project); + const key = project ? dbfKey(project) : ""; + const [state, setState] = useState>({ data: null, error: null, loading: false }); + useEffect(() => { + if (!project || !enabled) return; + let cancelled = false; + setState((previous) => ({ ...previous, loading: true, error: null })); + const timer = window.setTimeout(() => { + fetchBank(project, axis).then( + (data) => !cancelled && setState({ data, error: null, loading: false }), + (error) => !cancelled && setState({ data: null, error: errorMessage(error), loading: false }), + ); + }, EVALUATE_DEBOUNCE_MS); + return () => { + cancelled = true; + window.clearTimeout(timer); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key, axis, enabled]); + return state; +} diff --git a/web/src/state/jobs.ts b/web/src/state/jobs.ts new file mode 100644 index 0000000..ab3f0d3 --- /dev/null +++ b/web/src/state/jobs.ts @@ -0,0 +1,81 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { api, errorMessage } from "../api/client"; +import type { Job } from "../api/types"; + +const POLL_MS = 500; + +/** Start a server export job, poll it, and download the result when it is ready. */ +export function useExportJob() { + const [job, setJob] = useState(null); + const [error, setError] = useState(null); + const timer = useRef(null); + + const stopPolling = () => { + if (timer.current !== null) window.clearTimeout(timer.current); + timer.current = null; + }; + + useEffect(() => stopPolling, []); + + const poll = useCallback((id: string, autoDownload: boolean) => { + const step = async () => { + try { + const next = await api.job(id); + setJob(next); + if (next.status === "succeeded") { + if (autoDownload) download(next); + return; + } + if (next.status === "failed" || next.status === "cancelled") return; + } catch (reason) { + setError(errorMessage(reason)); + return; + } + timer.current = window.setTimeout(step, POLL_MS); + }; + step(); + }, []); + + const start = useCallback( + async (create: () => Promise, autoDownload = true) => { + stopPolling(); + setError(null); + try { + const created = await create(); + setJob(created); + poll(created.id, autoDownload); + } catch (reason) { + setJob(null); + setError(errorMessage(reason)); + } + }, + [poll], + ); + + const cancel = useCallback(async () => { + if (!job) return; + try { + setJob(await api.cancelJob(job.id)); + } catch (reason) { + setError(errorMessage(reason)); + } + }, [job]); + + const reset = useCallback(() => { + stopPolling(); + setJob(null); + setError(null); + }, []); + + const running = job?.status === "queued" || job?.status === "running"; + return { job, error, running, start, cancel, reset, download: () => job && download(job) }; +} + +function download(job: Job) { + const anchor = document.createElement("a"); + anchor.href = api.jobDownloadUrl(job.id); + anchor.download = job.download_name ?? ""; + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); +} diff --git a/web/src/state/store.ts b/web/src/state/store.ts new file mode 100644 index 0000000..0477dc3 --- /dev/null +++ b/web/src/state/store.ts @@ -0,0 +1,250 @@ +import { create } from "zustand"; +import type { Evaluation, Layout, Project, ServerConfig } from "../api/types"; +import { type ElementRef, layoutsEqual, renumber } from "../lib/geometry"; +import type { MessageKey } from "../i18n/messages"; + +export type ViewId = "array" | "dbf1d" | "dbf2d" | "angle"; +export type Language = "zh" | "en" | "ja"; +export type ThemeMode = "system" | "light" | "dark"; +export type DisplayMode = "db" | "magnitude"; +export type DialogId = "dictionary" | "patterns" | "report" | "projects" | "help" | null; + +export interface StatusMessage { + key: MessageKey; + params?: Record; + tone: "info" | "success" | "error"; + /** Free text that does not come from the message catalogue (server errors). */ + detail?: string; + at: number; +} + +const MAX_HISTORY = 50; +const STORAGE_KEY = "mimo-array-workbench:v1"; + +interface PersistedState { + project: Project; + projectId: string | null; + savedSnapshot: string | null; + language: Language; + theme: ThemeMode; + display: DisplayMode; + view: ViewId; +} + +function readPersisted(): Partial { + try { + const raw = window.localStorage.getItem(STORAGE_KEY); + return raw ? (JSON.parse(raw) as Partial) : {}; + } catch { + return {}; + } +} + +function writePersisted(state: PersistedState): void { + try { + window.localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); + } catch { + // storage unavailable (private mode / quota): the session still works + } +} + +function detectLanguage(): Language { + const lang = (navigator.language || "zh").toLowerCase(); + if (lang.startsWith("ja")) return "ja"; + if (lang.startsWith("en")) return "en"; + return "zh"; +} + +export function projectSnapshot(project: Project): string { + return JSON.stringify(project); +} + +interface AppState { + config: ServerConfig | null; + project: Project | null; + projectId: string | null; + savedSnapshot: string | null; + past: Layout[]; + future: Layout[]; + selection: ElementRef | null; + deleteMode: boolean; + view: ViewId; + dialog: DialogId; + language: Language; + theme: ThemeMode; + display: DisplayMode; + status: StatusMessage | null; + evaluation: Evaluation | null; + evaluationError: string | null; + evaluating: boolean; + + initialize(config: ServerConfig): void; + setStatus(key: MessageKey, tone?: StatusMessage["tone"], params?: StatusMessage["params"], detail?: string): void; + updateProject(update: Partial): void; + replaceProject(project: Project, projectId: string | null, saved: boolean): void; + markSaved(projectId: string, project: Project): void; + commitLayout(layout: Layout, selection?: ElementRef | null): void; + undo(): void; + redo(): void; + select(selection: ElementRef | null): void; + setDeleteMode(on: boolean): void; + setView(view: ViewId): void; + openDialog(dialog: DialogId): void; + setLanguage(language: Language): void; + setTheme(theme: ThemeMode): void; + setDisplay(display: DisplayMode): void; + setEvaluation(evaluation: Evaluation | null, error: string | null): void; + setEvaluating(evaluating: boolean): void; +} + +const persisted = typeof window === "undefined" ? {} : readPersisted(); + +export const useStore = create((set, get) => ({ + config: null, + project: null, + projectId: persisted.projectId ?? null, + savedSnapshot: persisted.savedSnapshot ?? null, + past: [], + future: [], + selection: null, + deleteMode: false, + view: persisted.view ?? "array", + dialog: null, + language: persisted.language ?? (typeof navigator === "undefined" ? "zh" : detectLanguage()), + theme: persisted.theme ?? "system", + display: persisted.display ?? "db", + status: null, + evaluation: null, + evaluationError: null, + evaluating: false, + + initialize(config) { + const draft = persisted.project; + const project = draft && draft.version === 2 && draft.layout ? draft : config.default_project; + set({ config, project }); + }, + + setStatus(key, tone = "info", params, detail) { + set({ status: { key, tone, params, detail, at: Date.now() } }); + }, + + updateProject(update) { + const project = get().project; + if (!project) return; + set({ project: { ...project, ...update } }); + }, + + replaceProject(project, projectId, saved) { + set({ + project, + projectId, + savedSnapshot: saved ? projectSnapshot(project) : null, + past: [], + future: [], + selection: null, + deleteMode: false, + evaluation: null, + evaluationError: null, + }); + }, + + markSaved(projectId, project) { + set({ projectId, savedSnapshot: projectSnapshot(project) }); + }, + + commitLayout(layout, selection) { + const { project, past, selection: current } = get(); + if (!project) return; + const ordered = renumber(layout, selection === undefined ? current : selection); + if (layoutsEqual(ordered.layout, project.layout)) { + set({ selection: ordered.follow }); + return; + } + set({ + project: { ...project, layout: ordered.layout }, + past: [...past, project.layout].slice(-MAX_HISTORY), + future: [], + selection: ordered.follow, + }); + }, + + undo() { + const { project, past, future } = get(); + if (!project || past.length === 0) { + get().setStatus("status.nothingToUndo"); + return; + } + const previous = past[past.length - 1]; + set({ + project: { ...project, layout: previous }, + past: past.slice(0, -1), + future: [project.layout, ...future].slice(0, MAX_HISTORY), + selection: null, + }); + get().setStatus("status.undo"); + }, + + redo() { + const { project, past, future } = get(); + if (!project || future.length === 0) { + get().setStatus("status.nothingToRedo"); + return; + } + const [next, ...rest] = future; + set({ + project: { ...project, layout: next }, + past: [...past, project.layout].slice(-MAX_HISTORY), + future: rest, + selection: null, + }); + get().setStatus("status.redo"); + }, + + select(selection) { + set({ selection }); + }, + setDeleteMode(on) { + set({ deleteMode: on, selection: on ? null : get().selection }); + }, + setView(view) { + set({ view }); + }, + openDialog(dialog) { + set({ dialog }); + }, + setLanguage(language) { + set({ language }); + }, + setTheme(theme) { + set({ theme }); + }, + setDisplay(display) { + set({ display }); + }, + setEvaluation(evaluation, error) { + set({ evaluation, evaluationError: error }); + }, + setEvaluating(evaluating) { + set({ evaluating }); + }, +})); + +// Persist the working draft and preferences so a browser reload keeps the session. +useStore.subscribe((state) => { + if (!state.project) return; + writePersisted({ + project: state.project, + projectId: state.projectId, + savedSnapshot: state.savedSnapshot, + language: state.language, + theme: state.theme, + display: state.display, + view: state.view, + }); +}); + +export function useIsDirty(): boolean { + return useStore((state) => + state.project ? state.savedSnapshot !== projectSnapshot(state.project) : false, + ); +} diff --git a/web/src/styles/global.css b/web/src/styles/global.css new file mode 100644 index 0000000..d584ce4 --- /dev/null +++ b/web/src/styles/global.css @@ -0,0 +1,1343 @@ +/* Design tokens: Carbon-led engineering workbench, light + dark. */ +:root { + color-scheme: light; + --font-sans: "IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", + "Hiragino Sans", "Microsoft YaHei UI", "Microsoft YaHei", "Noto Sans CJK SC", "Noto Sans SC", + "Yu Gothic UI", sans-serif; + --font-mono: "IBM Plex Mono", "SFMono-Regular", "Cascadia Mono", Consolas, "Liberation Mono", monospace; + + --canvas: #f2f4f8; + --surface: #ffffff; + --surface-subtle: #f6f7f9; + --surface-muted: #eceef2; + --surface-hover: #e8eaef; + --surface-pressed: #d6d9e0; + --surface-selected: #e0ebff; + --border: #e0e3e8; + --border-strong: #c6cad2; + --control-border: #8d93a0; + --text: #161616; + --text-secondary: #4d5360; + --text-tertiary: #6f7682; + --text-on-accent: #ffffff; + --accent: #0f62fe; + --accent-hover: #0353e9; + --accent-pressed: #002d9c; + --accent-tint: #d0e2ff; + --accent-soft: #edf4ff; + --focus: #0f62fe; + --success: #198038; + --success-fill: #defbe6; + --warning: #8e6a00; + --warning-fill: #fcf4d6; + --danger: #da1e28; + --danger-fill: #fff1f1; + + --tx: #e5484d; + --tx-edge: #a2191f; + --tx-fill: #fde8e8; + --rx: #0f62fe; + --rx-edge: #002d9c; + --rx-fill: #e5efff; + --virtual: #0f62fe; + --virtual-dup: #f1a10d; + --chart-line: #0f62fe; + --chart-secondary: #8a3ffc; + --chart-true: #f1a10d; + --chart-peak: #da1e28; + --chart-grid: #e6e8ec; + --chart-zero: #c6cad2; + --chart-band: rgba(15, 98, 254, 0.08); + + --radius-sm: 4px; + --radius: 6px; + --radius-lg: 10px; + --shadow-sm: 0 1px 2px rgba(22, 22, 22, 0.06); + --shadow: 0 1px 3px rgba(22, 22, 22, 0.08), 0 4px 12px rgba(22, 22, 22, 0.06); + --shadow-lg: 0 12px 40px rgba(22, 22, 22, 0.22); + --overview-width: 320px; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + color-scheme: dark; + --canvas: #121417; + --surface: #1b1e23; + --surface-subtle: #20242a; + --surface-muted: #262a31; + --surface-hover: #2c3139; + --surface-pressed: #39404a; + --surface-selected: #1d2f52; + --border: #2f343c; + --border-strong: #434a55; + --control-border: #6f7682; + --text: #f2f4f8; + --text-secondary: #b7bdc8; + --text-tertiary: #8d93a0; + --accent: #4589ff; + --accent-hover: #6ea6ff; + --accent-pressed: #a6c8ff; + --accent-tint: #1d3a6e; + --accent-soft: #172640; + --focus: #78a9ff; + --success: #42be65; + --success-fill: #0f2a19; + --warning: #f1c21b; + --warning-fill: #2e2608; + --danger: #ff8389; + --danger-fill: #3a1316; + --tx: #ff6b70; + --tx-edge: #ffb3b8; + --tx-fill: #3a1a1c; + --rx: #4589ff; + --rx-edge: #a6c8ff; + --rx-fill: #17284a; + --virtual: #6ea6ff; + --virtual-dup: #f1c21b; + --chart-line: #6ea6ff; + --chart-secondary: #be95ff; + --chart-true: #f1c21b; + --chart-peak: #ff8389; + --chart-grid: #2b3038; + --chart-zero: #4a515c; + --chart-band: rgba(110, 166, 255, 0.1); + --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4); + --shadow: 0 1px 3px rgba(0, 0, 0, 0.4), 0 6px 16px rgba(0, 0, 0, 0.3); + --shadow-lg: 0 16px 48px rgba(0, 0, 0, 0.55); + } +} + +:root[data-theme="dark"] { + color-scheme: dark; + --canvas: #121417; + --surface: #1b1e23; + --surface-subtle: #20242a; + --surface-muted: #262a31; + --surface-hover: #2c3139; + --surface-pressed: #39404a; + --surface-selected: #1d2f52; + --border: #2f343c; + --border-strong: #434a55; + --control-border: #6f7682; + --text: #f2f4f8; + --text-secondary: #b7bdc8; + --text-tertiary: #8d93a0; + --accent: #4589ff; + --accent-hover: #6ea6ff; + --accent-pressed: #a6c8ff; + --accent-tint: #1d3a6e; + --accent-soft: #172640; + --focus: #78a9ff; + --success: #42be65; + --success-fill: #0f2a19; + --warning: #f1c21b; + --warning-fill: #2e2608; + --danger: #ff8389; + --danger-fill: #3a1316; + --tx: #ff6b70; + --tx-edge: #ffb3b8; + --tx-fill: #3a1a1c; + --rx: #4589ff; + --rx-edge: #a6c8ff; + --rx-fill: #17284a; + --virtual: #6ea6ff; + --virtual-dup: #f1c21b; + --chart-line: #6ea6ff; + --chart-secondary: #be95ff; + --chart-true: #f1c21b; + --chart-peak: #ff8389; + --chart-grid: #2b3038; + --chart-zero: #4a515c; + --chart-band: rgba(110, 166, 255, 0.1); + --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4); + --shadow: 0 1px 3px rgba(0, 0, 0, 0.4), 0 6px 16px rgba(0, 0, 0, 0.3); + --shadow-lg: 0 16px 48px rgba(0, 0, 0, 0.55); +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html, +body, +#root { + height: 100%; +} + +body { + margin: 0; + background: var(--canvas); + color: var(--text); + font-family: var(--font-sans); + font-size: 13px; + line-height: 1.45; + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; +} + +button, +input, +select, +textarea { + font: inherit; + color: inherit; +} + +:focus-visible { + outline: 2px solid var(--focus); + outline-offset: 1px; +} + +.num { + font-variant-numeric: tabular-nums; +} + +.mono { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; +} + +.muted { + color: var(--text-secondary); +} + +.subtle { + color: var(--text-tertiary); +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +/* ── App shell ─────────────────────────────────────────────────── */ + +.app { + display: grid; + grid-template-rows: auto auto minmax(0, 1fr) auto; + height: 100%; + min-width: 0; +} + +.topbar { + display: flex; + align-items: center; + gap: 12px; + height: 52px; + padding: 0 14px; + background: var(--surface); + border-bottom: 1px solid var(--border); +} + +.brand { + display: flex; + align-items: center; + gap: 10px; + min-width: 0; +} + +.brand-mark { + display: grid; + place-items: center; + width: 30px; + height: 30px; + border-radius: 7px; + background: var(--accent); + color: var(--text-on-accent); + flex: none; +} + +.brand-name { + font-weight: 600; + font-size: 14px; + white-space: nowrap; +} + +.brand-divider { + width: 1px; + height: 22px; + background: var(--border); +} + +.project-title { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; +} + +.project-name-input { + min-width: 80px; + max-width: 280px; + height: 30px; + padding: 0 8px; + border: 1px solid transparent; + border-radius: var(--radius-sm); + background: transparent; + font-weight: 500; + font-size: 13.5px; + text-overflow: ellipsis; +} + +.project-name-input:hover { + border-color: var(--border); +} + +.project-name-input:focus { + border-color: var(--accent); + background: var(--surface); + outline: none; +} + +.save-state { + display: inline-flex; + align-items: center; + gap: 5px; + color: var(--text-tertiary); + font-size: 12px; + white-space: nowrap; +} + +.save-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--success); +} + +.save-dot.dirty { + background: var(--warning); +} + +.save-dot.local { + background: var(--text-tertiary); +} + +.topbar-spacer { + flex: 1; +} + +.topbar-actions { + display: flex; + align-items: center; + gap: 4px; +} + +.controlbar { + display: flex; + align-items: center; + gap: 16px; + min-height: 46px; + padding: 0 14px; + background: var(--surface); + border-bottom: 1px solid var(--border); + overflow-x: auto; + scrollbar-width: none; +} + +.controlbar::-webkit-scrollbar { + display: none; +} + +.view-tabs { + display: flex; + align-items: stretch; + align-self: stretch; + gap: 2px; +} + +.view-tab { + position: relative; + display: inline-flex; + align-items: center; + gap: 7px; + padding: 0 12px; + border: 0; + background: none; + color: var(--text-secondary); + font-weight: 500; + cursor: pointer; + white-space: nowrap; +} + +.view-tab:hover { + color: var(--text); + background: var(--surface-subtle); +} + +.view-tab[aria-selected="true"] { + color: var(--text); +} + +.view-tab[aria-selected="true"]::after { + content: ""; + position: absolute; + left: 8px; + right: 8px; + bottom: 0; + height: 2px; + border-radius: 2px 2px 0 0; + background: var(--accent); +} + +.controlbar-group { + display: flex; + align-items: center; + gap: 8px; + margin-left: auto; +} + +.workspace { + display: grid; + grid-template-columns: minmax(0, 1fr) var(--overview-width); + min-height: 0; +} + +.workspace-main { + min-width: 0; + min-height: 0; + overflow: auto; + padding: 12px; +} + +.overview { + min-height: 0; + overflow-y: auto; + border-left: 1px solid var(--border); + background: var(--surface); +} + +.statusbar { + display: flex; + align-items: center; + gap: 12px; + height: 28px; + padding: 0 14px; + border-top: 1px solid var(--border); + background: var(--surface); + color: var(--text-secondary); + font-size: 12px; +} + +.status-text { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.status-text.error { + color: var(--danger); +} + +.status-text.success { + color: var(--success); +} + +.status-meta { + display: inline-flex; + align-items: center; + gap: 6px; + white-space: nowrap; +} + +.spinner { + width: 12px; + height: 12px; + border: 2px solid var(--accent-tint); + border-top-color: var(--accent); + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +/* ── Controls ──────────────────────────────────────────────────── */ + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + height: 30px; + padding: 0 11px; + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + background: var(--surface); + color: var(--text); + font-weight: 500; + white-space: nowrap; + cursor: pointer; + transition: background-color 0.12s, border-color 0.12s, color 0.12s; +} + +.btn:hover:not(:disabled) { + background: var(--surface-hover); +} + +.btn:active:not(:disabled) { + background: var(--surface-pressed); +} + +.btn:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +.btn.primary { + border-color: var(--accent); + background: var(--accent); + color: var(--text-on-accent); +} + +.btn.primary:hover:not(:disabled) { + border-color: var(--accent-hover); + background: var(--accent-hover); +} + +.btn.ghost { + border-color: transparent; + background: transparent; +} + +.btn.ghost:hover:not(:disabled) { + background: var(--surface-hover); +} + +.btn.danger { + color: var(--danger); +} + +.btn.active, +.btn[aria-pressed="true"] { + border-color: var(--accent); + background: var(--accent-soft); + color: var(--accent); +} + +.btn.icon { + width: 30px; + padding: 0; +} + +.btn.sm { + height: 26px; + padding: 0 8px; + font-size: 12px; +} + +.btn.sm.icon { + width: 26px; + padding: 0; +} + +.btn svg { + flex: none; +} + +.btn-group { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.toolbar-sep { + width: 1px; + height: 20px; + margin: 0 4px; + background: var(--border); +} + +.field { + display: inline-flex; + align-items: center; + height: 30px; + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + background: var(--surface); + transition: border-color 0.12s; +} + +.field:focus-within { + border-color: var(--accent); + box-shadow: 0 0 0 1px var(--accent); +} + +.field.invalid { + border-color: var(--danger); + box-shadow: 0 0 0 1px var(--danger); +} + +.field-label { + padding: 0 0 0 9px; + color: var(--text-tertiary); + font-size: 12px; + white-space: nowrap; +} + +.field input { + width: 64px; + min-width: 0; + height: 100%; + padding: 0 6px 0 8px; + border: 0; + background: transparent; + outline: none; + font-variant-numeric: tabular-nums; +} + +.field.wide input { + width: 100%; +} + +.field-unit { + padding: 0 9px 0 0; + color: var(--text-tertiary); + font-size: 12px; +} + +.input { + height: 30px; + padding: 0 8px; + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + background: var(--surface); + outline: none; + min-width: 0; +} + +.input:focus { + border-color: var(--accent); + box-shadow: 0 0 0 1px var(--accent); +} + +.input.num { + text-align: right; +} + +select.input { + padding-right: 24px; +} + +.chip-button { + display: inline-flex; + align-items: center; + gap: 8px; + height: 30px; + padding: 0 10px; + border: 1px solid var(--border-strong); + border-radius: 15px; + background: var(--surface); + cursor: pointer; + white-space: nowrap; +} + +.chip-button:hover { + background: var(--surface-hover); +} + +.chip-label { + color: var(--text-tertiary); + font-size: 12px; +} + +.chip-value { + font-weight: 500; +} + +.chip-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--text-tertiary); +} + +.chip-dot.on { + background: var(--success); +} + +.chip-dot.warn { + background: var(--warning); +} + +.segmented { + display: inline-flex; + padding: 2px; + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + background: var(--surface-subtle); +} + +.segmented button { + height: 24px; + padding: 0 10px; + border: 0; + border-radius: 3px; + background: transparent; + color: var(--text-secondary); + font-weight: 500; + font-size: 12px; + cursor: pointer; + white-space: nowrap; +} + +.segmented button:hover { + color: var(--text); +} + +.segmented button[aria-pressed="true"] { + background: var(--surface); + color: var(--text); + box-shadow: var(--shadow-sm); +} + +.checkbox { + display: inline-flex; + align-items: center; + gap: 8px; + cursor: pointer; + user-select: none; +} + +.checkbox input { + width: 15px; + height: 15px; + margin: 0; + accent-color: var(--accent); +} + +.slider { + width: 100%; + accent-color: var(--accent); +} + +/* ── Panels ────────────────────────────────────────────────────── */ + +.panel { + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; + border: 1px solid var(--border); + border-radius: var(--radius-lg); + background: var(--surface); + box-shadow: var(--shadow-sm); +} + +.panel-header { + display: flex; + align-items: center; + gap: 10px; + min-height: 46px; + padding: 8px 12px 8px 14px; + border-bottom: 1px solid var(--border); +} + +.panel-title { + font-weight: 600; + font-size: 13.5px; +} + +.panel-subtitle { + color: var(--text-tertiary); + font-size: 12px; +} + +.panel-heading { + display: flex; + flex-direction: column; + min-width: 0; +} + +.panel-tools { + display: flex; + align-items: center; + gap: 2px; + margin-left: auto; + flex-wrap: nowrap; + flex-shrink: 0; + justify-content: flex-end; +} + +.panel-heading { + min-width: 0; + flex: 1 1 auto; +} + +.panel-heading .panel-subtitle { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.panel-body { + position: relative; + flex: 1; + min-height: 0; +} + +.panel-footer { + display: flex; + align-items: center; + gap: 10px; + min-height: 42px; + padding: 6px 12px; + border-top: 1px solid var(--border); + background: var(--surface-subtle); + border-radius: 0 0 var(--radius-lg) var(--radius-lg); + flex-wrap: wrap; +} + +.grid-2 { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + height: 100%; + min-height: 520px; +} + +.stack { + display: flex; + flex-direction: column; + gap: 12px; +} + +.callout { + display: flex; + gap: 10px; + padding: 10px 12px; + border-radius: var(--radius); + border: 1px solid var(--border); + background: var(--surface-subtle); + color: var(--text-secondary); +} + +.callout.info { + border-color: var(--accent-tint); + background: var(--accent-soft); +} + +.callout.success { + border-color: color-mix(in srgb, var(--success) 35%, transparent); + background: var(--success-fill); + color: var(--text); +} + +.callout.warning { + border-color: color-mix(in srgb, var(--warning) 40%, transparent); + background: var(--warning-fill); + color: var(--text); +} + +.callout.danger { + border-color: color-mix(in srgb, var(--danger) 40%, transparent); + background: var(--danger-fill); + color: var(--text); +} + +.callout svg { + flex: none; + margin-top: 1px; +} + +.empty-state { + position: absolute; + inset: 0; + display: grid; + place-items: center; + padding: 24px; + background: color-mix(in srgb, var(--surface) 88%, transparent); + z-index: 3; + text-align: center; +} + +.empty-state-inner { + max-width: 360px; + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; +} + +.empty-state h3 { + margin: 4px 0 0; + font-size: 14px; +} + +.empty-state p { + margin: 0 0 6px; + color: var(--text-secondary); +} + +.loading-overlay { + position: absolute; + top: 10px; + right: 12px; + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 8px; + border-radius: 12px; + background: var(--surface); + border: 1px solid var(--border); + color: var(--text-secondary); + font-size: 12px; + z-index: 4; + box-shadow: var(--shadow-sm); +} + +.kbd { + display: inline-block; + min-width: 20px; + padding: 1px 5px; + border: 1px solid var(--border-strong); + border-bottom-width: 2px; + border-radius: 4px; + background: var(--surface-subtle); + font-family: var(--font-mono); + font-size: 11px; + text-align: center; +} + +/* ── Menus ─────────────────────────────────────────────────────── */ + +.menu-anchor { + position: relative; +} + +.menu { + position: absolute; + top: calc(100% + 4px); + right: 0; + z-index: 50; + min-width: 220px; + padding: 4px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); + box-shadow: var(--shadow); +} + +.menu-item { + display: flex; + align-items: center; + gap: 9px; + width: 100%; + min-height: 32px; + padding: 0 10px; + border: 0; + border-radius: var(--radius-sm); + background: none; + text-align: left; + cursor: pointer; + white-space: nowrap; +} + +.menu-item:hover, +.menu-item:focus-visible { + background: var(--surface-hover); + outline: none; +} + +.menu-item[aria-checked="true"] { + color: var(--accent); + font-weight: 500; +} + +.menu-item .menu-check { + margin-left: auto; +} + +.menu-sep { + height: 1px; + margin: 4px 0; + background: var(--border); +} + +.menu-label { + padding: 6px 10px 2px; + color: var(--text-tertiary); + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +/* ── Dialog ────────────────────────────────────────────────────── */ + +.dialog-backdrop { + position: fixed; + inset: 0; + z-index: 100; + display: grid; + place-items: center; + padding: 24px; + background: rgba(10, 12, 16, 0.45); + animation: fade 0.12s ease-out; +} + +@keyframes fade { + from { + opacity: 0; + } +} + +.dialog { + display: flex; + flex-direction: column; + width: min(100%, 720px); + max-height: min(calc(100vh - 48px), 900px); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + background: var(--surface); + box-shadow: var(--shadow-lg); + animation: rise 0.16s ease-out; +} + +.dialog.wide { + width: min(100%, 1120px); +} + +.dialog.medium { + width: min(100%, 880px); +} + +@keyframes rise { + from { + transform: translateY(8px); + opacity: 0; + } +} + +.dialog-header { + display: flex; + align-items: center; + gap: 10px; + padding: 14px 16px 12px 20px; + border-bottom: 1px solid var(--border); +} + +.dialog-header h2 { + margin: 0; + font-size: 16px; + font-weight: 600; +} + +.dialog-body { + flex: 1; + min-height: 0; + overflow: auto; + padding: 16px 20px; +} + +.dialog-footer { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 20px; + border-top: 1px solid var(--border); + background: var(--surface-subtle); + border-radius: 0 0 var(--radius-lg) var(--radius-lg); +} + +.dialog-footer .spacer { + flex: 1; +} + +.section { + display: flex; + flex-direction: column; + gap: 10px; +} + +.section + .section { + margin-top: 20px; +} + +.section-title { + margin: 0; + font-size: 12px; + font-weight: 600; + color: var(--text-secondary); + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.form-grid { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + align-items: center; + gap: 8px 14px; +} + +.form-grid label { + color: var(--text-secondary); +} + +.range-input { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.range-input .input { + width: 72px; +} + +/* ── Tables ────────────────────────────────────────────────────── */ + +.table-wrap { + overflow: auto; + border: 1px solid var(--border); + border-radius: var(--radius); +} + +.table { + width: 100%; + border-collapse: collapse; + font-variant-numeric: tabular-nums; +} + +.table th, +.table td { + height: 32px; + padding: 0 10px; + border-bottom: 1px solid var(--border); + text-align: left; + white-space: nowrap; +} + +.table th { + position: sticky; + top: 0; + z-index: 1; + background: var(--surface-subtle); + color: var(--text-secondary); + font-weight: 600; + font-size: 12px; +} + +.table td.num, +.table th.num { + text-align: right; +} + +.table tbody tr:hover { + background: var(--surface-subtle); +} + +.table tbody tr.selected { + background: var(--surface-selected); +} + +.table tr.group-row td { + background: var(--surface-muted); + color: var(--text-secondary); + font-size: 11.5px; + font-weight: 600; + height: 26px; +} + +.table .input { + height: 26px; + width: 84px; +} + +/* ── Tags / badges ─────────────────────────────────────────────── */ + +.badge { + display: inline-flex; + align-items: center; + gap: 4px; + height: 20px; + padding: 0 7px; + border-radius: 10px; + background: var(--surface-muted); + color: var(--text-secondary); + font-size: 11.5px; + font-weight: 500; + white-space: nowrap; +} + +.badge.tx { + background: var(--tx-fill); + color: var(--tx-edge); +} + +.badge.rx { + background: var(--rx-fill); + color: var(--rx-edge); +} + +.badge.ok { + background: var(--success-fill); + color: var(--success); +} + +.badge.warn { + background: var(--warning-fill); + color: var(--warning); +} + +.badge.bad { + background: var(--danger-fill); + color: var(--danger); +} + +.tone-ok { + color: var(--success); +} + +.tone-warn { + color: var(--warning); +} + +.tone-bad { + color: var(--danger); +} + +@media (max-width: 1180px) { + :root { + --overview-width: 280px; + } +} + +@media (max-width: 980px) { + html, + body, + #root { + height: auto; + min-height: 100%; + } + + .app { + display: flex; + flex-direction: column; + height: auto; + min-height: 100vh; + } + + .topbar, + .controlbar { + position: sticky; + z-index: 20; + } + + .topbar { + top: 0; + } + + .controlbar { + top: 52px; + } + + .workspace { + display: block; + flex: 1; + } + + .overview { + border-left: 0; + border-top: 1px solid var(--border); + overflow: visible; + } + + .workspace-main { + overflow: visible; + } + + .grid-2 { + display: flex; + flex-direction: column; + height: auto; + min-height: 0; + } + + .panel-header { + flex-wrap: wrap; + } + + .panel-tools { + flex-wrap: wrap; + flex-shrink: 1; + } + + .panel-body { + flex: none; + height: 380px; + } + + .brand-name, + .brand-divider { + display: none; + } +} + +@media (max-width: 640px) { + .topbar { + padding: 0 8px; + gap: 6px; + } + + .controlbar { + padding: 0 8px; + } + + .workspace-main { + padding: 8px; + } + + .topbar-actions { + gap: 0; + } + + .topbar-actions .btn-label, + .topbar-actions .lucide-chevron-down, + .save-state-text { + display: none; + } + + .topbar-actions .btn { + padding: 0 7px; + } + + .project-name-input { + min-width: 0; + width: 100%; + } + + .project-title { + flex: 1; + } + + .topbar-spacer { + display: none; + } + + .dialog-backdrop { + padding: 8px; + } + + .dialog { + max-height: calc(100vh - 16px); + } + + .dialog-body { + padding: 12px; + } + + .form-grid { + grid-template-columns: minmax(0, 1fr); + } +} diff --git a/web/src/styles/views.css b/web/src/styles/views.css new file mode 100644 index 0000000..343e0eb --- /dev/null +++ b/web/src/styles/views.css @@ -0,0 +1,611 @@ +/* ── λ-plane plots ─────────────────────────────────────────────── */ + +.array-view { + display: flex; + flex-direction: column; + gap: 12px; + height: 100%; +} + +.array-panels { + flex: 1; + min-height: 520px; +} + +.plane { + position: absolute; + inset: 0; + overflow: hidden; + outline: none; + user-select: none; +} + +.plane:focus-visible { + box-shadow: inset 0 0 0 2px var(--focus); +} + +.plane svg { + display: block; +} + +.plane-tick { + fill: var(--text-tertiary); + font-size: 10.5px; + font-variant-numeric: tabular-nums; +} + +.plane-axis-label { + fill: var(--text-tertiary); + font-size: 11px; +} + +.element-label { + fill: var(--text); + font-size: 11px; + font-weight: 500; + paint-order: stroke; + stroke: var(--surface); + stroke-width: 3px; + stroke-linejoin: round; + pointer-events: none; +} + +.virtual-count { + fill: #1b1300; + font-size: 9px; + font-weight: 700; + pointer-events: none; +} + +.plane-tooltip { + position: absolute; + z-index: 5; + display: flex; + flex-direction: column; + gap: 1px; + padding: 6px 9px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); + box-shadow: var(--shadow); + font-size: 12px; + white-space: nowrap; + pointer-events: none; +} + +.plane-legend { + position: absolute; + top: 18px; + right: 22px; + display: flex; + gap: 12px; + padding: 3px 8px; + border-radius: 12px; + background: color-mix(in srgb, var(--surface) 86%, transparent); + color: var(--text-secondary); + font-size: 11.5px; + pointer-events: none; +} + +.plane-legend > span { + display: inline-flex; + align-items: center; + gap: 5px; +} + +.legend-swatch { + display: inline-block; + width: 9px; + height: 9px; +} + +.legend-swatch.tx { + width: 0; + height: 0; + border-left: 5px solid transparent; + border-right: 5px solid transparent; + border-bottom: 9px solid var(--tx); +} + +.legend-swatch.rx { + border-radius: 50%; + background: var(--rx); +} + +.legend-dot { + display: inline-block; + width: 8px; + height: 8px; + border-radius: 50%; +} + +.legend-dot.unique { + background: var(--virtual); +} + +.legend-dot.duplicate { + background: var(--virtual-dup); +} + +.inspector { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + min-height: 30px; +} + +.inspector .field input { + width: 58px; + text-align: right; +} + +.auto-layout { + display: flex; + align-items: center; + gap: 6px; + margin-left: auto; +} + +.field.compact input { + width: 34px; + text-align: right; +} + +.coordinate-panel { + flex: none; +} + +/* ── Chart panels ──────────────────────────────────────────────── */ + +.chart-body { + position: absolute; + inset: 6px 8px 4px 4px; +} + +.readout { + display: flex; + flex-wrap: wrap; + gap: 4px 16px; + font-size: 12px; +} + +.readout-item { + display: inline-flex; + align-items: baseline; + gap: 6px; +} + +.readout-label { + color: var(--text-tertiary); +} + +.readout-value { + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.scrubber { + display: flex; + align-items: center; + gap: 10px; + width: 100%; +} + +.scrubber input[type="range"] { + flex: 1; + min-width: 80px; +} + +.scrubber .angle-value { + min-width: 52px; + text-align: right; + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.dbf-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + height: 100%; + min-height: 520px; +} + +.dbf2d-layout { + display: grid; + grid-template-columns: minmax(0, 1fr); + height: 100%; + min-height: 560px; +} + +.dbf2d-controls { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px 24px; + width: 100%; +} + +.angle-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-auto-rows: minmax(260px, 1fr); + gap: 12px; + height: 100%; + min-height: 560px; +} + +/* ── Overview ──────────────────────────────────────────────────── */ + +.overview-section { + padding: 14px 16px; + border-bottom: 1px solid var(--border); +} + +.overview-section h3 { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 10px; + font-size: 12px; + font-weight: 600; + color: var(--text-secondary); + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.kpi-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; +} + +.kpi { + display: flex; + flex-direction: column; + gap: 2px; + padding: 9px 10px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface-subtle); + min-width: 0; +} + +.kpi-label { + color: var(--text-tertiary); + font-size: 11.5px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.kpi-value { + font-size: 17px; + font-weight: 600; + line-height: 1.25; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.kpi-sub { + color: var(--text-tertiary); + font-size: 11.5px; + font-variant-numeric: tabular-nums; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.metric-list { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 6px 12px; + margin: 0; +} + +.metric-list dt { + color: var(--text-secondary); +} + +.metric-list dd { + margin: 0; + text-align: right; + font-weight: 500; + font-variant-numeric: tabular-nums; +} + +.axis-tabs { + display: flex; + gap: 4px; + margin-bottom: 10px; +} + +.axis-card + .axis-card { + margin-top: 12px; + padding-top: 12px; + border-top: 1px dashed var(--border); +} + +.axis-card-title { + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 6px; + font-weight: 600; +} + +.notes { + display: flex; + flex-direction: column; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} + +.notes li { + display: flex; + gap: 8px; + align-items: flex-start; + color: var(--text-secondary); +} + +.notes li svg { + flex: none; + margin-top: 2px; + color: var(--warning); +} + +details.collapsible > summary { + display: flex; + align-items: center; + gap: 6px; + cursor: pointer; + list-style: none; +} + +details.collapsible > summary::-webkit-details-marker { + display: none; +} + +details.collapsible > summary .chevron { + transition: transform 0.15s; +} + +details.collapsible[open] > summary .chevron { + transform: rotate(90deg); +} + +/* ── Dialog content ────────────────────────────────────────────── */ + +.mode-cards { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; +} + +.mode-card { + display: flex; + gap: 10px; + padding: 10px 12px; + border: 1px solid var(--border-strong); + border-radius: var(--radius); + background: var(--surface); + text-align: left; + cursor: pointer; +} + +.mode-card:hover { + background: var(--surface-subtle); +} + +.mode-card[aria-checked="true"] { + border-color: var(--accent); + background: var(--accent-soft); + box-shadow: 0 0 0 1px var(--accent); +} + +.mode-card .radio { + flex: none; + width: 16px; + height: 16px; + margin-top: 1px; + border: 1.5px solid var(--control-border); + border-radius: 50%; +} + +.mode-card[aria-checked="true"] .radio { + border: 5px solid var(--accent); +} + +.mode-card strong { + display: block; + font-weight: 600; +} + +.mode-card span.desc { + color: var(--text-secondary); + font-size: 12px; +} + +.file-slot { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 10px; + border: 1px dashed var(--border-strong); + border-radius: var(--radius); + background: var(--surface-subtle); +} + +.file-slot.loaded { + border-style: solid; +} + +.file-slot .file-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.two-col { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + gap: 16px; +} + +.chart-box { + position: relative; + height: 300px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.slot-cell { + max-width: 150px; + overflow: hidden; + text-overflow: ellipsis; + font-size: 12px; +} + +.slot-empty { + color: var(--text-tertiary); +} + +.progress { + height: 6px; + border-radius: 3px; + background: var(--surface-muted); + overflow: hidden; +} + +.progress > div { + height: 100%; + background: var(--accent); + transition: width 0.25s; +} + +.project-list { + display: flex; + flex-direction: column; + gap: 6px; +} + +.project-row { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: var(--radius); +} + +.project-row:hover { + background: var(--surface-subtle); +} + +.project-row .meta { + flex: 1; + min-width: 0; +} + +.project-row .name { + font-weight: 600; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.help-content h3 { + margin: 18px 0 6px; + font-size: 14px; +} + +.help-content h3:first-child { + margin-top: 0; +} + +.help-content p, +.help-content li { + color: var(--text-secondary); +} + +.help-content ul, +.help-content ol { + margin: 4px 0; + padding-left: 20px; +} + +.help-layout { + display: grid; + grid-template-columns: 200px minmax(0, 1fr); + gap: 20px; +} + +.help-nav { + display: flex; + flex-direction: column; + gap: 2px; + position: sticky; + top: 0; + align-self: start; +} + +.help-nav button { + padding: 6px 10px; + border: 0; + border-radius: var(--radius-sm); + background: none; + text-align: left; + color: var(--text-secondary); + cursor: pointer; +} + +.help-nav button:hover { + background: var(--surface-hover); +} + +.help-nav button[aria-current="true"] { + background: var(--accent-soft); + color: var(--accent); + font-weight: 500; +} + +@media (max-width: 980px) { + .dbf-grid, + .angle-grid { + grid-template-columns: minmax(0, 1fr); + height: auto; + } + + .dbf-grid, + .angle-grid, + .dbf2d-layout, + .array-panels { + min-height: 0; + } + + .array-view { + height: auto; + } + + .mode-cards, + .two-col, + .help-layout, + .dbf2d-controls { + grid-template-columns: minmax(0, 1fr); + } + + .help-nav { + position: static; + flex-direction: row; + flex-wrap: wrap; + } + + .auto-layout { + margin-left: 0; + } +} diff --git a/web/src/views/AngleView.tsx b/web/src/views/AngleView.tsx new file mode 100644 index 0000000..99cb442 --- /dev/null +++ b/web/src/views/AngleView.tsx @@ -0,0 +1,175 @@ +import { ImageDown } from "lucide-react"; +import { useMemo } from "react"; +import { api } from "../api/client"; +import type { Axis, DbfBank } from "../api/types"; +import { Plot } from "../charts/Plot"; +import { baseLayout, useChartTheme } from "../charts/theme"; +import { Button, Spinner } from "../components/ui"; +import { useT } from "../i18n"; +import { wire } from "../lib/encoding"; +import { useDbfBank } from "../state/compute"; +import { useExportJob } from "../state/jobs"; +import { useStore } from "../state/store"; +import { EmptyCapability } from "./EmptyCapability"; + +export function AngleView() { + const t = useT(); + const project = useStore((state) => state.project)!; + const language = useStore((state) => state.language); + const evaluation = useStore((state) => state.evaluation); + const capability = evaluation?.capability ?? { azimuth: true, elevation: true, two_d: true }; + const az = useDbfBank("azimuth", capability.azimuth); + const el = useDbfBank("elevation", capability.elevation); + const exporter = useExportJob(); + + return ( +
+
+
+
+ {t("angle.title")} + {t("angle.subtitle")} +
+
+ {exporter.running && } + {exporter.error && {exporter.error}} + +
+
+
+
+ + + + +
+
+ ); +} + +function AnglePanel({ + axis, + kind, + state, + available, +}: { + axis: Axis; + kind: "error" | "margin"; + state: { data: DbfBank | null; loading: boolean; error: string | null }; + available: boolean; +}) { + const t = useT(); + const axisLabel = t(axis === "azimuth" ? "axis.azimuth" : "axis.elevation"); + return ( +
+
+ + {t(kind === "error" ? "angle.errorChart" : "angle.marginChart", { axis: axisLabel })} + + {state.loading && ( + + + + )} +
+
+ {available && state.data && } + {available && state.error &&

{state.error}

} + {!available && } +
+
+ ); +} + +function AngleChart({ bank, kind }: { bank: DbfBank; kind: "error" | "margin" }) { + const t = useT(); + const theme = useChartTheme(); + const threshold = useStore((state) => state.project!.ambiguity_margin_db); + const metrics = bank.metrics; + const left = wire(metrics.no_fold_left); + const right = wire(metrics.no_fold_right); + + const { data, layout } = useMemo(() => { + const x = bank.true_angles; + const band = + left !== null && right !== null && right > left + ? [{ type: "rect", xref: "x", yref: "paper", x0: left, x1: right, y0: 0, y1: 1, fillcolor: theme.band, line: { width: 0 }, layer: "below" }] + : []; + if (kind === "error") { + const y = bank.frames.errors; + // Scale to the errors inside the no-fold range so small errors stay readable; + // folded errors outside it may clip (same rule as the PDF report). + const inRange = y.filter( + (value, i) => + Number.isFinite(value) && (left === null || right === null || right <= left || (x[i] >= left && x[i] <= right)), + ); + const spread = Math.max(1, ...inRange.map((value) => Math.abs(value))); + const limit = Math.min(Math.max(spread * 1.25, 2), 180); + return { + data: [ + { + type: "scatter", + mode: "lines", + x, + y, + line: { color: theme.line, width: 1.8 }, + name: t("angle.errorSeries"), + hovertemplate: "%{x:+.0f}° %{y:+.2f}°", + }, + ], + layout: baseLayout(theme, { + shapes: band, + xaxis: { title: { text: t("axis.trueAngle") }, range: [-90, 90], dtick: 30 }, + yaxis: { title: { text: t("axis.error") }, range: [-limit, limit], zeroline: true }, + }), + }; + } + const raw = bank.frames.margins_db.map((value) => wire(value)); + const finite = raw.filter((value): value is number => value !== null && Number.isFinite(value)); + const top = Math.max(threshold * 2, 6, ...finite) * 1.1; + const y = raw.map((value) => (value === null ? null : value === Number.POSITIVE_INFINITY ? top : value)); + const capped = raw.map((value) => value === Number.POSITIVE_INFINITY); + return { + data: [ + { + type: "scatter", + mode: "lines", + x, + y, + line: { color: theme.secondary, width: 1.8 }, + name: t("angle.marginSeries"), + hovertemplate: "%{x:+.0f}° %{y:.2f} dB", + }, + { + type: "scatter", + mode: "markers", + x: x.filter((_, i) => capped[i]), + y: x.filter((_, i) => capped[i]).map(() => top), + marker: { size: 4, color: theme.secondary, symbol: "triangle-up" }, + hovertemplate: `%{x:+.0f}° ${t("overview.noCompetitor")}`, + }, + ], + layout: baseLayout(theme, { + shapes: [ + ...band, + { type: "line", xref: "paper", x0: 0, x1: 1, y0: threshold, y1: threshold, line: { color: theme.danger, width: 1.2, dash: "dash" } }, + ], + xaxis: { title: { text: t("axis.trueAngle") }, range: [-90, 90], dtick: 30 }, + yaxis: { title: { text: t("axis.margin") }, range: [0, top * 1.04], rangemode: "tozero" }, + }), + }; + }, [bank, kind, theme, threshold, left, right, t]); + + return ( +
+ +
+ ); +} diff --git a/web/src/views/ArrayView.tsx b/web/src/views/ArrayView.tsx new file mode 100644 index 0000000..f476ea2 --- /dev/null +++ b/web/src/views/ArrayView.tsx @@ -0,0 +1,351 @@ +import { + Eraser, + Maximize2, + Plus, + Redo2, + RotateCcw, + Table2, + Trash2, + Undo2, + Wand2, +} from "lucide-react"; +import { useMemo, useState } from "react"; +import { api, errorMessage } from "../api/client"; +import type { ElementKind, Layout, Point } from "../api/types"; +import { Button, NumberInput } from "../components/ui"; +import { useT } from "../i18n"; +import { elementName, nextElementPosition, snap, virtualGroups } from "../lib/geometry"; +import { parseNumber, trimNumber } from "../lib/format"; +import { useStore } from "../state/store"; +import { PhysicalEditor } from "./PhysicalEditor"; +import { VirtualPlot } from "./VirtualPlot"; + +const STARTER_LAYOUT: Layout = { tx: [{ x: 0, y: 2 }], rx: [{ x: 0, y: -2 }] }; + +export function ArrayView() { + const t = useT(); + const project = useStore((state) => state.project)!; + const config = useStore((state) => state.config)!; + const selection = useStore((state) => state.selection); + const deleteMode = useStore((state) => state.deleteMode); + const past = useStore((state) => state.past.length); + const future = useStore((state) => state.future.length); + const evaluation = useStore((state) => state.evaluation); + const { commitLayout, select, setDeleteMode, undo, redo, setStatus } = useStore.getState(); + + const [preview, setPreview] = useState(null); + const [fitSignal, setFitSignal] = useState(0); + const [showTable, setShowTable] = useState(false); + const [autoTx, setAutoTx] = useState(project.layout.tx.length); + const [autoRx, setAutoRx] = useState(project.layout.rx.length); + + const layout = project.layout; + const shown = preview ?? layout; + const groups = useMemo(() => virtualGroups(shown), [shown]); + const duplicate = groups.reduce((sum, group) => sum + group.count - 1, 0); + const mmPerLambda = 299.792458 / project.frequency_ghz; + const limits = { tx: config.limits.max_tx, rx: config.limits.max_rx }; + + const addElement = (kind: ElementKind) => { + if (layout[kind].length >= limits[kind]) { + setStatus("physical.limit", "error", { kind: kind === "tx" ? "Tx" : "Rx", max: limits[kind] }); + return; + } + const position = nextElementPosition(layout, kind, selection); + const next = { ...layout, [kind]: [...layout[kind], position] }; + commitLayout(next, { kind, index: next[kind].length - 1 }); + const follow = useStore.getState().selection; + setStatus("status.added", "success", { name: follow ? elementName(follow.kind, follow.index) : "" }); + }; + + const deleteElement = (ref: { kind: ElementKind; index: number }) => { + if (layout[ref.kind].length <= 1) { + setStatus("physical.lastElement", "error", { kind: ref.kind === "tx" ? "Tx" : "Rx" }); + return; + } + const name = elementName(ref.kind, ref.index); + const next = { ...layout, [ref.kind]: layout[ref.kind].filter((_, index) => index !== ref.index) }; + commitLayout(next, null); + setStatus("status.deleted", "success", { name }); + }; + + const applyAuto = async () => { + try { + const next = await api.autoLayout(autoTx, autoRx); + commitLayout(next, null); + setFitSignal((value) => value + 1); + setStatus("status.autoLayout", "success", { tx: autoTx, rx: autoRx }); + } catch (error) { + setStatus("overview.error", "error", undefined, errorMessage(error)); + } + }; + + const commitMove = (next: Layout, ref: { kind: ElementKind; index: number } | null) => { + commitLayout(next, ref); + const follow = useStore.getState().selection; + if (follow) { + const point = useStore.getState().project!.layout[follow.kind][follow.index]; + setStatus("status.moved", "info", { + name: elementName(follow.kind, follow.index), + x: trimNumber(point.x), + y: trimNumber(point.y), + }); + } + }; + + const updatePoint = (kind: ElementKind, index: number, point: Point) => { + const next = { ...layout, [kind]: layout[kind].map((p, i) => (i === index ? point : p)) }; + commitMove(next, { kind, index }); + }; + + const selected = selection ? layout[selection.kind][selection.index] : null; + const highlight = selection + ? { side: (selection.kind === "tx" ? 0 : 1) as 0 | 1, name: elementName(selection.kind, selection.index) } + : null; + const unique = evaluation && !preview ? evaluation.summary.unique_count : groups.length; + const total = shown.tx.length * shown.rx.length; + + return ( +
+
+
+
+
+ {t("physical.title")} + + {deleteMode ? t("physical.deleteHint") : t("physical.subtitle")} + +
+
+ + + +
+
+
+ +
+ {t("physical.legendTx")} · {layout.tx.length} + {t("physical.legendRx")} · {layout.rx.length} +
+
+
+
+ {selected && selection ? ( + <> + {elementName(selection.kind, selection.index)} + + + + ({trimNumber(selected.x * mmPerLambda, 2)}, {trimNumber(selected.y * mmPerLambda, 2)}) mm + + + ) : ( + {t("inspector.none")} + )} +
+
+ + {t("physical.auto")} + + + +
+
+
+ +
+
+
+ {t("virtual.title")} + {t("virtual.subtitle")} +
+
+ {t("virtual.info", { unique, total, duplicate })} +
+
+
+ +
+ {t("virtual.unique")} + {t("virtual.duplicate")} +
+
+
+
+ + {showTable && setShowTable(false)} />} +
+ ); +} + +function CoordinateTable({ + layout, + mmPerLambda, + onChange, + onClose, +}: { + layout: Layout; + mmPerLambda: number; + onChange: (kind: ElementKind, index: number, point: Point) => void; + onClose: () => void; +}) { + const t = useT(); + const selection = useStore((state) => state.selection); + const select = useStore((state) => state.select); + const rows: { kind: ElementKind; index: number; point: Point }[] = [ + ...layout.tx.map((point, index) => ({ kind: "tx" as const, index, point })), + ...layout.rx.map((point, index) => ({ kind: "rx" as const, index, point })), + ]; + return ( +
+
+ {t("physical.table")} +
+ +
+
+
+ + + + + + + + + + + + {rows.map(({ kind, index, point }) => ( + select({ kind, index })} + > + + + + + + + ))} + +
{t("table.channel")}{t("table.x")}{t("table.y")}{t("table.xmm")}{t("table.ymm")}
+ {elementName(kind, index)} + + parseNumber(text, ["λ"])} + format={(value) => trimNumber(value)} + onCommit={(value) => onChange(kind, index, { x: snap(value), y: point.y })} + /> + + parseNumber(text, ["λ"])} + format={(value) => trimNumber(value)} + onCommit={(value) => onChange(kind, index, { x: point.x, y: snap(value) })} + /> + {trimNumber(point.x * mmPerLambda, 2)}{trimNumber(point.y * mmPerLambda, 2)}
+
+
+ ); +} diff --git a/web/src/views/Dbf2dView.tsx b/web/src/views/Dbf2dView.tsx new file mode 100644 index 0000000..dc75b59 --- /dev/null +++ b/web/src/views/Dbf2dView.tsx @@ -0,0 +1,394 @@ +import { Pause, Play, RotateCcw } from "lucide-react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { api, errorMessage } from "../api/client"; +import type { Dbf2dFrame, Project } from "../api/types"; +import { Plot } from "../charts/Plot"; +import { baseLayout, useChartTheme } from "../charts/theme"; +import { Button, Spinner } from "../components/ui"; +import { useT } from "../i18n"; +import { decodeMatrix, matrixRows } from "../lib/encoding"; +import { dbToMagnitude, fmt, fmtSigned } from "../lib/format"; +import { dbfKey } from "../state/compute"; +import { useStore } from "../state/store"; +import { EmptyCapability } from "./EmptyCapability"; + +const FRAME_CACHE_LIMIT = 400; +const PREFETCH = 8; +const PLAY_FPS = 10; + +// Perceptually ordered dark-to-bright scale (magma-like) for correlation maps. +const MAGMA: [number, string][] = [ + [0, "#000004"], + [0.13, "#1c1044"], + [0.25, "#4f127b"], + [0.38, "#812581"], + [0.5, "#b5367a"], + [0.63, "#e55064"], + [0.75, "#fb8761"], + [0.88, "#fec287"], + [1, "#fcfdbf"], +]; + +interface DecodedFrame { + frame: Dbf2dFrame; + rows: number[][]; +} + +function angleKey(az: number, el: number) { + return `${az}|${el}`; +} + +function wrapAngle(value: number) { + return value > 90 ? -90 : value; +} + +function useFrameCache(project: Project, enabled: boolean, maxBatch: number) { + const key = dbfKey(project); + const cache = useRef(new Map()); + const inflight = useRef(new Set()); + const [scan, setScan] = useState<{ az: number[]; el: number[] } | null>(null); + const [version, setVersion] = useState(0); + const [error, setError] = useState(null); + const projectRef = useRef(project); + projectRef.current = project; + + useEffect(() => { + cache.current.clear(); + inflight.current.clear(); + setError(null); + setVersion((value) => value + 1); + }, [key]); + + const request = useCallback( + (angles: [number, number][]) => { + if (!enabled) return; + const pending = angles.filter(([az, el]) => { + const id = angleKey(az, el); + return !cache.current.has(id) && !inflight.current.has(id); + }); + if (pending.length === 0) return; + const requestKey = key; + for (let start = 0; start < pending.length; start += maxBatch) { + const chunk = pending.slice(start, start + maxBatch); + chunk.forEach(([az, el]) => inflight.current.add(angleKey(az, el))); + api + .dbf2d( + projectRef.current, + chunk.map(([azimuth, elevation]) => ({ azimuth, elevation })), + ) + .then((result) => { + if (requestKey !== dbfKey(projectRef.current)) return; + setScan((current) => current ?? { az: result.scan_azimuths, el: result.scan_elevations }); + for (const frame of result.frames) { + const id = angleKey(frame.true_azimuth, frame.true_elevation); + inflight.current.delete(id); + cache.current.set(id, { frame, rows: matrixRows(decodeMatrix(frame.spectrum_db)) }); + while (cache.current.size > FRAME_CACHE_LIMIT) { + const oldest = cache.current.keys().next().value; + if (oldest === undefined) break; + cache.current.delete(oldest); + } + } + setError(null); + setVersion((value) => value + 1); + }) + .catch((reason) => { + chunk.forEach(([az, el]) => inflight.current.delete(angleKey(az, el))); + setError(errorMessage(reason)); + }); + } + }, + [enabled, key, maxBatch], + ); + + const get = useCallback((az: number, el: number) => cache.current.get(angleKey(az, el)) ?? null, []); + return { request, get, scan, version, error }; +} + +export function Dbf2dView() { + const t = useT(); + const project = useStore((state) => state.project)!; + const config = useStore((state) => state.config)!; + const evaluation = useStore((state) => state.evaluation); + const available = evaluation?.capability.two_d ?? true; + const [trueAz, setTrueAz] = useState(0); + const [trueEl, setTrueEl] = useState(0); + const [playAz, setPlayAz] = useState(false); + const [playEl, setPlayEl] = useState(false); + const frames = useFrameCache(project, available, config.limits.max_2d_frames_per_request); + const { request, get } = frames; + + // Show the most recent frame that is available while the next one loads. + const current = get(trueAz, trueEl); + const [shown, setShown] = useState(null); + useEffect(() => { + if (current) setShown(current); + }, [current, frames.version]); + + useEffect(() => { + if (!available) return; + const angles: [number, number][] = [[trueAz, trueEl]]; + if (playAz || playEl) { + let az = trueAz; + let el = trueEl; + for (let i = 0; i < PREFETCH; i += 1) { + if (playAz) az = wrapAngle(az + 1); + if (playEl) el = wrapAngle(el + 1); + angles.push([az, el]); + } + } + const timer = window.setTimeout(() => request(angles), playAz || playEl ? 0 : 60); + return () => window.clearTimeout(timer); + }, [trueAz, trueEl, playAz, playEl, available, request, frames.version]); + + useEffect(() => { + if (!playAz && !playEl) return; + const timer = window.setInterval(() => { + const nextAz = playAz ? wrapAngle(trueAz + 1) : trueAz; + const nextEl = playEl ? wrapAngle(trueEl + 1) : trueEl; + if (get(nextAz, nextEl)) { + setTrueAz(nextAz); + setTrueEl(nextEl); + } + }, 1000 / PLAY_FPS); + return () => window.clearInterval(timer); + }, [playAz, playEl, trueAz, trueEl, get]); + + const loading = available && !current; + + return ( +
+
+
+
+ {t("dbf2d.title")} + {t("dbf2d.hint")} +
+ {shown && available && ( +
+ + {t("dbf2d.peak")} + + {fmtSigned(shown.frame.peak_azimuth)} / {fmtSigned(shown.frame.peak_elevation)} + + + + {t("dbf2d.delta")} + + {fmtSigned(shown.frame.peak_azimuth - shown.frame.true_azimuth)} /{" "} + {fmtSigned(shown.frame.peak_elevation - shown.frame.true_elevation)} + + + + peak + {fmt(shown.frame.peak_db, 2, " dB")} + +
+ )} +
+
+ {available && shown && frames.scan && ( + { + setPlayAz(false); + setPlayEl(false); + setTrueAz(Math.round(az)); + setTrueEl(Math.round(el)); + }} + /> + )} + {loading && ( +
+ {t("dbf2d.loading")} +
+ )} + {available && frames.error && ( +
+
+

{t("overview.error")}

+

{frames.error}

+
+
+ )} + {!available && ( + + )} +
+ {available && ( +
+
+ setPlayAz((value) => !value)} + onChange={(value) => { + setPlayAz(false); + setTrueAz(value); + }} + /> + setPlayEl((value) => !value)} + onChange={(value) => { + setPlayEl(false); + setTrueEl(value); + }} + /> +
+ +
+ )} +
+
+ ); +} + +function AxisScrubber({ + label, + value, + playing, + playLabel, + pauseLabel, + onToggle, + onChange, +}: { + label: string; + value: number; + playing: boolean; + playLabel: string; + pauseLabel: string; + onToggle: () => void; + onChange: (value: number) => void; +}) { + return ( +
+ + + {label} + + onChange(Number(event.target.value))} + /> + {fmtSigned(value)} +
+ ); +} + +function Heatmap({ + frame, + scanAz, + scanEl, + trueAz, + trueEl, + onPick, +}: { + frame: DecodedFrame; + scanAz: number[]; + scanEl: number[]; + trueAz: number; + trueEl: number; + onPick: (az: number, el: number) => void; +}) { + const t = useT(); + const theme = useChartTheme(); + const display = useStore((state) => state.display); + const magnitude = display === "magnitude"; + const z = useMemo( + () => + frame.rows.map((row) => + row.map((value) => (magnitude ? dbToMagnitude(value) : Math.max(-40, Math.min(0, value)))), + ), + [frame, magnitude], + ); + + const data = useMemo( + () => [ + { + type: "heatmap", + x: scanAz, + y: scanEl, + z, + zmin: magnitude ? 0 : -40, + zmax: magnitude ? 1 : 0, + colorscale: MAGMA, + colorbar: { + title: { text: t(magnitude ? "axis.correlationMag" : "axis.correlationDb"), side: "right", font: { size: 11, color: theme.textSecondary } }, + thickness: 12, + outlinewidth: 0, + tickfont: { size: 10, color: theme.textSecondary }, + len: 0.9, + }, + hovertemplate: magnitude + ? "Az %{x:+.0f}° El %{y:+.0f}°
%{z:.3f}" + : "Az %{x:+.0f}° El %{y:+.0f}°
%{z:.2f} dB", + }, + { + type: "scatter", + mode: "markers", + x: [frame.frame.peak_azimuth], + y: [frame.frame.peak_elevation], + marker: { symbol: "x-thin", size: 12, color: "#6ea6ff", line: { width: 2.5, color: "#6ea6ff" } }, + hoverinfo: "skip", + }, + ], + [scanAz, scanEl, z, frame, magnitude, theme, t], + ); + + const layout = useMemo( + () => + baseLayout(theme, { + margin: { l: 58, r: 8, t: 12, b: 46 }, + hovermode: "closest", + shapes: [ + { type: "line", x0: trueAz, x1: trueAz, y0: -90, y1: 90, line: { color: "rgba(255,255,255,0.85)", width: 1 } }, + { type: "line", x0: -90, x1: 90, y0: trueEl, y1: trueEl, line: { color: "rgba(255,255,255,0.85)", width: 1 } }, + ], + xaxis: { title: { text: t("axis.azAngle") }, range: [-90.5, 90.5], dtick: 30, showgrid: false, zeroline: false }, + yaxis: { title: { text: t("axis.elAngle") }, range: [-90.5, 90.5], dtick: 30, showgrid: false, zeroline: false }, + }), + [theme, trueAz, trueEl, t], + ); + + return ( +
+ onPick(point.x, point.y)} ariaLabel={t("dbf2d.title")} /> +
+ ); +} diff --git a/web/src/views/DbfView.tsx b/web/src/views/DbfView.tsx new file mode 100644 index 0000000..6ed7192 --- /dev/null +++ b/web/src/views/DbfView.tsx @@ -0,0 +1,237 @@ +import { Pause, Play, RotateCcw } from "lucide-react"; +import { useMemo } from "react"; +import type { Axis, DbfBank } from "../api/types"; +import { Plot } from "../charts/Plot"; +import { baseLayout, useChartTheme } from "../charts/theme"; +import { Button, Segmented, Spinner } from "../components/ui"; +import { useT } from "../i18n"; +import { decodeMatrix, matrixRow, wire } from "../lib/encoding"; +import { dbToMagnitude, fmt, fmtSigned } from "../lib/format"; +import { useDbfBank } from "../state/compute"; +import { type DisplayMode, useStore } from "../state/store"; +import { EmptyCapability } from "./EmptyCapability"; +import { PLAYBACK_SPEEDS, usePlayback } from "./usePlayback"; + +export function displayValues(values: number[], mode: DisplayMode): number[] { + return mode === "magnitude" + ? values.map(dbToMagnitude) + : values.map((value) => Math.max(-40, Math.min(0, Number.isFinite(value) ? value : -40))); +} + +export function DbfView() { + const evaluation = useStore((state) => state.evaluation); + const capability = evaluation?.capability ?? { azimuth: true, elevation: true, two_d: true }; + return ( +
+ + +
+ ); +} + +function DbfAxisPanel({ axis, available }: { axis: Axis; available: boolean }) { + const t = useT(); + const bank = useDbfBank(axis, available); + const count = bank.data?.true_angles.length ?? 181; + const center = bank.data ? Math.max(0, bank.data.true_angles.findIndex((angle) => angle === 0)) : 90; + const playback = usePlayback(count, center); + const axisLabel = t(axis === "azimuth" ? "axis.azimuth" : "axis.elevation"); + + return ( +
+
+
+ {t("dbf.title", { axis: axisLabel })} + {bank.data && ( + + {t("dbf.frame", { frame: playback.index + 1, total: count })} + + )} +
+
+ ({ value: String(fps), label: `${fps / 20}×` }))} + onChange={(value) => playback.setFps(Number(value))} + /> +
+
+
+ {available && bank.data && } + {available && bank.loading && ( +
+ {t("dbf.loading")} +
+ )} + {available && bank.error && !bank.loading && ( +
+
+

{t("overview.error")}

+

{bank.error}

+
+
+ )} + {!available && } +
+ {available && bank.data && ( +
+
+ +
+ +
+ )} +
+ ); +} + +function FrameReadout({ bank, frame }: { bank: DbfBank; frame: number }) { + const t = useT(); + const margin = wire(bank.frames.margins_db[frame]); + const quality = bank.frames.quality[frame]; + const error = bank.frames.errors[frame]; + const errorTone = Math.abs(error) <= 1 ? "" : Math.abs(error) <= 5 ? "tone-warn" : "tone-bad"; + return ( +
+ + {t("dbf.true")} + {fmtSigned(bank.true_angles[frame], 0)} + + + {t("dbf.peak")} + {fmtSigned(bank.frames.estimated[frame], 0)} + + + {t("dbf.error")} + {fmtSigned(error, 1)} + + + {t("dbf.margin")} + + {margin === Number.POSITIVE_INFINITY ? t("overview.noCompetitor") : fmt(margin, 1, " dB")} + + + {quality && quality !== "normal" && ( + {t(`cut.${quality}` as const)} + )} +
+ ); +} + +function SpectrumChart({ bank, frame, onSeek }: { bank: DbfBank; frame: number; onSeek: (index: number) => void }) { + const t = useT(); + const theme = useChartTheme(); + const display = useStore((state) => state.display); + const matrix = useMemo(() => decodeMatrix(bank.spectra_db), [bank]); + const axisTitle = t(bank.axis === "azimuth" ? "axis.azAngle" : "axis.elAngle"); + + const trueAngle = bank.true_angles[frame]; + const values = useMemo(() => displayValues(matrixRow(matrix, frame), display), [matrix, frame, display]); + const scan = bank.scan_angles; + const peakAngle = bank.frames.estimated[frame]; + const peakIndex = scan.indexOf(peakAngle); + const trueIndex = scan.reduce((best, angle, i) => (Math.abs(angle - trueAngle) < Math.abs(scan[best] - trueAngle) ? i : best), 0); + const magnitude = display === "magnitude"; + + const data = useMemo( + () => [ + { + type: "scatter", + mode: "lines", + x: scan, + y: values, + line: { color: theme.line, width: 2 }, + fill: magnitude ? "tozeroy" : "none", + fillcolor: theme.band, + name: t("dbf.legendSpectrum"), + hovertemplate: magnitude ? "%{x:+.0f}° %{y:.3f}" : "%{x:+.0f}° %{y:.2f} dB", + }, + { + type: "scatter", + mode: "markers", + x: [trueAngle], + y: [values[trueIndex]], + marker: { size: 9, color: theme.trueAngle, line: { color: theme.surface, width: 1.5 } }, + name: t("dbf.legendTrue"), + hoverinfo: "skip", + }, + { + type: "scatter", + mode: "markers", + x: [peakAngle], + y: [values[peakIndex >= 0 ? peakIndex : 0]], + marker: { size: 11, symbol: "x-thin", color: theme.peak, line: { color: theme.peak, width: 2.5 } }, + name: t("dbf.legendPeak"), + hoverinfo: "skip", + }, + ], + [scan, values, trueAngle, trueIndex, peakAngle, peakIndex, theme, magnitude, t], + ); + + const layout = useMemo( + () => + baseLayout(theme, { + margin: { l: 58, r: 14, t: 14, b: 46 }, + showlegend: true, + legend: { orientation: "h", x: 1, xanchor: "right", y: 1.02, yanchor: "bottom", font: { size: 11 } }, + shapes: [ + { + type: "line", + x0: trueAngle, + x1: trueAngle, + yref: "paper", + y0: 0, + y1: 1, + line: { color: theme.trueAngle, width: 1.6 }, + }, + ], + xaxis: { title: { text: axisTitle }, range: [-90, 90], dtick: 30, zeroline: false }, + yaxis: { + title: { text: t(magnitude ? "axis.correlationMag" : "axis.correlationDb") }, + range: magnitude ? [-0.02, 1.04] : [-40.5, 1], + dtick: magnitude ? 0.2 : 10, + zeroline: false, + }, + }), + [theme, trueAngle, axisTitle, magnitude, t], + ); + + return ( +
+ { + const index = bank.true_angles.reduce( + (best, angle, i) => (Math.abs(angle - point.x) < Math.abs(bank.true_angles[best] - point.x) ? i : best), + 0, + ); + onSeek(index); + }} + /> +
+ ); +} diff --git a/web/src/views/EmptyCapability.tsx b/web/src/views/EmptyCapability.tsx new file mode 100644 index 0000000..d1f38f4 --- /dev/null +++ b/web/src/views/EmptyCapability.tsx @@ -0,0 +1,29 @@ +import { Radar } from "lucide-react"; +import { Button } from "../components/ui"; +import { useT } from "../i18n"; +import { useStore, type ViewId } from "../state/store"; + +export function EmptyCapability({ + title, + body, + actionView = "array", +}: { + title: string; + body?: string; + actionView?: ViewId; +}) { + const t = useT(); + const setView = useStore((state) => state.setView); + return ( +
+
+ +

{title}

+

{body ?? t("empty.body")}

+ +
+
+ ); +} diff --git a/web/src/views/PhysicalEditor.tsx b/web/src/views/PhysicalEditor.tsx new file mode 100644 index 0000000..9437ad6 --- /dev/null +++ b/web/src/views/PhysicalEditor.tsx @@ -0,0 +1,325 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import type { ElementKind, Layout, Point } from "../api/types"; +import { type ElementRef, elementName, layoutBounds, snap } from "../lib/geometry"; +import { trimNumber } from "../lib/format"; +import { PLOT_MARGIN, PlaneGrid, useElementSize, usePlane } from "./plane"; + +interface DragState { + ref: ElementRef; + pointerId: number; + offset: { dx: number; dy: number }; + position: Point; + start: Point; + moved: boolean; +} + +interface PanState { + pointerId: number; + last: { x: number; y: number }; + moved: boolean; +} + +const MARKER = 7.5; + +function withPosition(layout: Layout, ref: ElementRef, position: Point): Layout { + const points = layout[ref.kind].map((point, index) => (index === ref.index ? position : point)); + return { ...layout, [ref.kind]: points }; +} + +export function PhysicalEditor({ + layout, + selection, + deleteMode, + mmPerLambda, + fitSignal, + onSelect, + onCommit, + onDelete, + onPreview, + onStatus, +}: { + layout: Layout; + selection: ElementRef | null; + deleteMode: boolean; + mmPerLambda: number; + fitSignal: number; + onSelect: (ref: ElementRef | null) => void; + onCommit: (layout: Layout, selection: ElementRef | null) => void; + onDelete: (ref: ElementRef) => void; + onPreview: (layout: Layout | null) => void; + onStatus?: (text: string) => void; +}) { + const [container, size] = useElementSize(); + const svg = useRef(null); + const [drag, setDrag] = useState(null); + const [pan, setPan] = useState(null); + const [hover, setHover] = useState(null); + + const allPoints = useMemo(() => [...layout.tx, ...layout.rx], [layout]); + const bounds = useMemo(() => layoutBounds(allPoints, 2), [allPoints]); + const fitKey = useMemo( + () => `${bounds.minX},${bounds.maxX},${bounds.minY},${bounds.maxY}`, + [bounds], + ); + const plane = usePlane(bounds, size.width, size.height, fitKey); + const { toScreen, toWorld, zoomAt, panBy, fit } = plane; + + useEffect(() => { + if (fitSignal > 0) fit(); + }, [fitSignal, fit]); + + const displayLayout = drag ? withPosition(layout, drag.ref, drag.position) : layout; + + const localPoint = useCallback((event: { clientX: number; clientY: number }) => { + const rect = svg.current?.getBoundingClientRect(); + return { x: event.clientX - (rect?.left ?? 0), y: event.clientY - (rect?.top ?? 0) }; + }, []); + + // Wheel zoom needs a non-passive listener to prevent page scrolling. + useEffect(() => { + const element = svg.current; + if (!element) return; + const onWheel = (event: WheelEvent) => { + event.preventDefault(); + const rect = element.getBoundingClientRect(); + zoomAt(event.clientX - rect.left, event.clientY - rect.top, Math.exp(-event.deltaY * 0.0015)); + }; + element.addEventListener("wheel", onWheel, { passive: false }); + return () => element.removeEventListener("wheel", onWheel); + }, [zoomAt]); + + const cancelDrag = useCallback(() => { + if (!drag) return; + setDrag(null); + onPreview(null); + }, [drag, onPreview]); + + useEffect(() => { + if (!drag) return; + const onKey = (event: KeyboardEvent) => { + if (event.key === "Escape") { + event.stopPropagation(); + cancelDrag(); + } + }; + window.addEventListener("keydown", onKey, true); + return () => window.removeEventListener("keydown", onKey, true); + }, [drag, cancelDrag]); + + const onElementPointerDown = (event: React.PointerEvent, ref: ElementRef) => { + if (event.button !== 0) return; + event.stopPropagation(); + if (deleteMode) { + onDelete(ref); + return; + } + const point = layout[ref.kind][ref.index]; + const local = localPoint(event); + const world = toWorld(local.x, local.y); + svg.current?.setPointerCapture(event.pointerId); + onSelect(ref); + setDrag({ + ref, + pointerId: event.pointerId, + offset: { dx: point.x - world.x, dy: point.y - world.y }, + position: point, + start: point, + moved: false, + }); + }; + + const onBackgroundPointerDown = (event: React.PointerEvent) => { + if (event.button !== 0 && event.button !== 1) return; + svg.current?.setPointerCapture(event.pointerId); + const local = localPoint(event); + setPan({ pointerId: event.pointerId, last: local, moved: false }); + }; + + const onPointerMove = (event: React.PointerEvent) => { + const local = localPoint(event); + if (drag && event.pointerId === drag.pointerId) { + const world = toWorld(local.x, local.y); + const position = { x: world.x + drag.offset.dx, y: world.y + drag.offset.dy }; + const moved = + drag.moved || Math.hypot(position.x - drag.start.x, position.y - drag.start.y) * plane.viewport.scale > 3; + const next = { ...drag, position, moved }; + setDrag(next); + if (moved) { + const snapped = { x: snap(position.x), y: snap(position.y) }; + onPreview(withPosition(layout, drag.ref, snapped)); + onStatus?.( + `${elementName(drag.ref.kind, drag.ref.index)} x=${trimNumber(snapped.x)} λ y=${trimNumber(snapped.y)} λ`, + ); + } + return; + } + if (pan && event.pointerId === pan.pointerId) { + const dx = local.x - pan.last.x; + const dy = local.y - pan.last.y; + if (pan.moved || Math.hypot(dx, dy) > 2) { + panBy(dx, dy); + setPan({ ...pan, last: local, moved: true }); + } + } + }; + + const onPointerUp = (event: React.PointerEvent) => { + if (drag && event.pointerId === drag.pointerId) { + if (drag.moved) { + const snapped = { x: snap(drag.position.x), y: snap(drag.position.y) }; + onCommit(withPosition(layout, drag.ref, snapped), drag.ref); + } + setDrag(null); + onPreview(null); + return; + } + if (pan && event.pointerId === pan.pointerId) { + if (!pan.moved) onSelect(null); + setPan(null); + } + }; + + const onKeyDown = (event: React.KeyboardEvent) => { + if (!selection) return; + const step = event.shiftKey ? 2.5 : 0.5; + const delta: Record = { + ArrowLeft: [-step, 0], + ArrowRight: [step, 0], + ArrowUp: [0, step], + ArrowDown: [0, -step], + }; + const move = delta[event.key]; + if (move) { + event.preventDefault(); + const point = layout[selection.kind][selection.index]; + if (!point) return; + onCommit(withPosition(layout, selection, { x: snap(point.x + move[0]), y: snap(point.y + move[1]) }), selection); + } + }; + + const renderElement = (kind: ElementKind, point: Point, index: number) => { + const ref = { kind, index }; + const { sx, sy } = toScreen(point.x, point.y); + const isSelected = selection?.kind === kind && selection.index === index; + const isHover = hover?.kind === kind && hover.index === index; + const isDragging = drag?.ref.kind === kind && drag.ref.index === index; + const color = kind === "tx" ? "var(--tx)" : "var(--rx)"; + const edge = kind === "tx" ? "var(--tx-edge)" : "var(--rx-edge)"; + const ring = deleteMode && isHover ? "var(--danger)" : "var(--accent)"; + const shape = + kind === "tx" ? ( + + ) : ( + + ); + return ( + onElementPointerDown(event, ref)} + onPointerEnter={() => setHover(ref)} + onPointerLeave={() => setHover((current) => (current?.kind === kind && current.index === index ? null : current))} + > + + {(isSelected || isHover) && ( + + )} + {shape} + {deleteMode && isHover && ( + + )} + + {elementName(kind, index)} + + + ); + }; + + const hovered = hover ? displayLayout[hover.kind][hover.index] : null; + const hoverScreen = hovered ? toScreen(hovered.x, hovered.y) : null; + const snapGhost = drag?.moved ? { x: snap(drag.position.x), y: snap(drag.position.y) } : null; + const ghostScreen = snapGhost ? toScreen(snapGhost.x, snapGhost.y) : null; + + return ( +
+ {size.width > 0 && ( + { + cancelDrag(); + setPan(null); + }} + style={{ cursor: pan?.moved ? "grabbing" : "default", touchAction: "none" }} + > + + + + + + + + {ghostScreen && ( + + )} + {displayLayout.rx.map((point, index) => renderElement("rx", point, index))} + {displayLayout.tx.map((point, index) => renderElement("tx", point, index))} + + + )} + {hover && hovered && hoverScreen && !drag && ( +
+ {elementName(hover.kind, hover.index)} + + ({trimNumber(hovered.x)}, {trimNumber(hovered.y)}) λ + + + ({trimNumber(hovered.x * mmPerLambda, 2)}, {trimNumber(hovered.y * mmPerLambda, 2)}) mm + +
+ )} +
+ ); +} diff --git a/web/src/views/VirtualPlot.tsx b/web/src/views/VirtualPlot.tsx new file mode 100644 index 0000000..c2d687d --- /dev/null +++ b/web/src/views/VirtualPlot.tsx @@ -0,0 +1,111 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { useT } from "../i18n"; +import type { VirtualGroup } from "../lib/geometry"; +import { layoutBounds } from "../lib/geometry"; +import { trimNumber } from "../lib/format"; +import { PLOT_MARGIN, PlaneGrid, useElementSize, usePlane } from "./plane"; + +export function VirtualPlot({ + groups, + fitSignal, + highlight, +}: { + groups: VirtualGroup[]; + fitSignal: number; + /** Highlight virtual points formed by the selected physical channel. */ + highlight: { side: 0 | 1; name: string } | null; +}) { + const t = useT(); + const [container, size] = useElementSize(); + const svg = useRef(null); + const [hover, setHover] = useState(null); + const bounds = useMemo(() => layoutBounds(groups, 2), [groups]); + const fitKey = `${bounds.minX},${bounds.maxX},${bounds.minY},${bounds.maxY}`; + const plane = usePlane(bounds, size.width, size.height, fitKey); + const { toScreen, zoomAt, fit } = plane; + + useEffect(() => { + if (fitSignal > 0) fit(); + }, [fitSignal, fit]); + + useEffect(() => { + const element = svg.current; + if (!element) return; + const onWheel = (event: WheelEvent) => { + event.preventDefault(); + const rect = element.getBoundingClientRect(); + zoomAt(event.clientX - rect.left, event.clientY - rect.top, Math.exp(-event.deltaY * 0.0015)); + }; + element.addEventListener("wheel", onWheel, { passive: false }); + return () => element.removeEventListener("wheel", onWheel); + }, [zoomAt, size.width]); + + const radius = Math.max(2.5, Math.min(6, plane.viewport.scale * 0.22)); + const hoverScreen = hover ? toScreen(hover.x, hover.y) : null; + + return ( +
+ {size.width > 0 && ( + + + + + + + + + {groups.map((group) => { + const { sx, sy } = toScreen(group.x, group.y); + const duplicate = group.count > 1; + const related = highlight + ? group.pairs.some((pair) => pair.split("-")[highlight.side] === highlight.name) + : false; + const dimmed = highlight !== null && !related; + return ( + setHover(group)} + onPointerLeave={() => setHover((current) => (current === group ? null : current))} + opacity={dimmed ? 0.4 : 1} + > + + + {duplicate && radius >= 4 && ( + + {group.count} + + )} + + ); + })} + + + )} + {hover && hoverScreen && ( +
+ + ({trimNumber(hover.x)}, {trimNumber(hover.y)}) λ + + {t("virtual.multiplicity", { count: hover.count })} + + {hover.pairs.slice(0, 8).join(", ")} + {hover.pairs.length > 8 ? ` … (${hover.pairs.length})` : ""} + +
+ )} +
+ ); +} diff --git a/web/src/views/plane.tsx b/web/src/views/plane.tsx new file mode 100644 index 0000000..ae20b3d --- /dev/null +++ b/web/src/views/plane.tsx @@ -0,0 +1,224 @@ +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; + +/** Shared viewport for the λ-plane plots (physical and virtual arrays). */ + +export interface Bounds { + minX: number; + maxX: number; + minY: number; + maxY: number; +} + +export interface Viewport { + /** λ coordinate at the viewport center. */ + cx: number; + cy: number; + /** Pixels per λ. */ + scale: number; +} + +export const PLOT_MARGIN = { left: 48, right: 14, top: 14, bottom: 32 }; + +export function useElementSize() { + const ref = useRef(null); + const [size, setSize] = useState({ width: 0, height: 0 }); + useLayoutEffect(() => { + const element = ref.current; + if (!element) return; + const observer = new ResizeObserver(([entry]) => { + const { width, height } = entry.contentRect; + setSize((previous) => + Math.abs(previous.width - width) < 0.5 && Math.abs(previous.height - height) < 0.5 + ? previous + : { width, height }, + ); + }); + observer.observe(element); + return () => observer.disconnect(); + }, []); + return [ref, size] as const; +} + +export function fitViewport(bounds: Bounds, width: number, height: number): Viewport { + const innerWidth = Math.max(10, width - PLOT_MARGIN.left - PLOT_MARGIN.right); + const innerHeight = Math.max(10, height - PLOT_MARGIN.top - PLOT_MARGIN.bottom); + const spanX = Math.max(2, bounds.maxX - bounds.minX); + const spanY = Math.max(2, bounds.maxY - bounds.minY); + const scale = Math.min(innerWidth / spanX, innerHeight / spanY); + return { + cx: (bounds.minX + bounds.maxX) / 2, + cy: (bounds.minY + bounds.maxY) / 2, + scale: Math.max(2, Math.min(scale, 120)), + }; +} + +export function usePlane(bounds: Bounds, width: number, height: number, autoFitKey: string) { + const [viewport, setViewport] = useState({ cx: 0, cy: 0, scale: 10 }); + const manual = useRef(false); + const boundsRef = useRef(bounds); + boundsRef.current = bounds; + + const fit = useCallback(() => { + manual.current = false; + if (width > 0 && height > 0) setViewport(fitViewport(boundsRef.current, width, height)); + }, [width, height]); + + // Auto-fit on size or layout change unless the user zoomed/panned. + useEffect(() => { + if (!manual.current && width > 0 && height > 0) { + setViewport(fitViewport(boundsRef.current, width, height)); + } + }, [width, height, autoFitKey]); + + const centerX = PLOT_MARGIN.left + (width - PLOT_MARGIN.left - PLOT_MARGIN.right) / 2; + const centerY = PLOT_MARGIN.top + (height - PLOT_MARGIN.top - PLOT_MARGIN.bottom) / 2; + + const toScreen = useCallback( + (x: number, y: number) => ({ + sx: centerX + (x - viewport.cx) * viewport.scale, + sy: centerY - (y - viewport.cy) * viewport.scale, + }), + [centerX, centerY, viewport], + ); + + const toWorld = useCallback( + (sx: number, sy: number) => ({ + x: viewport.cx + (sx - centerX) / viewport.scale, + y: viewport.cy - (sy - centerY) / viewport.scale, + }), + [centerX, centerY, viewport], + ); + + const zoomAt = useCallback( + (sx: number, sy: number, factor: number) => { + manual.current = true; + setViewport((current) => { + const scale = Math.max(2, Math.min(current.scale * factor, 200)); + const worldX = current.cx + (sx - centerX) / current.scale; + const worldY = current.cy - (sy - centerY) / current.scale; + return { + scale, + cx: worldX - (sx - centerX) / scale, + cy: worldY + (sy - centerY) / scale, + }; + }); + }, + [centerX, centerY], + ); + + const panBy = useCallback((dx: number, dy: number) => { + manual.current = true; + setViewport((current) => ({ + ...current, + cx: current.cx - dx / current.scale, + cy: current.cy + dy / current.scale, + })); + }, []); + + return { viewport, toScreen, toWorld, zoomAt, panBy, fit }; +} + +function niceStep(pixelsPerUnit: number, minPixels: number): number { + const candidates = [0.5, 1, 2, 5, 10, 20, 50, 100]; + return candidates.find((step) => step * pixelsPerUnit >= minPixels) ?? 100; +} + +export function PlaneGrid({ + width, + height, + viewport, + toScreen, + toWorld, + showMinor = true, +}: { + width: number; + height: number; + viewport: Viewport; + toScreen: (x: number, y: number) => { sx: number; sy: number }; + toWorld: (sx: number, sy: number) => { x: number; y: number }; + showMinor?: boolean; +}) { + const lines = useMemo(() => { + const left = PLOT_MARGIN.left; + const right = width - PLOT_MARGIN.right; + const top = PLOT_MARGIN.top; + const bottom = height - PLOT_MARGIN.bottom; + const topLeft = toWorld(left, top); + const bottomRight = toWorld(right, bottom); + const major = niceStep(viewport.scale, 46); + const minor = 0.5; + const result: { minor: string[]; major: string[]; xLabels: [number, number][]; yLabels: [number, number][] } = { + minor: [], + major: [], + xLabels: [], + yLabels: [], + }; + const drawMinor = showMinor && minor * viewport.scale >= 7; + const step = drawMinor ? minor : major; + const startX = Math.ceil(topLeft.x / step) * step; + for (let x = startX; x <= bottomRight.x + 1e-9; x += step) { + const { sx } = toScreen(x, 0); + const isMajor = Math.abs(x / major - Math.round(x / major)) < 1e-6; + (isMajor ? result.major : result.minor).push(`M${sx.toFixed(1)} ${top}V${bottom}`); + if (isMajor) result.xLabels.push([sx, x]); + } + const startY = Math.ceil(bottomRight.y / step) * step; + for (let y = startY; y <= topLeft.y + 1e-9; y += step) { + const { sy } = toScreen(0, y); + const isMajor = Math.abs(y / major - Math.round(y / major)) < 1e-6; + (isMajor ? result.major : result.minor).push(`M${left} ${sy.toFixed(1)}H${right}`); + if (isMajor) result.yLabels.push([sy, y]); + } + return { ...result, left, right, top, bottom }; + }, [width, height, viewport, toScreen, toWorld, showMinor]); + + const format = (value: number) => (Math.abs(value) < 1e-9 ? "0" : String(Math.round(value * 100) / 100)); + + return ( + + + + + + {lines.xLabels.map(([sx, value]) => ( + + {format(value)} + + ))} + {lines.yLabels.map(([sy, value]) => ( + + {format(value)} + + ))} + + x (λ) + + + y (λ) + + + ); +} + +export function clipId(prefix: string) { + return `${prefix}-${Math.random().toString(36).slice(2, 8)}`; +} diff --git a/web/src/views/usePlayback.ts b/web/src/views/usePlayback.ts new file mode 100644 index 0000000..3845aa8 --- /dev/null +++ b/web/src/views/usePlayback.ts @@ -0,0 +1,59 @@ +import { useCallback, useEffect, useRef, useState } from "react"; + +export const PLAYBACK_SPEEDS = [10, 20, 40] as const; + +/** Frame-index playback driven by requestAnimationFrame at a fixed frame rate. */ +export function usePlayback(count: number, initialIndex: number) { + const [index, setIndex] = useState(initialIndex); + const [playing, setPlaying] = useState(false); + const [fps, setFps] = useState(PLAYBACK_SPEEDS[1]); + const indexRef = useRef(index); + indexRef.current = index; + + useEffect(() => { + if (!playing || count <= 0) return; + let frame = 0; + let last = performance.now(); + let accumulator = 0; + const tick = (now: number) => { + accumulator += now - last; + last = now; + const interval = 1000 / fps; + if (accumulator >= interval) { + const steps = Math.floor(accumulator / interval); + accumulator -= steps * interval; + const next = indexRef.current + steps; + if (next >= count - 1) { + setIndex(count - 1); + setPlaying(false); + return; + } + setIndex(next); + } + frame = requestAnimationFrame(tick); + }; + frame = requestAnimationFrame(tick); + return () => cancelAnimationFrame(frame); + }, [playing, fps, count]); + + const toggle = useCallback(() => { + setPlaying((current) => { + if (!current && indexRef.current >= count - 1) setIndex(0); + return !current; + }); + }, [count]); + + const reset = useCallback(() => { + setPlaying(false); + setIndex(initialIndex); + }, [initialIndex]); + + const seek = useCallback( + (value: number) => { + setIndex(Math.max(0, Math.min(count - 1, value))); + }, + [count], + ); + + return { index, seek, playing, setPlaying, toggle, reset, fps, setFps }; +} diff --git a/web/tsconfig.json b/web/tsconfig.json new file mode 100644 index 0000000..e361200 --- /dev/null +++ b/web/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "isolatedModules": true, + "skipLibCheck": true, + "noEmit": true, + "resolveJsonModule": true, + "types": ["vite/client", "node"] + }, + "include": ["src"] +} diff --git a/web/vite.config.ts b/web/vite.config.ts new file mode 100644 index 0000000..848ccae --- /dev/null +++ b/web/vite.config.ts @@ -0,0 +1,26 @@ +/// +import { fileURLToPath } from "node:url"; +import react from "@vitejs/plugin-react"; +import { defineConfig } from "vite"; + +// The production build is written into the Python package so that +// `pip install` / the Docker image ship the web client with the API server. +const outDir = fileURLToPath(new URL("../src/virtual_array/server/static", import.meta.url)); + +export default defineConfig({ + plugins: [react()], + build: { + outDir, + emptyOutDir: true, + chunkSizeWarningLimit: 4000, + }, + server: { + port: 5173, + proxy: { + "/api": "http://127.0.0.1:8000", + }, + }, + test: { + environment: "node", + }, +}); From 7d7e9a9df88f29bd8881c96212214055a2f9cea7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 12:21:38 +0000 Subject: [PATCH 3/5] =?UTF-8?q?=E4=BC=98=E5=8C=96=EF=BC=9A=E9=9D=A2?= =?UTF-8?q?=E5=90=91=2060/77/92=20GHz=20FMCW=20=E9=9B=B7=E8=BE=BE=E4=BF=AE?= =?UTF-8?q?=E6=AD=A3=E8=AF=84=E4=BC=B0=E6=96=B9=E6=B3=95=E5=B9=B6=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E9=A2=91=E6=AE=B5/=E8=A7=84=E6=A0=BC=E8=83=BD?= =?UTF-8?q?=E5=8A=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 计算核心 - PSL 主瓣区改为按第一零点自适应(≥3 dB 下降),修复小阵列(60 GHz 3T4R 等)主瓣被误判为旁瓣、PSL≈0 dB 的问题;无孔径轴不再统计旁瓣 - 栅瓣检测排除主瓣区 - 新增 EvaluationSettings:测角评估按雷达视场(FOV)+ 搜索保护带进行,视场外栅瓣不再计为视场内模糊 - 新增峰值细化(在谱峰附近重新计算相关,0.002° 分辨率、无插值偏差),可评估亚度级测角误差 - 新增 requirements.py:按项目规格逐项检查(分辨率、视场内不模糊、最大误差、裕量、PSL) - 报告使用相同视场与细化设置,并输出视场、频段和规格检查结果 服务层 - 项目新增频段(60G/77G/92G 预设与扫频范围)、视场、编辑网格、规格;旧文档按频率推断频段 - 阵面 JSON 导入不再强制吸附 λ/2 网格 - 新增 /api/band(频段起止与设计频点的性能)和 /api/compare(多方案对比) - 评估结果新增实测分辨率、规格检查、阵元重叠/重合检查 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TgRQxvYJLtrCkPBUDGPWAw --- src/virtual_array/analysis.py | 352 +++++++++++++++++++++--- src/virtual_array/engine.py | 345 ++++++++++++++++++----- src/virtual_array/performance_report.py | 154 +++++++++-- src/virtual_array/project.py | 125 ++++++++- src/virtual_array/requirements.py | 130 +++++++++ src/virtual_array/server/app.py | 16 ++ tests/test_analysis.py | 115 +++++++- tests/test_project.py | 7 +- tests/test_server.py | 135 ++++++++- 9 files changed, 1234 insertions(+), 145 deletions(-) create mode 100644 src/virtual_array/requirements.py diff --git a/src/virtual_array/analysis.py b/src/virtual_array/analysis.py index dec5cbf..1dc44b0 100644 --- a/src/virtual_array/analysis.py +++ b/src/virtual_array/analysis.py @@ -31,6 +31,10 @@ DBF_QUALITY_OK = "正常" MAINLOBE_GUARD_AZ = 2.0 MAINLOBE_GUARD_EL = 6.0 +MAINLOBE_MIN_DROP_DB = 3.0 +GRATING_MIN_ABS_ANGLE_DEG = 20.0 +DBF_SEARCH_GUARD_DEG = 10.0 +DBF_REFINE_STAGES = ((1.0, 0.05), (0.05, 0.002)) DBF_CORRELATION_EPS = 1e-12 @@ -159,8 +163,14 @@ def dbf_angle_frame_series_from_spectra( true_angles_deg: np.ndarray, scan_angles_deg: np.ndarray, spectra_db: np.ndarray, + estimated_angles_deg: np.ndarray | None = None, ) -> DbfAngleFrameSeries: - """Extract per-frame DBF estimates, errors, peak margins, and quality flags.""" + """Extract per-frame DBF estimates, errors, peak margins, and quality flags. + + ``estimated_angles_deg`` optionally replaces the scan-grid peak angles with + refined estimates (see :func:`dbf_refine_peak_angles`); peak margins and + quality flags are still taken from the scan-grid spectra. + """ true_angles = np.asarray(true_angles_deg, dtype=float) scan_angles = np.asarray(scan_angles_deg, dtype=float) spectra = np.asarray(spectra_db, dtype=float) @@ -205,6 +215,11 @@ def dbf_angle_frame_series_from_spectra( quality_flags.append(quality_flag) estimate_array = np.asarray(estimates, dtype=float) + if estimated_angles_deg is not None: + refined = np.asarray(estimated_angles_deg, dtype=float) + if refined.shape != estimate_array.shape: + raise ValueError("estimated_angles_deg must have one value per true angle.") + estimate_array = refined.copy() return DbfAngleFrameSeries( true_angles_deg=true_angles.copy(), estimated_angles_deg=estimate_array, @@ -224,6 +239,8 @@ def calculate_metrics_and_psf( tx_pattern: ElementPattern | None = None, rx_pattern: ElementPattern | None = None, channel_patterns: ChannelPatternSet | None = None, + azimuth_fov: tuple[float, float] = AZIMUTH_FOV, + elevation_fov: tuple[float, float] = ELEVATION_FOV, ) -> tuple[np.ndarray, np.ndarray, np.ndarray, ArrayMetrics]: if unique is None or counts is None: unique, counts = array.unique_virtual_xy(decimals=decimals) @@ -235,8 +252,8 @@ def calculate_metrics_and_psf( azimuth_resolution = estimate_resolution(x_aperture) elevation_resolution = estimate_resolution(y_aperture) - azimuths = np.linspace(AZIMUTH_FOV[0], AZIMUTH_FOV[1], AF_GRID_SIZE) - elevations = np.linspace(ELEVATION_FOV[0], ELEVATION_FOV[1], AF_GRID_SIZE) + azimuths = np.linspace(azimuth_fov[0], azimuth_fov[1], AF_GRID_SIZE) + elevations = np.linspace(elevation_fov[0], elevation_fov[1], AF_GRID_SIZE) az_grid, el_grid = np.meshgrid(azimuths, elevations) az_rad = np.radians(az_grid) el_rad = np.radians(el_grid) @@ -269,9 +286,25 @@ def calculate_metrics_and_psf( main_index = np.unravel_index(np.argmax(af_db), af_db.shape) main_azimuth = float(az_grid[main_index]) main_elevation = float(el_grid[main_index]) + # The main lobe extends to the first null on each principal cut through the + # peak (at least 3 dB down). A fixed angular guard misclassifies the main + # lobe of small arrays (wide beams) as a sidelobe; an axis without aperture + # has no sidelobes at all. + az_bounds = ( + _mainlobe_bounds(azimuths, af_db[main_index[0], :], int(main_index[1])) + if x_aperture > 0 + else (float(azimuths[0]), float(azimuths[-1])) + ) + el_bounds = ( + _mainlobe_bounds(elevations, af_db[:, main_index[1]], int(main_index[0])) + if y_aperture > 0 + else (float(elevations[0]), float(elevations[-1])) + ) main_lobe_mask = ( - (np.abs(az_grid - main_azimuth) <= MAINLOBE_GUARD_AZ) - & (np.abs(el_grid - main_elevation) <= MAINLOBE_GUARD_EL) + (az_grid >= az_bounds[0]) + & (az_grid <= az_bounds[1]) + & (el_grid >= el_bounds[0]) + & (el_grid <= el_bounds[1]) ) sidelobe_values = np.where(~main_lobe_mask, af_db, -np.inf) sidelobe_index = np.unravel_index( @@ -283,8 +316,18 @@ def calculate_metrics_and_psf( azimuth_cut = af_db[el0_index, :] elevation_cut = af_db[:, az0_index] - az_cut_mask = np.abs(azimuths) > MAINLOBE_GUARD_AZ - el_cut_mask = np.abs(elevations) > MAINLOBE_GUARD_EL + az_cut_bounds = ( + _mainlobe_bounds(azimuths, azimuth_cut, int(np.argmax(azimuth_cut))) + if x_aperture > 0 + else (float(azimuths[0]), float(azimuths[-1])) + ) + el_cut_bounds = ( + _mainlobe_bounds(elevations, elevation_cut, int(np.argmax(elevation_cut))) + if y_aperture > 0 + else (float(elevations[0]), float(elevations[-1])) + ) + az_cut_mask = (azimuths < az_cut_bounds[0]) | (azimuths > az_cut_bounds[1]) + el_cut_mask = (elevations < el_cut_bounds[0]) | (elevations > el_cut_bounds[1]) azimuth_psl_db = float(np.max(np.where(az_cut_mask, azimuth_cut, -np.inf))) elevation_psl_db = float(np.max(np.where(el_cut_mask, elevation_cut, -np.inf))) @@ -295,7 +338,7 @@ def calculate_metrics_and_psf( azimuth_first_sidelobe(azimuths, azimuth_cut) ) azimuth_grating_lobe_db, azimuth_grating_lobe_angle = azimuth_grating_lobe( - azimuths, azimuth_cut + azimuths, azimuth_cut, mainlobe_bounds=az_cut_bounds ) elevation_3db_beamwidth = cut_3db_beamwidth(elevations, elevation_cut) @@ -659,6 +702,8 @@ def dbf_angle_metrics_from_spectra( spectra_db: np.ndarray, focus_limit_deg: float = DBF_ANGLE_FOCUS_DEG, ambiguity_margin_db: float = DBF_AMBIGUITY_MARGIN_DB, + estimated_angles_deg: np.ndarray | None = None, + focus_range_deg: tuple[float, float] | None = None, ) -> DbfAngleMetrics: true_angles = np.asarray(true_angles_deg, dtype=float) scan_angles = np.asarray(scan_angles_deg, dtype=float) @@ -670,6 +715,7 @@ def dbf_angle_metrics_from_spectra( true_angles, scan_angles, spectra, + estimated_angles_deg=estimated_angles_deg, ) true_angles = frame_series.true_angles_deg error_array = frame_series.errors_deg @@ -682,7 +728,10 @@ def dbf_angle_metrics_from_spectra( ambiguity_margin_db=ambiguity_margin_db, ) - focus_mask = np.abs(true_angles) <= focus_limit_deg + if focus_range_deg is not None: + focus_mask = (true_angles >= focus_range_deg[0]) & (true_angles <= focus_range_deg[1]) + else: + focus_mask = np.abs(true_angles) <= focus_limit_deg focus_errors = np.abs(error_array[focus_mask]) focus_max = float(np.max(focus_errors)) if focus_errors.size else None center_index = int(np.argmin(np.abs(true_angles))) @@ -934,52 +983,241 @@ def _dbf_spectrum_bank( channel_patterns: ChannelPatternSet | None = None, dbf_dictionary: DbfDictionaryConfig | None = None, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: - if true_angles_deg is None: - true_angles_deg = _default_dbf_angles() - else: - true_angles_deg = np.asarray(true_angles_deg, dtype=float) + if axis not in {"azimuth", "elevation"}: + raise ValueError(f"Unknown DBF axis: {axis!r}") + true_angles_deg, scan_angles_deg, signal_phase, dictionary_for = _dbf_axis_model( + array, + axis, + true_angles_deg, + scan_angles_deg, + channel_patterns=channel_patterns, + dbf_dictionary=dbf_dictionary, + ) + response = _dbf_correlation_response(dictionary_for(scan_angles_deg), signal_phase) + _ = tx_pattern, rx_pattern + spectra = response.T + spectra_db = 20.0 * np.log10(np.maximum(spectra, 1e-6)) + return true_angles_deg, scan_angles_deg, spectra_db - if scan_angles_deg is None: - scan_angles_deg = _default_dbf_angles() - else: - scan_angles_deg = np.asarray(scan_angles_deg, dtype=float) +def _dbf_axis_model( + array: AntennaArray, + axis: str, + true_angles_deg: np.ndarray | None, + scan_angles_deg: np.ndarray | None, + channel_patterns: ChannelPatternSet | None, + dbf_dictionary: DbfDictionaryConfig | None, +): # noqa: ANN202 - returns (true, scan, signals, dictionary builder) + """Signals for each true angle plus a dictionary builder for arbitrary angles. + + The steering sign of the automatic ideal dictionary is chosen once on the + scan grid, so refined searches use exactly the same dictionary. + """ + true_angles = ( + _default_dbf_angles() if true_angles_deg is None else np.asarray(true_angles_deg, dtype=float) + ) + scan_angles = ( + _default_dbf_angles() if scan_angles_deg is None else np.asarray(scan_angles_deg, dtype=float) + ) signal_phase = _dbf_signal_matrix( array, - true_angles_deg, + true_angles, axis=axis, channel_patterns=channel_patterns, ) if dbf_dictionary is not None and not dbf_dictionary.uses_auto_ideal_sign: - dictionary = dbf_dictionary.scan_matrix( - array, - scan_angles_deg, - axis=axis, - channel_patterns=channel_patterns, - ) + def dictionary_for(angles: np.ndarray) -> np.ndarray: + return dbf_dictionary.scan_matrix( + array, + np.asarray(angles, dtype=float), + axis=axis, + channel_patterns=channel_patterns, + ) else: steering_sign = _select_dbf_steering_sign( array, - true_angles_deg, - scan_angles_deg, + true_angles, + scan_angles, signal_phase, axis=axis, channel_patterns=channel_patterns, ) - dictionary = _dbf_scan_matrix( - array, - scan_angles_deg, - axis=axis, - steering_sign=steering_sign, - ) - response = _dbf_correlation_response(dictionary, signal_phase) + def dictionary_for(angles: np.ndarray) -> np.ndarray: + return _dbf_scan_matrix( + array, + np.asarray(angles, dtype=float), + axis=axis, + steering_sign=steering_sign, + ) + + return true_angles, scan_angles, signal_phase, dictionary_for + + +def dbf_refine_peak_angles( + array: AntennaArray, + axis: str, + true_angles_deg: np.ndarray, + scan_angles_deg: np.ndarray, + spectra_db: np.ndarray, + channel_patterns: ChannelPatternSet | None = None, + dbf_dictionary: DbfDictionaryConfig | None = None, + stages: tuple[tuple[float, float], ...] = DBF_REFINE_STAGES, +) -> np.ndarray: + """Refine each frame's scan-grid peak by re-evaluating the correlation finely. + + The coarse peak is the same strict ``argmax`` used for the performance + metrics. Each stage searches ``±span`` around the current estimate with + ``step`` resolution (default 1°/0.05° then 0.05°/0.002°), using the exact + signal and dictionary of the spectrum bank, so the refinement adds no + interpolation bias. Searches stay inside the scan range. + """ + true_angles = np.asarray(true_angles_deg, dtype=float) + scan_angles = np.asarray(scan_angles_deg, dtype=float) + spectra = np.asarray(spectra_db, dtype=float) + estimates = scan_angles[np.argmax(spectra, axis=1)].astype(float) + if _dictionary_is_nearest_neighbour(dbf_dictionary, axis): + return estimates + _true, _scan, signals, dictionary_for = _dbf_axis_model( + array, + axis, + true_angles, + scan_angles, + channel_patterns=channel_patterns, + dbf_dictionary=dbf_dictionary, + ) + low, high = float(scan_angles[0]), float(scan_angles[-1]) + signal_norms = np.linalg.norm(signals, axis=0) + for span, step in stages: + offsets = np.arange(-span, span + step / 2.0, step) + for start in range(0, len(true_angles), 32): + stop = min(start + 32, len(true_angles)) + candidates = np.clip(estimates[start:stop, None] + offsets[None, :], low, high) + dictionary = dictionary_for(candidates.ravel()).reshape( + stop - start, len(offsets), -1 + ) + response = np.abs(np.einsum("fkn,nf->fk", dictionary, signals[:, start:stop])) + norms = np.linalg.norm(dictionary, axis=2) * signal_norms[None, start:stop].T + correlation = np.divide( + response, + norms, + out=np.zeros_like(response), + where=norms > DBF_CORRELATION_EPS, + ) + best = np.argmax(correlation, axis=1) + estimates[start:stop] = candidates[np.arange(stop - start), best] + return estimates + + +def _dictionary_is_nearest_neighbour( + dbf_dictionary: DbfDictionaryConfig | None, + axis: str, +) -> bool: + if dbf_dictionary is None or dbf_dictionary.mode != "custom": + return False + table = dbf_dictionary.custom_table_for_axis(axis) + return table is not None and table.is_2d + + +@dataclass(frozen=True) +class EvaluationSettings: + """Field of view and search settings for one radar evaluation. + + True angles are swept across the FOV in 1° steps. The DBF search (scan) + range extends ``search_guard_deg`` beyond the FOV so a target at the FOV + edge is not flagged as an edge peak; real radars likewise only search + the directions they serve, which keeps grating lobes outside the FOV from + being counted as in-FOV ambiguity. + """ + + azimuth_fov_deg: tuple[float, float] = AZIMUTH_FOV + elevation_fov_deg: tuple[float, float] = ELEVATION_FOV + search_guard_deg: float = DBF_SEARCH_GUARD_DEG + refine_peaks: bool = True + + def __post_init__(self) -> None: + for name in ("azimuth_fov_deg", "elevation_fov_deg"): + low, high = (float(value) for value in getattr(self, name)) + if not (DBF_SCAN_FOV[0] <= low < 0.0 < high <= DBF_SCAN_FOV[1]): + raise ValueError(f"{name} must satisfy -90 <= low < 0 < high <= 90.") + object.__setattr__(self, name, (low, high)) + guard = float(self.search_guard_deg) + if not math.isfinite(guard) or guard < 0.0: + raise ValueError("search_guard_deg must be finite and non-negative.") + object.__setattr__(self, "search_guard_deg", guard) + + def fov(self, axis: str) -> tuple[float, float]: + if axis == "azimuth": + return self.azimuth_fov_deg + if axis == "elevation": + return self.elevation_fov_deg + raise ValueError(f"Unknown DBF axis: {axis!r}") + + def true_angles(self, axis: str) -> np.ndarray: + low, high = self.fov(axis) + return np.arange(math.ceil(low), math.floor(high) + DBF_SCAN_STEP_DEG / 2.0, DBF_SCAN_STEP_DEG) + + def scan_angles(self, axis: str) -> np.ndarray: + low, high = self.fov(axis) + start = max(DBF_SCAN_FOV[0], math.ceil(low) - self.search_guard_deg) + stop = min(DBF_SCAN_FOV[1], math.floor(high) + self.search_guard_deg) + return np.arange(start, stop + DBF_SCAN_STEP_DEG / 2.0, DBF_SCAN_STEP_DEG) + + +@dataclass(frozen=True) +class DbfAxisEvaluation: + axis: str + true_angles_deg: np.ndarray + scan_angles_deg: np.ndarray + spectra_db: np.ndarray + frame_series: DbfAngleFrameSeries + metrics: DbfAngleMetrics + + +def evaluate_dbf_axis( + array: AntennaArray, + axis: str, + settings: EvaluationSettings, + channel_patterns: ChannelPatternSet | None = None, + dbf_dictionary: DbfDictionaryConfig | None = None, + ambiguity_margin_db: float = DBF_AMBIGUITY_MARGIN_DB, +) -> DbfAxisEvaluation: + """FOV-bounded DBF evaluation of one axis with optional peak refinement.""" + bank = dbf_azimuth_spectrum_bank if axis == "azimuth" else dbf_elevation_spectrum_bank if axis not in {"azimuth", "elevation"}: raise ValueError(f"Unknown DBF axis: {axis!r}") - _ = tx_pattern, rx_pattern - spectra = response.T - spectra_db = 20.0 * np.log10(np.maximum(spectra, 1e-6)) - return true_angles_deg, scan_angles_deg, spectra_db + true_angles, scan_angles, spectra = bank( + array, + true_angles_deg=settings.true_angles(axis), + scan_angles_deg=settings.scan_angles(axis), + channel_patterns=channel_patterns, + dbf_dictionary=dbf_dictionary, + ) + estimates = ( + dbf_refine_peak_angles( + array, + axis, + true_angles, + scan_angles, + spectra, + channel_patterns=channel_patterns, + dbf_dictionary=dbf_dictionary, + ) + if settings.refine_peaks + else None + ) + frame_series = dbf_angle_frame_series_from_spectra( + true_angles, scan_angles, spectra, estimated_angles_deg=estimates + ) + metrics = dbf_angle_metrics_from_spectra( + true_angles, + scan_angles, + spectra, + ambiguity_margin_db=ambiguity_margin_db, + estimated_angles_deg=estimates, + focus_range_deg=settings.fov(axis), + ) + return DbfAxisEvaluation(axis, true_angles, scan_angles, spectra, frame_series, metrics) def _dbf_correlation_response( @@ -1340,13 +1578,17 @@ def azimuth_first_sidelobe( def azimuth_grating_lobe( azimuths: np.ndarray, azimuth_cut_db: np.ndarray, - min_abs_angle: float = 20.0, + min_abs_angle: float = GRATING_MIN_ABS_ANGLE_DEG, + mainlobe_bounds: tuple[float, float] | None = None, ) -> tuple[float | None, float | None]: - far_indices = np.flatnonzero(np.abs(azimuths) > min_abs_angle) + far = np.abs(azimuths) > min_abs_angle + if mainlobe_bounds is not None: + far &= (azimuths < mainlobe_bounds[0]) | (azimuths > mainlobe_bounds[1]) + far_indices = np.flatnonzero(far) if len(far_indices) == 0: return None, None peak_indices = local_peak_indices(azimuth_cut_db) - far_peak_indices = peak_indices[np.abs(azimuths[peak_indices]) > min_abs_angle] + far_peak_indices = peak_indices[far[peak_indices]] candidates = far_peak_indices if len(far_peak_indices) else far_indices best_index = int(candidates[np.argmax(azimuth_cut_db[candidates])]) return float(azimuth_cut_db[best_index]), float(azimuths[best_index]) @@ -1421,6 +1663,36 @@ def threshold_crossing_angle( return None +def _mainlobe_bounds( + angles: np.ndarray, + cut_db: np.ndarray, + peak_index: int, + min_drop_db: float = MAINLOBE_MIN_DROP_DB, +) -> tuple[float, float]: + """Angles of the first nulls around a peak, at least ``min_drop_db`` down. + + If the cut never drops by ``min_drop_db`` on one side, the main lobe is + taken to extend to the end of the cut on that side. + """ + values = np.asarray(cut_db, dtype=float) + peak = float(values[peak_index]) + bounds = [] + for direction in (-1, 1): + index = peak_index + while 0 <= index + direction < len(values) and peak - values[index] < min_drop_db: + index += direction + if peak - values[index] < min_drop_db: + bounds.append(float(angles[index])) + continue + while ( + 0 <= index + direction < len(values) + and values[index + direction] <= values[index] + ): + index += direction + bounds.append(float(angles[index])) + return bounds[0], bounds[1] + + def first_null_index(values_db: np.ndarray, peak_index: int, direction: int) -> int | None: index = peak_index + direction while 0 < index < len(values_db) - 1: diff --git a/src/virtual_array/engine.py b/src/virtual_array/engine.py index 3c46fd3..52e4c77 100644 --- a/src/virtual_array/engine.py +++ b/src/virtual_array/engine.py @@ -30,16 +30,13 @@ DBF_CUT_REASON_ERROR_JUMP, DBF_CUT_REASON_FLAT, DBF_QUALITY_OK, - DBF_SCAN_FOV, - DBF_SCAN_GRID_SIZE, ArrayMetrics, Dbf2dScanner, DbfAngleMetrics, + DbfAxisEvaluation, + EvaluationSettings, calculate_metrics_and_psf, - dbf_angle_frame_series_from_spectra, - dbf_angle_metrics_from_spectra, - dbf_azimuth_spectrum_bank, - dbf_elevation_spectrum_bank, + evaluate_dbf_axis, ) from .assets import AssetStore from .dbf_dictionary import ( @@ -66,15 +63,27 @@ ) from .geometry import AntennaArray from .project import ( + LIGHT_SPEED_MM_PER_NS, ChannelPatternBinding, Project, json_number, layout_to_v1, project_array, ) +from .requirements import ( + STATUS_FAIL, + STATUS_PASS, + RequirementCheck, + RequirementSpec, + check_requirements, + measured_resolution, +) from .version import APP_VERSION AXES = ("azimuth", "elevation") +MIN_ELEMENT_SPACING_LAMBDA = 0.5 +MAX_LAYOUT_WARNINGS = 12 +MAX_COMPARE_PROJECTS = 8 HALF_LAMBDA_TO_LAMBDA = 0.5 ROUND_DECIMALS = 9 @@ -125,6 +134,8 @@ class StudyContext: element_pattern: ElementPattern | None channel_patterns: ChannelPatternSet dictionary: DbfDictionaryConfig + settings: EvaluationSettings + operating_ghz: float def encode_array(values: np.ndarray, dtype: str = "float32") -> dict[str, Any]: @@ -170,15 +181,19 @@ def __init__(self, assets: AssetStore) -> None: # ── Project → core objects ─────────────────────────────────────── - def context(self, project: Project) -> StudyContext: + def context(self, project: Project, operating_ghz: float | None = None) -> StudyContext: + """Core objects for the project at an operating frequency (default: design).""" self._require_assets(project) - array = project_array(project) + frequency = project.frequency_ghz if operating_ghz is None else float(operating_ghz) + array = project_array(project, frequency) return StudyContext( project=project, array=array, element_pattern=self._element_pattern(project), channel_patterns=self._channel_pattern_set(project), dictionary=self._dictionary_config(project, array), + settings=evaluation_settings(project), + operating_ghz=frequency, ) def _require_assets(self, project: Project) -> None: @@ -263,16 +278,20 @@ def _dictionary_config(self, project: Project, array: AntennaArray) -> DbfDictio # ── Cache keys ─────────────────────────────────────────────────── @staticmethod - def _pattern_key(project: Project) -> str: + def _key(context: StudyContext, fields: set[str]) -> str: + project = context.project return _digest( - project.model_dump(include={"layout", "element_pattern", "channel_patterns"}) + [ + project.model_dump(include=fields | {"layout", "fov"}), + round(context.operating_ghz / project.frequency_ghz, 12), + ] ) - @staticmethod - def _dbf_key(project: Project) -> str: - return _digest( - project.model_dump(include={"layout", "channel_patterns", "dbf_dictionary"}) - ) + def _pattern_key(self, context: StudyContext) -> str: + return self._key(context, {"element_pattern", "channel_patterns"}) + + def _dbf_key(self, context: StudyContext) -> str: + return self._key(context, {"channel_patterns", "dbf_dictionary", "ambiguity_margin_db"}) # ── Evaluations ────────────────────────────────────────────────── @@ -286,55 +305,77 @@ def build() -> tuple[np.ndarray, np.ndarray, np.ndarray, ArrayMetrics]: tx_pattern=context.element_pattern, rx_pattern=context.element_pattern, channel_patterns=context.channel_patterns, + azimuth_fov=context.settings.azimuth_fov_deg, + elevation_fov=context.settings.elevation_fov_deg, ) - return self._metrics.get_or_create(self._pattern_key(context.project), build) + return self._metrics.get_or_create(self._pattern_key(context), build) - def _bank(self, context: StudyContext, axis: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + def _axis(self, context: StudyContext, axis: str) -> DbfAxisEvaluation: if axis not in AXES: raise ValueError(f"Unknown DBF axis: {axis!r}") - bank_function = dbf_azimuth_spectrum_bank if axis == "azimuth" else dbf_elevation_spectrum_bank - def build() -> tuple[np.ndarray, np.ndarray, np.ndarray]: + def build() -> DbfAxisEvaluation: try: - return bank_function( + return evaluate_dbf_axis( context.array, - tx_pattern=context.element_pattern, - rx_pattern=context.element_pattern, + axis, + context.settings, channel_patterns=context.channel_patterns, dbf_dictionary=context.dictionary, + ambiguity_margin_db=context.project.ambiguity_margin_db, ) except ValueError as exc: raise ProjectComputationError(str(exc)) from exc - return self._banks.get_or_create((self._dbf_key(context.project), axis), build) + return self._banks.get_or_create((self._dbf_key(context), axis), build) - def evaluate(self, project: Project) -> dict[str, Any]: - context = self.context(project) - array = context.array - af_db, azimuths, elevations, metrics = self._array_metrics(context) - _ = af_db, azimuths, elevations - capability = axis_capability(metrics) - half_wavelength_mm = project.wavelength_mm / 2.0 - - angle: dict[str, Any] = {} + def _angle_metrics( + self, context: StudyContext, capability: dict[str, bool] + ) -> tuple[dict[str, DbfAngleMetrics | None], dict[str, str]]: + metrics: dict[str, DbfAngleMetrics | None] = {} + errors: dict[str, str] = {} for axis in AXES: + metrics[axis] = None if not capability[axis]: - angle[axis] = None continue try: - true_angles, scan_angles, spectra = self._bank(context, axis) - angle[axis] = angle_metrics_payload( - dbf_angle_metrics_from_spectra( - true_angles, - scan_angles, - spectra, - ambiguity_margin_db=project.ambiguity_margin_db, - ) - ) + metrics[axis] = self._axis(context, axis).metrics except ProjectComputationError as exc: - angle[axis] = {"error": str(exc)} + errors[axis] = str(exc) + return metrics, errors + def _checks( + self, + context: StudyContext, + metrics: ArrayMetrics, + angle: dict[str, DbfAngleMetrics | None], + ) -> list[RequirementCheck]: + return check_requirements( + requirement_spec(context.project), + metrics, + angle, + {axis: context.settings.fov(axis) for axis in AXES}, + ) + + def evaluate(self, project: Project) -> dict[str, Any]: + context = self.context(project) + array = context.array + _af, _az, _el, metrics = self._array_metrics(context) + capability = axis_capability(metrics) + half_wavelength_mm = project.wavelength_mm / 2.0 + angle_metrics, angle_errors = self._angle_metrics(context, capability) + angle: dict[str, Any] = { + axis: ( + {"error": angle_errors[axis]} + if axis in angle_errors + else None + if angle_metrics[axis] is None + else angle_metrics_payload(angle_metrics[axis]) + ) + for axis in AXES + } + checks = self._checks(context, metrics, angle_metrics) utilization = metrics.unique_count / metrics.virtual_count if metrics.virtual_count else 0.0 return { "wavelength_mm": project.wavelength_mm, @@ -352,45 +393,46 @@ def evaluate(self, project: Project) -> dict[str, Any]: "x_aperture_mm": metrics.x_aperture * half_wavelength_mm, "y_aperture_mm": metrics.y_aperture * half_wavelength_mm, }, + "resolution": resolution_payload(metrics), "metrics": array_metrics_payload(metrics), "capability": capability, + "fov": {axis: list(context.settings.fov(axis)) for axis in AXES}, "virtual_points": virtual_points_payload(array), "angle": angle, + "requirements": [check_payload(check) for check in checks], + "layout_checks": layout_checks(project), "pattern_status": pattern_status(project), - "notes": note_codes(metrics), + "notes": note_codes(metrics, project), } def dbf_bank(self, project: Project, axis: str) -> dict[str, Any]: context = self.context(project) - true_angles, scan_angles, spectra = self._bank(context, axis) - series = dbf_angle_frame_series_from_spectra(true_angles, scan_angles, spectra) - metrics = dbf_angle_metrics_from_spectra( - true_angles, - scan_angles, - spectra, - ambiguity_margin_db=project.ambiguity_margin_db, - ) + evaluation = self._axis(context, axis) + series = evaluation.frame_series return { "axis": axis, - "true_angles": num_list(true_angles), - "scan_angles": num_list(scan_angles), - "spectra_db": encode_array(spectra), + "fov": list(context.settings.fov(axis)), + "true_angles": num_list(evaluation.true_angles_deg), + "scan_angles": num_list(evaluation.scan_angles_deg), + "spectra_db": encode_array(evaluation.spectra_db), "frames": { - "estimated": num_list(series.estimated_angles_deg), - "errors": num_list(series.errors_deg, 6), + "estimated": num_list(series.estimated_angles_deg, 4), + "errors": num_list(series.errors_deg, 4), "main_peak_db": num_list(series.main_peak_db, 4), "competitor_peak_db": num_list(series.competitor_peak_db, 4), "margins_db": num_list(series.peak_margins_db, 4), "quality": [CUT_REASON_CODES.get(flag, flag) for flag in series.quality_flags], }, - "metrics": angle_metrics_payload(metrics), + "metrics": angle_metrics_payload(evaluation.metrics), } def _scanner(self, context: StudyContext) -> Dbf2dScanner: return self._scanners.get_or_create( - self._dbf_key(context.project), + self._dbf_key(context), lambda: Dbf2dScanner( context.array, + scan_azimuths_deg=context.settings.scan_angles("azimuth"), + scan_elevations_deg=context.settings.scan_angles("elevation"), channel_patterns=context.channel_patterns, dbf_dictionary=context.dictionary, ), @@ -417,11 +459,90 @@ def dbf_2d(self, project: Project, frames: list[tuple[float, float]]) -> dict[st } ) return { + "fov": {axis: list(context.settings.fov(axis)) for axis in AXES}, "scan_azimuths": num_list(scanner.scan_azimuths_deg), "scan_elevations": num_list(scanner.scan_elevations_deg), "frames": results, } + def performance_summary(self, project: Project, operating_ghz: float | None = None) -> dict[str, Any]: + """Compact key-metric summary (used by the band sweep and comparisons).""" + context = self.context(project, operating_ghz) + _af, _az, _el, metrics = self._array_metrics(context) + capability = axis_capability(metrics) + angle, errors = self._angle_metrics(context, capability) + checks = self._checks(context, metrics, angle) + return { + "frequency_ghz": context.operating_ghz, + "wavelength_mm": LIGHT_SPEED_MM_PER_NS / context.operating_ghz, + "capability": capability, + "resolution": resolution_payload(metrics), + "psl_db": num(metrics.psl_db), + "azimuth_psl_db": num(metrics.azimuth_psl_db), + "elevation_psl_db": num(metrics.elevation_psl_db), + "angle": { + axis: ( + {"error": errors[axis]} + if axis in errors + else None + if angle[axis] is None + else angle_metrics_payload(angle[axis]) + ) + for axis in AXES + }, + "requirements": [check_payload(check) for check in checks], + "passed": sum(check.status == STATUS_PASS for check in checks), + "failed": sum(check.status == STATUS_FAIL for check in checks), + } + + def band_sweep(self, project: Project) -> dict[str, Any]: + """Performance at the band edges and the design frequency. + + The layout is physical, so its electrical spacing scales with the + operating frequency: grating-lobe onset, no-fold range and resolution + drift across an FMCW sweep. Imported channel phase data are single- + frequency measurements and are reused unchanged at every point. + """ + band = project.band + frequencies = sorted({band.start_ghz, project.frequency_ghz, band.stop_ghz}) + points = [ + {**self.performance_summary(project, frequency), "role": _band_role(project, frequency)} + for frequency in frequencies + ] + uses_measured_phase = any(binding.kind == "phase" for binding in project.channel_patterns) or ( + project.dbf_dictionary.mode == DBF_DICT_CUSTOM + ) + return { + "band": band.model_dump(), + "design_ghz": project.frequency_ghz, + "design_in_band": band.start_ghz <= project.frequency_ghz <= band.stop_ghz, + "uses_single_frequency_data": uses_measured_phase, + "points": points, + } + + def compare(self, projects: list[Project]) -> list[dict[str, Any]]: + if not 1 <= len(projects) <= MAX_COMPARE_PROJECTS: + raise ValueError(f"Compare between 1 and {MAX_COMPARE_PROJECTS} projects.") + results = [] + for project in projects: + try: + summary = self.performance_summary(project) + summary["error"] = None + except (ProjectComputationError, ValueError) as exc: + summary = {"error": str(exc)} + results.append( + { + "name": project.name, + "band": project.band.model_dump(), + "design_ghz": project.frequency_ghz, + "tx_count": len(project.layout.tx), + "rx_count": len(project.layout.rx), + "fov": project.fov.model_dump(), + **summary, + } + ) + return results + # ── Import helpers ─────────────────────────────────────────────── def element_pattern_preview(self, asset: str, swap_axes: bool = False) -> dict[str, Any]: @@ -499,7 +620,7 @@ def dictionary_preview(self, project: Project, axis: str) -> dict[str, Any]: if axis not in AXES: raise ValueError(f"Unknown DBF axis: {axis!r}") context = self.context(project) - angles = np.linspace(DBF_SCAN_FOV[0], DBF_SCAN_FOV[1], DBF_SCAN_GRID_SIZE) + angles = context.settings.scan_angles(axis) try: matrix = context.dictionary.scan_matrix( context.array, @@ -559,6 +680,8 @@ def report_snapshot(self, project: Project): # noqa: ANN201 from .performance_report import PerformanceReportSnapshot context = self.context(project) + _af, _az, _el, metrics = self._array_metrics(context) + angle, _errors = self._angle_metrics(context, axis_capability(metrics)) return PerformanceReportSnapshot( array=context.array, frequency_ghz=project.frequency_ghz, @@ -569,12 +692,99 @@ def report_snapshot(self, project: Project): # noqa: ANN201 current_config=self.layout_document(project), app_version=APP_VERSION, created_at=datetime.now().astimezone(), + evaluation=context.settings, + requirement_checks=tuple(self._checks(context, metrics, angle)), + band_ghz=(project.band.start_ghz, project.band.stop_ghz), ) # ── Payload helpers ────────────────────────────────────────────────── +def evaluation_settings(project: Project) -> EvaluationSettings: + return EvaluationSettings( + azimuth_fov_deg=tuple(float(v) for v in project.fov.azimuth), + elevation_fov_deg=tuple(float(v) for v in project.fov.elevation), + ) + + +def requirement_spec(project: Project) -> RequirementSpec: + return RequirementSpec(**project.requirements.model_dump()) + + +def check_payload(check: RequirementCheck) -> dict[str, Any]: + return { + "key": check.key, + "axis": check.axis, + "target": num(check.target), + "actual": num(check.actual), + "status": check.status, + } + + +def resolution_payload(metrics: ArrayMetrics) -> dict[str, Any]: + """Measured 3 dB beamwidth (primary) and the aperture-formula estimate.""" + return { + axis: { + "measured": num( + metrics.azimuth_3db_beamwidth if axis == "azimuth" else metrics.elevation_3db_beamwidth + ), + "estimate": num( + metrics.azimuth_resolution if axis == "azimuth" else metrics.elevation_resolution + ), + "value": num(measured_resolution(metrics, axis)), + } + for axis in AXES + } + + +def _band_role(project: Project, frequency: float) -> str: + roles = [] + if math.isclose(frequency, project.band.start_ghz): + roles.append("start") + if math.isclose(frequency, project.frequency_ghz): + roles.append("design") + if math.isclose(frequency, project.band.stop_ghz): + roles.append("stop") + return "+".join(roles) + + +def layout_checks(project: Project) -> list[dict[str, Any]]: + """Physical plausibility: coincident or overlapping antennas. + + Patch/series antennas at these bands are roughly λ/2 wide, so centres + closer than λ/2 overlap on the PCB; coincident positions are impossible. + """ + wavelength_mm = project.wavelength_mm + elements = [ + (name, point) + for names, points in ( + (project.tx_names, project.layout.tx), + (project.rx_names, project.layout.rx), + ) + for name, point in zip(names, points) + ] + issues: list[dict[str, Any]] = [] + for index, (name_a, a) in enumerate(elements): + for name_b, b in elements[index + 1 :]: + distance = math.hypot(a.x - b.x, a.y - b.y) + if distance >= MIN_ELEMENT_SPACING_LAMBDA - 1e-9: + continue + issues.append( + { + "code": "coincident" if distance < 1e-9 else "too_close", + "a": name_a, + "b": name_b, + "distance_lambda": round(distance, 6), + "distance_mm": round(distance * wavelength_mm, 4), + } + ) + issues.sort(key=lambda item: (item["code"] != "coincident", item["distance_lambda"])) + if not (project.band.start_ghz <= project.frequency_ghz <= project.band.stop_ghz): + issues.insert(0, {"code": "design_outside_band"}) + return issues[:MAX_LAYOUT_WARNINGS] + + def axis_capability(metrics: ArrayMetrics) -> dict[str, bool]: azimuth = metrics.azimuth_resolution is not None and metrics.x_aperture > 0 elevation = metrics.elevation_resolution is not None and metrics.y_aperture > 0 @@ -652,16 +862,20 @@ def pattern_status(project: Project) -> dict[str, str]: return status -def note_codes(metrics: ArrayMetrics) -> list[str]: +def note_codes(metrics: ArrayMetrics, project: Project | None = None) -> list[str]: notes = [] if metrics.duplicate_excess > 0: notes.append("duplicate_virtual") - if metrics.azimuth_psl_db > -10.0: + if metrics.x_aperture > 0 and metrics.azimuth_psl_db > -10.0: notes.append("windowing") - if metrics.elevation_ambiguity_level == "High": + if metrics.psl_db > -6.0: notes.append("ambiguity_high") - elif metrics.elevation_ambiguity_level == "Medium": + elif metrics.psl_db > -10.0: notes.append("ambiguity_medium") + estimate = metrics.azimuth_resolution + measured = metrics.azimuth_3db_beamwidth + if estimate is not None and measured is not None and measured > estimate * 1.15: + notes.append("resolution_optimistic") return notes @@ -670,6 +884,7 @@ def note_codes(metrics: ArrayMetrics) -> list[str]: "windowing": "建议加窗降低旁瓣", "ambiguity_high": "俯仰模糊风险高", "ambiguity_medium": "俯仰模糊风险中", + "resolution_optimistic": "口径公式估算的分辨率偏乐观", } @@ -741,4 +956,6 @@ def asset_name(asset: str | None) -> str | None: "configured_series": len(project.channel_patterns), }, "notes": [_NOTE_TEXT_ZH[code] for code in note_codes(metrics)], + "band_ghz": [project.band.start_ghz, project.band.stop_ghz], + "fov_deg": project.fov.model_dump(), } diff --git a/src/virtual_array/performance_report.py b/src/virtual_array/performance_report.py index 6bd682a..1a30bf1 100644 --- a/src/virtual_array/performance_report.py +++ b/src/virtual_array/performance_report.py @@ -30,15 +30,18 @@ ArrayMetrics, DbfAngleFrameSeries, DbfAngleMetrics, + EvaluationSettings, calculate_metrics_and_psf, dbf_angle_frame_series_from_spectra, dbf_angle_metrics_from_spectra, dbf_azimuth_spectrum_bank, dbf_elevation_spectrum_bank, + evaluate_dbf_axis, ) from .dbf_dictionary import DbfDictionaryConfig from .element_pattern import ChannelPatternSet, ElementPattern, virtual_channel_names from .geometry import AntennaArray +from .requirements import STATUS_FAIL, STATUS_PASS, RequirementCheck REPORT_SCHEMA_VERSION = 1 LIGHT_SPEED_MM_PER_NS = 299.792458 @@ -218,6 +221,11 @@ class PerformanceReportSnapshot: current_config: dict[str, Any] app_version: str created_at: datetime + # FOV-bounded evaluation with refined peaks (web server); None keeps the + # legacy ±90° scan-grid behaviour. + evaluation: EvaluationSettings | None = None + requirement_checks: tuple[RequirementCheck, ...] = () + band_ghz: tuple[float, float] | None = None @dataclass(frozen=True) @@ -636,6 +644,14 @@ def _compute_report_data( options: PerformanceReportOptions, ) -> _PerformanceReportData: unique, counts = snapshot.array.unique_virtual_xy() + fov_kwargs = ( + { + "azimuth_fov": snapshot.evaluation.azimuth_fov_deg, + "elevation_fov": snapshot.evaluation.elevation_fov_deg, + } + if snapshot.evaluation is not None + else {} + ) af_db, azimuths, elevations, metrics = calculate_metrics_and_psf( snapshot.array, unique, @@ -643,6 +659,7 @@ def _compute_report_data( tx_pattern=snapshot.element_pattern, rx_pattern=snapshot.element_pattern, channel_patterns=snapshot.channel_patterns, + **fov_kwargs, ) axes: list[_AxisReportData] = [] axis_specs = ( @@ -740,6 +757,24 @@ def _compute_angle_error_axis( axis: str, bank_function: Callable[..., tuple[np.ndarray, np.ndarray, np.ndarray]], ) -> _AngleErrorAxisData: + if snapshot.evaluation is not None: + evaluation = evaluate_dbf_axis( + snapshot.array, + axis, + snapshot.evaluation, + channel_patterns=snapshot.channel_patterns, + dbf_dictionary=snapshot.dbf_dictionary, + ambiguity_margin_db=snapshot.ambiguity_margin_db, + ) + return _AngleErrorAxisData( + axis=axis, + true_angles_deg=evaluation.true_angles_deg, + scan_angles_deg=evaluation.scan_angles_deg, + spectra_db=evaluation.spectra_db, + frame_series=evaluation.frame_series, + angle_metrics=evaluation.metrics, + display_range=angle_error_data_range(snapshot, axis, evaluation.true_angles_deg), + ) true_angles, scan_angles, spectra = bank_function( snapshot.array, tx_pattern=snapshot.element_pattern, @@ -1712,14 +1747,7 @@ def _report_manifest( "application_version": snapshot.app_version, "language": options.language, "frequency_ghz": snapshot.frequency_ghz, - "dbf_scan": { - "minimum_deg": DBF_SCAN_FOV[0], - "maximum_deg": DBF_SCAN_FOV[1], - "step_deg": DBF_SCAN_STEP_DEG, - "normalization": "normalized complex correlation; 0 dB equals correlation 1", - "peak_interpolation": "none; discrete scan-grid peak", - "tie_policy": "deterministic first maximum for performance metrics", - }, + "dbf_scan": _scan_manifest(snapshot), "spectrum_plots": { "db_enabled": options.include_spectrum_db, "normalized_magnitude_enabled": options.include_spectrum_magnitude, @@ -1727,9 +1755,30 @@ def _report_manifest( "layout": "one DBF spectrum plot per PDF page", }, "array_factor_fov": { - "azimuth_deg": list(AZIMUTH_FOV), - "elevation_deg": list(ELEVATION_FOV), + "azimuth_deg": list( + snapshot.evaluation.azimuth_fov_deg if snapshot.evaluation else AZIMUTH_FOV + ), + "elevation_deg": list( + snapshot.evaluation.elevation_fov_deg if snapshot.evaluation else ELEVATION_FOV + ), }, + "band_ghz": list(snapshot.band_ghz) if snapshot.band_ghz else None, + "requirement_checks": [ + { + "key": check.key, + "axis": check.axis, + "target": check.target, + "actual": ( + None + if check.actual is None + else float(check.actual) + if math.isfinite(check.actual) + else str(check.actual) + ), + "status": check.status, + } + for check in snapshot.requirement_checks + ], "thresholds": { "ambiguity_margin_db_strictly_greater_than": snapshot.ambiguity_margin_db, "absolute_error_limit_deg": options.error_limit_deg, @@ -1786,6 +1835,35 @@ def _report_manifest( } +def _scan_manifest(snapshot: PerformanceReportSnapshot) -> dict[str, Any]: + common = { + "step_deg": DBF_SCAN_STEP_DEG, + "normalization": "normalized complex correlation; 0 dB equals correlation 1", + "tie_policy": "deterministic first maximum for performance metrics", + } + settings = snapshot.evaluation + if settings is None: + return { + "minimum_deg": DBF_SCAN_FOV[0], + "maximum_deg": DBF_SCAN_FOV[1], + "peak_interpolation": "none; discrete scan-grid peak", + **common, + } + return { + "true_angle_fov_deg": { + "azimuth": list(settings.azimuth_fov_deg), + "elevation": list(settings.elevation_fov_deg), + }, + "search_guard_deg": settings.search_guard_deg, + "peak_interpolation": ( + "local re-evaluation of the correlation around the scan-grid peak (0.002° resolution)" + if settings.refine_peaks + else "none; discrete scan-grid peak" + ), + **common, + } + + def _dictionary_metadata(dictionary: DbfDictionaryConfig) -> dict[str, Any]: return { "mode": dictionary.mode, @@ -1966,8 +2044,10 @@ def _basic_metric_rows( [ "PSL / ISLR", ( - f"Az {metrics.azimuth_psl_db:.2f} dB; El {metrics.elevation_psl_db:.2f} dB; " - f"2D {metrics.psl_db:.2f} dB; Az ISLR {_format_number(metrics.azimuth_islr_db, ' dB')}" + f"Az {_format_number(metrics.azimuth_psl_db, ' dB')}; " + f"El {_format_number(metrics.elevation_psl_db, ' dB')}; " + f"2D {_format_number(metrics.psl_db, ' dB')}; " + f"Az ISLR {_format_number(metrics.azimuth_islr_db, ' dB')}" ), ], [ @@ -1979,17 +2059,41 @@ def _basic_metric_rows( f"{_format_db_angle(metrics.azimuth_grating_lobe_db, metrics.azimuth_grating_lobe_angle)}" ), ], - [ - _label(language, "capability"), - ( - f"{_status_label(metrics.front_radar_status, language)}; " - f"{_label(language, 'elevation_ambiguity')} " - f"{_ambiguity_label(metrics.elevation_ambiguity_level, language)}" - ), - ], + *_requirement_rows(snapshot, language), ] +def _requirement_rows(snapshot: PerformanceReportSnapshot, language: str) -> list[list[str]]: + rows: list[list[str]] = [] + if snapshot.evaluation is not None: + fov = snapshot.evaluation + text = ( + f"Az {fov.azimuth_fov_deg[0]:g}°..{fov.azimuth_fov_deg[1]:g}°; " + f"El {fov.elevation_fov_deg[0]:g}°..{fov.elevation_fov_deg[1]:g}°" + ) + if snapshot.band_ghz is not None: + text += f"; {_label(language, 'band')} {snapshot.band_ghz[0]:g}–{snapshot.band_ghz[1]:g} GHz" + rows.append([_label(language, "evaluation_fov"), text]) + if snapshot.requirement_checks: + passed = sum(check.status == STATUS_PASS for check in snapshot.requirement_checks) + applicable = sum(check.status in {STATUS_PASS, STATUS_FAIL} for check in snapshot.requirement_checks) + failed = [ + _requirement_label(check, language) + for check in snapshot.requirement_checks + if check.status == STATUS_FAIL + ] + summary = f"{passed}/{applicable} {_label(language, 'requirements_passed')}" + if failed: + summary += f"; {_label(language, 'requirements_failed')}: " + ", ".join(failed) + rows.append([_label(language, "requirements"), summary]) + return rows + + +def _requirement_label(check: RequirementCheck, language: str) -> str: + axis = f"{_axis_label(check.axis, language)} " if check.axis else "" + return f"{axis}{_label(language, 'requirement_' + check.key)}" + + def _axis_summary_row(axis_data: _AxisReportData, language: str) -> list[str]: summary = axis_data.focus_summary metrics = axis_data.angle_metrics @@ -2268,6 +2372,16 @@ def _label(language: str, key: str) -> str: "first_sidelobe": {"zh": "首旁瓣", "en": "first sidelobe", "ja": "第1サイドローブ"}, "grating_lobe": {"zh": "栅瓣", "en": "grating lobe", "ja": "グレーティングローブ"}, "capability": {"zh": "前视能力评价", "en": "Front-radar capability", "ja": "前方レーダー能力"}, + "evaluation_fov": {"zh": "评估视场", "en": "Evaluation FOV", "ja": "評価視野"}, + "band": {"zh": "频段", "en": "band", "ja": "周波数帯"}, + "requirements": {"zh": "规格检查", "en": "Requirement checks", "ja": "仕様チェック"}, + "requirements_passed": {"zh": "项通过", "en": "passed", "ja": "項目合格"}, + "requirements_failed": {"zh": "未通过", "en": "failed", "ja": "不合格"}, + "requirement_resolution": {"zh": "分辨率", "en": "resolution", "ja": "分解能"}, + "requirement_unambiguous_fov": {"zh": "视场内不模糊", "en": "unambiguous FOV", "ja": "視野内曖昧なし"}, + "requirement_max_error": {"zh": "视场内最大误差", "en": "max error in FOV", "ja": "視野内最大誤差"}, + "requirement_peak_margin": {"zh": "竞争峰裕量", "en": "peak margin", "ja": "競合ピークマージン"}, + "requirement_psl": {"zh": "峰值旁瓣电平", "en": "peak sidelobe level", "ja": "ピークサイドローブ"}, "elevation_ambiguity": {"zh": "俯仰模糊度", "en": "elevation ambiguity", "ja": "仰角曖昧度"}, "note_main_plane": { "zh": "方位与俯仰结果是正交主平面 1D 诊断:方位扫描固定真实俯仰 0°,俯仰扫描固定真实方位 0°;不等同于完整联合二维误差体验证。", diff --git a/src/virtual_array/project.py b/src/virtual_array/project.py index d55fb93..dc69a6f 100644 --- a/src/virtual_array/project.py +++ b/src/virtual_array/project.py @@ -12,6 +12,7 @@ from __future__ import annotations +import contextlib import math from typing import Any, Literal @@ -43,6 +44,18 @@ AUTO_LAYOUT_RX_Y_LAMBDA = -2.0 COORDINATE_LIMIT_LAMBDA = 500.0 LIGHT_SPEED_MM_PER_NS = 299.792458 +GRID_STEPS_LAMBDA = (0.5, 0.25, 0.125, 0.0) +DEFAULT_AZIMUTH_FOV = (-75, 75) +DEFAULT_ELEVATION_FOV = (-15, 15) + +# FMCW radar band presets: sweep range and the design (λ reference) frequency. +# 92 GHz has no single harmonised allocation; the 90–94 GHz default is a +# placeholder that projects should overwrite with their chip's sweep range. +BAND_PRESETS: dict[str, dict[str, float]] = { + "60G": {"start_ghz": 57.0, "stop_ghz": 64.0, "design_ghz": 60.0}, + "77G": {"start_ghz": 76.0, "stop_ghz": 81.0, "design_ghz": 77.0}, + "92G": {"start_ghz": 90.0, "stop_ghz": 94.0, "design_ghz": 92.0}, +} LAYOUT_UNITS_LAMBDA = {"lambda", "λ"} LEGACY_LAYOUT_UNITS_HALF_LAMBDA = {"lambda/2", "λ/2"} @@ -119,16 +132,80 @@ class ChannelPatternBinding(_Model): column: str = "" +class Band(_Model): + """FMCW sweep range of the radar the array is designed for.""" + + preset: Literal["60G", "77G", "92G", "custom"] = "77G" + start_ghz: float = Field(default=76.0, gt=0.0, le=1000.0) + stop_ghz: float = Field(default=81.0, gt=0.0, le=1000.0) + + @model_validator(mode="after") + def _ordered(self) -> Band: + if self.start_ghz >= self.stop_ghz: + raise ValueError("Band start frequency must be below the stop frequency.") + return self + + +class FieldOfView(_Model): + """Angular coverage the radar must serve; bounds all angle evaluations.""" + + azimuth: tuple[int, int] = DEFAULT_AZIMUTH_FOV + elevation: tuple[int, int] = DEFAULT_ELEVATION_FOV + + @field_validator("azimuth", "elevation") + @classmethod + def _contains_boresight(cls, value: tuple[int, int]) -> tuple[int, int]: + low, high = value + if not (-90 <= low < 0 < high <= 90): + raise ValueError("FOV must satisfy -90 <= start < 0 < stop <= 90 degrees.") + return value + + +class Requirements(_Model): + """Optional pass/fail targets; ``None`` means not checked.""" + + azimuth_resolution_deg: float | None = Field(default=None, gt=0.0, le=180.0) + elevation_resolution_deg: float | None = Field(default=None, gt=0.0, le=180.0) + azimuth_unambiguous_fov: bool = True + elevation_unambiguous_fov: bool = True + max_abs_error_deg: float | None = Field(default=None, gt=0.0, le=90.0) + min_peak_margin_db: float | None = Field(default=None, ge=0.0, le=60.0) + max_psl_db: float | None = Field(default=None, le=0.0, ge=-80.0) + + class Project(_Model): version: int = PROJECT_SCHEMA_VERSION name: str = Field(default="未命名阵列", max_length=120) + # Design frequency: the layout's λ is defined at this frequency. frequency_ghz: float = Field(default=DEFAULT_FREQUENCY_GHZ, gt=0.0, le=1000.0) ambiguity_margin_db: float = Field(default=DEFAULT_AMBIGUITY_MARGIN_DB, ge=0.0, le=60.0) + band: Band = Field(default_factory=Band) + fov: FieldOfView = Field(default_factory=FieldOfView) + grid_step_lambda: float = 0.5 + requirements: Requirements = Field(default_factory=Requirements) layout: Layout dbf_dictionary: DictionarySettings = Field(default_factory=DictionarySettings) element_pattern: ElementPatternSettings | None = None channel_patterns: list[ChannelPatternBinding] = Field(default_factory=list) + @model_validator(mode="before") + @classmethod + def _infer_band(cls, data: Any) -> Any: + # Documents written before bands existed: pick the preset containing + # the design frequency instead of silently defaulting to 77 GHz. + if isinstance(data, dict) and "band" not in data: + frequency = data.get("frequency_ghz", DEFAULT_FREQUENCY_GHZ) + with contextlib.suppress(TypeError, ValueError): + data = {**data, "band": band_for_frequency(float(frequency)).model_dump()} + return data + + @field_validator("grid_step_lambda") + @classmethod + def _known_grid(cls, value: float) -> float: + if value not in GRID_STEPS_LAMBDA: + raise ValueError(f"grid_step_lambda must be one of {GRID_STEPS_LAMBDA}.") + return value + @property def tx_names(self) -> list[str]: return [f"Tx{index}" for index in range(1, len(self.layout.tx) + 1)] @@ -159,19 +236,39 @@ def asset_ids(self) -> set[str]: return ids +def band_for_frequency(frequency_ghz: float) -> Band: + """The preset whose sweep contains the frequency, else a ±2.5% custom band.""" + for name, preset in BAND_PRESETS.items(): + if preset["start_ghz"] <= frequency_ghz <= preset["stop_ghz"]: + return Band(preset=name, start_ghz=preset["start_ghz"], stop_ghz=preset["stop_ghz"]) + return Band( + preset="custom", + start_ghz=round(frequency_ghz * 0.975, 3), + stop_ghz=round(frequency_ghz * 1.025, 3), + ) + + def snap_lambda(value: float) -> float: """Snap a λ coordinate to the λ/2 editor grid.""" return round(value / GRID_STEP_LAMBDA) * GRID_STEP_LAMBDA + 0.0 -def project_array(project: Project) -> AntennaArray: - """Build the core array (λ/2 units) from a project.""" +def project_array(project: Project, operating_frequency_ghz: float | None = None) -> AntennaArray: + """Build the core array (λ/2 units) from a project. + + The layout is physical: its λ is defined at the design frequency. At an + operating frequency ``f`` the electrical positions scale by ``f / f_design`` + (the antennas do not move, the wavelength does). + """ + scale = HALF_LAMBDA_PER_LAMBDA + if operating_frequency_ghz is not None: + scale *= float(operating_frequency_ghz) / project.frequency_ghz tx = [ - ArrayPoint(name=name, x=point.x * HALF_LAMBDA_PER_LAMBDA, y=point.y * HALF_LAMBDA_PER_LAMBDA) + ArrayPoint(name=name, x=point.x * scale, y=point.y * scale) for name, point in zip(project.tx_names, project.layout.tx) ] rx = [ - ArrayPoint(name=name, x=point.x * HALF_LAMBDA_PER_LAMBDA, y=point.y * HALF_LAMBDA_PER_LAMBDA) + ArrayPoint(name=name, x=point.x * scale, y=point.y * scale) for name, point in zip(project.rx_names, project.layout.rx) ] return AntennaArray(tx=tx, rx=rx) @@ -200,7 +297,7 @@ def default_project() -> Project: scale = 1.0 / HALF_LAMBDA_PER_LAMBDA return Project( - name="Case4 8T8R", + name="Case4 8T8R 77G", layout=Layout( tx=[Point(x=x * scale, y=y * scale) for x, y in zip(TX_X, TX_Y)], rx=[Point(x=x * scale, y=y * scale) for x, y in zip(RX_X, RX_Y)], @@ -212,7 +309,9 @@ def layout_from_v1(config: Any) -> Layout: """Parse a desktop-tool layout JSON (version 1) into a layout. Element names in the file are ignored: channels are numbered by list - order, exactly as the desktop importer did. + order, exactly as the desktop importer did. Coordinates are kept as + given (the desktop importer snapped them to λ/2, which silently moved + off-grid antennas of real layouts). """ if not isinstance(config, dict): raise ValueError("Layout config must be a JSON object.") @@ -237,8 +336,8 @@ def layout_from_v1(config: Any) -> Layout: if not isinstance(raw_point, dict): raise ValueError(f"{kind}[{index}] must be an object.") try: - x = snap_lambda(float(raw_point["x"]) * scale) - y = snap_lambda(float(raw_point["y"]) * scale) + x = _clean(float(raw_point["x"]) * scale) + y = _clean(float(raw_point["y"]) * scale) parsed.append(Point(x=x, y=y)) except KeyError as exc: raise ValueError(f"{kind}[{index}] is missing coordinate {exc}.") from exc @@ -262,6 +361,7 @@ def project_from_document(document: Any) -> Project: updates: dict[str, Any] = {} if frequency is not None and frequency > 0: updates["frequency_ghz"] = frequency + updates["band"] = band_for_frequency(frequency) if margin is not None and margin >= 0: updates["ambiguity_margin_db"] = margin if updates: @@ -291,6 +391,11 @@ def layout_to_v1(project: Project, evaluation: dict[str, Any] | None = None) -> return document +def _clean(value: float) -> float: + rounded = round(value, 9) + return 0.0 if rounded == 0 else rounded + + def json_number(value: float | None, digits: int = 6) -> float | int | None: if value is None or not math.isfinite(value): return None @@ -325,7 +430,11 @@ def _parse_number(value: Any) -> float | None: "DBF_DICT_CUSTOM", "DBF_DICT_IDEAL", "DBF_DICT_IDEAL_REVERSED", + "BAND_PRESETS", + "Band", "ChannelPatternBinding", + "FieldOfView", + "Requirements", "DictionarySettings", "ElementPatternSettings", "Layout", diff --git a/src/virtual_array/requirements.py b/src/virtual_array/requirements.py new file mode 100644 index 0000000..c39687a --- /dev/null +++ b/src/virtual_array/requirements.py @@ -0,0 +1,130 @@ +"""Pass/fail checks of array performance against project requirements. + +Requirements replace the former fixed automotive "front radar" grading: a +60 GHz presence sensor, a 77 GHz corner radar and a 92 GHz imaging radar have +very different targets, so each project states its own. Every requirement is +optional; unset requirements are not checked. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +from .analysis import ArrayMetrics, DbfAngleMetrics + +STATUS_PASS = "pass" +STATUS_FAIL = "fail" +STATUS_NOT_APPLICABLE = "na" + + +@dataclass(frozen=True) +class RequirementSpec: + azimuth_resolution_deg: float | None = None + elevation_resolution_deg: float | None = None + azimuth_unambiguous_fov: bool = True + elevation_unambiguous_fov: bool = True + max_abs_error_deg: float | None = None + min_peak_margin_db: float | None = None + max_psl_db: float | None = None + + +@dataclass(frozen=True) +class RequirementCheck: + key: str + axis: str | None + target: float | None + actual: float | None + status: str + + +def measured_resolution(metrics: ArrayMetrics, axis: str) -> float | None: + """3 dB beamwidth of the actual array response, else the aperture estimate.""" + if axis == "azimuth": + measured, estimate = metrics.azimuth_3db_beamwidth, metrics.azimuth_resolution + else: + measured, estimate = metrics.elevation_3db_beamwidth, metrics.elevation_resolution + if estimate is None: + return None + return measured if measured is not None else estimate + + +def check_requirements( + spec: RequirementSpec, + metrics: ArrayMetrics, + angle: dict[str, DbfAngleMetrics | None], + fov: dict[str, tuple[float, float]], +) -> list[RequirementCheck]: + checks: list[RequirementCheck] = [] + for axis, limit in ( + ("azimuth", spec.azimuth_resolution_deg), + ("elevation", spec.elevation_resolution_deg), + ): + if limit is None: + continue + actual = measured_resolution(metrics, axis) + status = STATUS_PASS if actual is not None and actual <= limit else STATUS_FAIL + checks.append(RequirementCheck("resolution", axis, limit, actual, status)) + + for axis, required in ( + ("azimuth", spec.azimuth_unambiguous_fov), + ("elevation", spec.elevation_unambiguous_fov), + ): + if not required: + continue + axis_metrics = angle.get(axis) + low, high = fov[axis] + if axis_metrics is None: + checks.append(RequirementCheck("unambiguous_fov", axis, high - low, None, STATUS_NOT_APPLICABLE)) + continue + left, right = axis_metrics.no_fold_left, axis_metrics.no_fold_right + covered = ( + left is not None + and right is not None + and left <= low + 1e-9 + and right >= high - 1e-9 + ) + width = axis_metrics.no_fold_width + checks.append( + RequirementCheck( + "unambiguous_fov", + axis, + high - low, + width, + STATUS_PASS if covered else STATUS_FAIL, + ) + ) + + if spec.max_abs_error_deg is not None: + for axis in ("azimuth", "elevation"): + axis_metrics = angle.get(axis) + if axis_metrics is None: + continue + actual = axis_metrics.focus_max_abs_error + ok = actual is not None and math.isfinite(actual) and actual <= spec.max_abs_error_deg + checks.append( + RequirementCheck( + "max_error", axis, spec.max_abs_error_deg, actual, STATUS_PASS if ok else STATUS_FAIL + ) + ) + + if spec.min_peak_margin_db is not None: + for axis in ("azimuth", "elevation"): + axis_metrics = angle.get(axis) + if axis_metrics is None: + continue + actual = axis_metrics.min_peak_margin_db + ok = actual is not None and actual >= spec.min_peak_margin_db + checks.append( + RequirementCheck( + "peak_margin", axis, spec.min_peak_margin_db, actual, STATUS_PASS if ok else STATUS_FAIL + ) + ) + + if spec.max_psl_db is not None: + actual = metrics.psl_db + ok = not math.isfinite(actual) or actual <= spec.max_psl_db + checks.append( + RequirementCheck("psl", None, spec.max_psl_db, actual, STATUS_PASS if ok else STATUS_FAIL) + ) + return checks diff --git a/src/virtual_array/server/app.py b/src/virtual_array/server/app.py index b85dc95..b7f3096 100644 --- a/src/virtual_array/server/app.py +++ b/src/virtual_array/server/app.py @@ -21,7 +21,9 @@ from ..engine import Engine, ProjectComputationError from ..logging_config import configure_logging from ..project import ( + BAND_PRESETS, GRID_STEP_LAMBDA, + GRID_STEPS_LAMBDA, MAX_RX_COUNT, MAX_TX_COUNT, ChannelPatternBinding, @@ -136,6 +138,10 @@ class SaveProjectRequest(ProjectRequest): pass +class CompareRequest(BaseModel): + projects: list[Project] = Field(min_length=1, max_length=8) + + # ── Application ────────────────────────────────────────────────────── @@ -203,7 +209,9 @@ def config() -> dict[str, Any]: "grid_step_lambda": GRID_STEP_LAMBDA, "max_asset_bytes": MAX_ASSET_BYTES, "max_2d_frames_per_request": MAX_2D_FRAMES_PER_REQUEST, + "grid_steps_lambda": list(GRID_STEPS_LAMBDA), }, + "band_presets": BAND_PRESETS, "dbf": { "scan_fov": list(DBF_SCAN_FOV), "scan_step_deg": DBF_SCAN_STEP_DEG, @@ -221,6 +229,14 @@ def layout_auto(request: AutoLayoutRequest) -> Layout: def evaluate(request: ProjectRequest) -> dict[str, Any]: return engine.evaluate(request.project) + @app.post("/api/band") + def band_sweep(request: ProjectRequest) -> dict[str, Any]: + return engine.band_sweep(request.project) + + @app.post("/api/compare") + def compare(request: CompareRequest) -> list[dict[str, Any]]: + return engine.compare(request.projects) + @app.post("/api/dbf/bank") def dbf_bank(request: BankRequest) -> dict[str, Any]: return engine.dbf_bank(request.project, request.axis) diff --git a/tests/test_analysis.py b/tests/test_analysis.py index ca44954..d112d81 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, + EvaluationSettings, calculate_metrics_and_psf, dbf_2d_normalization_reference, dbf_2d_spectrum, @@ -15,13 +16,17 @@ dbf_azimuth_angle_metrics, dbf_azimuth_spectrum, dbf_azimuth_spectrum_bank, + dbf_elevation_angle_metrics, dbf_elevation_spectrum, dbf_elevation_spectrum_bank, dbf_peak_index, estimate_resolution, + evaluate_dbf_axis, ) +from virtual_array.dbf_dictionary import DbfDictionaryConfig from virtual_array.element_pattern import ( PATTERN_KIND_AMPLITUDE, + PATTERN_KIND_PHASE, PATTERN_PLANE_HORIZONTAL, ChannelPatternSet, PatternSeries, @@ -77,8 +82,43 @@ def test_single_element_array_factor_is_flat() -> None: assert np.allclose(af_db, 0.0) assert metrics.azimuth_resolution is None assert metrics.elevation_resolution is None - assert metrics.azimuth_psl_db == pytest.approx(0.0) - assert metrics.psl_grade == "Bad" + # No aperture on either axis: the whole FOV is main lobe, so no sidelobe exists. + assert np.isneginf(metrics.azimuth_psl_db) + assert np.isneginf(metrics.psl_db) + + +def test_small_ula_psl_uses_first_null_mainlobe() -> None: + # 4-element λ/2 ULA (e.g. a 60 GHz 1T4R module): wide beam, -11.3 dB sidelobes. + array = AntennaArray.from_xy(tx_x=[0], tx_y=[0], rx_x=[0, 1, 2, 3], rx_y=[0, 0, 0, 0]) + + _af, _az, _el, metrics = calculate_metrics_and_psf(array) + + assert metrics.azimuth_psl_db == pytest.approx(-11.30, abs=0.05) + assert metrics.psl_db == pytest.approx(-11.30, abs=0.05) + assert np.isneginf(metrics.elevation_psl_db) + assert metrics.elevation_ambiguity_level == "Low" + + +def test_twelve_element_virtual_ula_psl_matches_uniform_theory() -> None: + array = AntennaArray.from_xy( + tx_x=[0, 4, 8], tx_y=[0, 0, 0], rx_x=[0, 1, 2, 3], rx_y=[0, 0, 0, 0] + ) + + _af, _az, _el, metrics = calculate_metrics_and_psf(array) + + assert metrics.azimuth_psl_db == pytest.approx(-13.1, abs=0.15) + assert metrics.azimuth_3db_beamwidth == pytest.approx(8.46, abs=0.1) + + +def test_metrics_follow_configured_fov() -> None: + array = build_array() + + _af, azimuths, elevations, _metrics = calculate_metrics_and_psf( + array, azimuth_fov=(-60.0, 60.0), elevation_fov=(-30.0, 30.0) + ) + + assert azimuths[0] == -60.0 and azimuths[-1] == 60.0 + assert elevations[0] == -30.0 and elevations[-1] == 30.0 def test_dbf_azimuth_spectrum_defaults_to_full_scan_range() -> None: @@ -461,3 +501,74 @@ def test_dbf_angle_metrics_treat_flat_spectrum_as_unusable() -> None: def test_estimate_resolution_uses_half_lambda_aperture_units() -> None: assert estimate_resolution(0.0) is None assert estimate_resolution(75.0) == pytest.approx(1.3537, abs=1e-4) + + +def test_evaluation_settings_bound_true_and_scan_angles() -> None: + settings = EvaluationSettings(azimuth_fov_deg=(-60, 60), elevation_fov_deg=(-15, 15)) + + assert settings.true_angles("azimuth")[[0, -1]].tolist() == [-60.0, 60.0] + assert settings.scan_angles("azimuth")[[0, -1]].tolist() == [-70.0, 70.0] + assert settings.scan_angles("elevation")[[0, -1]].tolist() == [-25.0, 25.0] + with pytest.raises(ValueError): + EvaluationSettings(azimuth_fov_deg=(5, 60)) + + +def test_fov_bounded_evaluation_ignores_out_of_fov_grating_lobes() -> None: + # case4 elevation virtual spacing is λ: grating lobes at ±90° make the + # full-hemisphere search ambiguous, but a ±15° radar FOV is unambiguous. + array = build_array() + + full = dbf_elevation_angle_metrics(array) + bounded = evaluate_dbf_axis(array, "elevation", EvaluationSettings()).metrics + + assert full.no_fold_width == 0.0 + assert bounded.no_fold_left == -15.0 + assert bounded.no_fold_right == 15.0 + + +def test_refined_peaks_are_exact_for_ideal_array_and_resolve_subdegree_errors() -> None: + array = AntennaArray.from_xy( + tx_x=[0, 4, 8], tx_y=[0, 0, 0], rx_x=[0, 1, 2, 3], rx_y=[0, 0, 0, 0] + ) + ideal = evaluate_dbf_axis(array, "azimuth", EvaluationSettings()) + assert np.max(np.abs(ideal.frame_series.errors_deg)) < 0.005 + + # Imported phase cuts carry the geometry; a 3°-per-element error on the Rx + # steers the beam by a fraction of a degree: invisible on the 1° scan + # grid, resolved by the refinement. + angles = np.arange(-90.0, 91.0, 1.0) + geometry = {"Tx1": 0, "Tx2": 4, "Tx3": 8, "Rx1": 0, "Rx2": 1, "Rx3": 2, "Rx4": 3} + patterns = ChannelPatternSet() + for name, x in geometry.items(): + error = 3.0 * (x if name.startswith("Rx") else 0) + patterns.set_series( + name, + PATTERN_KIND_PHASE, + PATTERN_PLANE_HORIZONTAL, + PatternSeries( + name="phase.csv", + source_path="phase.csv", + angle_column="Theta", + value_column=name, + value_kind=PATTERN_KIND_PHASE, + angles_deg=angles, + values=np.degrees(np.pi * x * np.sin(np.radians(angles))) + error, + ), + ) + coarse = evaluate_dbf_axis( + array, + "azimuth", + EvaluationSettings(refine_peaks=False), + channel_patterns=patterns, + dbf_dictionary=DbfDictionaryConfig(mode="ideal"), + ) + refined = evaluate_dbf_axis( + array, + "azimuth", + EvaluationSettings(), + channel_patterns=patterns, + dbf_dictionary=DbfDictionaryConfig(mode="ideal"), + ) + 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 diff --git a/tests/test_project.py b/tests/test_project.py index 86596f3..0d95331 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -43,7 +43,7 @@ def test_layout_v1_example_imports_with_lambda_coordinates() -> None: assert layout.rx[6] == Point(x=9, y=5) -def test_layout_v1_snaps_to_half_lambda_grid_and_accepts_legacy_unit() -> None: +def test_layout_v1_keeps_exact_coordinates_and_accepts_legacy_unit() -> None: layout = layout_from_v1( { "version": 1, @@ -53,8 +53,9 @@ def test_layout_v1_snaps_to_half_lambda_grid_and_accepts_legacy_unit() -> None: } ) - assert layout.tx[0] == Point(x=1.5, y=-0.5) - assert layout.rx[0] == Point(x=0.0, y=0.0) + # Real layouts are not always on the λ/2 grid; import must not move antennas. + assert layout.tx[0] == Point(x=1.5, y=-0.6) + assert layout.rx[0] == Point(x=0.2, y=0.0) @pytest.mark.parametrize( diff --git a/tests/test_server.py b/tests/test_server.py index fc709e8..d363b19 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -12,8 +12,9 @@ from virtual_array.analysis import ( Dbf2dScanner, + EvaluationSettings, dbf_2d_spectrum, - dbf_azimuth_spectrum_bank, + evaluate_dbf_axis, ) from virtual_array.element_pattern import ( PATTERN_KIND_PHASE, @@ -166,12 +167,13 @@ def test_evaluate_rejects_invalid_project(client, project) -> None: def test_dbf_bank_matches_core_computation(client, project) -> None: result = client.post("/api/dbf/bank", json={"project": project, "axis": "azimuth"}).json() - _true, _scan, expected = dbf_azimuth_spectrum_bank(build_array()) + expected = evaluate_dbf_axis(build_array(), "azimuth", EvaluationSettings()) spectra = decode(result["spectra_db"]) - assert spectra.shape == (181, 181) - assert np.allclose(spectra, expected, atol=1e-4) - assert len(result["frames"]["errors"]) == 181 - assert result["frames"]["quality"][90] == "normal" + # Default FOV ±75° (true angles) with a 10° search guard (scan ±85°). + assert spectra.shape == (151, 171) + assert np.allclose(spectra, expected.spectra_db, atol=1e-4) + assert len(result["frames"]["errors"]) == 151 + assert result["frames"]["quality"][75] == "normal" def test_dbf_2d_returns_frames(client, project) -> None: @@ -182,7 +184,8 @@ def test_dbf_2d_returns_frames(client, project) -> None: assert response.status_code == 200 frame = response.json()["frames"][0] - assert decode(frame["spectrum_db"]).shape == (181, 181) + # Scan grid: azimuth ±85°, elevation ±25° (FOV plus search guard). + assert decode(frame["spectrum_db"]).shape == (51, 171) assert frame["peak_azimuth"] == pytest.approx(10.0) @@ -291,7 +294,7 @@ def test_custom_dictionary_preview_and_mismatch_error(client) -> None: assert preview["channel_count"] == 6 assert preview["tables"]["azimuth"]["channel_mode"] == "virtual" - assert decode(preview["phase_deg"]).shape == (181, 6) + assert decode(preview["phase_deg"]).shape == (171, 6) assert mismatch.status_code == 422 assert "virtual channel" in mismatch.json()["detail"] @@ -396,3 +399,119 @@ def test_report_rejects_invalid_options(client) -> None: assert response.status_code == 422 assert client.get("/api/jobs/" + "f" * 32).status_code == 404 + + +# ── Radar-band evaluation ──────────────────────────────────────────── + + +def test_config_exposes_band_presets(client) -> None: + presets = client.get("/api/config").json()["band_presets"] + assert presets["60G"] == {"start_ghz": 57.0, "stop_ghz": 64.0, "design_ghz": 60.0} + assert set(presets) == {"60G", "77G", "92G"} + + +def test_evaluate_reports_measured_resolution_fov_and_requirements(client, project) -> None: + project["requirements"] = {"azimuth_resolution_deg": 1.5, "max_psl_db": -10} + + result = client.post("/api/evaluate", json={"project": project}).json() + + assert result["fov"] == {"azimuth": [-75, 75], "elevation": [-15, 15]} + assert result["resolution"]["azimuth"]["measured"] == pytest.approx(1.72, abs=0.01) + assert result["resolution"]["azimuth"]["estimate"] == pytest.approx(1.354, abs=0.01) + # case4 elevation virtual spacing is λ, but the ±15° FOV is unambiguous. + assert result["angle"]["elevation"]["no_fold_left"] == -15 + statuses = {(c["key"], c["axis"]): c["status"] for c in result["requirements"]} + assert statuses[("resolution", "azimuth")] == "fail" + assert statuses[("unambiguous_fov", "azimuth")] == "pass" + assert statuses[("unambiguous_fov", "elevation")] == "pass" + assert statuses[("psl", None)] == "fail" + assert "resolution_optimistic" in result["notes"] + + +def test_dbf_bank_is_bounded_by_fov_with_search_guard(client, project) -> None: + project["fov"] = {"azimuth": [-60, 60], "elevation": [-20, 20]} + + result = client.post("/api/dbf/bank", json={"project": project, "axis": "azimuth"}).json() + + assert result["true_angles"][0] == -60 and result["true_angles"][-1] == 60 + assert result["scan_angles"][0] == -70 and result["scan_angles"][-1] == 70 + assert decode(result["spectra_db"]).shape == (121, 141) + assert max(abs(e) for e in result["frames"]["errors"]) < 0.01 + + +def test_layout_checks_flag_overlapping_antennas(client) -> None: + project = small_project() + project["layout"]["rx"][1] = {"x": 0.25, "y": -2} + project["layout"]["tx"][1] = {"x": 0, "y": 0} + + checks = client.post("/api/evaluate", json={"project": project}).json()["layout_checks"] + + assert checks[0]["code"] == "coincident" + assert {checks[0]["a"], checks[0]["b"]} == {"Tx1", "Tx2"} + assert any(c["code"] == "too_close" and c["distance_lambda"] == 0.25 for c in checks) + + +def test_band_sweep_scales_electrical_spacing_with_frequency(client) -> None: + project = default_project().model_dump(mode="json") + project["frequency_ghz"] = 60.0 + project["band"] = {"preset": "60G", "start_ghz": 57.0, "stop_ghz": 64.0} + project["fov"] = {"azimuth": [-90, 90], "elevation": [-15, 15]} + # λ/2 ULA at 60 GHz: unambiguous over ±90° only up to the design frequency. + project["layout"] = { + "tx": [{"x": 0, "y": 0}, {"x": 2, "y": 0}], + "rx": [{"x": 0, "y": 0}, {"x": 0.5, "y": 0}, {"x": 1, "y": 0}, {"x": 1.5, "y": 0}], + } + + sweep = client.post("/api/band", json={"project": project}).json() + + assert [p["frequency_ghz"] for p in sweep["points"]] == [57.0, 60.0, 64.0] + assert [p["role"] for p in sweep["points"]] == ["start", "design", "stop"] + resolution = [p["resolution"]["azimuth"]["value"] for p in sweep["points"]] + assert resolution[0] > resolution[1] > resolution[2] + width_at_stop = sweep["points"][2]["angle"]["azimuth"]["no_fold_width"] + width_at_design = sweep["points"][1]["angle"]["azimuth"]["no_fold_width"] + assert width_at_stop < width_at_design + + +def test_compare_summarises_several_projects(client, project) -> None: + other = small_project() + other["name"] = "small" + + result = client.post("/api/compare", json={"projects": [project, other]}).json() + + assert [item["name"] for item in result] == [project["name"], "small"] + assert result[0]["tx_count"] == 8 and result[1]["tx_count"] == 2 + assert result[0]["error"] is None + assert client.post("/api/compare", json={"projects": []}).status_code == 422 + + +def test_legacy_document_infers_band_from_frequency(client) -> None: + project = default_project().model_dump(mode="json") + project.pop("band") + project["frequency_ghz"] = 60.5 + + imported = client.post("/api/import/document", json={"document": project}).json() + + assert imported["project"]["band"]["preset"] == "60G" + + +def test_report_includes_fov_and_requirement_rows(client) -> None: + project = small_project() + project["requirements"] = {"azimuth_resolution_deg": 30} + job = client.post( + "/api/reports", + json={"project": project, "options": {"title": "fov report", "include_raw_data": True}}, + ).json() + + status = wait_for_job(client, job) + download = client.get(f"/api/jobs/{job['id']}/download") + + assert status["status"] == "succeeded", status + with zipfile.ZipFile(io.BytesIO(download.content)) as archive: + manifest_name = next(n for n in archive.namelist() if n.endswith("report_manifest.json")) + import json + + manifest = json.loads(archive.read(manifest_name)) + assert manifest["array_factor_fov"]["azimuth_deg"] == [-75.0, 75.0] + assert manifest["dbf_scan"]["search_guard_deg"] == 10.0 + assert manifest["requirement_checks"][0]["key"] == "resolution" From ff12b70d4680dead6715762f18d6ceda93c408ac Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 12:33:24 +0000 Subject: [PATCH 4/5] =?UTF-8?q?=E4=BC=98=E5=8C=96=EF=BC=9A=E5=89=8D?= =?UTF-8?q?=E7=AB=AF=E6=94=AF=E6=8C=81=E9=A2=91=E6=AE=B5/=E8=A7=86?= =?UTF-8?q?=E5=9C=BA/=E8=A7=84=E6=A0=BC=EF=BC=8C=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E9=A2=91=E6=AE=B5=E4=B8=8E=E5=AF=B9=E6=AF=94=E8=A7=86=E5=9B=BE?= =?UTF-8?q?=EF=BC=8C=E8=87=AA=E5=8A=A8=E6=8E=92=E9=98=B5=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E6=A0=87=E5=87=86=20MIMO=20=E5=B8=83=E5=B1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 顶部频段切换(60G/77G/92G/自定义)与设计频率;评估设置对话框(扫频范围、视场、规格、编辑网格) - 概览:分辨率改为实测 3 dB 波束宽度(附公式估算)、视场内最大误差、规格检查、布局检查;移除车载专用的前向雷达评级 - 新增「频段与对比」视图:扫频起止/设计频率性能表与多方案对比 - 1D/2D/测角视图按视场显示(视场边界、搜索范围),误差显示到 0.001° - 坐标支持 λ/mm 输入,编辑网格可选 λ/2、λ/4、λ/8、自由 - 自动排阵改为 Rx λ/2、Tx N_Rx·λ/2,得到无重复的 λ/2 虚拟 ULA - 文档补充评估方法说明 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TgRQxvYJLtrCkPBUDGPWAw --- CLAUDE.md | 18 +- README.md | 28 ++- src/virtual_array/project.py | 21 +- tests/test_project.py | 9 +- web/src/App.tsx | 6 +- web/src/api/client.ts | 4 + web/src/api/types.ts | 92 ++++++++ web/src/components/Chrome.tsx | 36 +++- web/src/components/Overview.tsx | 178 +++++++++++---- web/src/dialogs/ReportDialog.tsx | 27 ++- web/src/dialogs/SettingsDialog.tsx | 255 ++++++++++++++++++++++ web/src/i18n/help.ts | 46 +++- web/src/i18n/messages.ts | 271 ++++++++++++++++++++--- web/src/lib/geometry.ts | 4 +- web/src/state/compute.ts | 10 +- web/src/state/store.ts | 28 ++- web/src/styles/global.css | 11 + web/src/styles/views.css | 67 ++++++ web/src/views/AngleView.tsx | 10 +- web/src/views/ArrayView.tsx | 88 +++++--- web/src/views/BandView.tsx | 333 +++++++++++++++++++++++++++++ web/src/views/Dbf2dView.tsx | 57 +++-- web/src/views/DbfView.tsx | 31 ++- web/src/views/PhysicalEditor.tsx | 18 +- web/src/views/plane.tsx | 6 +- web/src/views/usePlayback.ts | 7 + 26 files changed, 1480 insertions(+), 181 deletions(-) create mode 100644 web/src/dialogs/SettingsDialog.tsx create mode 100644 web/src/views/BandView.tsx diff --git a/CLAUDE.md b/CLAUDE.md index befd04a..5c5a83e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -MIMO Array Visualizer — a web workbench for interactively editing and evaluating MIMO Tx/Rx antenna array layouts. A Python FastAPI server runs the computation core (virtual array geometry, 2D array factor, DBF dictionary spectra, angle-estimation metrics, PDF reports); a React + TypeScript client provides the UI. It is deployed on a local server and used from a browser. +MIMO Array Visualizer — a web workbench for evaluating MIMO Tx/Rx antenna arrays of 60/77/92 GHz FMCW radars. A Python FastAPI server runs the computation core (virtual array geometry, 2D array factor, DBF dictionary spectra, angle-estimation metrics, PDF reports); a React + TypeScript client provides the UI. It is deployed on a local server and used from a browser. ## Commands @@ -43,12 +43,14 @@ docker compose up -d --build - **`element_pattern.py`** — element patterns and per-channel HFSS amplitude/phase series (`ChannelPatternSet`). - **`performance_report.py`** — multi-page PDF report, angle-error PNG, CSV/JSON data package (matplotlib). - **`phasor.py`** — fast `exp(1j*phase)` helper used in hot loops. +- **`EvaluationSettings` / `evaluate_dbf_axis`** (in `analysis.py`) — FOV-bounded true angles, scan = FOV ± 10° guard, refined peaks (`dbf_refine_peak_angles`, 0.002°). The legacy bank functions keep the ±90° grid for backward compatibility. +- **`requirements.py`** — `RequirementSpec` → `check_requirements()` pass/fail list; resolution uses the measured 3 dB beamwidth. ### Service layer -- **`project.py`** — Pydantic `Project` document (schema version 2, coordinates in **λ**, grid 0.5 λ). Imported files are referenced by asset ID. Converts to the core array via `project_array()` (λ → λ/2). Reads/writes the desktop-era v1 layout JSON (`layout_from_v1`, `layout_to_v1`). +- **`project.py`** — Pydantic `Project` document (schema version 2, coordinates in **λ at the design frequency `frequency_ghz`**), plus `band` (60G/77G/92G presets, sweep range), `fov`, `grid_step_lambda`, `requirements`. `project_array(project, operating_ghz)` scales electrical positions by f/f_design. v1 import keeps exact coordinates (no snapping). Imported files are referenced by asset ID. Converts to the core array via `project_array()` (λ → λ/2). Reads/writes the desktop-era v1 layout JSON (`layout_from_v1`, `layout_to_v1`). - **`assets.py`** — content-addressed store (`/assets//`). -- **`engine.py`** — `Engine` turns a project into core objects and returns JSON-ready payloads (`evaluate`, `dbf_bank`, `dbf_2d`, `dictionary_preview`, `resolve_channel_patterns`, `layout_document`, `report_snapshot`). LRU caches are keyed by the JSON digest of only the fields each result depends on. +- **`engine.py`** — `Engine` turns a project into core objects and returns JSON-ready payloads (`evaluate`, `dbf_bank`, `dbf_2d`, `band_sweep`, `compare`, `dictionary_preview`, `resolve_channel_patterns`, `layout_document`, `report_snapshot`). LRU caches are keyed by the JSON digest of only the fields each result depends on. ### Server (`src/virtual_array/server/`) @@ -61,8 +63,8 @@ docker compose up -d --build - `api/` typed client + payload types (mirror `project.py` / `engine.py`). - `state/store.ts` (zustand: project, undo/redo of layout edits, selection, UI prefs; persisted to localStorage), `state/compute.ts` (debounced evaluation, DBF bank cache), `state/actions.ts` (save/open/import/export), `state/jobs.ts`. -- `views/` — `ArrayView` (SVG `PhysicalEditor` with drag/snap/zoom + `VirtualPlot`), `DbfView` (1D playback, client-side from one bank request), `Dbf2dView` (heatmap, prefetching frame batches), `AngleView`. -- `dialogs/` — DBF dictionary, channel amp/phase + element pattern, report, project library, help. +- `views/` — `ArrayView` (SVG `PhysicalEditor` with drag/snap/zoom + `VirtualPlot`), `DbfView` (1D playback, client-side from one bank request), `Dbf2dView` (heatmap, prefetching frame batches), `AngleView`, `BandView` (in-band performance + design comparison). +- `dialogs/` — evaluation settings (band/FOV/requirements/grid), DBF dictionary, channel amp/phase + element pattern, report, project library, help. - `i18n/messages.ts` — zh/en/ja strings (zh is the reference; a unit test checks keys and placeholders match). - `charts/` — lazily loaded Plotly wrapper and theme tokens. @@ -70,14 +72,16 @@ docker compose up -d --build ``` Browser edits Project ──POST /api/evaluate──▶ Engine.evaluate ─▶ ArrayMetrics + DBF angle metrics - ──POST /api/dbf/bank──▶ 181×181 spectra (base64 float32) → 1D playback in browser + ──POST /api/dbf/bank──▶ FOV true × (FOV±10°) scan spectra + refined peaks → 1D playback in browser + ──POST /api/band, /api/compare──▶ in-band sweep / design comparison summaries ──POST /api/dbf/2d────▶ batched 2D frames (Dbf2dScanner) ──POST /api/reports───▶ background job → PDF/zip download ``` ## Conventions -- Project/API coordinates are λ; the core uses λ/2. Convert only in `project_array()`. +- 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. - 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. diff --git a/README.md b/README.md index 0b56ad1..d33a7c6 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ **中文** | [English](#english) -MIMO 阵列工作台:在浏览器中交互式编辑、评估 MIMO 雷达 Tx/Rx 天线阵列布局。部署在本地服务器上,局域网内用浏览器即可使用,无需在每台电脑上安装软件。 +MIMO 阵列工作台:评估 60 GHz / 77 GHz / 92 GHz 毫米波 FMCW 雷达的 MIMO Tx/Rx 天线阵列性能。部署在本地服务器上,局域网内用浏览器即可使用,无需在每台电脑上安装软件。 -可计算虚拟阵列几何、2D 阵列因子与方向图指标(PSL、ISLR、3 dB 波束宽度、栅瓣),以及基于 DBF 字典的测角性能(不模糊范围、测角误差、竞争峰裕量、截断原因),并输出多页 PDF 性能报告。 +可计算虚拟阵列几何、阵列方向图指标(实测 3 dB 分辨率、PSL、ISLR、栅瓣),以及基于 DBF 字典、限定在雷达视场内的测角性能(不模糊范围、亚度级测角误差、竞争峰裕量),并给出频段内性能、规格检查和多方案对比,输出多页 PDF 性能报告。 --- @@ -19,6 +19,15 @@ MIMO 阵列工作台:在浏览器中交互式编辑、评估 MIMO 雷达 Tx/Rx - **阵列概览**:通道数、虚拟通道利用率、口径(mm/λ)、分辨率、测角评估、方向图指标和提示。 - 中文 / English / 日本語界面,浅色 / 深色 / 跟随系统主题,桌面和手机宽度均可用。 +### 雷达评估 + +- **频段**:60G(57–64 GHz)、77G(76–81 GHz)、92G(默认 90–94 GHz,需按芯片修改)预设,可自定义扫频范围;阵列坐标以设计频率下的 λ 保存。 +- **评估视场**:测角评估与方向图指标都限定在雷达视场内(DBF 搜索外扩 10°),视场外栅瓣不计入视场内模糊。 +- **频段内性能**:天线物理位置固定,在扫频起止与设计频率处重新评估分辨率、不模糊范围、误差、裕量和 PSL。 +- **规格检查**:分辨率、视场内不模糊、视场内最大误差、竞争峰裕量、2D 峰值旁瓣逐项判定通过/未通过。 +- **方案对比**:从项目库选取多个方案(如 60/77/92 GHz 各自的阵列)与当前项目并排比较。 +- **布局检查**:阵元重合、间距小于 λ/2(可能物理重叠)、设计频率不在扫频范围内时给出提示。 + ### 功能 - **DBF 字典**:理想几何、理想反向相位、通道幅相校准、导入 CSV/XLSX 字典(方位/俯仰分别导入,支持虚拟或物理通道列,可选相位取反和 0° 校准);附相位矩阵预览和质量提示。 @@ -125,6 +134,19 @@ tests/ pytest deploy/, scripts/, Dockerfile, docker-compose.yml 部署 ``` +### 评估方法说明 + +| 项目 | 做法 | 原因 | +| --- | --- | --- | +| 分辨率 | 阵列响应 0° 切面的实测 3 dB 波束宽度;0.886/D 公式仅作参考 | 公式对稀疏/小阵列不准(case4 公式 1.35°,实测 1.72°) | +| PSL 主瓣区 | 主峰两侧至第一零点(至少下降 3 dB) | 固定 ±2°/±6° 保护区会把小阵列(如 60 GHz 3T4R)的主瓣算成旁瓣 | +| 测角范围 | 真实角在视场内 1° 步进;搜索范围外扩 10° | 实际雷达只在视场内搜索;全 ±90° 搜索会把视场外栅瓣误判为模糊 | +| 测角误差 | 1° 网格取峰后,在峰附近重新计算相关细化到 0.002° | 只用 1° 网格时误差只能是整数度,无法评估 HFSS 实测数据的亚度级误差 | +| 频段内性能 | 物理坐标固定,电长度按 f/f设计 缩放;字典按工作频率匹配 | 反映 FMCW 扫频内栅瓣起始角和分辨率的漂移 | +| 自动排阵 | Rx 间距 λ/2、Tx 间距 NRx·λ/2 | 得到无重复、无栅瓣的 λ/2 虚拟 ULA(标准 MIMO 布局) | + +导入的 HFSS 通道相位和自定义字典是单频点数据,频段内评估只缩放几何、不改变这些数据,界面会给出提示。 + ### 从桌面版迁移 桌面版(PySide6)已由 Web 版取代,代码保留在 git 历史中。桌面版导出的阵面 JSON 可直接通过「导入 → 导入阵面 JSON」打开,频率和裕量设置会一并读取。桌面版中按本地路径引用的字典和方向图文件,需要在 Web 版中重新上传一次;之后会保存在服务器上,也可以随项目包一起迁移。 @@ -136,7 +158,7 @@ deploy/, scripts/, Dockerfile, docker-compose.yml 部署 MIMO Array Visualizer is a web workbench for editing and evaluating MIMO radar Tx/Rx antenna layouts. Run it on a local server and use it from any browser on the LAN. - **UI**: drag-and-snap SVG array editor with undo/redo, live virtual-array preview, 1D DBF spectrum playback, 2D DBF heatmap, angle-error/peak-margin view, overview panel; Chinese/English/Japanese; light/dark themes. -- **Analysis**: virtual geometry, 2D array factor metrics (PSL, ISLR, beamwidth, grating lobes), DBF-dictionary angle evaluation (no-fold range, error, peak margin, cut reasons) with ideal, reversed, channel-calibrated or imported CSV/XLSX dictionaries, HFSS channel amp/phase and element patterns. +- **Analysis** for 60/77/92 GHz FMCW radars: band presets with sweep ranges, FOV-bounded DBF angle evaluation with sub-degree peak refinement, measured 3 dB resolution, first-null PSL, in-band performance at the sweep edges, requirement pass/fail, design comparison, layout overlap checks; ideal, reversed, channel-calibrated or imported dictionaries, HFSS channel amp/phase and element patterns. - **Workflow**: shared server-side project library, desktop-compatible layout JSON, portable `.mimo.zip` bundles, background PDF reports with CSV/JSON data packages, REST API at `/api/docs`. **Deploy with Docker**: `docker compose up -d --build`, then open `http://:8000/`. diff --git a/src/virtual_array/project.py b/src/virtual_array/project.py index dc69a6f..d1b2dd7 100644 --- a/src/virtual_array/project.py +++ b/src/virtual_array/project.py @@ -274,20 +274,29 @@ def project_array(project: Project, operating_frequency_ghz: float | None = None return AntennaArray(tx=tx, rx=rx) -def centered_positions(count: int) -> list[float]: - offset = (count - 1) * AUTO_LAYOUT_SPACING_LAMBDA / 2.0 - return [snap_lambda(index * AUTO_LAYOUT_SPACING_LAMBDA - offset) for index in range(count)] +def centered_positions(count: int, spacing: float = AUTO_LAYOUT_SPACING_LAMBDA) -> list[float]: + """Positions centred on 0 as far as the λ/2 grid allows (even counts sit ½ step left).""" + offset = snap_lambda((count - 1) * spacing / 2.0) + return [_clean(index * spacing - offset) for index in range(count)] def auto_layout(tx_count: int, rx_count: int) -> Layout: - """Centered Tx and Rx rows: the desktop tool's "Apply Array" quick start.""" + """Standard TDM/DDM-MIMO azimuth layout: a filled λ/2 virtual ULA. + + Rx are spaced λ/2 and Tx are spaced ``rx_count · λ/2``, so the + ``tx_count · rx_count`` virtual channels form a uniform λ/2 line without + duplicates or grating lobes (e.g. 3T4R → 12-element virtual ULA). Tx and + Rx sit on separate rows only so they are distinguishable in the editor. + """ if not 1 <= tx_count <= MAX_TX_COUNT: raise ValueError(f"Tx count must be from 1 to {MAX_TX_COUNT}.") if not 1 <= rx_count <= MAX_RX_COUNT: raise ValueError(f"Rx count must be from 1 to {MAX_RX_COUNT}.") + rx_spacing = GRID_STEP_LAMBDA + tx_spacing = rx_count * GRID_STEP_LAMBDA return Layout( - tx=[Point(x=x, y=AUTO_LAYOUT_TX_Y_LAMBDA) for x in centered_positions(tx_count)], - rx=[Point(x=x, y=AUTO_LAYOUT_RX_Y_LAMBDA) for x in centered_positions(rx_count)], + tx=[Point(x=x, y=AUTO_LAYOUT_TX_Y_LAMBDA) for x in centered_positions(tx_count, tx_spacing)], + rx=[Point(x=x, y=AUTO_LAYOUT_RX_Y_LAMBDA) for x in centered_positions(rx_count, rx_spacing)], ) diff --git a/tests/test_project.py b/tests/test_project.py index 0d95331..f02c7c9 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -113,13 +113,16 @@ def test_project_from_v2_document_round_trips() -> None: assert restored == project -def test_auto_layout_centers_rows_on_half_lambda_grid() -> None: +def test_auto_layout_builds_filled_half_lambda_virtual_ula() -> None: layout = auto_layout(3, 4) - assert [point.x for point in layout.tx] == [-1.0, 0.0, 1.0] - assert [point.x for point in layout.rx] == [-1.5, -0.5, 0.5, 1.5] + assert [point.x for point in layout.tx] == [-2.0, 0.0, 2.0] + assert [point.x for point in layout.rx] == [-1.0, -0.5, 0.0, 0.5] assert {point.y for point in layout.tx} == {2.0} assert {point.y for point in layout.rx} == {-2.0} + virtual_x = sorted(tx.x + rx.x for tx in layout.tx for rx in layout.rx) + assert len(set(virtual_x)) == 12 + assert np.allclose(np.diff(virtual_x), 0.5) with pytest.raises(ValueError): auto_layout(0, 4) diff --git a/web/src/App.tsx b/web/src/App.tsx index 1a3a8b6..6fab1d7 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -17,9 +17,11 @@ const DictionaryDialog = lazy(() => import("./dialogs/DictionaryDialog").then((m const PatternsDialog = lazy(() => import("./dialogs/PatternsDialog").then((m) => ({ default: m.PatternsDialog }))); const ReportDialog = lazy(() => import("./dialogs/ReportDialog").then((m) => ({ default: m.ReportDialog }))); const ProjectsDialog = lazy(() => import("./dialogs/ProjectsDialog").then((m) => ({ default: m.ProjectsDialog }))); +const SettingsDialog = lazy(() => import("./dialogs/SettingsDialog").then((m) => ({ default: m.SettingsDialog }))); +const BandView = lazy(() => import("./views/BandView").then((m) => ({ default: m.BandView }))); const HelpDialog = lazy(() => import("./dialogs/HelpDialog").then((m) => ({ default: m.HelpDialog }))); -const VIEW_KEYS: Record = { "1": "array", "2": "dbf1d", "3": "dbf2d", "4": "angle" }; +const VIEW_KEYS: Record = { "1": "array", "2": "dbf1d", "3": "dbf2d", "4": "angle", "5": "band" }; function useThemeAttribute(theme: ThemeMode) { useEffect(() => { @@ -152,6 +154,7 @@ function Workbench() { {view === "dbf1d" && } {view === "dbf2d" && } {view === "angle" && } + {view === "band" && } @@ -163,6 +166,7 @@ function Workbench() { {dialog === "report" && } {dialog === "projects" && } {dialog === "help" && } + {dialog === "settings" && }
); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 017fd6e..040b7e3 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -1,5 +1,7 @@ import type { AssetInfo, + BandSweep, + CompareItem, Axis, ChannelPatternBinding, Dbf2dResult, @@ -89,6 +91,8 @@ export const api = { post("/api/layout/auto", { tx_count, rx_count }), evaluate: (project: Project, signal?: AbortSignal) => post("/api/evaluate", { project }, signal), + band: (project: Project, signal?: AbortSignal) => post("/api/band", { project }, signal), + compare: (projects: Project[]) => post("/api/compare", { projects }), dbfBank: (project: Project, axis: Axis, signal?: AbortSignal) => post("/api/dbf/bank", { project, axis }, signal), dbf2d: (project: Project, frames: { azimuth: number; elevation: number }[], signal?: AbortSignal) => diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 91087e7..3aa17ff 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -40,11 +40,39 @@ export interface ChannelPatternBinding { column: string; } +export type BandPreset = "60G" | "77G" | "92G" | "custom"; + +export interface Band { + preset: BandPreset; + start_ghz: number; + stop_ghz: number; +} + +export interface FieldOfView { + azimuth: [number, number]; + elevation: [number, number]; +} + +export interface Requirements { + azimuth_resolution_deg: number | null; + elevation_resolution_deg: number | null; + azimuth_unambiguous_fov: boolean; + elevation_unambiguous_fov: boolean; + max_abs_error_deg: number | null; + min_peak_margin_db: number | null; + max_psl_db: number | null; +} + export interface Project { version: 2; name: string; + /** Design frequency: the layout's λ is defined here. */ frequency_ghz: number; ambiguity_margin_db: number; + band: Band; + fov: FieldOfView; + grid_step_lambda: number; + requirements: Requirements; layout: Layout; dbf_dictionary: DictionarySettings; element_pattern: ElementPatternSettings | null; @@ -117,6 +145,62 @@ export interface VirtualPointGroup { export type AmpPhaseState = "ideal" | "imported" | "mixed"; +export interface AxisResolution { + measured: WireNumber; + estimate: WireNumber; + value: WireNumber; +} + +export type RequirementKey = "resolution" | "unambiguous_fov" | "max_error" | "peak_margin" | "psl"; + +export interface RequirementCheck { + key: RequirementKey; + axis: Axis | null; + target: WireNumber; + actual: WireNumber; + status: "pass" | "fail" | "na"; +} + +export interface LayoutCheck { + code: "coincident" | "too_close" | "design_outside_band"; + a?: string; + b?: string; + distance_lambda?: number; + distance_mm?: number; +} + +export interface PerformanceSummary { + frequency_ghz: number; + wavelength_mm: number; + capability: { azimuth: boolean; elevation: boolean; two_d: boolean }; + resolution: Record; + psl_db: WireNumber; + azimuth_psl_db: WireNumber; + elevation_psl_db: WireNumber; + angle: Record; + requirements: RequirementCheck[]; + passed: number; + failed: number; +} + +export interface BandSweep { + band: Band; + design_ghz: number; + design_in_band: boolean; + uses_single_frequency_data: boolean; + points: (PerformanceSummary & { role: string })[]; +} + +export type CompareItem = { + name: string; + band: Band; + design_ghz: number; + tx_count: number; + rx_count: number; + fov: FieldOfView; + error: string | null; +} & Partial; + export interface Evaluation { wavelength_mm: number; half_wavelength_mm: number; @@ -133,16 +217,21 @@ export interface Evaluation { x_aperture_mm: number; y_aperture_mm: number; }; + resolution: Record; metrics: ArrayMetrics; capability: { azimuth: boolean; elevation: boolean; two_d: boolean }; + fov: Record; virtual_points: VirtualPointGroup[]; angle: Record; + requirements: RequirementCheck[]; + layout_checks: LayoutCheck[]; pattern_status: { amplitude: AmpPhaseState; phase: AmpPhaseState }; notes: string[]; } export interface DbfBank { axis: Axis; + fov: [number, number]; true_angles: number[]; scan_angles: number[]; spectra_db: EncodedArray; @@ -167,6 +256,7 @@ export interface Dbf2dFrame { } export interface Dbf2dResult { + fov: Record; scan_azimuths: number[]; scan_elevations: number[]; frames: Dbf2dFrame[]; @@ -275,6 +365,8 @@ export interface ServerConfig { grid_step_lambda: number; max_asset_bytes: number; max_2d_frames_per_request: number; + grid_steps_lambda: number[]; }; + band_presets: Record<"60G" | "77G" | "92G", { start_ghz: number; stop_ghz: number; design_ghz: number }>; dbf: { scan_fov: [number, number]; scan_step_deg: number; scan_grid_size: number }; } diff --git a/web/src/components/Chrome.tsx b/web/src/components/Chrome.tsx index 980a5bd..c6ab863 100644 --- a/web/src/components/Chrome.tsx +++ b/web/src/components/Chrome.tsx @@ -18,9 +18,11 @@ import { Package, Radar, Save, + Settings2, Sun, Target, Upload, + Waves, } from "lucide-react"; import type { ReactNode } from "react"; import { LANGUAGE_LABELS, useT } from "../i18n"; @@ -160,16 +162,18 @@ export function TopBar() { ); } -const VIEWS: { id: ViewId; icon: ReactNode; key: "view.array" | "view.dbf1d" | "view.dbf2d" | "view.angle" }[] = [ +const VIEWS: { id: ViewId; icon: ReactNode; key: "view.array" | "view.dbf1d" | "view.dbf2d" | "view.angle" | "view.band" }[] = [ { id: "array", icon: , key: "view.array" }, { id: "dbf1d", icon: , key: "view.dbf1d" }, { id: "dbf2d", icon: , key: "view.dbf2d" }, { id: "angle", icon: , key: "view.angle" }, + { id: "band", icon: , key: "view.band" }, ]; export function ControlBar() { const t = useT(); const project = useStore((state) => state.project)!; + const config = useStore((state) => state.config)!; const view = useStore((state) => state.view); const display = useStore((state) => state.display); const evaluation = useStore((state) => state.evaluation); @@ -196,7 +200,28 @@ export function ControlBar() { ))}
-
{evaluation && ( <> +

{t("overview.angleTitle")}

- {evaluation.notes.length > 0 && ( + {(evaluation.notes.length > 0 || evaluation.layout_checks.length > 0) && (

{t("overview.notes")}

    + {evaluation.layout_checks.map((check, index) => ( +
  • + + {layoutCheckText(check, t)} +
  • + ))} {evaluation.notes.map((note) => (
  • @@ -93,10 +133,30 @@ export function Overview() { ); } +function layoutCheckText(check: LayoutCheck, t: Translate): string { + if (check.code === "design_outside_band") return t("layout.design_outside_band"); + return t(`layout.${check.code}` as const, { + a: check.a ?? "", + b: check.b ?? "", + lambda: trimNumber(check.distance_lambda ?? 0, 3), + mm: trimNumber(check.distance_mm ?? 0, 2), + }); +} + function Kpis({ evaluation }: { evaluation: Evaluation }) { const t = useT(); - const { summary, metrics } = evaluation; + const { summary, resolution } = evaluation; const utilization = Math.round(summary.utilization * 100); + const resolutionKpi = (axis: Axis) => { + const value = wire(resolution[axis].value); + const estimate = wire(resolution[axis].estimate); + return { + value: fmt(value, 2, "°"), + sub: estimate !== null && value !== null ? t("overview.resolutionSub", { value: fmt(estimate, 2, "°") }) : undefined, + }; + }; + const az = resolutionKpi("azimuth"); + const el = resolutionKpi("elevation"); return (
    @@ -109,22 +169,34 @@ function Kpis({ evaluation }: { evaluation: Evaluation }) { - - + +
    ); } -function Kpi({ label, value, sub, tone }: { label: string; value: string; sub?: string; tone?: "warn" }) { +function Kpi({ + label, + value, + sub, + tone, + title, +}: { + label: string; + value: string; + sub?: string; + tone?: "warn"; + title?: string; +}) { return ( -
    +
    {label} @@ -134,14 +206,57 @@ function Kpi({ label, value, sub, tone }: { label: string; value: string; sub?: ); } +function RequirementSection({ evaluation }: { evaluation: Evaluation }) { + const t = useT(); + const openDialog = useStore((state) => state.openDialog); + const checks = evaluation.requirements; + const applicable = checks.filter((check) => check.status !== "na"); + const passed = applicable.filter((check) => check.status === "pass").length; + return ( +
    +

    + {t("overview.requirements")} + {applicable.length > 0 && ( + + {t("overview.passCount", { passed, total: applicable.length })} + + )} + + +

    + {checks.length === 0 ? ( +

    + {t("overview.requirementsNone")} +

    + ) : ( +
      + {checks.map((check, index) => ( +
    • + + {requirementLabel(check, t)} + {check.status === "na" ? t("req.na") : requirementValue(check, t)} +
    • + ))} +
    + )} +
    + ); +} + function AngleCard({ axis, evaluation }: { axis: Axis; evaluation: Evaluation }) { const t = useT(); const result = evaluation.angle[axis]; const title = t(axis === "azimuth" ? "axis.azimuth" : "axis.elevation"); + const [low, high] = evaluation.fov[axis]; return (
    {title} + + {t("overview.fov", { low, high })} + {!evaluation.capability[axis] && {t("overview.noAperture")}}
    {result && "error" in result ? ( @@ -150,8 +265,8 @@ function AngleCard({ axis, evaluation }: { axis: Axis; evaluation: Evaluation })
    {t("overview.noFold")}
    {noFoldText(result)}
    -
    {t("overview.maxError")}
    -
    {fmt(wire(result.no_fold_max_abs_error), 1, "°")}
    +
    {t("overview.focusError")}
    +
    {errorText(wire(result.focus_max_abs_error))}
    {t("overview.peakMargin")}
    {marginText(result, t)}
    {t("overview.cutReason")}
    @@ -165,8 +280,9 @@ function AngleCard({ axis, evaluation }: { axis: Axis; evaluation: Evaluation }) function PatternMetrics({ evaluation }: { evaluation: Evaluation }) { const t = useT(); const m = evaluation.metrics; - const at = (value: number | null, angle: number | null, prefix = "") => - value === null || !Number.isFinite(value) ? "—" : `${fmt(value, 1, " dB")}${angle === null ? "" : ` @ ${prefix}${fmtSigned(angle, 1)}`}`; + const at = (value: number | null, angle: number | null) => + value === null || !Number.isFinite(value) ? "—" : `${fmt(value, 1, " dB")}${angle === null ? "" : ` @ ${fmtSigned(angle, 1)}`}`; + const sidelobeAt = `Az ${fmtSigned(wire(m.sidelobe_azimuth), 1)}, El ${fmtSigned(wire(m.sidelobe_elevation), 1)}`; return (
    @@ -184,27 +300,13 @@ function PatternMetrics({ evaluation }: { evaluation: Evaluation }) {
    {t("overview.elPsl")}
    {fmt(wire(m.elevation_psl_db), 2, " dB")}
    {t("overview.psl2d")}
    -
    - {fmt(wire(m.psl_db), 2, " dB")} -
    +
    {fmt(wire(m.psl_db), 2, " dB")}
    {t("overview.islr")}
    {fmt(wire(m.azimuth_islr_db), 2, " dB")}
    {t("overview.firstSidelobe")}
    {at(wire(m.azimuth_first_sidelobe_db), wire(m.azimuth_first_sidelobe_angle))}
    {t("overview.grating")}
    {at(wire(m.azimuth_grating_lobe_db), wire(m.azimuth_grating_lobe_angle))}
    -
    {t("overview.frontRadar")}
    -
    - - {t(`grade.${m.front_radar_status}` as never)} - -
    -
    {t("overview.ambiguity")}
    -
    - - {t(`level.${m.elevation_ambiguity_level}` as never)} - -
    diff --git a/web/src/dialogs/ReportDialog.tsx b/web/src/dialogs/ReportDialog.tsx index 65aea48..be75985 100644 --- a/web/src/dialogs/ReportDialog.tsx +++ b/web/src/dialogs/ReportDialog.tsx @@ -10,9 +10,11 @@ import { type Language, useStore } from "../state/store"; type RangeKey = "azimuth_focus" | "elevation_focus" | "azimuth_hold" | "elevation_hold"; -function angleParser(text: string) { - const value = parseNumber(text, ["°"]); - return value !== null && value >= -90 && value <= 90 ? value : null; +function angleParser(range: [number, number]) { + return (text: string) => { + const value = parseNumber(text, ["°"]); + return value !== null && value >= range[0] && value <= range[1] ? value : null; + }; } export function ReportDialog({ onClose }: { onClose: () => void }) { @@ -22,10 +24,10 @@ export function ReportDialog({ onClose }: { onClose: () => void }) { const capability = useStore((state) => state.evaluation?.capability) ?? { azimuth: true, elevation: true, two_d: true }; const [options, setOptions] = useState(() => ({ title: translate(language, "reportDialog.defaultTitle"), - azimuth_focus: { start: -70, stop: 70 }, - elevation_focus: { start: -15, stop: 15 }, - azimuth_hold: { start: -70, stop: 70 }, - elevation_hold: { start: -15, stop: 15 }, + azimuth_focus: { start: project.fov.azimuth[0], stop: project.fov.azimuth[1] }, + elevation_focus: { start: project.fov.elevation[0], stop: project.fov.elevation[1] }, + azimuth_hold: { start: project.fov.azimuth[0], stop: project.fov.azimuth[1] }, + elevation_hold: { start: project.fov.elevation[0], stop: project.fov.elevation[1] }, azimuth_hold_stride_frames: 1, elevation_hold_stride_frames: 1, error_limit_deg: 1, @@ -50,17 +52,20 @@ export function ReportDialog({ onClose }: { onClose: () => void }) { }); const noOutput = !options.include_spectrum_db && !options.include_spectrum_magnitude; - const rangeRow = (key: RangeKey, label: string) => ( + const rangeRow = (key: RangeKey, label: string) => { + const parse = angleParser(project.fov[key.startsWith("azimuth") ? "azimuth" : "elevation"]); + return ( <> - trimNumber(v, 1)} onCommit={(v) => setRange(key, "start", v)} aria-label={`${label} ${t("reportDialog.start")}`} /> + trimNumber(v, 1)} onCommit={(v) => setRange(key, "start", v)} aria-label={`${label} ${t("reportDialog.start")}`} /> ~ - trimNumber(v, 1)} onCommit={(v) => setRange(key, "stop", v)} aria-label={`${label} ${t("reportDialog.stop")}`} /> + trimNumber(v, 1)} onCommit={(v) => setRange(key, "stop", v)} aria-label={`${label} ${t("reportDialog.stop")}`} /> ° - ); + ); + }; const strideRow = (key: "azimuth_hold_stride_frames" | "elevation_hold_stride_frames") => ( <> diff --git a/web/src/dialogs/SettingsDialog.tsx b/web/src/dialogs/SettingsDialog.tsx new file mode 100644 index 0000000..aa7d932 --- /dev/null +++ b/web/src/dialogs/SettingsDialog.tsx @@ -0,0 +1,255 @@ +import { useState } from "react"; +import type { BandPreset, FieldOfView, Project, Requirements } from "../api/types"; +import { Button, Callout, Dialog, NumberInput, Segmented } from "../components/ui"; +import { useT } from "../i18n"; +import { parseNumber, trimNumber } from "../lib/format"; +import { useStore } from "../state/store"; + +type Draft = Pick; +type NumericRequirement = + | "azimuth_resolution_deg" + | "elevation_resolution_deg" + | "max_abs_error_deg" + | "min_peak_margin_db" + | "max_psl_db"; + +const REQUIREMENT_DEFAULTS: Record = { + azimuth_resolution_deg: 2, + elevation_resolution_deg: 5, + max_abs_error_deg: 0.5, + min_peak_margin_db: 3, + max_psl_db: -10, +}; + +function positive(text: string, max = 1000) { + const value = parseNumber(text, ["ghz", "°", "db"]); + return value !== null && value > 0 && value <= max ? value : null; +} + +export function SettingsDialog({ onClose }: { onClose: () => void }) { + const t = useT(); + const project = useStore((state) => state.project)!; + const config = useStore((state) => state.config)!; + const { updateProject } = useStore.getState(); + const [draft, setDraft] = useState({ + band: project.band, + fov: project.fov, + requirements: project.requirements, + grid_step_lambda: project.grid_step_lambda, + frequency_ghz: project.frequency_ghz, + }); + const bandValid = draft.band.start_ghz < draft.band.stop_ghz; + const fovValid = (["azimuth", "elevation"] as const).every((axis) => { + const [low, high] = draft.fov[axis]; + return low >= -90 && low < 0 && high > 0 && high <= 90; + }); + + const choosePreset = (preset: BandPreset) => { + if (preset === "custom") { + setDraft((current) => ({ ...current, band: { ...current.band, preset } })); + return; + } + const values = config.band_presets[preset]; + setDraft((current) => ({ + ...current, + band: { preset, start_ghz: values.start_ghz, stop_ghz: values.stop_ghz }, + frequency_ghz: values.design_ghz, + })); + }; + const setFov = (axis: keyof FieldOfView, edge: 0 | 1, value: number) => + setDraft((current) => { + const range = [...current.fov[axis]] as [number, number]; + range[edge] = Math.round(value); + return { ...current, fov: { ...current.fov, [axis]: range } }; + }); + const setRequirement = (key: K, value: Requirements[K]) => + setDraft((current) => ({ ...current, requirements: { ...current.requirements, [key]: value } })); + + const numericRow = (key: NumericRequirement, label: string, unit: string, parse: (text: string) => number | null) => { + const value = draft.requirements[key]; + return ( + <> + + + trimNumber(v, 3)} + onCommit={(v) => setRequirement(key, v)} + /> + {unit} + + + ); + }; + + return ( + + + + + + } + > +
    +

    {t("settings.band")}

    +

    + {t("settings.bandHint")} +

    + +
    + + positive(text)} + format={(v) => trimNumber(v, 3)} + onCommit={(v) => setDraft((c) => ({ ...c, band: { ...c.band, preset: "custom", start_ghz: v } }))} + /> + + positive(text)} + format={(v) => trimNumber(v, 3)} + onCommit={(v) => setDraft((c) => ({ ...c, band: { ...c.band, preset: "custom", stop_ghz: v } }))} + /> + + positive(text)} + format={(v) => trimNumber(v, 3)} + onCommit={(v) => setDraft((c) => ({ ...c, frequency_ghz: v }))} + /> +
    + {!bandValid && {t("settings.invalidBand")}} + {draft.band.preset === "92G" && {t("settings.preset92Note")}} +
    + +
    +

    {t("settings.fov")}

    +

    + {t("settings.fovHint")} +

    +
    + {(["azimuth", "elevation"] as const).map((axis) => ( + setFov(axis, edge, v)} /> + ))} +
    + {!fovValid && {t("settings.invalidFov")}} +
    + +
    +

    {t("settings.requirements")}

    +

    + {t("settings.requirementsHint")} +

    +
    + {numericRow("azimuth_resolution_deg", t("settings.reqAzRes"), "°", (text) => positive(text, 180))} + {numericRow("elevation_resolution_deg", t("settings.reqElRes"), "°", (text) => positive(text, 180))} + {numericRow("max_abs_error_deg", t("settings.reqError"), "°", (text) => positive(text, 90))} + {numericRow("min_peak_margin_db", t("settings.reqMargin"), "dB", (text) => { + const value = parseNumber(text, ["db"]); + return value !== null && value >= 0 && value <= 60 ? value : null; + })} + {numericRow("max_psl_db", t("settings.reqPsl"), "dB", (text) => { + const value = parseNumber(text, ["db"]); + return value !== null && value <= 0 && value >= -80 ? value : null; + })} +
    + + +
    + +
    +

    {t("settings.grid")}

    +

    + {t("settings.gridHint")} +

    + ({ + value: String(step), + label: step === 0 ? t("settings.gridFree") : `λ/${Math.round(1 / step)}`, + }))} + onChange={(value) => setDraft((c) => ({ ...c, grid_step_lambda: Number(value) }))} + /> +
    +
    + ); +} + +function FovRow({ + label, + value, + onChange, +}: { + label: string; + value: [number, number]; + onChange: (edge: 0 | 1, value: number) => void; +}) { + const parse = (text: string) => { + const v = parseNumber(text, ["°"]); + return v !== null && v >= -90 && v <= 90 ? Math.round(v) : null; + }; + return ( + <> + + + onChange(0, v)} /> + ~ + onChange(1, v)} /> + ° + + + ); +} diff --git a/web/src/i18n/help.ts b/web/src/i18n/help.ts index 590e972..ad2792d 100644 --- a/web/src/i18n/help.ts +++ b/web/src/i18n/help.ts @@ -14,9 +14,9 @@ export const SHORTCUTS: { keys: string[]; zh: string; en: string; ja: string }[] { keys: ["Ctrl", "S"], zh: "保存到项目库", en: "Save to the project library", ja: "プロジェクトライブラリに保存" }, { keys: ["Ctrl", "O"], zh: "导入阵面 JSON / 项目包", en: "Import array JSON / bundle", ja: "配置 JSON / パッケージを読み込む" }, { keys: ["Ctrl", "E"], zh: "导出阵面 JSON", en: "Export array JSON", ja: "配置 JSON を書き出す" }, - { keys: ["1", "–", "4"], zh: "切换视图(阵列 / 1D / 2D / 测角)", en: "Switch view (array / 1D / 2D / angle)", ja: "表示切替(配置 / 1D / 2D / 測角)" }, + { keys: ["1", "–", "5"], zh: "切换视图(阵列 / 1D / 2D / 测角 / 频段与对比)", en: "Switch view (array / 1D / 2D / angle / band & compare)", ja: "表示切替(配置 / 1D / 2D / 測角 / 周波数帯・比較)" }, { keys: ["Delete"], zh: "删除选中通道", en: "Delete the selected channel", ja: "選択チャネルを削除" }, - { keys: ["←", "→", "↑", "↓"], zh: "微调选中通道 0.5 λ(Shift:2.5 λ)", en: "Nudge selection by 0.5 λ (Shift: 2.5 λ)", ja: "選択を 0.5 λ 移動(Shift:2.5 λ)" }, + { keys: ["←", "→", "↑", "↓"], zh: "按编辑网格微调选中通道(Shift:5 倍)", en: "Nudge selection by one grid step (Shift: ×5)", ja: "選択をグリッド 1 目盛り移動(Shift:5 倍)" }, { keys: ["Esc"], zh: "取消拖动 / 退出删除模式 / 清除选择", en: "Cancel drag / exit delete mode / clear selection", ja: "ドラッグ取消 / 削除モード終了 / 選択解除" }, ]; @@ -32,6 +32,18 @@ const zh: HelpSection[] = [ "满意后点击「保存」存入项目库,或「导出」为阵面 JSON / 项目包,再用「性能报告」生成 PDF。", ], }, + { + id: "band", + title: "频段、视场与规格", + bullets: [ + "顶部「频段」可在 60G(57–64 GHz)、77G(76–81 GHz)、92G 之间切换,同时设置设计频率。阵列坐标以设计频率下的 λ 保存,切换频段时 λ 布局不变、毫米尺寸随之变化。92 GHz 默认 90–94 GHz 只是占位值,请在「评估设置」中改为芯片的实际扫频范围。", + "「评估视场」限定测角评估和方向图指标的统计范围。实际雷达只在视场内搜索,视场外的栅瓣不再算作视场内模糊;视场外目标需要靠单元方向图抑制。", + "分辨率以阵列响应实测 3 dB 波束宽度为准;口径公式 0.886/D 对小阵列和稀疏阵列偏乐观,仅作参考。PSL 的主瓣区按第一零点自动确定。", + "「规格要求」逐项给出通过/未通过:分辨率、视场内不模糊、视场内最大误差、竞争峰裕量、2D 峰值旁瓣。", + "「频段与对比」视图:频段内性能在扫频起止和设计频率处重新评估(天线位置固定、电长度变化);方案对比可把项目库中的 60/77/92 GHz 方案与当前项目并排比较。", + "编辑网格可选 λ/2、λ/4、λ/8 或自由;坐标可以按 λ 或 mm 输入。导入的阵面坐标保持原值,不再强制吸附。阵元间距小于 λ/2 或位置重合时会在提示中报出。", + ], + }, { id: "layout", title: "阵列编辑", @@ -55,7 +67,7 @@ const zh: HelpSection[] = [ id: "dbf1d", title: "1D DBF 角谱", paragraphs: [ - "每个方向有 181 帧,模拟真实角 −90°~+90°(1° 步进)的信号与 DBF 字典的归一化相关。", + "真实角在评估视场内以 1° 步进逐帧模拟,DBF 搜索范围比视场外扩 10°;峰值先在 1° 网格上取最大,再在附近重新计算相关细化到 0.002°,因此可以评估亚度级误差。", ], bullets: [ "「播放」从当前帧开始,播放到 +90° 自动停止;拖动滑条或点击图中任意位置跳转到该真实角。", @@ -125,6 +137,18 @@ const en: HelpSection[] = [ "Save to the project library, export array JSON or a project bundle, and use Report to generate a PDF.", ], }, + { + id: "band", + title: "Band, FOV and requirements", + bullets: [ + "The Band control switches between 60G (57–64 GHz), 77G (76–81 GHz) and 92G and sets the design frequency. Coordinates are stored in λ at the design frequency, so switching bands keeps the λ layout and rescales millimetres. The 92 GHz default of 90–94 GHz is a placeholder; set your chip's sweep in Evaluation settings.", + "The evaluation FOV bounds the angle evaluation and the array-pattern metrics. Real radars only search their FOV, so grating lobes outside it are no longer counted as in-FOV ambiguity; out-of-FOV targets must be suppressed by the element pattern.", + "Resolution is the measured 3 dB beamwidth of the array response; the 0.886/D aperture formula is optimistic for small and sparse arrays and shown for reference. The PSL main lobe is bounded at the first nulls.", + "Requirements give pass/fail for resolution, unambiguous FOV, max error in FOV, peak margin and 2D peak sidelobe.", + "The Band & compare view re-evaluates the array at the sweep edges and the design frequency (antennas fixed, electrical spacing changing), and compares library designs (e.g. 60/77/92 GHz) side by side.", + "The editor grid can be λ/2, λ/4, λ/8 or free, and coordinates can be typed in λ or mm. Imported coordinates are kept as given. Elements closer than λ/2 or coincident are reported.", + ], + }, { id: "layout", title: "Editing the array", @@ -148,7 +172,7 @@ const en: HelpSection[] = [ id: "dbf1d", title: "1D DBF spectra", paragraphs: [ - "Each axis has 181 frames simulating true angles from −90° to +90° (1° steps), correlated with the DBF dictionary.", + "True angles are simulated across the evaluation FOV in 1° steps; the DBF search extends 10° beyond the FOV. Peaks are taken on the 1° grid and then refined to 0.002° by re-evaluating the correlation, so sub-degree errors are visible.", ], bullets: [ "Play starts from the current frame and stops at +90°. Drag the slider or click anywhere in the chart to jump.", @@ -218,6 +242,18 @@ const ja: HelpSection[] = [ "プロジェクトライブラリに保存するか、配置 JSON / パッケージを書き出し、「性能レポート」で PDF を生成します。", ], }, + { + id: "band", + title: "周波数帯・視野・仕様", + bullets: [ + "上部の周波数帯で 60G(57–64 GHz)、77G(76–81 GHz)、92G を切り替え、設計周波数も設定します。座標は設計周波数での λ で保存されるため、切り替えても λ 配置は変わらず mm 寸法が変わります。92 GHz の 90–94 GHz は仮の値なので、評価設定でチップの実際の掃引範囲を入力してください。", + "評価視野は測角評価とアレイパターン指標の範囲を決めます。実際のレーダーは視野内のみ探索するため、視野外のグレーティングローブは視野内の曖昧さとして扱いません。視野外の目標は素子パターンで抑圧する必要があります。", + "分解能はアレイ応答の実測 3 dB ビーム幅です。開口式 0.886/D は小規模・スパースアレイで楽観的なため参考値です。PSL のメインローブは第 1 ヌルで決めます。", + "仕様では分解能、視野内の曖昧なし、視野内最大誤差、競合ピークマージン、2D ピークサイドローブを合否判定します。", + "「周波数帯・比較」では掃引の両端と設計周波数で再評価し(アンテナ位置固定・電気長変化)、ライブラリの設計(60/77/92 GHz など)を並べて比較できます。", + "編集グリッドは λ/2・λ/4・λ/8・自由から選べ、座標は λ または mm で入力できます。読み込んだ座標はそのまま保持されます。λ/2 未満の間隔や重なりは注意として表示します。", + ], + }, { id: "layout", title: "アレイ編集", @@ -240,7 +276,7 @@ const ja: HelpSection[] = [ { id: "dbf1d", title: "1D DBF スペクトル", - paragraphs: ["各軸 181 フレームで、真の角度 −90°〜+90°(1° 刻み)の信号と DBF 辞書の正規化相関を示します。"], + paragraphs: ["真の角度は評価視野内を 1° 刻みで模擬し、DBF 探索は視野の 10° 外側まで行います。ピークは 1° グリッドで求めた後、相関を再計算して 0.002° まで細分化するため、1° 未満の誤差も評価できます。"], bullets: [ "再生は現在のフレームから始まり +90° で停止します。スライダーまたはグラフのクリックで移動できます。", "黄色の線が真の角度、赤い × がピークです。下部に誤差、競合ピークマージン、ピーク品質を表示します。", diff --git a/web/src/i18n/messages.ts b/web/src/i18n/messages.ts index 4484b8a..4d5f278 100644 --- a/web/src/i18n/messages.ts +++ b/web/src/i18n/messages.ts @@ -13,7 +13,7 @@ export const zh = { "project.unsaved": "未保存的更改", "project.local": "未存入项目库", - "top.frequency": "频率", + "top.frequency": "设计频率", "top.margin": "裕量", "top.marginTitle": "竞争峰裕量阈值(不模糊判定)", "top.dictionary": "DBF 字典", @@ -146,8 +146,6 @@ export const zh = { "overview.islr": "方位 ISLR", "overview.firstSidelobe": "方位第一旁瓣", "overview.grating": "方位栅瓣", - "overview.frontRadar": "前向雷达评级", - "overview.ambiguity": "俯仰模糊风险", "overview.notes": "提示", "overview.computing": "计算中…", "overview.error": "计算失败", @@ -156,17 +154,10 @@ export const zh = { "cut.error_jump": "误差跳变", "cut.boundary_limited": "边界受限", "cut.unreliable": "谱不可靠", - "cut.data_boundary": "到达数据边界", + "cut.data_boundary": "覆盖整个视场", "cut.normal": "正常", "cut.pair": "负 {negative} / 正 {positive}", - "grade.Good": "良好", - "grade.Acceptable": "可用", - "grade.Risky": "有风险", - "grade.Bad": "较差", - "level.High": "高", - "level.Medium": "中", - "level.Low": "低", "note.duplicate_virtual": "存在重复虚拟通道,虚拟孔径利用率下降", "note.windowing": "方位旁瓣偏高,建议加窗", @@ -350,6 +341,82 @@ export const zh = { "status.newProject": "已新建项目", "status.opened": "已打开:{name}", "status.uploadFailed": "上传失败:{message}", + "top.band": "频段", + "top.bandCustom": "自定义", + "top.design": "设计频率", + "top.designTitle": "版图的 λ 按设计频率定义;切换频段时阵列以 λ 保持,毫米尺寸随之变化", + "top.settings": "评估设置", + "view.band": "频段与对比", + "settings.title": "评估设置", + "settings.band": "频段与扫频范围", + "settings.bandHint": "FMCW 扫频范围用于「频段与对比」中的频段内评估:天线物理位置固定,电长度随工作频率变化。", + "settings.start": "起始 (GHz)", + "settings.stop": "截止 (GHz)", + "settings.design": "设计频率 (GHz)", + "settings.preset92Note": "92 GHz 没有统一的频段划分,默认 90–94 GHz 只是占位值,请改为所用芯片的实际扫频范围。", + "settings.fov": "评估视场", + "settings.fovHint": "测角评估只在视场内进行(搜索范围外扩 10°),阵列方向图指标也在视场内统计。视场外的目标需要靠单元方向图抑制。", + "settings.requirements": "规格要求", + "settings.requirementsHint": "勾选后启用;未启用的项目不检查。分辨率按实测 3 dB 波束宽度判定。", + "settings.reqAzRes": "方位分辨率 ≤", + "settings.reqElRes": "俯仰分辨率 ≤", + "settings.reqUnambAz": "方位视场内不模糊", + "settings.reqUnambEl": "俯仰视场内不模糊", + "settings.reqError": "视场内最大测角误差 ≤", + "settings.reqMargin": "竞争峰裕量 ≥", + "settings.reqPsl": "2D 峰值旁瓣 ≤", + "settings.grid": "编辑网格", + "settings.gridFree": "自由", + "settings.gridHint": "拖动和方向键微调时吸附的步长;导入和手动输入的坐标保持原值。", + "settings.invalidBand": "起始频率必须小于截止频率", + "settings.invalidFov": "视场需满足 起始 < 0 < 截止,且在 ±90° 内", + "overview.resolutionSub": "公式估算 {value}", + "overview.resolutionTitle": "实测 3 dB 波束宽度(阵列响应),公式 0.886/D 仅作参考", + "overview.focusError": "视场内最大误差", + "overview.fov": "视场 {low}°~{high}°", + "overview.requirements": "规格检查", + "overview.requirementsNone": "未设置规格要求", + "overview.passCount": "{passed}/{total} 项通过", + "overview.edit": "设置", + "overview.layoutChecks": "布局检查", + "req.resolution": "{axis}分辨率", + "req.unambiguous_fov": "{axis}视场内不模糊", + "req.max_error": "{axis}最大误差", + "req.peak_margin": "{axis}竞争峰裕量", + "req.psl": "2D 峰值旁瓣", + "req.pass": "通过", + "req.fail": "未通过", + "req.na": "不适用", + "layout.coincident": "{a} 与 {b} 位置重合", + "layout.too_close": "{a} 与 {b} 间距 {lambda} λ({mm} mm),小于 λ/2,天线可能重叠", + "layout.design_outside_band": "设计频率不在扫频范围内", + "note.resolution_optimistic": "口径公式估算的分辨率偏乐观,以实测 3 dB 波束宽度为准", + "inspector.unit": "单位", + "band.title": "频段内性能", + "band.subtitle": "天线物理位置固定,在扫频起止频率和设计频率处分别评估", + "band.metric": "指标", + "band.role.start": "起始", + "band.role.design": "设计", + "band.role.stop": "截止", + "band.singleFrequency": "当前使用了单频点导入的相位或字典数据:频段评估只缩放几何,导入数据保持不变。", + "band.resolution": "{axis}分辨率", + "band.noFold": "{axis}不模糊范围", + "band.maxError": "{axis}视场内最大误差", + "band.margin": "{axis}最小裕量", + "band.psl": "2D PSL", + "band.checks": "规格检查", + "band.wavelength": "波长", + "compare.title": "方案对比", + "compare.subtitle": "从项目库选择方案与当前项目并排比较;每个方案使用自己的频段、视场和规格", + "compare.current": "当前项目", + "compare.run": "开始对比", + "compare.empty": "项目库为空,先把各方案保存到项目库。", + "compare.pickHint": "最多选择 7 个项目", + "compare.design": "设计频率", + "compare.channels": "通道", + "compare.fov": "视场", + "compare.band": "频段", + "dbf.fovLine": "视场边界", } as const; export type MessageKey = keyof typeof zh; @@ -368,7 +435,7 @@ export const en: Messages = { "project.unsaved": "Unsaved changes", "project.local": "Not in library", - "top.frequency": "Freq", + "top.frequency": "Design", "top.margin": "Margin", "top.marginTitle": "Competitor-peak margin threshold (no-fold test)", "top.dictionary": "DBF dictionary", @@ -501,8 +568,6 @@ export const en: Messages = { "overview.islr": "Az ISLR", "overview.firstSidelobe": "Az first sidelobe", "overview.grating": "Az grating lobe", - "overview.frontRadar": "Front-radar grade", - "overview.ambiguity": "Elevation ambiguity", "overview.notes": "Notes", "overview.computing": "Computing…", "overview.error": "Computation failed", @@ -511,17 +576,10 @@ export const en: Messages = { "cut.error_jump": "Error jump", "cut.boundary_limited": "At boundary", "cut.unreliable": "Unreliable spectrum", - "cut.data_boundary": "Data edge", + "cut.data_boundary": "Full FOV covered", "cut.normal": "Normal", "cut.pair": "Neg {negative} / Pos {positive}", - "grade.Good": "Good", - "grade.Acceptable": "Acceptable", - "grade.Risky": "Risky", - "grade.Bad": "Bad", - "level.High": "High", - "level.Medium": "Medium", - "level.Low": "Low", "note.duplicate_virtual": "Duplicate virtual channels reduce aperture utilization", "note.windowing": "High azimuth sidelobes; windowing recommended", @@ -568,7 +626,7 @@ export const en: Messages = { "dbf2d.loading": "Computing 2D spectrum…", "angle.title": "Angle error and peak margin", - "angle.subtitle": "Per-frame true angle −90° to +90° (1° steps)", + "angle.subtitle": "Per-frame true angles across the FOV (1° steps), peaks refined to 0.002°", "angle.errorChart": "{axis} angle error", "angle.marginChart": "{axis} peak margin", "angle.noFold": "No-fold range", @@ -705,6 +763,82 @@ export const en: Messages = { "status.newProject": "New project created", "status.opened": "Opened: {name}", "status.uploadFailed": "Upload failed: {message}", + "top.band": "Band", + "top.bandCustom": "Custom", + "top.design": "Design", + "top.designTitle": "The layout's λ is defined at the design frequency; switching bands keeps the layout in λ and rescales millimetres", + "top.settings": "Evaluation settings", + "view.band": "Band & compare", + "settings.title": "Evaluation settings", + "settings.band": "Band and sweep range", + "settings.bandHint": "The FMCW sweep range drives the in-band evaluation: antennas stay put while their electrical spacing changes with the operating frequency.", + "settings.start": "Start (GHz)", + "settings.stop": "Stop (GHz)", + "settings.design": "Design (GHz)", + "settings.preset92Note": "There is no single harmonised 92 GHz allocation; the 90–94 GHz default is a placeholder — enter your chip's actual sweep range.", + "settings.fov": "Evaluation FOV", + "settings.fovHint": "Angle evaluation runs inside the FOV (search extends 10° beyond it); array-pattern metrics are taken inside the FOV too. Targets outside the FOV must be suppressed by the element pattern.", + "settings.requirements": "Requirements", + "settings.requirementsHint": "Tick to enable; unticked items are not checked. Resolution uses the measured 3 dB beamwidth.", + "settings.reqAzRes": "Az resolution ≤", + "settings.reqElRes": "El resolution ≤", + "settings.reqUnambAz": "Azimuth FOV unambiguous", + "settings.reqUnambEl": "Elevation FOV unambiguous", + "settings.reqError": "Max angle error in FOV ≤", + "settings.reqMargin": "Peak margin ≥", + "settings.reqPsl": "2D peak sidelobe ≤", + "settings.grid": "Editor grid", + "settings.gridFree": "Free", + "settings.gridHint": "Snap step for dragging and arrow-key nudges; imported and typed coordinates are kept as entered.", + "settings.invalidBand": "Start must be below stop", + "settings.invalidFov": "FOV must satisfy start < 0 < stop within ±90°", + "overview.resolutionSub": "formula {value}", + "overview.resolutionTitle": "Measured 3 dB beamwidth of the array response; the 0.886/D formula is for reference", + "overview.focusError": "Max error in FOV", + "overview.fov": "FOV {low}° to {high}°", + "overview.requirements": "Requirement checks", + "overview.requirementsNone": "No requirements set", + "overview.passCount": "{passed}/{total} passed", + "overview.edit": "Edit", + "overview.layoutChecks": "Layout checks", + "req.resolution": "{axis} resolution", + "req.unambiguous_fov": "{axis} FOV unambiguous", + "req.max_error": "{axis} max error", + "req.peak_margin": "{axis} peak margin", + "req.psl": "2D peak sidelobe", + "req.pass": "Pass", + "req.fail": "Fail", + "req.na": "N/A", + "layout.coincident": "{a} and {b} are at the same position", + "layout.too_close": "{a}–{b} spacing {lambda} λ ({mm} mm) is below λ/2; the antennas may overlap", + "layout.design_outside_band": "The design frequency is outside the sweep range", + "note.resolution_optimistic": "The aperture-formula resolution is optimistic; use the measured 3 dB beamwidth", + "inspector.unit": "Unit", + "band.title": "In-band performance", + "band.subtitle": "Antennas fixed in place, evaluated at the sweep edges and the design frequency", + "band.metric": "Metric", + "band.role.start": "Start", + "band.role.design": "Design", + "band.role.stop": "Stop", + "band.singleFrequency": "Imported phase or dictionary data are single-frequency: the band evaluation scales the geometry only.", + "band.resolution": "{axis} resolution", + "band.noFold": "{axis} no-fold range", + "band.maxError": "{axis} max error in FOV", + "band.margin": "{axis} min margin", + "band.psl": "2D PSL", + "band.checks": "Requirements", + "band.wavelength": "Wavelength", + "compare.title": "Design comparison", + "compare.subtitle": "Compare library designs with the current project; each uses its own band, FOV and requirements", + "compare.current": "Current project", + "compare.run": "Compare", + "compare.empty": "The library is empty; save designs to the library first.", + "compare.pickHint": "Select up to 7 projects", + "compare.design": "Design", + "compare.channels": "Channels", + "compare.fov": "FOV", + "compare.band": "Band", + "dbf.fovLine": "FOV edge", }; export const ja: Messages = { @@ -720,7 +854,7 @@ export const ja: Messages = { "project.unsaved": "未保存の変更", "project.local": "ライブラリ未登録", - "top.frequency": "周波数", + "top.frequency": "設計周波数", "top.margin": "マージン", "top.marginTitle": "競合ピークマージンしきい値(折り返し判定)", "top.dictionary": "DBF 辞書", @@ -853,8 +987,6 @@ export const ja: Messages = { "overview.islr": "方位 ISLR", "overview.firstSidelobe": "方位第 1 サイドローブ", "overview.grating": "方位グレーティングローブ", - "overview.frontRadar": "前方レーダ評価", - "overview.ambiguity": "仰角曖昧性リスク", "overview.notes": "注意", "overview.computing": "計算中…", "overview.error": "計算に失敗しました", @@ -863,17 +995,10 @@ export const ja: Messages = { "cut.error_jump": "誤差ジャンプ", "cut.boundary_limited": "境界制限", "cut.unreliable": "スペクトル不良", - "cut.data_boundary": "データ端", + "cut.data_boundary": "視野全体をカバー", "cut.normal": "正常", "cut.pair": "負 {negative} / 正 {positive}", - "grade.Good": "良好", - "grade.Acceptable": "使用可", - "grade.Risky": "リスクあり", - "grade.Bad": "不良", - "level.High": "高", - "level.Medium": "中", - "level.Low": "低", "note.duplicate_virtual": "重複した仮想チャネルがあり、開口利用率が下がっています", "note.windowing": "方位サイドローブが高いため、窓関数を推奨します", @@ -920,7 +1045,7 @@ export const ja: Messages = { "dbf2d.loading": "2D スペクトルを計算しています…", "angle.title": "測角誤差と競合ピークマージン", - "angle.subtitle": "フレームごとの真の角度 −90°〜+90°(1° 刻み)", + "angle.subtitle": "視野内のフレームごとの真の角度(1° 刻み)、ピークは 0.002° まで細分化", "angle.errorChart": "{axis}測角誤差", "angle.marginChart": "{axis}競合ピークマージン", "angle.noFold": "折り返しなし範囲", @@ -1057,4 +1182,80 @@ export const ja: Messages = { "status.newProject": "新規プロジェクトを作成しました", "status.opened": "開きました:{name}", "status.uploadFailed": "アップロードに失敗しました:{message}", + "top.band": "周波数帯", + "top.bandCustom": "カスタム", + "top.design": "設計周波数", + "top.designTitle": "レイアウトの λ は設計周波数で定義されます。周波数帯を切り替えると λ のまま保持され、mm 寸法が変わります", + "top.settings": "評価設定", + "view.band": "周波数帯・比較", + "settings.title": "評価設定", + "settings.band": "周波数帯と掃引範囲", + "settings.bandHint": "FMCW の掃引範囲は帯域内評価に使われます。アンテナの物理位置は固定で、電気長が動作周波数とともに変わります。", + "settings.start": "開始 (GHz)", + "settings.stop": "終了 (GHz)", + "settings.design": "設計周波数 (GHz)", + "settings.preset92Note": "92 GHz には統一された割り当てがないため、既定の 90–94 GHz は仮の値です。使用チップの実際の掃引範囲を入力してください。", + "settings.fov": "評価視野", + "settings.fovHint": "測角評価は視野内で行います(探索は 10° 外側まで)。アレイパターン指標も視野内で集計します。視野外の目標は素子パターンで抑圧する必要があります。", + "settings.requirements": "仕様", + "settings.requirementsHint": "チェックした項目のみ判定します。分解能は実測 3 dB ビーム幅で判定します。", + "settings.reqAzRes": "方位分解能 ≤", + "settings.reqElRes": "仰角分解能 ≤", + "settings.reqUnambAz": "方位視野内で曖昧なし", + "settings.reqUnambEl": "仰角視野内で曖昧なし", + "settings.reqError": "視野内最大測角誤差 ≤", + "settings.reqMargin": "競合ピークマージン ≥", + "settings.reqPsl": "2D ピークサイドローブ ≤", + "settings.grid": "編集グリッド", + "settings.gridFree": "自由", + "settings.gridHint": "ドラッグと矢印キー移動のスナップ幅です。読み込み・入力した座標はそのまま保持します。", + "settings.invalidBand": "開始は終了より小さくしてください", + "settings.invalidFov": "視野は ±90° 内で 開始 < 0 < 終了 である必要があります", + "overview.resolutionSub": "式による推定 {value}", + "overview.resolutionTitle": "アレイ応答の実測 3 dB ビーム幅。0.886/D の式は参考値です", + "overview.focusError": "視野内最大誤差", + "overview.fov": "視野 {low}°〜{high}°", + "overview.requirements": "仕様チェック", + "overview.requirementsNone": "仕様が未設定です", + "overview.passCount": "{passed}/{total} 項目合格", + "overview.edit": "設定", + "overview.layoutChecks": "配置チェック", + "req.resolution": "{axis}分解能", + "req.unambiguous_fov": "{axis}視野内で曖昧なし", + "req.max_error": "{axis}最大誤差", + "req.peak_margin": "{axis}競合ピークマージン", + "req.psl": "2D ピークサイドローブ", + "req.pass": "合格", + "req.fail": "不合格", + "req.na": "対象外", + "layout.coincident": "{a} と {b} が同じ位置です", + "layout.too_close": "{a}–{b} 間隔 {lambda} λ({mm} mm)が λ/2 未満で、アンテナが重なる可能性があります", + "layout.design_outside_band": "設計周波数が掃引範囲外です", + "note.resolution_optimistic": "開口式による分解能は楽観的です。実測 3 dB ビーム幅を基準にしてください", + "inspector.unit": "単位", + "band.title": "帯域内性能", + "band.subtitle": "アンテナ位置を固定し、掃引の両端と設計周波数で評価します", + "band.metric": "指標", + "band.role.start": "開始", + "band.role.design": "設計", + "band.role.stop": "終了", + "band.singleFrequency": "読み込んだ位相・辞書データは単一周波数です。帯域評価では幾何のみをスケーリングします。", + "band.resolution": "{axis}分解能", + "band.noFold": "{axis}折り返しなし範囲", + "band.maxError": "{axis}視野内最大誤差", + "band.margin": "{axis}最小マージン", + "band.psl": "2D PSL", + "band.checks": "仕様チェック", + "band.wavelength": "波長", + "compare.title": "設計比較", + "compare.subtitle": "ライブラリの設計を現在のプロジェクトと比較します。各設計は自身の周波数帯・視野・仕様を使います", + "compare.current": "現在のプロジェクト", + "compare.run": "比較する", + "compare.empty": "ライブラリが空です。先に設計を保存してください。", + "compare.pickHint": "最大 7 件まで選択できます", + "compare.design": "設計周波数", + "compare.channels": "チャネル", + "compare.fov": "視野", + "compare.band": "周波数帯", + "dbf.fovLine": "視野境界", }; diff --git a/web/src/lib/geometry.ts b/web/src/lib/geometry.ts index 62e4b81..ed23346 100644 --- a/web/src/lib/geometry.ts +++ b/web/src/lib/geometry.ts @@ -7,8 +7,10 @@ export interface ElementRef { index: number; } +/** Snap to the editor grid; step 0 means free placement (1e-6 λ resolution). */ export function snap(value: number, step = GRID_STEP): number { - const snapped = Math.round(value / step) * step; + const grid = step > 0 ? step : 1e-6; + const snapped = Math.round(Math.round(value / grid) * grid * 1e9) / 1e9; return Object.is(snapped, -0) ? 0 : snapped; } diff --git a/web/src/state/compute.ts b/web/src/state/compute.ts index ac81056..4c15a6b 100644 --- a/web/src/state/compute.ts +++ b/web/src/state/compute.ts @@ -11,9 +11,15 @@ export function evaluationKey(project: Project): string { return JSON.stringify(rest); } -/** Fields that affect DBF spectra (frequency, margin and element pattern do not). */ +/** Fields that affect DBF spectra and metrics (frequency and element pattern do not). */ export function dbfKey(project: Project): string { - return JSON.stringify([project.layout, project.channel_patterns, project.dbf_dictionary]); + return JSON.stringify([ + project.layout, + project.channel_patterns, + project.dbf_dictionary, + project.fov, + project.ambiguity_margin_db, + ]); } export function useEvaluationSync(): void { diff --git a/web/src/state/store.ts b/web/src/state/store.ts index 0477dc3..0f6a481 100644 --- a/web/src/state/store.ts +++ b/web/src/state/store.ts @@ -3,11 +3,12 @@ import type { Evaluation, Layout, Project, ServerConfig } from "../api/types"; import { type ElementRef, layoutsEqual, renumber } from "../lib/geometry"; import type { MessageKey } from "../i18n/messages"; -export type ViewId = "array" | "dbf1d" | "dbf2d" | "angle"; +export type ViewId = "array" | "dbf1d" | "dbf2d" | "angle" | "band"; export type Language = "zh" | "en" | "ja"; export type ThemeMode = "system" | "light" | "dark"; export type DisplayMode = "db" | "magnitude"; -export type DialogId = "dictionary" | "patterns" | "report" | "projects" | "help" | null; +export type CoordUnit = "lambda" | "mm"; +export type DialogId = "dictionary" | "patterns" | "report" | "projects" | "help" | "settings" | null; export interface StatusMessage { key: MessageKey; @@ -29,6 +30,7 @@ interface PersistedState { theme: ThemeMode; display: DisplayMode; view: ViewId; + coordUnit: CoordUnit; } function readPersisted(): Partial { @@ -55,6 +57,17 @@ function detectLanguage(): Language { return "zh"; } +function withDefaults(draft: Project, defaults: Project): Project { + return { + ...defaults, + ...draft, + band: draft.band ?? defaults.band, + fov: draft.fov ?? defaults.fov, + grid_step_lambda: draft.grid_step_lambda ?? defaults.grid_step_lambda, + requirements: { ...defaults.requirements, ...(draft.requirements ?? {}) }, + }; +} + export function projectSnapshot(project: Project): string { return JSON.stringify(project); } @@ -73,6 +86,7 @@ interface AppState { language: Language; theme: ThemeMode; display: DisplayMode; + coordUnit: CoordUnit; status: StatusMessage | null; evaluation: Evaluation | null; evaluationError: string | null; @@ -93,6 +107,7 @@ interface AppState { setLanguage(language: Language): void; setTheme(theme: ThemeMode): void; setDisplay(display: DisplayMode): void; + setCoordUnit(unit: CoordUnit): void; setEvaluation(evaluation: Evaluation | null, error: string | null): void; setEvaluating(evaluating: boolean): void; } @@ -113,6 +128,7 @@ export const useStore = create((set, get) => ({ language: persisted.language ?? (typeof navigator === "undefined" ? "zh" : detectLanguage()), theme: persisted.theme ?? "system", display: persisted.display ?? "db", + coordUnit: persisted.coordUnit ?? "lambda", status: null, evaluation: null, evaluationError: null, @@ -120,7 +136,9 @@ export const useStore = create((set, get) => ({ initialize(config) { const draft = persisted.project; - const project = draft && draft.version === 2 && draft.layout ? draft : config.default_project; + const usable = draft && draft.version === 2 && draft.layout; + // Drafts saved before bands/FOV existed: fill new fields from the defaults. + const project = usable ? withDefaults(draft, config.default_project) : config.default_project; set({ config, project }); }, @@ -221,6 +239,9 @@ export const useStore = create((set, get) => ({ setDisplay(display) { set({ display }); }, + setCoordUnit(coordUnit) { + set({ coordUnit }); + }, setEvaluation(evaluation, error) { set({ evaluation, evaluationError: error }); }, @@ -240,6 +261,7 @@ useStore.subscribe((state) => { theme: state.theme, display: state.display, view: state.view, + coordUnit: state.coordUnit, }); }); diff --git a/web/src/styles/global.css b/web/src/styles/global.css index d584ce4..d6135fc 100644 --- a/web/src/styles/global.css +++ b/web/src/styles/global.css @@ -1207,6 +1207,17 @@ select.input { color: var(--danger); } +@media (max-width: 1640px) { + .chip-label, + .controlbar .field-label { + display: none; + } + + .controlbar .field input { + padding-left: 9px; + } +} + @media (max-width: 1180px) { :root { --overview-width: 280px; diff --git a/web/src/styles/views.css b/web/src/styles/views.css index 343e0eb..67e7bce 100644 --- a/web/src/styles/views.css +++ b/web/src/styles/views.css @@ -609,3 +609,70 @@ details.collapsible[open] > summary .chevron { margin-left: 0; } } + +.checks { + display: flex; + flex-direction: column; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} + +.checks li { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; + gap: 8px; +} + +.check-label { + color: var(--text-secondary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.check-value { + font-size: 12px; + font-weight: 500; + white-space: nowrap; +} + +.notes li.bad svg { + color: var(--danger); +} + +.overview-section h3 .badge { + text-transform: none; + letter-spacing: 0; +} + +.metric-table td:first-child { + color: var(--text-secondary); +} + +.metric-table td.num svg { + vertical-align: -2px; +} + +.metric-table td.cell-fail { + background: var(--danger-fill); +} + +.pick-list { + display: flex; + flex-wrap: wrap; + gap: 6px 16px; + align-items: center; +} + +.pick-item { + padding: 4px 10px; + border: 1px solid var(--border); + border-radius: 14px; +} + +.pick-item .subtle { + font-size: 12px; +} diff --git a/web/src/views/AngleView.tsx b/web/src/views/AngleView.tsx index 99cb442..301d27a 100644 --- a/web/src/views/AngleView.tsx +++ b/web/src/views/AngleView.tsx @@ -110,8 +110,8 @@ function AngleChart({ bank, kind }: { bank: DbfBank; kind: "error" | "margin" }) (value, i) => Number.isFinite(value) && (left === null || right === null || right <= left || (x[i] >= left && x[i] <= right)), ); - const spread = Math.max(1, ...inRange.map((value) => Math.abs(value))); - const limit = Math.min(Math.max(spread * 1.25, 2), 180); + const spread = Math.max(0, ...inRange.map((value) => Math.abs(value))); + const limit = Math.min(Math.max(spread * 1.25, 0.1), 180); return { data: [ { @@ -121,12 +121,12 @@ function AngleChart({ bank, kind }: { bank: DbfBank; kind: "error" | "margin" }) y, line: { color: theme.line, width: 1.8 }, name: t("angle.errorSeries"), - hovertemplate: "%{x:+.0f}° %{y:+.2f}°", + hovertemplate: "%{x:+.0f}° %{y:+.3f}°", }, ], layout: baseLayout(theme, { shapes: band, - xaxis: { title: { text: t("axis.trueAngle") }, range: [-90, 90], dtick: 30 }, + xaxis: { title: { text: t("axis.trueAngle") }, range: [x[0], x[x.length - 1]], dtick: x[x.length - 1] - x[0] > 90 ? 30 : 10 }, yaxis: { title: { text: t("axis.error") }, range: [-limit, limit], zeroline: true }, }), }; @@ -161,7 +161,7 @@ function AngleChart({ bank, kind }: { bank: DbfBank; kind: "error" | "margin" }) ...band, { type: "line", xref: "paper", x0: 0, x1: 1, y0: threshold, y1: threshold, line: { color: theme.danger, width: 1.2, dash: "dash" } }, ], - xaxis: { title: { text: t("axis.trueAngle") }, range: [-90, 90], dtick: 30 }, + xaxis: { title: { text: t("axis.trueAngle") }, range: [x[0], x[x.length - 1]], dtick: x[x.length - 1] - x[0] > 90 ? 30 : 10 }, yaxis: { title: { text: t("axis.margin") }, range: [0, top * 1.04], rangemode: "tozero" }, }), }; diff --git a/web/src/views/ArrayView.tsx b/web/src/views/ArrayView.tsx index f476ea2..c0eff8f 100644 --- a/web/src/views/ArrayView.tsx +++ b/web/src/views/ArrayView.tsx @@ -16,12 +16,39 @@ import { Button, NumberInput } from "../components/ui"; import { useT } from "../i18n"; import { elementName, nextElementPosition, snap, virtualGroups } from "../lib/geometry"; import { parseNumber, trimNumber } from "../lib/format"; -import { useStore } from "../state/store"; +import { type CoordUnit, useStore } from "../state/store"; +import { Segmented } from "../components/ui"; import { PhysicalEditor } from "./PhysicalEditor"; import { VirtualPlot } from "./VirtualPlot"; const STARTER_LAYOUT: Layout = { tx: [{ x: 0, y: 2 }], rx: [{ x: 0, y: -2 }] }; +/** Coordinate entry in λ or mm; typed values are kept exactly (no grid snap). */ +function CoordInput({ + value, + unit, + mmPerLambda, + onCommit, + className, +}: { + value: number; + unit: CoordUnit; + mmPerLambda: number; + onCommit: (lambda: number) => void; + className?: string; +}) { + const scale = unit === "mm" ? mmPerLambda : 1; + return ( + parseNumber(text, unit === "mm" ? ["mm"] : ["λ"])} + format={(v) => trimNumber(v, unit === "mm" ? 3 : 4)} + onCommit={(v) => onCommit(snap(v / scale, 0))} + /> + ); +} + export function ArrayView() { const t = useT(); const project = useStore((state) => state.project)!; @@ -31,7 +58,8 @@ export function ArrayView() { const past = useStore((state) => state.past.length); const future = useStore((state) => state.future.length); const evaluation = useStore((state) => state.evaluation); - const { commitLayout, select, setDeleteMode, undo, redo, setStatus } = useStore.getState(); + const unit = useStore((state) => state.coordUnit); + const { commitLayout, select, setDeleteMode, undo, redo, setStatus, setCoordUnit } = useStore.getState(); const [preview, setPreview] = useState(null); const [fitSignal, setFitSignal] = useState(0); @@ -169,6 +197,7 @@ export function ArrayView() { selection={selection} deleteMode={deleteMode} mmPerLambda={mmPerLambda} + gridStep={project.grid_step_lambda} fitSignal={fitSignal} onSelect={select} onCommit={commitMove} @@ -187,29 +216,40 @@ export function ArrayView() { {elementName(selection.kind, selection.index)} - ({trimNumber(selected.x * mmPerLambda, 2)}, {trimNumber(selected.y * mmPerLambda, 2)}) mm + {unit === "mm" + ? `(${trimNumber(selected.x)}, ${trimNumber(selected.y)}) λ` + : `(${trimNumber(selected.x * mmPerLambda, 2)}, ${trimNumber(selected.y * mmPerLambda, 2)}) mm`} + ) : ( {t("inspector.none")} @@ -324,23 +364,17 @@ function CoordinateTable({ {elementName(kind, index)} - parseNumber(text, ["λ"])} - format={(value) => trimNumber(value)} - onCommit={(value) => onChange(kind, index, { x: snap(value), y: point.y })} - /> + onChange(kind, index, { x, y: point.y })} /> - parseNumber(text, ["λ"])} - format={(value) => trimNumber(value)} - onCommit={(value) => onChange(kind, index, { x: point.x, y: snap(value) })} - /> + onChange(kind, index, { x: point.x, y })} /> + + + onChange(kind, index, { x, y: point.y })} /> + + + onChange(kind, index, { x: point.x, y })} /> - {trimNumber(point.x * mmPerLambda, 2)} - {trimNumber(point.y * mmPerLambda, 2)} ))} diff --git a/web/src/views/BandView.tsx b/web/src/views/BandView.tsx new file mode 100644 index 0000000..00c421f --- /dev/null +++ b/web/src/views/BandView.tsx @@ -0,0 +1,333 @@ +import { GitCompare, RefreshCw } from "lucide-react"; +import { type ReactNode, useEffect, useState } from "react"; +import { api, errorMessage } from "../api/client"; +import type { AngleMetrics, Axis, BandSweep, CompareItem, PerformanceSummary, ProjectSummary, RequirementCheck } from "../api/types"; +import { errorText, marginText, noFoldText, StatusIcon } from "../components/Overview"; +import { Button, Callout, Spinner } from "../components/ui"; +import { type Translate, useT } from "../i18n"; +import { wire } from "../lib/encoding"; +import { fmt, trimNumber } from "../lib/format"; +import { evaluationKey } from "../state/compute"; +import { useStore } from "../state/store"; + +const MAX_PICK = 7; + +type Summary = Partial; + +function angleOf(summary: Summary, axis: Axis): AngleMetrics | null { + const value = summary.angle?.[axis]; + return value && !("error" in value) ? value : null; +} + +function checkStatus(summary: Summary, key: RequirementCheck["key"], axis: Axis | null) { + return summary.requirements?.find((check) => check.key === key && check.axis === axis)?.status; +} + +function cellClass(status: string | undefined) { + return status === "fail" ? "cell-fail" : status === "pass" ? "cell-pass" : ""; +} + +interface MetricRow { + label: string; + render: (summary: Summary) => ReactNode; + status?: (summary: Summary) => string | undefined; +} + +function metricRows(t: Translate): MetricRow[] { + const rows: MetricRow[] = []; + for (const axis of ["azimuth", "elevation"] as Axis[]) { + const name = t(axis === "azimuth" ? "axis.azimuth" : "axis.elevation"); + rows.push( + { + label: t("band.resolution", { axis: name }), + render: (s) => fmt(wire(s.resolution?.[axis].value ?? null), 2, "°"), + status: (s) => checkStatus(s, "resolution", axis), + }, + { + label: t("band.noFold", { axis: name }), + render: (s) => (angleOf(s, axis) ? noFoldText(angleOf(s, axis)!) : "—"), + status: (s) => checkStatus(s, "unambiguous_fov", axis), + }, + { + label: t("band.maxError", { axis: name }), + render: (s) => (angleOf(s, axis) ? errorText(wire(angleOf(s, axis)!.focus_max_abs_error)) : "—"), + status: (s) => checkStatus(s, "max_error", axis), + }, + { + label: t("band.margin", { axis: name }), + render: (s) => (angleOf(s, axis) ? marginText(angleOf(s, axis)!, t) : "—"), + status: (s) => checkStatus(s, "peak_margin", axis), + }, + ); + } + rows.push( + { + label: t("band.psl"), + render: (s) => fmt(wire(s.psl_db ?? null), 1, " dB"), + status: (s) => checkStatus(s, "psl", null), + }, + { + label: t("band.checks"), + render: (s) => { + const applicable = (s.requirements ?? []).filter((check) => check.status !== "na"); + if (applicable.length === 0) return "—"; + const passed = applicable.filter((check) => check.status === "pass").length; + return ( + + {t("overview.passCount", { passed, total: applicable.length })} + + ); + }, + }, + ); + return rows; +} + +export function BandView() { + return ( +
    + + +
    + ); +} + +function BandPanel() { + const t = useT(); + const project = useStore((state) => state.project)!; + const key = evaluationKey(project); + const [sweep, setSweep] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(false); + + useEffect(() => { + const controller = new AbortController(); + setLoading(true); + const timer = window.setTimeout(() => { + api + .band(project, controller.signal) + .then((result) => { + setSweep(result); + setError(null); + }) + .catch((reason) => { + if ((reason as Error).name !== "AbortError") setError(errorMessage(reason)); + }) + .finally(() => !controller.signal.aborted && setLoading(false)); + }, 150); + return () => { + window.clearTimeout(timer); + controller.abort(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + + const rows = metricRows(t); + const roleLabel = (role: string) => + role + .split("+") + .map((part) => t(`band.role.${part}` as "band.role.start")) + .join(" / "); + + return ( +
    +
    +
    + + {t("band.title")} + {sweep && ( + + {trimNumber(sweep.band.start_ghz, 3)}–{trimNumber(sweep.band.stop_ghz, 3)} GHz + + )} + + {t("band.subtitle")} +
    +
    {loading && }
    +
    +
    + {error && {error}} + {sweep && !sweep.design_in_band && {t("layout.design_outside_band")}} + {sweep?.uses_single_frequency_data && {t("band.singleFrequency")}} + {sweep && ( +
    + + + + + {sweep.points.map((point) => ( + + ))} + + + + + + {sweep.points.map((point) => ( + + ))} + + {rows.map((row) => ( + + + {sweep.points.map((point) => ( + + ))} + + ))} + +
    {t("band.metric")} + {trimNumber(point.frequency_ghz, 3)} GHz +
    + {roleLabel(point.role)} +
    +
    {t("band.wavelength")} + {fmt(point.wavelength_mm, 3, " mm")} +
    {row.label} + {row.status?.(point) && } {row.render(point)} +
    +
    + )} +
    +
    + ); +} + +function ComparePanel() { + const t = useT(); + const project = useStore((state) => state.project)!; + const projectId = useStore((state) => state.projectId); + const [library, setLibrary] = useState(null); + const [picked, setPicked] = useState([]); + const [results, setResults] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(false); + + useEffect(() => { + api.listProjects().then( + (items) => setLibrary(items.filter((item) => item.id !== projectId)), + (reason) => setError(errorMessage(reason)), + ); + }, [projectId]); + + const run = async () => { + setLoading(true); + setError(null); + try { + const records = await Promise.all(picked.map((id) => api.getProject(id))); + setResults(await api.compare([project, ...records.map((record) => record.project)])); + } catch (reason) { + setError(errorMessage(reason)); + } finally { + setLoading(false); + } + }; + + const rows = metricRows(t); + return ( +
    +
    +
    + {t("compare.title")} + {t("compare.subtitle")} +
    +
    + {loading && } + +
    +
    +
    + {error && {error}} + {library && library.length === 0 &&

    {t("compare.empty")}

    } + {library && library.length > 0 && ( +
    + {t("compare.pickHint")} + {library.map((item) => ( + + ))} +
    + )} + {results && ( +
    + + + + + {results.map((item, index) => ( + + ))} + + + + + + {results.map((item, index) => ( + + ))} + + + + {results.map((item, index) => ( + + ))} + + + + {results.map((item, index) => ( + + ))} + + + + {results.map((item, index) => ( + + ))} + + {rows.map((row) => ( + + + {results.map((item, index) => ( + + ))} + + ))} + +
    {t("band.metric")} + {item.name} + {index === 0 &&
    {t("compare.current")}
    } +
    {t("compare.band")} + {trimNumber(item.band.start_ghz, 2)}–{trimNumber(item.band.stop_ghz, 2)} GHz +
    {t("compare.design")}{trimNumber(item.design_ghz, 3)} GHz
    {t("compare.channels")}{item.tx_count}T × {item.rx_count}R
    {t("compare.fov")} + Az {item.fov.azimuth[0]}~{item.fov.azimuth[1]}° · El {item.fov.elevation[0]}~{item.fov.elevation[1]}° +
    {row.label} + {item.error ? ( + index === 0 || row === rows[0] ? {item.error} : "—" + ) : ( + <> + {row.status?.(item) && } {row.render(item)} + + )} +
    +
    + )} +
    +
    + ); +} diff --git a/web/src/views/Dbf2dView.tsx b/web/src/views/Dbf2dView.tsx index dc75b59..b2ee46d 100644 --- a/web/src/views/Dbf2dView.tsx +++ b/web/src/views/Dbf2dView.tsx @@ -38,8 +38,8 @@ function angleKey(az: number, el: number) { return `${az}|${el}`; } -function wrapAngle(value: number) { - return value > 90 ? -90 : value; +function wrapAngle(value: number, range: [number, number]) { + return value > range[1] ? range[0] : value; } function useFrameCache(project: Project, enabled: boolean, maxBatch: number) { @@ -111,6 +111,8 @@ export function Dbf2dView() { const config = useStore((state) => state.config)!; const evaluation = useStore((state) => state.evaluation); const available = evaluation?.capability.two_d ?? true; + const azRange = project.fov.azimuth; + const elRange = project.fov.elevation; const [trueAz, setTrueAz] = useState(0); const [trueEl, setTrueEl] = useState(0); const [playAz, setPlayAz] = useState(false); @@ -132,27 +134,33 @@ export function Dbf2dView() { let az = trueAz; let el = trueEl; for (let i = 0; i < PREFETCH; i += 1) { - if (playAz) az = wrapAngle(az + 1); - if (playEl) el = wrapAngle(el + 1); + if (playAz) az = wrapAngle(az + 1, azRange); + if (playEl) el = wrapAngle(el + 1, elRange); angles.push([az, el]); } } const timer = window.setTimeout(() => request(angles), playAz || playEl ? 0 : 60); return () => window.clearTimeout(timer); - }, [trueAz, trueEl, playAz, playEl, available, request, frames.version]); + }, [trueAz, trueEl, playAz, playEl, available, request, frames.version, azRange, elRange]); useEffect(() => { if (!playAz && !playEl) return; const timer = window.setInterval(() => { - const nextAz = playAz ? wrapAngle(trueAz + 1) : trueAz; - const nextEl = playEl ? wrapAngle(trueEl + 1) : trueEl; + const nextAz = playAz ? wrapAngle(trueAz + 1, azRange) : trueAz; + const nextEl = playEl ? wrapAngle(trueEl + 1, elRange) : trueEl; if (get(nextAz, nextEl)) { setTrueAz(nextAz); setTrueEl(nextEl); } }, 1000 / PLAY_FPS); return () => window.clearInterval(timer); - }, [playAz, playEl, trueAz, trueEl, get]); + }, [playAz, playEl, trueAz, trueEl, get, azRange, elRange]); + + // Keep the true angle inside the FOV when it changes. + useEffect(() => { + setTrueAz((value) => Math.min(Math.max(value, azRange[0]), azRange[1])); + setTrueEl((value) => Math.min(Math.max(value, elRange[0]), elRange[1])); + }, [azRange, elRange]); const loading = available && !current; @@ -190,6 +198,7 @@ export function Dbf2dView() { {available && shown && frames.scan && ( { setPlayAz(false); setPlayEl(false); - setTrueAz(Math.round(az)); - setTrueEl(Math.round(el)); + setTrueAz(Math.min(Math.max(Math.round(az), azRange[0]), azRange[1])); + setTrueEl(Math.min(Math.max(Math.round(el), elRange[0]), elRange[1])); }} /> )} @@ -228,6 +237,7 @@ export function Dbf2dView() {
    {t("dbf.peak")} - {fmtSigned(bank.frames.estimated[frame], 0)} + {fmtSigned(bank.frames.estimated[frame], 2)} {t("dbf.error")} - {fmtSigned(error, 1)} + {fmtSigned(error, Math.abs(error) < 1 ? 3 : 2)} {t("dbf.margin")} @@ -151,8 +151,11 @@ function SpectrumChart({ bank, frame, onSeek }: { bank: DbfBank; frame: number; const values = useMemo(() => displayValues(matrixRow(matrix, frame), display), [matrix, frame, display]); const scan = bank.scan_angles; const peakAngle = bank.frames.estimated[frame]; - const peakIndex = scan.indexOf(peakAngle); - const trueIndex = scan.reduce((best, angle, i) => (Math.abs(angle - trueAngle) < Math.abs(scan[best] - trueAngle) ? i : best), 0); + const nearest = (target: number) => + scan.reduce((best, angle, i) => (Math.abs(angle - target) < Math.abs(scan[best] - target) ? i : best), 0); + const peakIndex = nearest(peakAngle); + const trueIndex = nearest(trueAngle); + const [fovLow, fovHigh] = bank.fov; const magnitude = display === "magnitude"; const data = useMemo( @@ -181,7 +184,7 @@ function SpectrumChart({ bank, frame, onSeek }: { bank: DbfBank; frame: number; type: "scatter", mode: "markers", x: [peakAngle], - y: [values[peakIndex >= 0 ? peakIndex : 0]], + y: [values[peakIndex]], marker: { size: 11, symbol: "x-thin", color: theme.peak, line: { color: theme.peak, width: 2.5 } }, name: t("dbf.legendPeak"), hoverinfo: "skip", @@ -197,6 +200,15 @@ function SpectrumChart({ bank, frame, onSeek }: { bank: DbfBank; frame: number; showlegend: true, legend: { orientation: "h", x: 1, xanchor: "right", y: 1.02, yanchor: "bottom", font: { size: 11 } }, shapes: [ + ...[fovLow, fovHigh].map((edge) => ({ + type: "line", + x0: edge, + x1: edge, + yref: "paper", + y0: 0, + y1: 1, + line: { color: theme.zero, width: 1, dash: "dot" }, + })), { type: "line", x0: trueAngle, @@ -207,7 +219,12 @@ function SpectrumChart({ bank, frame, onSeek }: { bank: DbfBank; frame: number; line: { color: theme.trueAngle, width: 1.6 }, }, ], - xaxis: { title: { text: axisTitle }, range: [-90, 90], dtick: 30, zeroline: false }, + xaxis: { + title: { text: axisTitle }, + range: [scan[0], scan[scan.length - 1]], + dtick: scan[scan.length - 1] - scan[0] > 90 ? 30 : 10, + zeroline: false, + }, yaxis: { title: { text: t(magnitude ? "axis.correlationMag" : "axis.correlationDb") }, range: magnitude ? [-0.02, 1.04] : [-40.5, 1], @@ -215,7 +232,7 @@ function SpectrumChart({ bank, frame, onSeek }: { bank: DbfBank; frame: number; zeroline: false, }, }), - [theme, trueAngle, axisTitle, magnitude, t], + [theme, trueAngle, axisTitle, magnitude, t, scan, fovLow, fovHigh], ); return ( diff --git a/web/src/views/PhysicalEditor.tsx b/web/src/views/PhysicalEditor.tsx index 9437ad6..01936de 100644 --- a/web/src/views/PhysicalEditor.tsx +++ b/web/src/views/PhysicalEditor.tsx @@ -31,6 +31,7 @@ export function PhysicalEditor({ selection, deleteMode, mmPerLambda, + gridStep, fitSignal, onSelect, onCommit, @@ -42,6 +43,7 @@ export function PhysicalEditor({ selection: ElementRef | null; deleteMode: boolean; mmPerLambda: number; + gridStep: number; fitSignal: number; onSelect: (ref: ElementRef | null) => void; onCommit: (layout: Layout, selection: ElementRef | null) => void; @@ -145,7 +147,7 @@ export function PhysicalEditor({ const next = { ...drag, position, moved }; setDrag(next); if (moved) { - const snapped = { x: snap(position.x), y: snap(position.y) }; + const snapped = { x: snap(position.x, gridStep), y: snap(position.y, gridStep) }; onPreview(withPosition(layout, drag.ref, snapped)); onStatus?.( `${elementName(drag.ref.kind, drag.ref.index)} x=${trimNumber(snapped.x)} λ y=${trimNumber(snapped.y)} λ`, @@ -166,7 +168,7 @@ export function PhysicalEditor({ const onPointerUp = (event: React.PointerEvent) => { if (drag && event.pointerId === drag.pointerId) { if (drag.moved) { - const snapped = { x: snap(drag.position.x), y: snap(drag.position.y) }; + const snapped = { x: snap(drag.position.x, gridStep), y: snap(drag.position.y, gridStep) }; onCommit(withPosition(layout, drag.ref, snapped), drag.ref); } setDrag(null); @@ -181,7 +183,8 @@ export function PhysicalEditor({ const onKeyDown = (event: React.KeyboardEvent) => { if (!selection) return; - const step = event.shiftKey ? 2.5 : 0.5; + const base = gridStep > 0 ? gridStep : 0.1; + const step = event.shiftKey ? base * 5 : base; const delta: Record = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], @@ -193,7 +196,10 @@ export function PhysicalEditor({ event.preventDefault(); const point = layout[selection.kind][selection.index]; if (!point) return; - onCommit(withPosition(layout, selection, { x: snap(point.x + move[0]), y: snap(point.y + move[1]) }), selection); + onCommit( + withPosition(layout, selection, { x: snap(point.x + move[0], gridStep), y: snap(point.y + move[1], gridStep) }), + selection, + ); } }; @@ -257,7 +263,7 @@ export function PhysicalEditor({ const hovered = hover ? displayLayout[hover.kind][hover.index] : null; const hoverScreen = hovered ? toScreen(hovered.x, hovered.y) : null; - const snapGhost = drag?.moved ? { x: snap(drag.position.x), y: snap(drag.position.y) } : null; + const snapGhost = drag?.moved && gridStep > 0 ? { x: snap(drag.position.x, gridStep), y: snap(drag.position.y, gridStep) } : null; const ghostScreen = snapGhost ? toScreen(snapGhost.x, snapGhost.y) : null; return ( @@ -292,7 +298,7 @@ export function PhysicalEditor({ /> - + 0 ? gridStep : 0.5} {...plane} /> {ghostScreen && ( { sx: number; sy: number }; toWorld: (sx: number, sy: number) => { x: number; y: number }; showMinor?: boolean; + minorStep?: number; }) { const lines = useMemo(() => { const left = PLOT_MARGIN.left; @@ -146,7 +148,7 @@ export function PlaneGrid({ const topLeft = toWorld(left, top); const bottomRight = toWorld(right, bottom); const major = niceStep(viewport.scale, 46); - const minor = 0.5; + const minor = minorStep; const result: { minor: string[]; major: string[]; xLabels: [number, number][]; yLabels: [number, number][] } = { minor: [], major: [], @@ -170,7 +172,7 @@ export function PlaneGrid({ if (isMajor) result.yLabels.push([sy, y]); } return { ...result, left, right, top, bottom }; - }, [width, height, viewport, toScreen, toWorld, showMinor]); + }, [width, height, viewport, toScreen, toWorld, showMinor, minorStep]); const format = (value: number) => (Math.abs(value) < 1e-9 ? "0" : String(Math.round(value * 100) / 100)); diff --git a/web/src/views/usePlayback.ts b/web/src/views/usePlayback.ts index 3845aa8..8588b00 100644 --- a/web/src/views/usePlayback.ts +++ b/web/src/views/usePlayback.ts @@ -10,6 +10,13 @@ export function usePlayback(count: number, initialIndex: number) { const indexRef = useRef(index); indexRef.current = index; + // A new spectrum bank (e.g. another FOV) moves the reference frame: stop and + // return to it instead of keeping a stale index. + useEffect(() => { + setPlaying(false); + setIndex(initialIndex); + }, [initialIndex, count]); + useEffect(() => { if (!playing || count <= 0) return; let frame = 0; From 44ef4b9277725a5ef154b8eae883363b5a0a99f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 12:55:05 +0000 Subject: [PATCH 5/5] =?UTF-8?q?UI/UX=20=E7=BB=9F=E4=B8=80=E4=B8=8E?= =?UTF-8?q?=E4=BC=98=E5=8C=96=EF=BC=9A=E5=8F=82=E6=95=B0=E6=A0=8F=E3=80=81?= =?UTF-8?q?=E9=9D=A2=E6=9D=BF=E7=BB=93=E6=9E=84=E3=80=81=E6=B5=8B=E8=A7=92?= =?UTF-8?q?=E8=A7=86=E5=9B=BE=E4=B8=8E=E5=AF=B9=E8=AF=9D=E6=A1=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 顶部参数栏改为「标签在上、数值在下」的参数条,窄屏不再隐藏标签;频段改为下拉菜单(60G/77G/92G/自定义) - 所有视图面板统一为:标题区 → 工具栏行 → 图表 → 底部读数行 - 阵列布局:物理阵列工具栏整合添加/自动排阵(弹出式)/删除/撤销/适配/坐标表,底部单行检视器 - 1D/2D DBF:播放与扫描控件移入工具栏,读数移到底部 - 测角性能:方位/俯仰两栏,误差与裕量上下对齐,图例与指标汇总;去掉单独的标题卡 - 测角误差图 PNG 导出移入顶部「导出」菜单,状态栏提示结果 - 概览的测角评估改为方位/俯仰对照表 - 通道幅相对话框改为两个标签页,空槽位悬停时才显示「+」 - 项目库空状态、菜单勾选图标、图表坐标轴标题字体统一 - 修正 ±90° 等过时文案;手机宽度下工具栏改为换行,避免控件被隐藏 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TgRQxvYJLtrCkPBUDGPWAw --- README.md | 6 +- web/src/charts/theme.ts | 12 +- web/src/components/Chrome.tsx | 232 ++++++++++++++++++-------- web/src/components/Overview.tsx | 97 +++++++---- web/src/components/ui.tsx | 24 ++- web/src/dialogs/PatternsDialog.tsx | 46 +++-- web/src/dialogs/ProjectsDialog.tsx | 10 +- web/src/i18n/help.ts | 6 +- web/src/i18n/messages.ts | 88 ++++++---- web/src/styles/global.css | 199 ++++++++++++++++++++-- web/src/styles/views.css | 250 ++++++++++++++++++++++++++-- web/src/views/AngleView.tsx | 169 ++++++++++++------- web/src/views/ArrayView.tsx | 258 ++++++++++++++++++----------- web/src/views/Dbf2dView.tsx | 143 ++++++++-------- web/src/views/DbfView.tsx | 72 ++++---- 15 files changed, 1168 insertions(+), 444 deletions(-) diff --git a/README.md b/README.md index d33a7c6..5174fa7 100644 --- a/README.md +++ b/README.md @@ -13,10 +13,10 @@ MIMO 阵列工作台:评估 60 GHz / 77 GHz / 92 GHz 毫米波 FMCW 雷达的 ### 界面 - **阵列布局**:SVG 编辑器,可拖拽 Tx/Rx,松开后吸附到 λ/2 网格;支持滚轮缩放、平移、方向键微调、删除模式、撤销/重做(50 步)、自动排阵(T/R 数量),坐标表可批量精确编辑(同时显示 mm)。拖动时虚拟阵列实时预览;选中物理通道时,与之相关的虚拟点会高亮。 -- **1D DBF**:方位/俯仰字典角谱,共 181 帧真实角(−90°~+90°)。播放、拖动、点击图上任意位置都可跳转;实时显示峰值、误差、竞争峰裕量和峰质量。 +- **1D DBF**:方位/俯仰字典角谱,真实角为视场内 1° 步进的逐帧角度。播放、拖动、点击图上任意位置都可跳转;实时显示峰值、误差、竞争峰裕量和峰质量。 - **2D DBF**:方位 × 俯仰相关热图。点击热图设定真实角;方位、俯仰可分别或同时扫描,服务器端预取后续帧。 -- **测角性能**:逐帧测角误差和竞争峰裕量曲线,标注不模糊范围和裕量阈值,可导出出版级 PNG。 -- **阵列概览**:通道数、虚拟通道利用率、口径(mm/λ)、分辨率、测角评估、方向图指标和提示。 +- **测角性能**:方位/俯仰两栏,每栏上下排列测角误差与竞争峰裕量曲线,标注不模糊范围和裕量阈值,底部汇总关键指标;「导出 → 导出测角误差图 PNG」生成出版级图片。 +- **阵列概览**:通道数、虚拟通道利用率、口径(mm/λ)、分辨率、规格检查、方位/俯仰对照的测角评估表、方向图指标和提示。 - 中文 / English / 日本語界面,浅色 / 深色 / 跟随系统主题,桌面和手机宽度均可用。 ### 雷达评估 diff --git a/web/src/charts/theme.ts b/web/src/charts/theme.ts index 95a0d95..aa0dffd 100644 --- a/web/src/charts/theme.ts +++ b/web/src/charts/theme.ts @@ -92,7 +92,15 @@ export function baseLayout(theme: ChartTheme, overrides: Record = { }, dragmode: false, ...overrides, - xaxis: { ...axis, ...(overrides.xaxis ?? {}) }, - yaxis: { ...axis, ...(overrides.yaxis ?? {}) }, + xaxis: mergeAxis(axis, overrides.xaxis), + yaxis: mergeAxis(axis, overrides.yaxis), }; } + +/** Merge axis overrides while keeping the themed title font. */ +function mergeAxis(base: Record, override: Record | undefined): Record { + if (!override) return base; + const merged = { ...base, ...override }; + if (override.title) merged.title = { ...base.title, ...override.title }; + return merged; +} diff --git a/web/src/components/Chrome.tsx b/web/src/components/Chrome.tsx index c6ab863..5bd3b70 100644 --- a/web/src/components/Chrome.tsx +++ b/web/src/components/Chrome.tsx @@ -9,6 +9,7 @@ import { FolderOpen, Grid3x3, HelpCircle, + ImageDown, Languages, LineChart, Map as MapIcon, @@ -18,19 +19,37 @@ import { Package, Radar, Save, - Settings2, Sun, Target, Upload, Waves, } from "lucide-react"; -import type { ReactNode } from "react"; +import { type ReactNode, useEffect } from "react"; +import { api } from "../api/client"; import { LANGUAGE_LABELS, useT } from "../i18n"; import { fmt, parseNumber, trimNumber } from "../lib/format"; import { exportBundle, exportLayout, importFile, newProject, saveProject } from "../state/actions"; +import { useExportJob } from "../state/jobs"; import { type Language, type ThemeMode, useIsDirty, useStore, type ViewId } from "../state/store"; import { Button, Menu, MenuItem, NumberInput, Segmented, Spinner, useFilePicker } from "./ui"; +/** Angle-error PNG export from the top bar, reporting progress in the status bar. */ +function useAngleImageExport() { + const job = useExportJob(); + const setStatus = useStore((state) => state.setStatus); + const status = job.job?.status; + useEffect(() => { + if (status === "running" || status === "queued") setStatus("status.imageGenerating"); + else if (status === "succeeded") setStatus("status.exported", "success", { name: job.job?.download_name ?? "" }); + else if (status === "failed") setStatus("status.exportFailed", "error", { message: job.job?.error ?? "" }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [status]); + useEffect(() => { + if (job.error) setStatus("status.exportFailed", "error", { message: job.error }); + }, [job.error, setStatus]); + return job; +} + export function TopBar() { const t = useT(); const project = useStore((state) => state.project)!; @@ -40,6 +59,8 @@ export function TopBar() { const { updateProject, openDialog, setLanguage, setTheme } = useStore.getState(); const dirty = useIsDirty(); const pickImport = useFilePicker(".json,.zip,application/json,application/zip", importFile); + const capability = useStore((state) => state.evaluation?.capability); + const angleImage = useAngleImageExport(); return (
    @@ -96,7 +117,7 @@ export function TopBar() { ( - @@ -110,6 +131,17 @@ export function TopBar() { } onSelect={() => { close(); exportBundle(); }}> {t("menu.exportBundle")} +
    + } + disabled={angleImage.running || (capability !== undefined && !capability.azimuth && !capability.elevation)} + onSelect={() => { + close(); + angleImage.start(() => api.createAngleErrorImage(project, 1.0, language)); + }} + > + {t("menu.exportAngleImage")} + )}
    @@ -170,6 +202,43 @@ const VIEWS: { id: ViewId; icon: ReactNode; key: "view.array" | "view.dbf1d" | " { id: "band", icon: , key: "view.band" }, ]; +function fovText(range: [number, number]): string { + return range[0] === -range[1] ? `±${range[1]}°` : `${range[0]}~${range[1]}°`; +} + +function ParamItem({ + label, + children, + onClick, + title, + dot, +}: { + label: string; + children: ReactNode; + onClick?: () => void; + title?: string; + dot?: "on" | "warn" | "off"; +}) { + const body = ( + <> + + {dot && } + {label} + + {children} + + ); + return onClick ? ( + + ) : ( + + ); +} + export function ControlBar() { const t = useT(); const project = useStore((state) => state.project)!; @@ -180,7 +249,13 @@ export function ControlBar() { const { setView, updateProject, setDisplay, openDialog } = useStore.getState(); const dictMode = project.dbf_dictionary.mode; const pattern = evaluation?.pattern_status; - const patternActive = pattern && (pattern.amplitude !== "ideal" || pattern.phase !== "ideal"); + const patternDot = !pattern || (pattern.amplitude === "ideal" && pattern.phase === "ideal") + ? "off" + : pattern.amplitude === "mixed" || pattern.phase === "mixed" + ? "warn" + : "on"; + const band = project.band; + const bandLabel = band.preset === "custom" ? t("top.bandCustom") : band.preset; return (
    -
    - { - if (preset === "custom") { - openDialog("settings"); - return; - } - const values = config.band_presets[preset]; - updateProject({ - band: { preset, start_ghz: values.start_ghz, stop_ghz: values.stop_ghz }, - frequency_ghz: values.design_ghz, - }); - }} - /> -