refactor: 在旧的PhyExp基础上进行重构,采用了monorepo结构,分为frontend和backend两个子项目

这个提交包含在:
2026-05-23 18:15:31 +08:00
当前提交 41813abe48
共有 87 个文件被更改,包括 13257 次插入 和 0 次删除

10
backend/.gitignore vendored 普通文件
查看文件

@ -0,0 +1,10 @@
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info
# Virtual environments
.venv

1
backend/.python-version 普通文件
查看文件

@ -0,0 +1 @@
3.11

172
backend/ARCHITECTURE.md 普通文件
查看文件

@ -0,0 +1,172 @@
# PhyExp 后端架构文档
## 项目概述
- **项目名称:** PhyExp Backend (Physics Experiment Backend)
- **类型:** Python FastAPI REST 服务
- **描述:** 为物理实验教学平台提供表单配置、字段验证、声速实验计算及示波器数据采集能力
## 目录结构
```
backend/
├── pyproject.toml # Python 项目配置 (uv)
├── uv.lock # 依赖锁定文件
├── .python-version # Python 版本约束
├── config/
│ └── experiments/ # 实验配置文件 (JSON)
│ ├── voice_speed.json # 声速测量实验配置
│ └── _voice_speed.json # 旧版备份
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI 应用入口, CORS, 路由注册
│ ├── models.py # 兼容性重导出 (实际定义在 schemas/)
│ ├── schemas/ # Pydantic 数据模型
│ │ ├── __init__.py # 统一导出
│ │ ├── experiment.py # 网格实验配置模型 (GridSheet, GridCell...)
│ │ └── validation.py # 验证请求/响应、测量分析模型
│ ├── api/ # REST API 路由层
│ │ ├── __init__.py
│ │ ├── form.py # GET /form, /form/list — 加载实验配置
│ │ ├── value.py # POST/GET/DELETE /value — 字段值 CRUD + 验证
│ │ ├── device.py # GET /device/status, POST /device/peak — 示波器控制
│ │ └── measurement.py # POST /measurement/{method} — 测量数据分析
│ ├── core/ # 业务逻辑层
│ │ ├── __init__.py
│ │ ├── config_loader.py # ExperimentConfigService — 加载/验证 JSON 配置
│ │ ├── dependencies.py # 服务单例 + 字段查找辅助函数
│ │ ├── measurement.py # MeasurementService — 声速实验统计算法
│ │ ├── reading_guard.py # ReadingGuardManager — 读数顺序守卫 + 容差校验
│ │ ├── session_store.py # SessionStore — 线程安全内存 KV 存储
│ │ └── validation.py # FieldValidator — 基础字段校验 (数字/正则/必填)
│ └── hardware/ # 示波器硬件交互层
│ ├── __init__.py
│ ├── oscilloscope.py # Oscilloscope — PyUSB SCPI 协议驱动
│ ├── progress.py # SCPI 命令枚举 + 执行器
│ └── service.py # OscilloscopeService — 探针/峰值/频率采集 (含模拟回退)
```
## 技术栈
| 分类 | 技术 | 版本 |
| ---------- | -------------------- | ------- |
| 框架 | FastAPI | 0.116+ |
| 数据验证 | Pydantic v2 | 2.11+ |
| 服务器 | Uvicorn | 0.35+ |
| 硬件通信 | PyUSB + libusb | 1.3+ |
| 包管理 | uv | - |
## API 端点
| 方法 | 路径 | 说明 |
| ------ | ----------------------------------- | ------------------------ |
| GET | `/` | 服务信息 + 端点列表 |
| GET | `/health` | 健康检查 |
| GET | `/form?experiment=voice_speed` | 加载实验网格配置 |
| GET | `/form/list` | 列出可用实验 |
| GET | `/form/{experiment_name}` | 按名称加载实验配置 |
| POST | `/value?experiment=...` | 验证并存储字段值 |
| GET | `/value` | 获取所有字段值 |
| GET | `/value/{field_id}` | 获取单个字段值 |
| DELETE | `/value/{field_id}` | 删除单个字段值 |
| DELETE | `/value` | 清除所有字段值 |
| GET | `/device/status` | 探针示波器状态 |
| POST | `/device/peak` | 捕获峰值 |
| POST | `/device/manual-answer` | 设置读数守卫手动答案 |
| POST | `/measurement/{method}` | 分析测量数据 (声速计算) |
## 核心架构
### 数据模型
```
ExperimentGridConfig
├── title: str
├── description?: str
└── sheets: GridSheet[]
├── id: str
├── title?: str
├── columns: int
├── columnHeaders?: str[]
├── columnWidths?: str[]
├── rowHeaders?: str[]
└── cells: GridCell[][] # 2D 矩阵
├── GridLabelCell { type: "label", content: str }
├── GridInputCell { type: "input", fieldId: str, validation?, readingGuard? }
└── GridComputedCell { type: "computed", areaId: str, expression, variables[] }
```
### 请求流程
```
POST /value { field_id, value }
→ find_field(experiment, field_id) # 从配置中查找字段定义
→ FieldValidator.validate_by_config() # 基础校验 (类型/范围/正则)
→ reading_guard_manager.validate() # 读数顺序 + 容差校验
→ session_store.set_value() # 存储到内存
→ { accept: bool, message: str }
```
### 会话管理
- 通过 `X-Session-Id` 请求头或默认 `"default"` 标识会话
- `SessionStore` 是线程安全的内存 KV 存储
- 字段值按 `{ session_id → { field_id → value } }` 组织
### 硬件交互
- `OscilloscopeService` 提供三层设备状态:`ONLINE | OFFLINE | SIMULATED`
- 连接真实示波器失败时自动回退到模拟模式
- `ReadingGuardManager` 可通过 `source: "device_peak"` 自动从示波器采集参考值
## 实验配置格式
实验配置以 JSON 文件存储在 `config/experiments/` 目录下。每个文件定义了一个实验的完整数据表结构。
### GridSheet 概念
每个实验由多个 Sheet 组成(类似 Excel 工作表),每个 Sheet 是一个二维单元格矩阵:
```json
{
"id": "table1",
"title": "表1 声源频率与介质温度",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$f/kHz$"},
{"type": "input", "fieldId": "f1", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f2", ...},
...
],
[
{"type": "label", "content": "$\\bar{f}/kHz$"},
{"type": "computed", "areaId": "frequency_avg", "expression": "(f1+f2+f3+f4+f5)/5", "format": "0.00", "colSpan": 5}
]
]
}
```
### 单元格类型
| 类型 | 用途 | 关键字段 |
| ---------- | ------------------------ | ----------------------------------- |
| `label` | 静态标签/表头 (支持 LaTeX) | `content` |
| `input` | 学生数据输入 | `fieldId`, `validation`, `readingGuard` |
| `computed` | 自动计算结果 | `areaId`, `expression`, `variables`, `format` |
## 声速实验计算
`MeasurementService` 支持三种测量方法的统计算法:
1. **驻波法 / 相位法** (`standing_wave` / `phase`)
- 取前 5 个与后 5 个读数的配对差值
- 波长 λ = 2 × mean(Δ) / 1000 [m]
- 声速 v = f × λ
- 不确定度 Δv = f × 2 × σ(Δ) / 1000
2. **时差法** (`time_diff`)
- 每对 (距离, 时间差) 独立计算速度
- v = mean(v_i)
- 不确定度 Δv = σ(v_i)

0
backend/README.md 普通文件
查看文件

65
backend/app/README.md 普通文件
查看文件

@ -0,0 +1,65 @@
# 物理实验后端(FastAPI)
该目录实现了与前端 `ExperimentForm` 对齐的后端 API,覆盖:
1. 实验配置下发(`/form`)
2. 字段值验证与会话存储(`/value`)
3. 声速实验三方法计算(`/measurement`)
## 架构概览
- `main.py`: FastAPI 入口、CORS、路由注册
- `models.py`: 与前端协议对应的 Pydantic 模型
- `api/form.py`: 实验表单配置接口
- `api/value.py`: 字段值验证与会话数据接口
- `api/measurement.py`: 驻波法/相位法/时差法计算接口
- `core/config_loader.py`: 配置文件加载与校验
- `core/validation.py`: 配置驱动字段验证
- `core/session_store.py`: 内存会话态字段存储
- `core/measurement.py`: 声速实验计算逻辑
- `../config/experiments/*.json`: 实验配置文件
## 运行
在 `backend` 目录执行:
```bash
uv run uvicorn main:app --app-dir src --reload --host 0.0.0.0 --port 8000
```
或直接:
```bash
python src/main.py
```
## 主要接口
1. `GET /form?experiment=voice_speed`
2. `GET /form/list`
3. `POST /value`
4. `GET /value`
5. `DELETE /value`
6. `POST /measurement/{standing_wave|phase|time_diff}`
7. `GET /health`
## 会话设计
- 通过请求头 `X-Session-Id` 区分不同学生/实验会话。
- 未提供时使用默认会话 `default`。
- 当前为内存存储,后续可替换为 Redis/数据库。
## 计算方法说明
- `standing_wave` / `phase`:
- 输入 `cursor_readings_mm` 至少 10 个读数。
- 使用“后五次减前五次”配对差统计平均值与不确定度。
- 依据 `frequency_hz` 计算波长与声速。
- `time_diff`:
- 输入 `distance_readings_mm` 与 `time_deltas_us`,按组计算速度并求均值与标准差。
## 下一步建议
1. 将 `oscilloscope.py` 与 OCR 能力接入 `measurement` 路由。
2. 将 `session_store` 升级为持久化存储。
3. 增加 `pytest` 接口测试覆盖边界输入。

1
backend/app/__init__.py 普通文件
查看文件

@ -0,0 +1 @@
#

