refactor: 在旧的PhyExp基础上进行重构,采用了monorepo结构,分为frontend和backend两个子项目
这个提交包含在:
0
backend/app/core/__init__.py
普通文件
0
backend/app/core/__init__.py
普通文件
@ -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
|
||||
45
backend/app/core/dependencies.py
普通文件
45
backend/app/core/dependencies.py
普通文件
@ -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"
|
||||
90
backend/app/core/measurement.py
普通文件
90
backend/app/core/measurement.py
普通文件
@ -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,
|
||||
},
|
||||
)
|
||||
127
backend/app/core/reading_guard.py
普通文件
127
backend/app/core/reading_guard.py
普通文件
@ -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
|
||||
53
backend/app/core/validation.py
普通文件
53
backend/app/core/validation.py
普通文件
@ -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")
|
||||
在新工单中引用
屏蔽一个用户