Files
tcad-bodeplot/ARCHITECTURE.md
T

7.7 KiB
Raw Blame History

Difference Equation Analyzer (DEA) - Architecture & Functionality

Overview

DEA is a specialized tool for designing, visualizing, and validating discrete-time filters. It bridges the gap between theoretical filter design (floating-point) and hardware implementation (fixed-point/MCU).

🏗 System Architecture

1. Backend (Python 3.12 + FastAPI)

The backend is responsible for heavy mathematical computations and data processing.

  • API Entry (dea_api.py): Routes requests to appropriate modules and serves the Vue.js frontend from static/.
  • Computation Engine (dea/):
    • filter_design.py: Uses scipy.signal to calculate coefficients for various filter topologies.
    • bode.py: Computes magnitude and phase response. Supports comparing "Ideal" (float) vs "Fixed" (quantized) responses.
    • csv_processing.py: Processes time-domain CSV data. It applies the current filter to the signal and downsamples the result for efficient visualization.
    • validation.py: Protects against unstable filter designs and invalid inputs.

2. Frontend (Vue 3 + Vite + Tailwind)

A reactive "Single Page Application" (SPA) approach.

⚠️ 開發 vs 部署 (Development vs Production)

  • 開發模式 (Development): 透過 npm run dev 啟動 Vite dev server (預設 http://localhost:5173)。前端原始碼修改後會自動熱更新 (HMR),不需要 手動 build。API 請求透過 vite.config.js 的 proxy 設定轉發至後端。
  • 生產模式 (Production): 透過 http://localhost:8000/ui/ 存取。FastAPI 直接 serve static/build/ 裡的 production bundle。修改 src/ 原始碼後,必須執行 npm run build 才會生效。忘記 build 會導致前端程式碼與後端不同步,所有新功能看起來都「沒有作用」。
  • Reactive Logic (src/app-options.js):
    • Manages the state of all coefficients.
    • Implements "Fine-tuning" sliders that allow real-time adjustment of poles/zeros.
    • Handles Fixed-Point conversion logic (Q-format shifting).
  • UI Components (src/App.vue):
    • Control Sidebar: Interactive inputs for all filter parameters.
    • Visualization: Dual-plot system using Plotly.js for Bode plots and Time-domain waveforms.
  • Hardware Bridge: Uses the Web Serial API to send commands directly to connected MCUs (requires HTTPS).

🚀 Execution Flow

  1. Design: User selects a filter type or enters coefficients manually.
  2. Quantize: User adjusts Q-format bits to see how quantization affects the frequency response.
  3. Verify: User uploads a CSV to see how the filter behaves with real-world signals.
  4. Deploy: User clicks "Write to MCU" to send the coefficients to their hardware.

🛠 Tech Stack

  • Backend: FastAPI, NumPy, SciPy, Pandas, Uvicorn.
  • Frontend: Vue 3, Vite, Tailwind CSS, Plotly.js.
  • Security: Restricted to LAN/Loopback; implemented security headers and HTTPS support.

💎 V2 Feature: Parallel Fixed-Point Simulation

本分支 (dev-v2-integretimedomain) 的核心任務是在時域分析中實作「雙路徑對照系統」:

1. 雙路徑模擬邏輯 (Dual-Path Logic)

  • 理想路徑 (Float Path): 使用 64-bit 浮點數進行運算,作為效能基準。
  • 硬體模擬路徑 (Integer Path):
    • 輸入量化: 將原始訊號依 Q_{in} 轉為整數。
    • 整數運算: 使用整數係數 (Q_{coeff}) 進行差分方程式計算。
    • 位移校準: 運算過程中考慮累加器位元數,並依 Q_{out} 進行最終縮放。
    • 效果: 模擬真實 DSP 的捨入誤差 (Rounding Error) 與量化雜訊。

2. 資料流更新

  • API /api/filter: 接收檔案 ID 與係數參數,返回兩組數列(Float / Fixed)。
  • UI 圖表: 同時繪製兩條曲線,讓開發者直觀判斷量化是否導致不穩定 (Instability) 或顯著失真。

3. 高效能資料處理架構 (High-Performance Data Processing)

  • 檔案快取與防呆:
    • 支援高達 300 MB 的 CSV 檔案上傳。
    • 當檔案被選擇後,立即背景上傳至後端暫存區 (temp_csv/),避免重複傳輸。
    • 嚴格限制時域運算最多處理 1,200,000 筆 資料點,保護伺服器不因 O(N) 的純 Python 整數運算而死當。
  • 精準記憶體讀取:
    • 利用 Pandas 的 usecols 參數,僅載入使用者選定的單一訊號欄位,極大幅度降低記憶體佔用。
  • 即時預覽 (Live Preview):
    • 透過前端的 Debounce 機制 (500ms),當使用者點擊 +/- 按鈕微調 Q-format 參數或係數時,系統會自動使用快取的檔案呼叫 API 並重繪圖表,達成無縫且直覺的實驗體驗。

🛠 Firmware Implementation Guidelines (韌體實作指引)

在將此工具設計出來的濾波器係數移植到 C 語言或 MCU (如 RISC-V) 時,請務必遵守以下實作準則,以確保硬體行為與本系統的模擬結果 100% 一致:

1. 高精度狀態變數架構 (Extended Precision State Variables)

為了極小化截斷誤差 (Truncation Error),硬體實作的迴圈請不要對前饋 (Feed-forward) 進行位移。

  • 作法:讓歷史陣列 y_history[] 保存前饋乘加後的高精度格式 (Q_{in+b})。僅在計算回授 (Feedback) 的乘積後,才對回授項進行右移對齊,並在最終輸出給硬體腳位時做最後的右移。這等於讓 IIR 濾波器內部默默保留了額外的 Q_b bits 小數精度。

2. 消除直流偏移 (DC Bias) 的 1-Clock Rounding 演算法秘技

傳統的右移 (>>) 會造成無條件捨去向下取整 (Floor),這會引入永遠為負的平均誤差 (-0.5 LSB),導致濾波器產生直流偏移。必須改用四捨五入 (Rounding)。

  • 硬體現狀:標準的 RISC-V 指令集 (RV32I / RV32IMAC) 沒有硬體的 round off shift 指令 (其 SRA 指令是純 Floor)。除非晶片具備 DSP 擴充指令集 ('P' Extension)。
  • C 語言實作秘技:絕對不要為了四捨五入去呼叫 C standard library 的 round(),這會啟動浮點數運算,吃掉上百個 Clock。請用純整數實作:
    // 完美的 1-clock 整數四捨五入寫法 (Round to nearest):
    // 編譯器會將 (1 << (shift_bits - 1)) 編譯為常數,只會多消耗一個 ADD 指令。
    y_out = (acc + (1 << (shift_bits - 1))) >> shift_bits;
    
    這個技巧已實作於本工具前端的「Round (+0.5 補償)」選項中,開啟後可大幅提升信噪比與波形穩定性。

⚙️ Development Environment Notes (開發環境注意事項)

1. Vite Proxy 設定

vite.config.js 中的 proxy target 必須使用 http://(而非 https://),因為 uvicorn 預設以 HTTP 模式啟動。若設定為 https://,Vite 會嘗試發送 TLS 握手封包到純 HTTP 的 uvicorn,導致所有 API 請求失敗 (502 Bad Gateway)uvicorn 日誌會大量出現 Invalid HTTP request received. 警告。

// ✅ 正確
proxy: { '/api': { target: 'http://127.0.0.1:8000', changeOrigin: true } }

// ❌ 錯誤 — 會導致 API 全部失敗
proxy: { '/api': { target: 'https://127.0.0.1:8000', secure: false } }

2. Production Build 流程

若使用者透過 http://localhost:8000/ui/ 存取系統(FastAPI serve 靜態檔),則前端程式碼修改後必須執行以下命令:

npm run build   # 將 src/ 編譯輸出至 static/build/

然後在瀏覽器中按 Ctrl+Shift+R (硬重新整理) 以清除快取載入最新版本。

3. 兩種存取方式對照表

項目 Vite Dev Server Production (FastAPI)
URL http://localhost:5173 http://localhost:8000/ui/
修改後生效 自動 (HMR) npm run build
適用場景 開發 / 除錯 正式使用 / Demo
API 轉發 透過 Vite proxy 直接打同一 port