查看文件

48
backend/app/api/device.py 普通文件
查看文件

@ -0,0 +1,48 @@
from __future__ import annotations
from fastapi import APIRouter, Header
from app.core.dependencies import reading_guard_manager, resolve_session_id
from app.hardware.service import oscilloscope_service
from app.models import ManualAnswerRequest
router = APIRouter(prefix="/device", tags=["device"])
@router.get("/status")
async def get_device_status():
snapshot = oscilloscope_service.probe()
return {
"status": snapshot.status,
"device_idn": snapshot.device_idn,
"peak_value": snapshot.peak_value,
"frequency_hz": snapshot.frequency_hz,
"raw_response": snapshot.raw_response,
"note": snapshot.note,
}
@router.post("/peak")
async def capture_peak_value():
snapshot = oscilloscope_service.capture_peak()
return {
"status": snapshot.status,
"peak_value": snapshot.peak_value,
"note": snapshot.note,
}
@router.post("/manual-answer")
async def set_manual_answer(
request: ManualAnswerRequest,
x_session_id: str | None = Header(default=None),
):
session_id = resolve_session_id(x_session_id)
reading_guard_manager.set_manual_answer(session_id, request.field_id, request.value)
return {
"success": True,
"session_id": session_id,
"field_id": request.field_id,
"message": "已设置该字段标准读数",
}

26
backend/app/api/form.py 普通文件
查看文件

@ -0,0 +1,26 @@
from __future__ import annotations
from fastapi import APIRouter
from app.core.dependencies import config_service
router = APIRouter(prefix="/form", tags=["form"])
@router.get("")
async def get_experiment_form(experiment: str = "voice_speed"):
config = config_service.load_validated(experiment)
return config.model_dump(by_alias=True)
@router.get("/list")
async def list_available_experiments():
experiments = config_service.list_experiments()
return {"experiments": experiments, "count": len(experiments)}
@router.get("/{experiment_name}")
async def get_specific_experiment_form(experiment_name: str):
config = config_service.load_validated(experiment_name)
return config.model_dump(by_alias=True)

查看文件

@ -0,0 +1,19 @@
from __future__ import annotations
from fastapi import APIRouter, HTTPException
from app.core.dependencies import measurement_service
from app.schemas.validation import AnalyzeMeasurementRequest, AnalyzeMeasurementResponse, MeasurementMethod
router = APIRouter(prefix="/measurement", tags=["measurement"])
@router.post("/{method}")
async def analyze_measurement(method: MeasurementMethod, payload: AnalyzeMeasurementRequest) -> AnalyzeMeasurementResponse:
try:
return measurement_service.analyze(method, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc)) from exc

72
backend/app/api/value.py 普通文件
查看文件

@ -0,0 +1,72 @@
from __future__ import annotations
from fastapi import APIRouter, Header, HTTPException, Query
from app.core.dependencies import find_field, list_fields, reading_guard_manager, resolve_session_id, session_store
from app.core.validation import FieldValidator
from app.schemas.validation import FieldValidationRequest, FieldValidationResponse
router = APIRouter(prefix="/value", tags=["value"])
@router.post("")
async def validate_field_value(
request: FieldValidationRequest,
experiment: str = Query(default="voice_speed"),
x_session_id: str | None = Header(default=None),
) -> FieldValidationResponse:
session_id = resolve_session_id(x_session_id)
field = find_field(experiment, request.field_id)
base_result = FieldValidator.validate_by_config(request.field_id, request.value, field.validation)
if not base_result.accept:
return base_result
guard_result = reading_guard_manager.validate(
session_id=session_id,
current_field=field,
current_value=request.value,
all_fields=list_fields(experiment),
)
if guard_result is not None:
guard_accept, guard_message = guard_result
if not guard_accept:
return FieldValidationResponse(accept=False, message=guard_message)
session_store.set_value(session_id, request.field_id, request.value)
return FieldValidationResponse(accept=True, message=guard_message)
session_store.set_value(session_id, request.field_id, request.value)
return base_result
@router.get("")
async def get_all_field_values(x_session_id: str | None = Header(default=None)):
session_id = resolve_session_id(x_session_id)
fields = session_store.get_all(session_id)
return {"fields": fields, "count": len(fields), "session_id": session_id}
@router.get("/{field_id}")
async def get_field_value(field_id: str, x_session_id: str | None = Header(default=None)):
session_id = resolve_session_id(x_session_id)
value = session_store.get_value(session_id, field_id)
if value is None:
raise HTTPException(status_code=404, detail=f"field '{field_id}' not found or has no value")
return {"field_id": field_id, "value": value, "session_id": session_id}
@router.delete("/{field_id}")
async def delete_field_value(field_id: str, x_session_id: str | None = Header(default=None)):
session_id = resolve_session_id(x_session_id)
ok = session_store.delete_value(session_id, field_id)
if not ok:
raise HTTPException(status_code=404, detail=f"field '{field_id}' not found")
return {"message": f"field '{field_id}' value deleted", "success": True, "session_id": session_id}
@router.delete("")
async def clear_all_field_values(x_session_id: str | None = Header(default=None)):
session_id = resolve_session_id(x_session_id)
removed_count = session_store.clear(session_id)
return {"message": f"cleared {removed_count} field values", "success": True, "session_id": session_id}

查看文件

查看文件

@ -0,0 +1,52 @@
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Dict, List
from fastapi import HTTPException
from app.schemas.experiment import ExperimentGridConfig
class ExperimentConfigService:
def __init__(self, config_root: Path):
self.config_root = config_root
def _config_path(self, experiment_name: str) -> Path:
return self.config_root / f"{experiment_name}.json"
def load_raw(self, experiment_name: str = "voice_speed") -> Dict[str, Any]:
path = self._config_path(experiment_name)
if not path.exists():
raise HTTPException(status_code=404, detail=f"experiment config '{experiment_name}' not found")
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise HTTPException(status_code=500, detail=f"experiment config format error: {exc}") from exc
def load_validated(self, experiment_name: str = "voice_speed") -> ExperimentGridConfig:
payload = self.load_raw(experiment_name)
try:
return ExperimentGridConfig(**payload)
except Exception as exc:
raise HTTPException(status_code=500, detail=f"config validation failed: {exc}") from exc
def list_experiments(self) -> List[Dict[str, str]]:
if not self.config_root.exists():
return []
result: List[Dict[str, str]] = []
for file in sorted(self.config_root.glob("*.json")):
try:
payload = json.loads(file.read_text(encoding="utf-8"))
result.append(
{
"name": file.stem,
"title": payload.get("title", file.stem),
"description": payload.get("description", ""),
}
)
except Exception:
continue
return result

查看文件

@ -0,0 +1,45 @@
from __future__ import annotations
from pathlib import Path
from typing import List, Optional
from fastapi import HTTPException
from app.core.config_loader import ExperimentConfigService
from app.core.measurement import MeasurementService
from app.core.reading_guard import reading_guard_manager
from app.core.session_store import SessionStore
from app.schemas.experiment import ExperimentGridConfig, GridInputCell
BASE_DIR = Path(__file__).resolve().parent.parent
CONFIG_ROOT = BASE_DIR.parent / "config" / "experiments"
config_service = ExperimentConfigService(config_root=CONFIG_ROOT)
session_store = SessionStore()
measurement_service = MeasurementService()
def _iter_input_cells(config: ExperimentGridConfig):
for sheet in config.sheets:
for row in sheet.cells:
for cell in row:
if isinstance(cell, GridInputCell):
yield cell
def find_field(experiment_name: str, field_id: str) -> GridInputCell:
config = config_service.load_validated(experiment_name)
for cell in _iter_input_cells(config):
if cell.fieldId == field_id:
return cell
raise HTTPException(status_code=404, detail=f"field '{field_id}' not found in experiment '{experiment_name}'")
def list_fields(experiment_name: str) -> List[GridInputCell]:
config = config_service.load_validated(experiment_name)
return list(_iter_input_cells(config))
def resolve_session_id(session_id: Optional[str]) -> str:
return session_id or "default"

查看文件

