Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -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
6 changes: 5 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -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
34 changes: 34 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,8 @@ dist/
*.egg-info/
*.log
.claude/
node_modules/
web/dist/
src/virtual_array/server/static/
data/
*.tsbuildinfo
61 changes: 22 additions & 39 deletions .opencode/skills/mimo-project/SKILL.md
Original file line number Diff line number Diff line change
@@ -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、同占位符(有单元测试校验)。
- 修改计算核心时保持现有测试的数值结果不变。
38 changes: 0 additions & 38 deletions .opencode/skills/python-gui/SKILL.md

This file was deleted.

96 changes: 55 additions & 41 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,71 +4,85 @@ 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 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

```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.
- **`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.

- **`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 **λ 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 (`<data>/assets/<sha256>/<original name>`).
- **`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.

- **`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`, `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.

### 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──▶ 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

- 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 λ 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.
- Tests use `examples/case4_5tx7rx_sel.py::build_array()` (also the default project) as the reference layout.
35 changes: 19 additions & 16 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -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,讨论范围和预期行为。
Loading
Loading