@ -0,0 +1,90 @@
from __future__ import annotations
import statistics
from typing import Dict, List
from fastapi import HTTPException
from app.schemas.validation import AnalyzeMeasurementRequest, AnalyzeMeasurementResponse, MeasurementMethod
class MeasurementService:
@staticmethod
def _theoretical_velocity(temperature_c: float | None) -> float | None:
if temperature_c is None:
return None
return 331.3 * ((1.0 + temperature_c / 273.15) ** 0.5)
@staticmethod
def _pairwise_deltas(readings_mm: List[float]) -> List[float]:
if len(readings_mm) < 10:
raise HTTPException(status_code=400, detail="standing wave / phase method requires at least 10 cursor readings")
first5 = readings_mm[:5]
last5 = readings_mm[5:10]
return [b - a for a, b in zip(first5, last5)]
def analyze(self, method: MeasurementMethod, payload: AnalyzeMeasurementRequest) -> AnalyzeMeasurementResponse:
if method in (MeasurementMethod.STANDING_WAVE, MeasurementMethod.PHASE):
return self._analyze_wave_method(method, payload)
if method == MeasurementMethod.TIME_DIFF:
return self._analyze_time_diff(payload)
raise HTTPException(status_code=400, detail="unsupported measurement method")
def _analyze_wave_method(
self,
method: MeasurementMethod,
payload: AnalyzeMeasurementRequest,
) -> AnalyzeMeasurementResponse:
if payload.frequency_hz is None:
raise HTTPException(status_code=400, detail="standing wave / phase method requires frequency_hz")
deltas = self._pairwise_deltas(payload.cursor_readings_mm)
mean_delta_mm = statistics.mean(deltas)
std_delta_mm = statistics.pstdev(deltas) if len(deltas) > 1 else 0.0
wavelength_m = (2.0 * mean_delta_mm) / 1000.0
velocity = payload.frequency_hz * wavelength_m
uncertainty = payload.frequency_hz * (2.0 * std_delta_mm / 1000.0)
return AnalyzeMeasurementResponse(
method=method,
sample_count=len(deltas),
velocity_mps=velocity,
wavelength_m=wavelength_m,
uncertainty_mps=uncertainty,
theoretical_velocity_mps=self._theoretical_velocity(payload.temperature_c),
details={
"pair_deltas_mm": deltas,
"mean_delta_mm": mean_delta_mm,
"std_delta_mm": std_delta_mm,
"note": "using pairwise difference (last 5 minus first 5)",
},
)
def _analyze_time_diff(self, payload: AnalyzeMeasurementRequest) -> AnalyzeMeasurementResponse:
distances = payload.distance_readings_mm
times = payload.time_deltas_us
if len(distances) < 1 or len(times) < 1:
raise HTTPException(status_code=400, detail="time diff method requires distance_readings_mm and time_deltas_us")
if len(distances) != len(times):
raise HTTPException(status_code=400, detail="distance_readings_mm and time_deltas_us must have same length")
velocities: List[float] = []
for d_mm, t_us in zip(distances, times):
if t_us <= 0:
raise HTTPException(status_code=400, detail="time_deltas_us must be greater than 0")
velocities.append((d_mm / 1000.0) / (t_us / 1_000_000.0))
mean_v = statistics.mean(velocities)
std_v = statistics.pstdev(velocities) if len(velocities) > 1 else 0.0
return AnalyzeMeasurementResponse(
method=MeasurementMethod.TIME_DIFF,
sample_count=len(velocities),
velocity_mps=mean_v,
uncertainty_mps=std_v,
theoretical_velocity_mps=self._theoretical_velocity(payload.temperature_c),
details={
"single_velocity_mps": velocities,
},
)

查看文件

@ -0,0 +1,127 @@
from __future__ import annotations
from dataclasses import dataclass, field
from threading import Lock
from typing import Any, Dict, List, Optional
from app.hardware.service import oscilloscope_service
from app.schemas.experiment import GridInputCell, ReadingGuardSource
@dataclass
class GuardSessionState:
strict_fields: List[str] = field(default_factory=list)
cursor: int = 0
pending_field: Optional[str] = None
pending_answer: Optional[float] = None
tolerance: float = 0.0
source: ReadingGuardSource = ReadingGuardSource.MANUAL
manual_answers: Dict[str, Any] = field(default_factory=dict)
class ReadingGuardManager:
def __init__(self) -> None:
self._lock = Lock()
self._sessions: Dict[str, GuardSessionState] = {}
def set_manual_answer(self, session_id: str, field_id: str, value: Any) -> None:
with self._lock:
state = self._sessions.setdefault(session_id, GuardSessionState())
state.manual_answers[field_id] = value
def _capture_answer(self, source: ReadingGuardSource, field_id: str, state: GuardSessionState) -> Optional[float]:
if source == ReadingGuardSource.DEVICE_PEAK:
snapshot = oscilloscope_service.capture_peak()
if snapshot.peak_value is None:
return None
return float(snapshot.peak_value)
if source == ReadingGuardSource.DEVICE_FREQUENCY:
snapshot = oscilloscope_service.capture_frequency()
if snapshot.frequency_hz is None:
return None
return float(snapshot.frequency_hz)
if source == ReadingGuardSource.MANUAL:
value = state.manual_answers.get(field_id)
if value is None:
return None
return float(value)
return None
def _ensure_initialized(self, session_id: str, fields: List[GridInputCell]) -> GuardSessionState:
state = self._sessions.setdefault(session_id, GuardSessionState())
if not state.strict_fields:
strict_fields = [
f.fieldId
for f in fields
if f.readingGuard is not None and f.readingGuard.enabled
]
state.strict_fields = strict_fields
if strict_fields:
state.pending_field = strict_fields[0]
field0 = next(f for f in fields if f.fieldId == strict_fields[0])
state.tolerance = field0.readingGuard.tolerance if field0.readingGuard else 0.0
state.source = field0.readingGuard.source if field0.readingGuard else ReadingGuardSource.MANUAL
state.pending_answer = self._capture_answer(state.source, state.pending_field, state)
return state
def _arm_next(self, state: GuardSessionState, fields_map: Dict[str, GridInputCell]) -> None:
if state.cursor >= len(state.strict_fields):
state.pending_field = None
state.pending_answer = None
return
next_field = state.strict_fields[state.cursor]
config = fields_map[next_field].readingGuard
state.pending_field = next_field
state.tolerance = config.tolerance if config else 0.0
state.source = config.source if config else ReadingGuardSource.MANUAL
state.pending_answer = self._capture_answer(state.source, next_field, state)
def validate(
self,
session_id: str,
current_field: GridInputCell,
current_value: Any,
all_fields: List[GridInputCell],
) -> Optional[tuple[bool, str]]:
state = self._ensure_initialized(session_id, all_fields)
if not state.strict_fields:
return None
if current_field.readingGuard is None or not current_field.readingGuard.enabled:
return None
if state.pending_field is None:
return True, "reading process completed"
if current_field.fieldId != state.pending_field:
return False, f"should submit field {state.pending_field}, please follow experiment reading order"
if state.pending_answer is None:
return False, "standard reading not yet captured, please retry"
try:
student_value = float(current_value)
except Exception:
return False, "reading fields must be numeric"
error = abs(student_value - state.pending_answer)
if error > state.tolerance:
return (
False,
f"reading mismatch, expected {state.pending_answer:.6g}, tolerance ±{state.tolerance:.6g}, please re-enter",
)
state.cursor += 1
fields_map = {f.fieldId: f for f in all_fields}
self._arm_next(state, fields_map)
if state.pending_field is None:
return True, "reading correct, all reading steps completed"
return True, f"reading correct, awaiting next: {state.pending_field}"
reading_guard_manager = ReadingGuardManager()

查看文件

@ -0,0 +1,34 @@
from __future__ import annotations
from threading import Lock
from typing import Any, Dict
class SessionStore:
def __init__(self) -> None:
self._lock = Lock()
self._values: Dict[str, Dict[str, Any]] = {}
def set_value(self, session_id: str, field_id: str, value: Any) -> None:
with self._lock:
self._values.setdefault(session_id, {})[field_id] = value
def get_value(self, session_id: str, field_id: str) -> Any:
return self._values.get(session_id, {}).get(field_id)
def get_all(self, session_id: str) -> Dict[str, Any]:
return dict(self._values.get(session_id, {}))
def delete_value(self, session_id: str, field_id: str) -> bool:
with self._lock:
bucket = self._values.get(session_id)
if not bucket or field_id not in bucket:
return False
del bucket[field_id]
return True
def clear(self, session_id: str) -> int:
with self._lock:
count = len(self._values.get(session_id, {}))
self._values[session_id] = {}
return count

查看文件

@ -0,0 +1,53 @@
from __future__ import annotations
import math
import re
from typing import Any
from app.schemas.experiment import ValidationConfig, ValidationType
from app.schemas.validation import FieldValidationResponse
class FieldValidator:
@staticmethod
def _as_float(value: Any) -> float:
if isinstance(value, str) and value.strip() == "":
raise ValueError("empty value")
return float(value)
@classmethod
def validate_by_config(
cls,
field_id: str,
value: Any,
config: ValidationConfig | None,
) -> FieldValidationResponse:
if config is None:
return FieldValidationResponse(accept=True, message="validation passed")
if config.required and (value is None or (isinstance(value, str) and value.strip() == "")):
return FieldValidationResponse(accept=False, message=f"field {field_id} is required")
if value is None:
return FieldValidationResponse(accept=True, message="validation passed")
if config.type == ValidationType.NUMBER:
try:
num = cls._as_float(value)
except Exception:
return FieldValidationResponse(accept=False, message="please enter a valid number")
if config.min is not None and num < config.min:
return FieldValidationResponse(accept=False, message=f"value cannot be less than {config.min}")
if config.max is not None and num > config.max:
return FieldValidationResponse(accept=False, message=f"value cannot be greater than {config.max}")
if math.isnan(num) or math.isinf(num):
return FieldValidationResponse(accept=False, message="invalid numeric value")
return FieldValidationResponse(accept=True, message="validation passed")
if config.type == ValidationType.REGEX and config.pattern is not None:
text = str(value)
if re.fullmatch(config.pattern, text) is None:
return FieldValidationResponse(accept=False, message="field format mismatch")
return FieldValidationResponse(accept=True, message="validation passed")
return FieldValidationResponse(accept=True, message="validation passed")

100
backend/app/exp.md 普通文件
查看文件

@ -0,0 +1,100 @@
# 声速测量实验
## 频率测量
通过示波器读取原始波形通道即可直接测量,
学生读数五次,取平均
## 测量温度
通过温度计测量声速,输入一次
根据公式计算理论声速
## 三个方法
### 驻波法
获取示波器两个通道的图像,主要是接受波通道
```
:MEASUrement:CH<n>:<items>?
功能描述
获取通道测量项的值。
参数
名称
类型
范围
默认值
<n>
离散型
{1|2}
1
{MAX|MIN|PKPK|VTOP|VBASe|VAMP|AVERage|
SQUAresum|CYCRms| CURSorrms|
OVERShoot|PREShoot|PERiod|
FREQuency|RTime|FTime|PWIDth|NWIDth|
<items>
离散型
--
PDUTy|NDUTy|SCREenduty|FRR|FRF|FFR|FFF|
LRR|LRF|LFR|LFF|RDELay|FDELay|RPHAse|
PPULsenum|NPULsenum|RISEedgenum|
FALLedgenum|AREA|CYCLearea|HARDfrequency}
参数注释
Items(电压)
注释
Items(时间)
注释
MAX
最大值
PERiod
周期
MIN
最小值
FREQuency
频率
PKPK
峰峰值
RTime
上升时间
VTOP
顶端值
FTime
下降时间
VBASe
底端值
PWIDth
正脉宽
VAMP
幅度
NWIDth
负脉宽
AVERage
平均值
PDUTy
正占空比
SQUAresum
均方根值
NDUTy
负占空比
CYCRms
周期均方根
SCREenduty
屏幕脉宽比
CURSorrms
游标均方根
```
用MEASure命令测量峰值,同时截图,在峰值发生下降时将前一个图(即最高点)时游标卡尺读数送入OCR获取游标卡尺读数
总共测十次,后五次减去前五次作差取平均算不确定度,在频率已知的情况下即可获取到声速
### 相位法
在表现上使用XY模式观测李萨如图形,但是在示波器端实现和前者没有区别,只是学生端看起来不一样
也测量十次
### 时差法
分析读出的波形,接着计量CH1起始点到CH2起始点的时间之差(学生端使用示波器光标模式,程序端其实是找到两个波形的起始点)
学生需要填写游标卡尺数据(程序用截图+OCR)
测十次

5
backend/app/form.json 普通文件
查看文件

@ -0,0 +1,5 @@
{
"meta":{
"author":"AI+物理实验"
}
}

查看文件

@ -0,0 +1,14 @@
from app.hardware.service import HardwareSnapshot, HardwareStatus, OscilloscopeService, oscilloscope_service
from app.hardware.oscilloscope import Oscilloscope
from app.hardware.progress import Commands, ExecuteCmdInDev, work
__all__ = [
"HardwareSnapshot",
"HardwareStatus",
"OscilloscopeService",
"oscilloscope_service",
"Oscilloscope",
"Commands",
"ExecuteCmdInDev",
"work",
]

查看文件

@ -0,0 +1,157 @@
import usb.core
import usb.util
from typing import Optional, Tuple
class Oscilloscope:
"""基于PyUSB的通用示波器SCPI协议类,支持批量端点通信"""
DEFAULT_VID = 0x5345
DEFAULT_PID = 0x1234
DEFAULT_TIMEOUT_MS = 3000
MAX_PACKET_SIZE = 512 # 通常批量端点最大包大小,实际会从设备读取
def __init__(self, vid: int = DEFAULT_VID, pid: int = DEFAULT_PID):
"""
初始化示波器对象,但不立即连接。
:param vid: USB Vendor ID
:param pid: USB Product ID
"""
self.vid = vid
self.pid = pid
self.device: Optional[usb.core.Device] = None
self.ep_out: Optional[usb.core.Endpoint] = None
self.ep_in: Optional[usb.core.Endpoint] = None
self._attached_drivers = [] # 记录分离的内核驱动接口
def connect(self) -> None:
"""连接USB设备,配置端点,准备通信"""
# 1. 查找设备
dev = usb.core.find(idVendor=self.vid, idProduct=self.pid)
if dev is None:
raise RuntimeError(f"设备未找到 (VID={self.vid:04x}, PID={self.pid:04x})")
if isinstance(dev, usb.core.Device):
self.device = dev
else:
raise TypeError("No Device Found")
# 2. 分离内核驱动(若占用)
try:
cfg = self.device.get_active_configuration()
for intf in cfg:
if self.device.is_kernel_driver_active(intf.bInterfaceNumber):
self.device.detach_kernel_driver(intf.bInterfaceNumber)
self._attached_drivers.append(intf.bInterfaceNumber)
except Exception as E:
raise E
# 3. 设置配置(通常第一个配置即可)
try:
self.device.set_configuration()
except usb.core.USBError as e:
raise RuntimeError(f"设置USB配置失败: {e}")
# 4. 获取批量输入/输出端点(默认接口0,备用设置0)
try:
intf = self.device.get_active_configuration()[(0, 0)] #type:ignore
except KeyError:
raise RuntimeError("未找到接口 (0,0)")
self.ep_out = None
self.ep_in = None
for ep in intf:
if usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_OUT and isinstance(ep, usb.core.Endpoint):
self.ep_out = ep
elif usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_IN and isinstance(ep, usb.core.Endpoint):
self.ep_in = ep
if not self.ep_out or not self.ep_in:
raise RuntimeError("未找到批量输入/输出端点")
def disconnect(self) -> None:
"""断开设备并重新附加内核驱动(如果之前分离过)"""
if self.device is None:
return
# 重新附加内核驱动
for intf_num in self._attached_drivers:
try:
self.device.attach_kernel_driver(intf_num)
except usb.core.USBError:
pass # 忽略重新附加失败
self.device = None
self.ep_out = None
self.ep_in = None
self._attached_drivers.clear()
def send_command_raw(self, cmd: bytes, timeout: int = DEFAULT_TIMEOUT_MS) -> Optional[bytes]:
"""
发送SCPI命令并返回响应数据。
:param cmd: SCPI命令字符串(会自动添加换行符)
:param timeout: 超时时间(毫秒)
:return: 响应字节数据,若失败则返回None
"""
if self.device is None or self.ep_out is None or self.ep_in is None:
raise RuntimeError("设备未连接,请先调用connect()")
# 发送命令
try:
# self.device.write(self.ep_out.bEndpointAddress, cmd_bytes, timeout=timeout)
self.device.write(self.ep_out, cmd, timeout=timeout)
# self.ep_out.write(cmd_bytes, timeout)
except usb.core.USBError as e:
print(f"发送命令失败: {e}")
return None
# 读取响应(直到超时或收到短包)
response = b''
max_packet = self.ep_in.wMaxPacketSize # type: ignore
while True:
try:
# data = self.device.read(self.ep_in.bEndpointAddress, max_packet, timeout=timeout)
data = self.device.read(self.ep_in, max_packet, timeout=timeout)
if not data:
break
response += data.tobytes()
if len(data) < max_packet:
break
except usb.core.USBError as e:
if e.errno == 110: # 超时,表示没有更多数据
break
else:
print(f"读取响应失败: {e}")
return None
return response
def send_command(self, cmd: str, timeout: int = DEFAULT_TIMEOUT_MS) -> Optional[bytes]:
"""
发送SCPI命令并返回响应数据。
:param cmd: SCPI命令字符串(会自动添加换行符)
:param timeout: 超时时间(毫秒)
:return: 响应字节数据,若失败则返回None
"""
if self.device is None or self.ep_out is None or self.ep_in is None:
raise RuntimeError("设备未连接,请先调用connect()")
# 确保命令以换行结尾
if not cmd.endswith('\n'):
cmd += '\n'
cmd_bytes = cmd.encode('ascii')
return self.send_command_raw(cmd_bytes, timeout)
# 可选:提供原始端点访问属性
@property
def out_endpoint(self) -> Optional[usb.core.Endpoint]:
return self.ep_out
@property
def in_endpoint(self) -> Optional[usb.core.Endpoint]:
return self.ep_in
# 支持上下文管理器(with语句)
def __enter__(self):
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.disconnect()

查看文件

@ -0,0 +1,56 @@
from __future__ import annotations
from enum import Enum
from multiprocessing.connection import Connection
from typing import Optional
from app.hardware.oscilloscope import Oscilloscope
class Status(Enum):
IDLE = 0
Waiting = 1
# 规范
# CH1 接原始信号
# CH2 接返回信号
class Commands(Enum):
IDN = ('*IDN?', str)
MEASU_CH1_FREQ = (':MEASUrement:CH1:FREQuency?', float)
MEASU_CH2 = (':MEASUrement:CH2:MAX?', int)
DATA_CH2 = (':DATA:WAVE:SCREen:CH2?', bytes)
def ExecuteCmdInDev(dev:Oscilloscope, cmd:Commands):
resp = dev.send_command(cmd.value[0])
ret = None
if resp:
parser = cmd.value[1]
if parser is str:
ret = resp.decode("ascii", errors="ignore")
elif parser is bytes:
ret = resp
elif parser in (int, float):
ret = parser(resp.decode("ascii", errors="ignore").strip())
else:
ret = parser(resp)
return ret
#
# 工作流程:
# 发动本线程,
# 进入空闲状态,
# 等待用户指出
def work(con:Connection):
with Oscilloscope() as OWON:
idn = ExecuteCmdInDev(OWON, Commands.IDN)
if idn:
print(idn)
peak = ExecuteCmdInDev(OWON, Commands.MEASU_CH2)
if peak is not None:
con.send({"status": Status.Waiting.name, "peak": peak, "idn": idn})
data = ExecuteCmdInDev(OWON, Commands.DATA_CH2)
if data is not None:
con.send({"status": Status.IDLE.name, "data": data})

查看文件

@ -0,0 +1,86 @@
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import Optional
from fastapi import HTTPException
from app.hardware.oscilloscope import Oscilloscope
from app.hardware.progress import Commands, ExecuteCmdInDev
class HardwareStatus(str, Enum):
ONLINE = "online"
OFFLINE = "offline"
SIMULATED = "simulated"
@dataclass
class HardwareSnapshot:
status: HardwareStatus
device_idn: Optional[str] = None
peak_value: Optional[int] = None
frequency_hz: Optional[float] = None
raw_response: Optional[str] = None
note: Optional[str] = None
class OscilloscopeService:
def __init__(self) -> None:
self._cached_status = HardwareStatus.OFFLINE
def _open_device(self) -> Oscilloscope:
try:
return Oscilloscope()
except Exception as exc:
raise HTTPException(status_code=503, detail=f"示波器初始化失败: {exc}") from exc
def probe(self) -> HardwareSnapshot:
try:
with self._open_device() as device:
idn = ExecuteCmdInDev(device, Commands.IDN)
peak_value = ExecuteCmdInDev(device, Commands.MEASU_CH2)
frequency_hz = ExecuteCmdInDev(device, Commands.MEASU_CH1_FREQ)
self._cached_status = HardwareStatus.ONLINE
return HardwareSnapshot(
status=HardwareStatus.ONLINE,
device_idn=idn if isinstance(idn, str) else None,
peak_value=peak_value if isinstance(peak_value, int) else None,
frequency_hz=frequency_hz if isinstance(frequency_hz, float) else None,
raw_response=idn if isinstance(idn, str) else None,
note="已连接真实示波器",
)
except Exception as exc:
self._cached_status = HardwareStatus.SIMULATED
return HardwareSnapshot(
status=HardwareStatus.SIMULATED,
device_idn=None,
peak_value=None,
frequency_hz=None,
raw_response=None,
note=f"示波器不可用,已切换为模拟模式: {exc}",
)
def capture_peak(self) -> HardwareSnapshot:
snapshot = self.probe()
if snapshot.status == HardwareStatus.ONLINE:
return snapshot
return HardwareSnapshot(
status=HardwareStatus.SIMULATED,
peak_value=None,
note="当前没有连接示波器,返回模拟峰值",
)
def capture_frequency(self) -> HardwareSnapshot:
snapshot = self.probe()
if snapshot.status == HardwareStatus.ONLINE:
return snapshot
return HardwareSnapshot(
status=HardwareStatus.SIMULATED,
frequency_hz=None,
note="当前没有连接示波器,无法读取实时频率",
)
oscilloscope_service = OscilloscopeService()

60
backend/app/main.py 普通文件
查看文件

@ -0,0 +1,60 @@
from __future__ import annotations
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from app.api.form import router as form_router
from app.api.device import router as device_router
from app.api.measurement import router as measurement_router
from app.api.value import router as value_router
App = FastAPI(
title="Physics Experiment Backend",
description="Backend service for experiment forms, field validation, and sound velocity calculations",
version="1.0.0",
)
App.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
App.include_router(form_router)
App.include_router(device_router)
App.include_router(value_router)
App.include_router(measurement_router)
@App.get("/")
async def root():
return {
"message": "Physics Experiment Backend",
"version": "1.0.0",
"endpoints": {
"form": ["GET /form", "GET /form/list", "GET /form/{experiment_name}"],
"value": [
"POST /value",
"GET /value",
"GET /value/{field_id}",
"DELETE /value/{field_id}",
"DELETE /value",
],
"device": ["GET /device/status", "POST /device/peak"],
"measurement": ["POST /measurement/{standing_wave|phase|time_diff}"],
"system": ["GET /health"],
},
}
@App.get("/health")
async def health_check():
return {"status": "healthy", "service": "physics-experiment-backend"}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True, log_level="info")

39
backend/app/models.py 普通文件
查看文件

@ -0,0 +1,39 @@
from app.schemas.experiment import (
ExperimentGridConfig,
GridCell,
GridComputedCell,
GridInputCell,
GridLabelCell,
GridSheet,
ReadingGuardConfig,
ReadingGuardSource,
ValidationConfig,
ValidationType,
)
from app.schemas.validation import (
AnalyzeMeasurementRequest,
AnalyzeMeasurementResponse,
FieldValidationRequest,
FieldValidationResponse,
ManualAnswerRequest,
MeasurementMethod,
)
__all__ = [
"ExperimentGridConfig",
"GridCell",
"GridComputedCell",
"GridInputCell",
"GridLabelCell",
"GridSheet",
"ReadingGuardConfig",
"ReadingGuardSource",
"ValidationConfig",
"ValidationType",
"AnalyzeMeasurementRequest",
"AnalyzeMeasurementResponse",
"FieldValidationRequest",
"FieldValidationResponse",
"ManualAnswerRequest",
"MeasurementMethod",
]

9
backend/app/out.pyi 普通文件
查看文件

@ -0,0 +1,9 @@
import numbers
def get_number(path:str) -> numbers.Number:
"""从一个图像文件中使用OCR技术提取数字并返回。"""
pass
def capture_image() -> str:
"""捕获图像并保存到文件系统中,返回图像文件的路径。"""
pass

查看文件

@ -0,0 +1,39 @@
from app.schemas.experiment import (
ExperimentGridConfig,
GridCell,
GridComputedCell,
GridInputCell,
GridLabelCell,
GridSheet,
ReadingGuardConfig,
ReadingGuardSource,
ValidationConfig,
ValidationType,
)
from app.schemas.validation import (
AnalyzeMeasurementRequest,
AnalyzeMeasurementResponse,
FieldValidationRequest,
FieldValidationResponse,
ManualAnswerRequest,
MeasurementMethod,
)
__all__ = [
"ExperimentGridConfig",
"GridCell",
"GridComputedCell",
"GridInputCell",
"GridLabelCell",
"GridSheet",
"ReadingGuardConfig",
"ReadingGuardSource",
"ValidationConfig",
"ValidationType",
"AnalyzeMeasurementRequest",
"AnalyzeMeasurementResponse",
"FieldValidationRequest",
"FieldValidationResponse",
"ManualAnswerRequest",
"MeasurementMethod",
]

查看文件

@ -0,0 +1,81 @@
from __future__ import annotations
from enum import Enum
from typing import Any, List, Literal, Optional, Union
from pydantic import BaseModel, Field
class ValidationType(str, Enum):
NUMBER = "number"
TEXT = "text"
REGEX = "regex"
class ValidationConfig(BaseModel):
type: ValidationType
min: Optional[float] = None
max: Optional[float] = None
pattern: Optional[str] = None
required: bool = False
class ReadingGuardSource(str, Enum):
DEVICE_PEAK = "device_peak"
DEVICE_FREQUENCY = "device_frequency"
MANUAL = "manual"
class ReadingGuardConfig(BaseModel):
enabled: bool = False
source: ReadingGuardSource = ReadingGuardSource.MANUAL
tolerance: float = 0.0
class GridLabelCell(BaseModel):
type: Literal["label"] = "label"
content: str
colSpan: Optional[int] = None
rowSpan: Optional[int] = None
style: Optional[str] = None
class GridInputCell(BaseModel):
type: Literal["input"] = "input"
fieldId: str
placeholder: Optional[str] = None
unit: Optional[str] = None
colSpan: Optional[int] = None
rowSpan: Optional[int] = None
validation: Optional[ValidationConfig] = None
readingGuard: Optional[ReadingGuardConfig] = None
defaultValue: Optional[Any] = None
class GridComputedCell(BaseModel):
type: Literal["computed"] = "computed"
areaId: str
expression: str
variables: List[str] = Field(default_factory=list)
format: Optional[str] = None
colSpan: Optional[int] = None
rowSpan: Optional[int] = None
GridCell = Union[GridLabelCell, GridInputCell, GridComputedCell]
class GridSheet(BaseModel):
id: str
title: Optional[str] = None
columns: int
columnHeaders: Optional[List[str]] = None
columnWidths: Optional[List[str]] = None
rowHeaders: Optional[List[str]] = None
cells: List[List[Optional[GridCell]]]
class ExperimentGridConfig(BaseModel):
title: str
description: Optional[str] = None
sheets: List[GridSheet]

查看文件

@ -0,0 +1,52 @@
from __future__ import annotations
from enum import Enum
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field, model_validator
class FieldValidationRequest(BaseModel):
field_id: str
value: Any
class FieldValidationResponse(BaseModel):
accept: bool
message: str
class ManualAnswerRequest(BaseModel):
field_id: str
value: Any
class MeasurementMethod(str, Enum):
STANDING_WAVE = "standing_wave"
PHASE = "phase"
TIME_DIFF = "time_diff"
class AnalyzeMeasurementRequest(BaseModel):
frequency_hz: Optional[float] = Field(default=None, gt=0)
temperature_c: Optional[float] = None
cursor_readings_mm: List[float] = Field(default_factory=list)
distance_readings_mm: List[float] = Field(default_factory=list)
time_deltas_us: List[float] = Field(default_factory=list)
@model_validator(mode="after")
def ensure_enough_data(self) -> "AnalyzeMeasurementRequest":
total = len(self.cursor_readings_mm) + len(self.distance_readings_mm) + len(self.time_deltas_us)
if total == 0:
raise ValueError("at least one set of measurement data required")
return self
class AnalyzeMeasurementResponse(BaseModel):
method: MeasurementMethod
sample_count: int
velocity_mps: Optional[float] = None
wavelength_m: Optional[float] = None
uncertainty_mps: Optional[float] = None
theoretical_velocity_mps: Optional[float] = None
details: Dict[str, Any] = Field(default_factory=dict)

查看文件

@ -0,0 +1,969 @@
{
"title": "超声波声速测量实验(记录表)",
"description": "按纸质实验记录单组织:基本信息、表1频率与温度、表2驻波法、表3相位法、表4时差法、表5方法比较。",
"containers": [
{
"id": "basic_info",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(3, minmax(0, 1fr))"
},
"children": [
{
"id": "basic_title",
"type": "label",
"content": "## 基本信息"
},
{
"id": "basic_break_1",
"type": "newline"
},
{
"id": "class_name",
"type": "field",
"label": "班级",
"placeholder": "例如:纳米专业2班",
"validation": {
"type": "text",
"required": true
}
},
{
"id": "student_name",
"type": "field",
"label": "姓名",
"placeholder": "请输入姓名",
"validation": {
"type": "text",
"required": true
}
},
{
"id": "student_id",
"type": "field",
"label": "学号",
"placeholder": "请输入学号",
"validation": {
"type": "regex",
"pattern": "^[0-9]{6,20}$",
"required": true
}
}
]
},
{
"id": "table1",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(5, minmax(0, 1fr))"
},
"children": [
{
"id": "table1_title",
"type": "label",
"content": "## 表1 声源频率与介质温度"
},
{
"id": "table1_break_1",
"type": "newline"
},
{
"id": "f1",
"type": "field",
"label": "$f_{1}$",
"placeholder": "36.540",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "f2",
"type": "field",
"label": "$f_{2}$",
"placeholder": "36.539",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "f3",
"type": "field",
"label": "$f_{3}$",
"placeholder": "36.540",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "f4",
"type": "field",
"label": "$f_{4}$",
"placeholder": "36.538",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "f5",
"type": "field",
"label": "$f_{5}$",
"placeholder": "36.542",
"unit": "$kHz$",
"validation": {
"type": "number",
"min": 30,
"max": 45,
"required": true
}
},
{
"id": "table1_break_2",
"type": "newline"
},
{
"id": "temperature",
"type": "field",
"label": "介质温度 $t$",
"placeholder": "25.0",
"unit": "$^\\circ C$",
"validation": {
"type": "number",
"min": 0,
"max": 60,
"required": true
}
},
{
"id": "frequency_avg",
"type": "area",
"label": "平均频率 $\\bar{f}$",
"expression": "(f1+f2+f3+f4+f5)/5",
"variables": [
"f1",
"f2",
"f3",
"f4",
"f5"
],
"format": "0.000"
},
{
"id": "v0_theory",
"type": "area",
"label": "理论声速 $v_{0}$",
"expression": "331.5 + 0.6 * temperature",
"variables": [
"temperature"
],
"format": "0.00"
}
]
},
{
"id": "table2_standing",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(5, minmax(0, 1fr))"
},
"children": [
{
"id": "table2_title",
"type": "label",
"content": "## 表2 驻波法测量"
},
{
"id": "table2_break_1",
"type": "newline"
},
{
"id": "s_l0",
"type": "field",
"label": "$L_{0}$",
"placeholder": "144.02",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l1",
"type": "field",
"label": "$L_{1}$",
"placeholder": "148.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l2",
"type": "field",
"label": "$L_{2}$",
"placeholder": "153.50",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l3",
"type": "field",
"label": "$L_{3}$",
"placeholder": "158.30",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l4",
"type": "field",
"label": "$L_{4}$",
"placeholder": "163.00",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table2_break_2",
"type": "newline"
},
{
"id": "s_l5",
"type": "field",
"label": "$L_{5}$",
"placeholder": "167.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l6",
"type": "field",
"label": "$L_{6}$",
"placeholder": "172.66",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l7",
"type": "field",
"label": "$L_{7}$",
"placeholder": "177.30",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l8",
"type": "field",
"label": "$L_{8}$",
"placeholder": "182.29",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "s_l9",
"type": "field",
"label": "$L_{9}$",
"placeholder": "186.84",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table2_break_3",
"type": "newline"
},
{
"id": "s_d1",
"type": "area",
"label": "$\\Delta L_{1}$",
"expression": "s_l5 - s_l0",
"variables": ["s_l5", "s_l0"],
"format": "0.00"
},
{
"id": "s_d2",
"type": "area",
"label": "$\\Delta L_{2}$",
"expression": "s_l6 - s_l1",
"variables": ["s_l6", "s_l1"],
"format": "0.00"
},
{
"id": "s_d3",
"type": "area",
"label": "$\\Delta L_{3}$",
"expression": "s_l7 - s_l2",
"variables": ["s_l7", "s_l2"],
"format": "0.00"
},
{
"id": "s_d4",
"type": "area",
"label": "$\\Delta L_{4}$",
"expression": "s_l8 - s_l3",
"variables": ["s_l8", "s_l3"],
"format": "0.00"
},
{
"id": "s_d5",
"type": "area",
"label": "$\\Delta L_{5}$",
"expression": "s_l9 - s_l4",
"variables": ["s_l9", "s_l4"],
"format": "0.00"
},
{
"id": "table2_break_4",
"type": "newline"
},
{
"id": "s_d_avg",
"type": "area",
"label": "$\\overline{\\Delta L}$",
"expression": "(s_d1 + s_d2 + s_d3 + s_d4 + s_d5) / 5",
"variables": ["s_d1", "s_d2", "s_d3", "s_d4", "s_d5"],
"format": "0.00"
},
{
"id": "lambda_standing",
"type": "area",
"label": "$\\lambda$",
"expression": "(2 / 5) * s_d_avg",
"variables": ["s_d_avg"],
"format": "0.00"
},
{
"id": "v_standing",
"type": "area",
"label": "声速 $v$",
"expression": "frequency_avg * lambda_standing",
"variables": ["frequency_avg", "lambda_standing"],
"format": "0.00"
},
{
"id": "err_standing",
"type": "area",
"label": "$A_{\\%}$",
"expression": "((v_standing - v0_theory) / v0_theory) * 100",
"variables": ["v_standing", "v0_theory"],
"format": "0.000"
}
]
},
{
"id": "table3_phase",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(5, minmax(0, 1fr))"
},
"children": [
{
"id": "table3_title",
"type": "label",
"content": "## 表3 相位法测量"
},
{
"id": "table3_break_1",
"type": "newline"
},
{
"id": "p_l0",
"type": "field",
"label": "$L_{0}$",
"placeholder": "182.10",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l1",
"type": "field",
"label": "$L_{1}$",
"placeholder": "191.28",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l2",
"type": "field",
"label": "$L_{2}$",
"placeholder": "196.20",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l3",
"type": "field",
"label": "$L_{3}$",
"placeholder": "201.00",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l4",
"type": "field",
"label": "$L_{4}$",
"placeholder": "205.54",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table3_break_2",
"type": "newline"
},
{
"id": "p_l5",
"type": "field",
"label": "$L_{5}$",
"placeholder": "210.40",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l6",
"type": "field",
"label": "$L_{6}$",
"placeholder": "215.22",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l7",
"type": "field",
"label": "$L_{7}$",
"placeholder": "219.96",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l8",
"type": "field",
"label": "$L_{8}$",
"placeholder": "224.68",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "p_l9",
"type": "field",
"label": "$L_{9}$",
"placeholder": "229.40",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table3_break_3",
"type": "newline"
},
{
"id": "p_d1",
"type": "area",
"label": "$\\Delta L_{1}$",
"expression": "p_l5 - p_l0",
"variables": ["p_l5", "p_l0"],
"format": "0.00"
},
{
"id": "p_d2",
"type": "area",
"label": "$\\Delta L_{2}$",
"expression": "p_l6 - p_l1",
"variables": ["p_l6", "p_l1"],
"format": "0.00"
},
{
"id": "p_d3",
"type": "area",
"label": "$\\Delta L_{3}$",
"expression": "p_l7 - p_l2",
"variables": ["p_l7", "p_l2"],
"format": "0.00"
},
{
"id": "p_d4",
"type": "area",
"label": "$\\Delta L_{4}$",
"expression": "p_l8 - p_l3",
"variables": ["p_l8", "p_l3"],
"format": "0.00"
},
{
"id": "p_d5",
"type": "area",
"label": "$\\Delta L_{5}$",
"expression": "p_l9 - p_l4",
"variables": ["p_l9", "p_l4"],
"format": "0.00"
},
{
"id": "table3_break_4",
"type": "newline"
},
{
"id": "p_d_avg",
"type": "area",
"label": "$\\overline{\\Delta L}$",
"expression": "(p_d1 + p_d2 + p_d3 + p_d4 + p_d5) / 5",
"variables": ["p_d1", "p_d2", "p_d3", "p_d4", "p_d5"],
"format": "0.00"
},
{
"id": "lambda_phase",
"type": "area",
"label": "$\\lambda$",
"expression": "(2 / 5) * p_d_avg",
"variables": ["p_d_avg"],
"format": "0.00"
},
{
"id": "v_phase",
"type": "area",
"label": "声速 $v$",
"expression": "frequency_avg * lambda_phase",
"variables": ["frequency_avg", "lambda_phase"],
"format": "0.00"
},
{
"id": "err_phase",
"type": "area",
"label": "$A_{\\%}$",
"expression": "((v_phase - v0_theory) / v0_theory) * 100",
"variables": ["v_phase", "v0_theory"],
"format": "0.000"
}
]
},
{
"id": "table4_timediff",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(5, minmax(0, 1fr))"
},
"children": [
{
"id": "table4_title",
"type": "label",
"content": "## 表4 时差法测量"
},
{
"id": "table4_break_1",
"type": "newline"
},
{
"id": "t_l1",
"type": "field",
"label": "$L_{1}$",
"placeholder": "202.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l2",
"type": "field",
"label": "$L_{2}$",
"placeholder": "245.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l3",
"type": "field",
"label": "$L_{3}$",
"placeholder": "197.60",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l4",
"type": "field",
"label": "$L_{4}$",
"placeholder": "157.56",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l5",
"type": "field",
"label": "$L_{5}$",
"placeholder": "123.30",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table4_break_2",
"type": "newline"
},
{
"id": "t_l6",
"type": "field",
"label": "$L_{6}$",
"placeholder": "140.00",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l7",
"type": "field",
"label": "$L_{7}$",
"placeholder": "161.80",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l8",
"type": "field",
"label": "$L_{8}$",
"placeholder": "132.30",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l9",
"type": "field",
"label": "$L_{9}$",
"placeholder": "173.14",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "t_l10",
"type": "field",
"label": "$L_{10}$",
"placeholder": "152.46",
"unit": "$mm$",
"validation": { "type": "number", "min": 0, "max": 400, "required": true }
},
{
"id": "table4_break_3",
"type": "newline"
},
{
"id": "t_t1",
"type": "field",
"label": "$T_{1}$",
"placeholder": "584",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t2",
"type": "field",
"label": "$T_{2}$",
"placeholder": "712",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t3",
"type": "field",
"label": "$T_{3}$",
"placeholder": "572",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t4",
"type": "field",
"label": "$T_{4}$",
"placeholder": "456",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t5",
"type": "field",
"label": "$T_{5}$",
"placeholder": "356",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "table4_break_4",
"type": "newline"
},
{
"id": "t_t6",
"type": "field",
"label": "$T_{6}$",
"placeholder": "404",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t7",
"type": "field",
"label": "$T_{7}$",
"placeholder": "472",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t8",
"type": "field",
"label": "$T_{8}$",
"placeholder": "380",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t9",
"type": "field",
"label": "$T_{9}$",
"placeholder": "500",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "t_t10",
"type": "field",
"label": "$T_{10}$",
"placeholder": "440",
"unit": "$\\mu s$",
"validation": { "type": "number", "min": 0, "max": 2000, "required": true }
},
{
"id": "table4_break_5",
"type": "newline"
},
{
"id": "t_dl1",
"type": "area",
"label": "$\\Delta L_{1}$",
"expression": "t_l6 - t_l1",
"variables": ["t_l6", "t_l1"],
"format": "0.00"
},
{
"id": "t_dl2",
"type": "area",
"label": "$\\Delta L_{2}$",
"expression": "t_l7 - t_l2",
"variables": ["t_l7", "t_l2"],
"format": "0.00"
},
{
"id": "t_dl3",
"type": "area",
"label": "$\\Delta L_{3}$",
"expression": "t_l8 - t_l3",
"variables": ["t_l8", "t_l3"],
"format": "0.00"
},
{
"id": "t_dl4",
"type": "area",
"label": "$\\Delta L_{4}$",
"expression": "t_l9 - t_l4",
"variables": ["t_l9", "t_l4"],
"format": "0.00"
},
{
"id": "t_dl5",
"type": "area",
"label": "$\\Delta L_{5}$",
"expression": "t_l10 - t_l5",
"variables": ["t_l10", "t_l5"],
"format": "0.00"
},
{
"id": "table4_break_6",
"type": "newline"
},
{
"id": "t_dt1",
"type": "area",
"label": "$\\Delta T_{1}$",
"expression": "t_t6 - t_t1",
"variables": ["t_t6", "t_t1"],
"format": "0.00"
},
{
"id": "t_dt2",
"type": "area",
"label": "$\\Delta T_{2}$",
"expression": "t_t7 - t_t2",
"variables": ["t_t7", "t_t2"],
"format": "0.00"
},
{
"id": "t_dt3",
"type": "area",
"label": "$\\Delta T_{3}$",
"expression": "t_t8 - t_t3",
"variables": ["t_t8", "t_t3"],
"format": "0.00"
},
{
"id": "t_dt4",
"type": "area",
"label": "$\\Delta T_{4}$",
"expression": "t_t9 - t_t4",
"variables": ["t_t9", "t_t4"],
"format": "0.00"
},
{
"id": "t_dt5",
"type": "area",
"label": "$\\Delta T_{5}$",
"expression": "t_t10 - t_t5",
"variables": ["t_t10", "t_t5"],
"format": "0.00"
},
{
"id": "table4_break_7",
"type": "newline"
},
{
"id": "t_dl_avg",
"type": "area",
"label": "$\\overline{\\Delta L}$",
"expression": "(t_dl1 + t_dl2 + t_dl3 + t_dl4 + t_dl5) / 5",
"variables": ["t_dl1", "t_dl2", "t_dl3", "t_dl4", "t_dl5"],
"format": "0.00"
},
{
"id": "t_dt_avg",
"type": "area",
"label": "$\\overline{\\Delta T}$",
"expression": "(t_dt1 + t_dt2 + t_dt3 + t_dt4 + t_dt5) / 5",
"variables": ["t_dt1", "t_dt2", "t_dt3", "t_dt4", "t_dt5"],
"format": "0.00"
},
{
"id": "v_time",
"type": "area",
"label": "声速 $v$",
"expression": "1000 * t_dl_avg / t_dt_avg",
"variables": ["t_dl_avg", "t_dt_avg"],
"format": "0.00"
},
{
"id": "err_time",
"type": "area",
"label": "$A_{\\%}$",
"expression": "((v_time - v0_theory) / v0_theory) * 100",
"variables": ["v_time", "v0_theory"],
"format": "0.000"
}
]
},
{
"id": "table5_compare",
"type": "container",
"layout": "grid",
"style": {
"gridTemplateColumns": "repeat(3, minmax(0, 1fr))"
},
"children": [
{
"id": "table5_title",
"type": "label",
"content": "## 表5 几种方法比较"
},
{
"id": "table5_break_1",
"type": "newline"
},
{
"id": "cmp_v_standing",
"type": "area",
"label": "驻波法声速 $v$",
"expression": "v_standing",
"variables": ["v_standing"],
"format": "0.00"
},
{
"id": "cmp_v_phase",
"type": "area",
"label": "相位法声速 $v$",
"expression": "v_phase",
"variables": ["v_phase"],
"format": "0.00"
},
{
"id": "cmp_v_time",
"type": "area",
"label": "时差法声速 $v$",
"expression": "v_time",
"variables": ["v_time"],
"format": "0.00"
},
{
"id": "table5_break_2",
"type": "newline"
},
{
"id": "cmp_err_standing",
"type": "area",
"label": "驻波法 $A_{\\%}$",
"expression": "err_standing",
"variables": ["err_standing"],
"format": "0.000"
},
{
"id": "cmp_err_phase",
"type": "area",
"label": "相位法 $A_{\\%}$",
"expression": "err_phase",
"variables": ["err_phase"],
"format": "0.000"
},
{
"id": "cmp_err_time",
"type": "area",
"label": "时差法 $A_{\\%}$",
"expression": "err_time",
"variables": ["err_time"],
"format": "0.000"
}
]
},
{
"id": "notes_container",
"type": "container",
"layout": "vertical",
"children": [
{
"id": "notes_title",
"type": "label",
"content": "## 实验结论"
},
{
"id": "notes_break_1",
"type": "newline"
},
{
"id": "observation",
"type": "field",
"label": "实验现象与过程记录",
"placeholder": "记录波形变化、李萨如图形变化、时差读数现象等",
"validation": {
"type": "text",
"required": true
}
},
{
"id": "conclusion",
"type": "field",
"label": "结论与误差分析",
"placeholder": "比较三种方法差异,分析系统误差和随机误差来源",
"validation": {
"type": "text",
"required": true
}
}
]
}
]
}

查看文件

@ -0,0 +1,249 @@
{
"title": "超声波声速测量实验(记录表)",
"description": "基于网格表单组织:基本信息、表1频率与温度、表2驻波法、表3相位法、表4时差法、表5方法比较。",
"sheets": [
{
"id": "basic_info",
"title": "基本信息",
"columns": 3,
"cells": [
[
{"type": "label", "content": "班级", "style": "header"},
{"type": "input", "fieldId": "class_name", "placeholder": "纳米专业2班", "validation": {"type": "text", "required": true}},
{"type": "input", "fieldId": "student_name", "placeholder": "请输入姓名", "validation": {"type": "text", "required": true}}
],
[
{"type": "label", "content": "学号", "style": "header"},
{"type": "input", "fieldId": "student_id", "placeholder": "请输入学号", "colSpan": 2, "validation": {"type": "regex", "pattern": "^[0-9]{6,20}$", "required": true}},
null
]
]
},
{
"id": "table1_frequency",
"title": "表1 声源频率与介质温度",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$f/kHz$"},
{"type": "input", "fieldId": "f1", "placeholder": "36.540", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f2", "placeholder": "36.539", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f3", "placeholder": "36.540", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f4", "placeholder": "36.538", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}},
{"type": "input", "fieldId": "f5", "placeholder": "36.542", "unit": "$kHz$", "validation": {"type": "number", "min": 30, "max": 45, "required": true}}
],
[
{"type": "label", "content": "$t/^\\circ C$"},
{"type": "input", "fieldId": "temperature", "placeholder": "25.0", "unit": "$^\\circ C$", "colSpan": 5, "validation": {"type": "number", "min": 0, "max": 60, "required": true}}
],
[
{"type": "label", "content": "$\\bar{f}/kHz$"},
{"type": "computed", "areaId": "frequency_avg", "expression": "(f1+f2+f3+f4+f5)/5", "variables": ["f1","f2","f3","f4","f5"], "format": "0.000", "colSpan": 5}
],
[
{"type": "label", "content": "$v_0/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v0_theory", "expression": "331.5 + 0.6 * temperature", "variables": ["temperature"], "format": "0.00", "colSpan": 5}
]
]
},
{
"id": "table2_standing",
"title": "表2 驻波法测量",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$L_i/mm$"},
{"type": "input", "fieldId": "s_l0", "placeholder": "144.02", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l1", "placeholder": "148.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l2", "placeholder": "153.50", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l3", "placeholder": "158.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l4", "placeholder": "163.00", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$L_{i+5}/mm$"},
{"type": "input", "fieldId": "s_l5", "placeholder": "167.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l6", "placeholder": "172.66", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l7", "placeholder": "177.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l8", "placeholder": "182.29", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "s_l9", "placeholder": "186.84", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$\\Delta L_i/mm$"},
{"type": "computed", "areaId": "s_d1", "expression": "s_l5 - s_l0", "variables": ["s_l5","s_l0"], "format": "0.00"},
{"type": "computed", "areaId": "s_d2", "expression": "s_l6 - s_l1", "variables": ["s_l6","s_l1"], "format": "0.00"},
{"type": "computed", "areaId": "s_d3", "expression": "s_l7 - s_l2", "variables": ["s_l7","s_l2"], "format": "0.00"},
{"type": "computed", "areaId": "s_d4", "expression": "s_l8 - s_l3", "variables": ["s_l8","s_l3"], "format": "0.00"},
{"type": "computed", "areaId": "s_d5", "expression": "s_l9 - s_l4", "variables": ["s_l9","s_l4"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\overline{\\Delta L}/mm$"},
{"type": "computed", "areaId": "s_d_avg", "expression": "(s_d1 + s_d2 + s_d3 + s_d4 + s_d5) / 5", "variables": ["s_d1","s_d2","s_d3","s_d4","s_d5"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$\\lambda/mm$"},
{"type": "computed", "areaId": "lambda_standing", "expression": "(2 / 5) * s_d_avg", "variables": ["s_d_avg"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$v/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v_standing", "expression": "frequency_avg * lambda_standing", "variables": ["frequency_avg","lambda_standing"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$A_{\\%}$"},
{"type": "computed", "areaId": "err_standing", "expression": "((v_standing - v0_theory) / v0_theory) * 100", "variables": ["v_standing","v0_theory"], "format": "0.000", "colSpan": 5}
]
]
},
{
"id": "table3_phase",
"title": "表3 相位法测量",
"columns": 6,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5"],
"cells": [
[
{"type": "label", "content": "$L_i/mm$"},
{"type": "input", "fieldId": "p_l0", "placeholder": "182.10", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l1", "placeholder": "191.28", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l2", "placeholder": "196.20", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l3", "placeholder": "201.00", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l4", "placeholder": "205.54", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$L_{i+5}/mm$"},
{"type": "input", "fieldId": "p_l5", "placeholder": "210.40", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l6", "placeholder": "215.22", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l7", "placeholder": "219.96", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l8", "placeholder": "224.68", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "p_l9", "placeholder": "229.40", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$\\Delta L_i/mm$"},
{"type": "computed", "areaId": "p_d1", "expression": "p_l5 - p_l0", "variables": ["p_l5","p_l0"], "format": "0.00"},
{"type": "computed", "areaId": "p_d2", "expression": "p_l6 - p_l1", "variables": ["p_l6","p_l1"], "format": "0.00"},
{"type": "computed", "areaId": "p_d3", "expression": "p_l7 - p_l2", "variables": ["p_l7","p_l2"], "format": "0.00"},
{"type": "computed", "areaId": "p_d4", "expression": "p_l8 - p_l3", "variables": ["p_l8","p_l3"], "format": "0.00"},
{"type": "computed", "areaId": "p_d5", "expression": "p_l9 - p_l4", "variables": ["p_l9","p_l4"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\overline{\\Delta L}/mm$"},
{"type": "computed", "areaId": "p_d_avg", "expression": "(p_d1 + p_d2 + p_d3 + p_d4 + p_d5) / 5", "variables": ["p_d1","p_d2","p_d3","p_d4","p_d5"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$\\lambda/mm$"},
{"type": "computed", "areaId": "lambda_phase", "expression": "(2 / 5) * p_d_avg", "variables": ["p_d_avg"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$v/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v_phase", "expression": "frequency_avg * lambda_phase", "variables": ["frequency_avg","lambda_phase"], "format": "0.00", "colSpan": 5}
],
[
{"type": "label", "content": "$A_{\\%}$"},
{"type": "computed", "areaId": "err_phase", "expression": "((v_phase - v0_theory) / v0_theory) * 100", "variables": ["v_phase","v0_theory"], "format": "0.000", "colSpan": 5}
]
]
},
{
"id": "table4_timediff",
"title": "表4 时差法测量",
"columns": 11,
"columnHeaders": ["测量项目", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
"cells": [
[
{"type": "label", "content": "$L_i/mm$"},
{"type": "input", "fieldId": "t_l1", "placeholder": "202.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l2", "placeholder": "245.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l3", "placeholder": "197.60", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l4", "placeholder": "157.56", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l5", "placeholder": "123.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l6", "placeholder": "140.00", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l7", "placeholder": "161.80", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l8", "placeholder": "132.30", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l9", "placeholder": "173.14", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}},
{"type": "input", "fieldId": "t_l10", "placeholder": "152.46", "unit": "$mm$", "validation": {"type": "number", "min": 0, "max": 400, "required": true}}
],
[
{"type": "label", "content": "$T_i/\\mu s$"},
{"type": "input", "fieldId": "t_t1", "placeholder": "584", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t2", "placeholder": "712", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t3", "placeholder": "572", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t4", "placeholder": "456", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t5", "placeholder": "356", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t6", "placeholder": "404", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t7", "placeholder": "472", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t8", "placeholder": "380", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t9", "placeholder": "500", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}},
{"type": "input", "fieldId": "t_t10", "placeholder": "440", "unit": "$\\mu s$", "validation": {"type": "number", "min": 0, "max": 2000, "required": true}}
],
[
{"type": "label", "content": "$\\Delta L_i/mm$"},
{"type": "computed", "areaId": "t_dl1", "expression": "t_l6 - t_l1", "variables": ["t_l6","t_l1"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl2", "expression": "t_l7 - t_l2", "variables": ["t_l7","t_l2"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl3", "expression": "t_l8 - t_l3", "variables": ["t_l8","t_l3"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl4", "expression": "t_l9 - t_l4", "variables": ["t_l9","t_l4"], "format": "0.00"},
{"type": "computed", "areaId": "t_dl5", "expression": "t_l10 - t_l5", "variables": ["t_l10","t_l5"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\Delta T_i/\\mu s$"},
{"type": "computed", "areaId": "t_dt1", "expression": "t_t6 - t_t1", "variables": ["t_t6","t_t1"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt2", "expression": "t_t7 - t_t2", "variables": ["t_t7","t_t2"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt3", "expression": "t_t8 - t_t3", "variables": ["t_t8","t_t3"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt4", "expression": "t_t9 - t_t4", "variables": ["t_t9","t_t4"], "format": "0.00"},
{"type": "computed", "areaId": "t_dt5", "expression": "t_t10 - t_t5", "variables": ["t_t10","t_t5"], "format": "0.00"}
],
[
{"type": "label", "content": "$\\overline{\\Delta L}/mm$"},
{"type": "computed", "areaId": "t_dl_avg", "expression": "(t_dl1 + t_dl2 + t_dl3 + t_dl4 + t_dl5) / 5", "variables": ["t_dl1","t_dl2","t_dl3","t_dl4","t_dl5"], "format": "0.00", "colSpan": 10}
],
[
{"type": "label", "content": "$\\overline{\\Delta T}/\\mu s$"},
{"type": "computed", "areaId": "t_dt_avg", "expression": "(t_dt1 + t_dt2 + t_dt3 + t_dt4 + t_dt5) / 5", "variables": ["t_dt1","t_dt2","t_dt3","t_dt4","t_dt5"], "format": "0.00", "colSpan": 10}
],
[
{"type": "label", "content": "$v/(m\\cdot s^{-1})$"},
{"type": "computed", "areaId": "v_time", "expression": "1000 * t_dl_avg / t_dt_avg", "variables": ["t_dl_avg","t_dt_avg"], "format": "0.00", "colSpan": 10}
],
[
{"type": "label", "content": "$A_{\\%}$"},
{"type": "computed", "areaId": "err_time", "expression": "((v_time - v0_theory) / v0_theory) * 100", "variables": ["v_time","v0_theory"], "format": "0.000", "colSpan": 10}
]
]
},
{
"id": "table5_compare",
"title": "表5 几种方法比较",
"columns": 3,
"columnHeaders": ["方法", "声速 $v/(m\\cdot s^{-1})$", "相对误差 $A_{\\%}$"],
"cells": [
[
{"type": "label", "content": "驻波法"},
{"type": "computed", "areaId": "cmp_v_standing", "expression": "v_standing", "variables": ["v_standing"], "format": "0.00"},
{"type": "computed", "areaId": "cmp_err_standing", "expression": "err_standing", "variables": ["err_standing"], "format": "0.000"}
],
[
{"type": "label", "content": "相位法"},
{"type": "computed", "areaId": "cmp_v_phase", "expression": "v_phase", "variables": ["v_phase"], "format": "0.00"},
{"type": "computed", "areaId": "cmp_err_phase", "expression": "err_phase", "variables": ["err_phase"], "format": "0.000"}
],
[
{"type": "label", "content": "时差法"},
{"type": "computed", "areaId": "cmp_v_time", "expression": "v_time", "variables": ["v_time"], "format": "0.00"},
{"type": "computed", "areaId": "cmp_err_time", "expression": "err_time", "variables": ["err_time"], "format": "0.000"}
]
]
},
{
"id": "notes",
"title": "实验结论",
"columns": 1,
"cells": [
[
{"type": "input", "fieldId": "observation", "placeholder": "记录波形变化、李萨如图形变化、时差读数现象等", "validation": {"type": "text", "required": true}}
],
[
{"type": "input", "fieldId": "conclusion", "placeholder": "比较三种方法差异,分析系统误差和随机误差来源", "validation": {"type": "text", "required": true}}
]
]
}
]
}

13
backend/pyproject.toml 普通文件
查看文件

@ -0,0 +1,13 @@
[project]
name = "backend"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"fastapi[standard]>=0.116.1",
"libusb>=1.0.29.post7",
"pydantic>=2.11.3",
"pyusb>=1.3.1",
"uvicorn>=0.35.0",
]

1619
backend/uv.lock 自动生成的 普通文件

文件差异内容过多而无法显示 加载差异