data_service.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. from __future__ import annotations
  2. from collections import OrderedDict
  3. from datetime import datetime, timedelta
  4. from functools import lru_cache
  5. from time import monotonic
  6. from typing import Any, Callable
  7. import numpy as np
  8. from ..algorithms.cycles import (
  9. DetectedCycle,
  10. PULSES_PER_REVOLUTION,
  11. build_angle_vector,
  12. detect_cycles,
  13. downsample_indices,
  14. )
  15. from ..config import settings
  16. from ..db import get_connection
  17. MEASUREMENT_TYPES = ("位移", "加速度", "压力")
  18. MEASUREMENT_COLORS = {
  19. "压力": "#e4572e",
  20. "位移": "#1f7a8c",
  21. "加速度": "#7b61a8",
  22. }
  23. PHASES = (
  24. ("排气", "#7b1fa2", 0.0, 120.0),
  25. ("压缩", "#c62828", 120.0, 195.0),
  26. ("膨胀", "#1565c0", 195.0, 270.0),
  27. ("进气", "#2e7d32", 270.0, 330.0),
  28. )
  29. ANNOTATION_LABELS = ("正常", "异常")
  30. CYLINDER_BORE_MM = {
  31. "一缸": 360.0,
  32. "二缸": 490.0,
  33. "三缸": 390.0,
  34. "四缸": 490.0,
  35. "五缸": 390.0,
  36. "六缸": 490.0,
  37. }
  38. PISTON_STROKE_MM = 148.0
  39. CONNECTING_ROD_LENGTH_MM = 460.0
  40. CLEARANCE_VOLUME_L_BY_BORE = {
  41. 490.0: 1.51,
  42. 390.0: 0.74,
  43. 360.0: 0.62,
  44. }
  45. DEMO_POINT_NAME = "7号机组一缸压力盖侧"
  46. DEMO_START = datetime(2026, 4, 12, 8, 0, 0)
  47. DEMO_POINT_COUNT = 72
  48. DEMO_SAMPLE_COUNT = 32768
  49. DEMO_REVOLUTION_SAMPLES = 800
  50. DEMO_ID_BY_TYPE = {name: 100000 + index * 1000 for index, name in enumerate(MEASUREMENT_TYPES)}
  51. def _time_string(value: Any) -> str:
  52. if isinstance(value, datetime):
  53. return value.strftime("%Y-%m-%d %H:%M:%S")
  54. return str(value)
  55. def _parse_time(value: str | None) -> datetime | None:
  56. if not value:
  57. return None
  58. return datetime.fromisoformat(value.replace("Z", "+00:00").replace("T", " "))
  59. def _safe_float(value: Any) -> float | None:
  60. if value is None:
  61. return None
  62. number = float(value)
  63. return number if np.isfinite(number) else None
  64. def _annotation_dict(row: dict[str, Any]) -> dict[str, Any]:
  65. return {
  66. "id": int(row["id"]),
  67. "waveFileId": int(row["wave_file_id"]),
  68. "label": row["label"],
  69. "periodStart": int(row["period_start"]),
  70. "periodEnd": int(row["period_end"]),
  71. "sampleIndexStart": int(row["sample_index_start"]),
  72. "sampleIndexEnd": int(row["sample_index_end"]),
  73. }
  74. def _validate_measurement_types(values: list[str] | tuple[str, ...] | None) -> list[str]:
  75. selected = list(values or MEASUREMENT_TYPES)
  76. invalid = [value for value in selected if value not in MEASUREMENT_TYPES]
  77. if invalid:
  78. raise ValueError(f"不支持的数据名称:{'、'.join(invalid)}")
  79. return [value for value in MEASUREMENT_TYPES if value in selected]
  80. class DataService:
  81. # 数据库失败后的重试冷却时间(秒)。超过该时间后自动重连数据库,
  82. # 避免一次网络抖动就把服务永久锁死在演示数据模式。
  83. DB_RETRY_COOLDOWN = 30.0
  84. def __init__(self) -> None:
  85. self._db_failed = settings.demo_mode == "always"
  86. self._db_failed_at = monotonic() if self._db_failed else 0.0
  87. self._last_db_error = ""
  88. self._demo_annotations: dict[int, dict[str, Any]] = {}
  89. self._demo_annotation_seq = 1
  90. @property
  91. def source(self) -> str:
  92. return "demo" if self._db_failed else "database"
  93. @property
  94. def last_db_error(self) -> str:
  95. return self._last_db_error
  96. def _run_with_fallback(
  97. self,
  98. database_function: Callable[[], Any],
  99. demo_function: Callable[[], Any],
  100. ) -> tuple[Any, str]:
  101. if self._db_failed:
  102. if settings.demo_mode == "always":
  103. return demo_function(), "demo"
  104. if monotonic() - self._db_failed_at < self.DB_RETRY_COOLDOWN:
  105. return demo_function(), "demo"
  106. # 冷却结束,重新尝试数据库,数据库恢复后可自动切回真实数据。
  107. try:
  108. result = database_function()
  109. self._db_failed = False
  110. self._last_db_error = ""
  111. return result, "database"
  112. except Exception as error:
  113. if settings.demo_mode == "never":
  114. raise
  115. self._db_failed = True
  116. self._db_failed_at = monotonic()
  117. self._last_db_error = str(error)
  118. return demo_function(), "demo"
  119. def query_options(self) -> dict[str, Any]:
  120. def database_query():
  121. placeholders = ", ".join(["%s"] * len(MEASUREMENT_TYPES))
  122. with get_connection() as connection:
  123. with connection.cursor() as cursor:
  124. cursor.execute(
  125. f"""
  126. SELECT point_name, measurement_type,
  127. MAX(sample_time) AS max_time,
  128. MIN(sample_time) AS min_time,
  129. COUNT(*) AS file_count
  130. FROM wave_file
  131. WHERE measurement_type IN ({placeholders})
  132. GROUP BY point_name, measurement_type
  133. ORDER BY point_name, measurement_type
  134. """,
  135. MEASUREMENT_TYPES,
  136. )
  137. rows = cursor.fetchall()
  138. return [
  139. {
  140. "pointName": row["point_name"],
  141. "measurementType": row["measurement_type"],
  142. "minTime": _time_string(row["min_time"]),
  143. "maxTime": _time_string(row["max_time"]),
  144. "fileCount": int(row["file_count"]),
  145. }
  146. for row in rows
  147. ]
  148. rows, source = self._run_with_fallback(database_query, self._demo_options)
  149. point_names = list(dict.fromkeys(row["pointName"] for row in rows))
  150. return {
  151. "source": source,
  152. "measurementTypes": list(MEASUREMENT_TYPES),
  153. "pointNames": point_names,
  154. "options": rows,
  155. "notice": self._source_notice(source),
  156. }
  157. def time_points(
  158. self,
  159. point_name: str,
  160. measurement_types: list[str] | None,
  161. min_time: str | None,
  162. max_time: str | None,
  163. ) -> dict[str, Any]:
  164. if not point_name.strip():
  165. raise ValueError("机组与部位不能为空")
  166. types = _validate_measurement_types(measurement_types)
  167. start = _parse_time(min_time)
  168. end = _parse_time(max_time)
  169. if start and end and start > end:
  170. raise ValueError("开始时间不能晚于结束时间")
  171. def database_query():
  172. type_placeholders = ", ".join(["%s"] * len(types))
  173. clauses = [
  174. "point_name = %s",
  175. f"measurement_type IN ({type_placeholders})",
  176. ]
  177. params: list[Any] = [point_name, *types]
  178. if start:
  179. clauses.append("sample_time >= %s")
  180. params.append(start)
  181. if end:
  182. clauses.append("sample_time <= %s")
  183. params.append(end)
  184. with get_connection() as connection:
  185. with connection.cursor() as cursor:
  186. cursor.execute(
  187. f"""
  188. SELECT id, point_name, measurement_type, sample_time,
  189. sample_count, sample_frequency_hz, rpm
  190. FROM wave_file
  191. WHERE {' AND '.join(clauses)}
  192. ORDER BY sample_time ASC, id ASC
  193. """,
  194. params,
  195. )
  196. rows = cursor.fetchall()
  197. return self._group_time_points(rows)
  198. def demo_query():
  199. return self._demo_time_points(point_name, types, start, end)
  200. points, source = self._run_with_fallback(database_query, demo_query)
  201. return {
  202. "source": source,
  203. "pointName": point_name,
  204. "measurementTypes": types,
  205. "total": len(points),
  206. "points": points,
  207. "notice": self._source_notice(source),
  208. }
  209. @staticmethod
  210. def _group_time_points(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
  211. grouped: OrderedDict[Any, dict[str, Any]] = OrderedDict()
  212. for row in rows:
  213. key = row["sample_time"]
  214. point = grouped.setdefault(
  215. key,
  216. {
  217. "sampleTime": _time_string(key),
  218. "files": {},
  219. },
  220. )
  221. point["files"][row["measurement_type"]] = {
  222. "id": int(row["id"]),
  223. "sampleCount": int(row["sample_count"] or 0),
  224. "sampleFrequencyHz": int(row["sample_frequency_hz"] or 0),
  225. "rpm": float(row["rpm"] or 0),
  226. }
  227. return [
  228. {"index": index, **point}
  229. for index, point in enumerate(grouped.values())
  230. ]
  231. def wave_window(
  232. self,
  233. point_name: str,
  234. measurement_types: list[str],
  235. points: list[dict[str, Any]],
  236. max_points: int,
  237. no_sampling: bool = False,
  238. ) -> dict[str, Any]:
  239. types = _validate_measurement_types(measurement_types)
  240. if not points:
  241. raise ValueError("至少选择一个时间点")
  242. if len(points) > 200:
  243. raise ValueError("单次最多预览 200 个时间点,请缩小时间窗口")
  244. max_points = min(max(int(max_points), 256), 200000)
  245. def database_query():
  246. return self._build_wave_window(
  247. point_name,
  248. types,
  249. points,
  250. max_points,
  251. self._load_db_wave,
  252. no_sampling,
  253. )
  254. def demo_query():
  255. return self._build_wave_window(
  256. point_name,
  257. types,
  258. points,
  259. max_points,
  260. self._load_demo_wave,
  261. no_sampling,
  262. )
  263. result, source = self._run_with_fallback(database_query, demo_query)
  264. result["source"] = source
  265. result["notice"] = self._source_notice(source)
  266. return result
  267. def period_detail(self, wave_file_id: int, period_number: int) -> dict[str, Any]:
  268. if wave_file_id <= 0 or period_number <= 0:
  269. raise ValueError("wave_file_id 和周期编号必须为正整数")
  270. def database_query():
  271. metadata, samples = self._load_db_wave(wave_file_id)
  272. return self._build_period_detail(metadata, samples, period_number)
  273. def demo_query():
  274. metadata, samples = self._load_demo_wave(
  275. wave_file_id,
  276. "压力",
  277. DEMO_POINT_NAME,
  278. DEMO_START,
  279. )
  280. return self._build_period_detail(metadata, samples, period_number)
  281. result, source = self._run_with_fallback(database_query, demo_query)
  282. result["source"] = source
  283. result["notice"] = self._source_notice(source)
  284. return result
  285. def annotation_config(self) -> dict[str, Any]:
  286. return {
  287. "source": self.source,
  288. "annotationWidth": settings.annotation_width,
  289. "notice": self._source_notice(self.source),
  290. }
  291. def list_annotations(self, wave_file_ids: list[int]) -> dict[str, Any]:
  292. ids = sorted({int(value) for value in wave_file_ids if value})
  293. if not ids:
  294. return {
  295. "source": self.source,
  296. "annotations": [],
  297. "notice": self._source_notice(self.source),
  298. }
  299. def database_query():
  300. placeholders = ", ".join(["%s"] * len(ids))
  301. with get_connection() as connection:
  302. with connection.cursor() as cursor:
  303. cursor.execute(
  304. f"""
  305. SELECT id, wave_file_id, label, period_start, period_end,
  306. sample_index_start, sample_index_end
  307. FROM wave_annotation
  308. WHERE wave_file_id IN ({placeholders})
  309. ORDER BY id ASC
  310. """,
  311. ids,
  312. )
  313. rows = cursor.fetchall()
  314. return [_annotation_dict(row) for row in rows]
  315. def demo_query():
  316. return [
  317. _annotation_dict(annotation)
  318. for annotation in self._demo_annotations.values()
  319. if annotation["wave_file_id"] in ids
  320. ]
  321. annotations, source = self._run_with_fallback(database_query, demo_query)
  322. return {
  323. "source": source,
  324. "annotations": annotations,
  325. "notice": self._source_notice(source),
  326. }
  327. def create_annotation(self, payload: dict[str, Any]) -> dict[str, Any]:
  328. self._validate_annotation(payload)
  329. wave_file_id = int(payload["wave_file_id"])
  330. label = payload["label"]
  331. period_start = int(payload["period_start"])
  332. period_end = int(payload["period_end"])
  333. sample_index_start = int(payload["sample_index_start"])
  334. sample_index_end = int(payload["sample_index_end"])
  335. def database_query():
  336. with get_connection() as connection:
  337. with connection.cursor() as cursor:
  338. cursor.execute(
  339. """
  340. INSERT INTO wave_annotation
  341. (wave_file_id, label, period_start, period_end,
  342. sample_index_start, sample_index_end)
  343. VALUES (%s, %s, %s, %s, %s, %s)
  344. """,
  345. (
  346. wave_file_id,
  347. label,
  348. period_start,
  349. period_end,
  350. sample_index_start,
  351. sample_index_end,
  352. ),
  353. )
  354. annotation_id = cursor.lastrowid
  355. cursor.execute(
  356. """
  357. SELECT id, wave_file_id, label, period_start, period_end,
  358. sample_index_start, sample_index_end
  359. FROM wave_annotation
  360. WHERE id = %s
  361. """,
  362. (annotation_id,),
  363. )
  364. return _annotation_dict(cursor.fetchone())
  365. def demo_query():
  366. annotation_id = self._demo_annotation_seq
  367. self._demo_annotation_seq += 1
  368. annotation = {
  369. "id": annotation_id,
  370. "wave_file_id": wave_file_id,
  371. "label": label,
  372. "period_start": period_start,
  373. "period_end": period_end,
  374. "sample_index_start": sample_index_start,
  375. "sample_index_end": sample_index_end,
  376. }
  377. self._demo_annotations[annotation_id] = annotation
  378. return _annotation_dict(annotation)
  379. result, source = self._run_with_fallback(database_query, demo_query)
  380. result["source"] = source
  381. result["notice"] = self._source_notice(source)
  382. return result
  383. def delete_annotation(self, annotation_id: int) -> dict[str, Any]:
  384. if annotation_id <= 0:
  385. raise ValueError("标注 id 必须为正整数")
  386. def database_query():
  387. with get_connection() as connection:
  388. with connection.cursor() as cursor:
  389. cursor.execute(
  390. "DELETE FROM wave_annotation WHERE id = %s",
  391. (annotation_id,),
  392. )
  393. return int(cursor.rowcount)
  394. def demo_query():
  395. if annotation_id not in self._demo_annotations:
  396. return 0
  397. del self._demo_annotations[annotation_id]
  398. return 1
  399. deleted, source = self._run_with_fallback(database_query, demo_query)
  400. if not deleted:
  401. raise ValueError(f"标注 id={annotation_id} 不存在")
  402. return {
  403. "deleted": annotation_id,
  404. "source": source,
  405. "notice": self._source_notice(source),
  406. }
  407. @staticmethod
  408. def _validate_annotation(payload: dict[str, Any]) -> None:
  409. label = payload.get("label")
  410. if label not in ANNOTATION_LABELS:
  411. raise ValueError("样本类型只能是 正常 或 异常")
  412. for field in ("wave_file_id", "period_start", "period_end", "sample_index_start", "sample_index_end"):
  413. if payload.get(field) is None:
  414. raise ValueError(f"{field} 不能为空")
  415. if int(payload["wave_file_id"]) <= 0:
  416. raise ValueError("wave_file_id 必须为正整数")
  417. if int(payload["period_start"]) <= 0 or int(payload["period_end"]) <= 0:
  418. raise ValueError("周期编号必须为正整数")
  419. if int(payload["period_start"]) > int(payload["period_end"]):
  420. raise ValueError("起始周期不能大于结束周期")
  421. if int(payload["sample_index_start"]) < 0 or int(payload["sample_index_end"]) < 0:
  422. raise ValueError("采样点索引不能为负")
  423. if int(payload["sample_index_start"]) > int(payload["sample_index_end"]):
  424. raise ValueError("起始采样点不能大于结束采样点")
  425. def health(self) -> dict[str, Any]:
  426. return {
  427. "status": "ok",
  428. "source": self.source,
  429. "databaseError": self._last_db_error or None,
  430. }
  431. def _source_notice(self, source: str) -> str | None:
  432. if source == "demo":
  433. if self._last_db_error:
  434. return f"当前为演示数据:数据库暂不可用({self._last_db_error})"
  435. return "当前为演示数据:可设置 DEMO_MODE=never 强制使用数据库"
  436. return "已连接 MySQL 数据库"
  437. def _build_wave_window(
  438. self,
  439. point_name: str,
  440. types: list[str],
  441. points: list[dict[str, Any]],
  442. max_points: int,
  443. loader: Callable[..., tuple[dict[str, Any], np.ndarray]],
  444. no_sampling: bool = False,
  445. ) -> dict[str, Any]:
  446. series_data: dict[str, list[dict[str, Any]]] = {measurement_type: [] for measurement_type in types}
  447. angle_data: list[dict[str, Any]] = []
  448. volume_data: list[dict[str, Any]] = []
  449. volume_info: dict[str, Any] | None = None
  450. cycles: list[dict[str, Any]] = []
  451. triggers: list[float] = []
  452. files: list[dict[str, Any]] = []
  453. diagnostics: list[dict[str, Any]] = []
  454. second_series_data: list[dict[str, Any]] = []
  455. second_finite_count = 0
  456. second_non_zero_count = 0
  457. second_min: float | None = None
  458. second_max: float | None = None
  459. source_type = "压力" if "压力" in types else types[0]
  460. load_cache: dict[int, tuple[dict[str, Any], np.ndarray]] = {}
  461. for slot, point in enumerate(points):
  462. source_measurement_type = source_type
  463. source_file = point.get("files", {}).get(source_measurement_type)
  464. if not source_file:
  465. available = [
  466. (measurement_type, file_info)
  467. for measurement_type, file_info in point.get("files", {}).items()
  468. if measurement_type in types and file_info
  469. ]
  470. if available:
  471. source_measurement_type, source_file = available[0]
  472. else:
  473. continue
  474. source_id = int(source_file["id"] if isinstance(source_file, dict) else source_file)
  475. try:
  476. source_metadata, source_samples = self._load_for_window(
  477. loader,
  478. source_id,
  479. source_measurement_type,
  480. point_name,
  481. point["sampleTime"],
  482. load_cache,
  483. )
  484. except ValueError:
  485. # A selected file may legitimately have no samples. A database
  486. # connection error must escape and activate the demo fallback.
  487. continue
  488. detected, diagnostic = detect_cycles(source_samples)
  489. angle_vector = build_angle_vector(len(source_samples), detected)
  490. full_angle_vector = np.full(len(source_samples), np.nan, dtype=float)
  491. for detected_cycle in detected:
  492. full_angle_vector[detected_cycle.start_offset:detected_cycle.end_offset] = detected_cycle.angle
  493. current_volume, current_volume_info = self._build_volume_vector(
  494. len(source_samples),
  495. detected,
  496. point_name,
  497. )
  498. if current_volume_info is not None:
  499. volume_info = current_volume_info
  500. sample_indices = source_samples[:, 0].astype(np.int64)
  501. sample_span = max(len(source_samples), 1)
  502. finite_second = source_samples[:, 2][np.isfinite(source_samples[:, 2])]
  503. if len(finite_second):
  504. second_finite_count += int(len(finite_second))
  505. second_non_zero_count += int(np.count_nonzero(finite_second != 0))
  506. current_min = float(np.min(finite_second))
  507. current_max = float(np.max(finite_second))
  508. second_min = current_min if second_min is None else min(second_min, current_min)
  509. second_max = current_max if second_max is None else max(second_max, current_max)
  510. required = {0, len(source_samples) - 1}
  511. for cycle in detected:
  512. required.update(
  513. {
  514. cycle.start_offset,
  515. max(cycle.end_offset - 1, cycle.start_offset),
  516. *cycle.trigger_offsets,
  517. },
  518. )
  519. start_x = slot + cycle.start_offset / sample_span
  520. end_x = slot + cycle.end_offset / sample_span
  521. start_sample_index = int(sample_indices[cycle.start_offset])
  522. end_sample_index = int(sample_indices[max(cycle.end_offset - 1, cycle.start_offset)])
  523. cycles.append(
  524. {
  525. "id": f"{source_id}:{cycle.number}",
  526. "waveFileId": source_id,
  527. "periodNo": cycle.number,
  528. "pointIndex": slot,
  529. "sampleTime": point["sampleTime"],
  530. "startX": start_x,
  531. "endX": end_x,
  532. "startSampleIndex": start_sample_index,
  533. "endSampleIndex": end_sample_index,
  534. "sourceType": source_measurement_type,
  535. },
  536. )
  537. for trigger_offset in sorted(required):
  538. if trigger_offset in required and any(
  539. trigger_offset == run_offset
  540. for cycle in detected
  541. for run_offset in cycle.trigger_offsets
  542. ):
  543. triggers.append(slot + trigger_offset / sample_span)
  544. diagnostics.append(
  545. {
  546. "waveFileId": source_id,
  547. "measurementType": source_measurement_type,
  548. "sampleTime": point["sampleTime"],
  549. **diagnostic,
  550. },
  551. )
  552. for measurement_type in types:
  553. file_info = point.get("files", {}).get(measurement_type)
  554. if not file_info:
  555. continue
  556. file_id = int(file_info["id"] if isinstance(file_info, dict) else file_info)
  557. if file_id == source_id:
  558. metadata, samples = source_metadata, source_samples
  559. else:
  560. try:
  561. metadata, samples = self._load_for_window(
  562. loader,
  563. file_id,
  564. measurement_type,
  565. point_name,
  566. point["sampleTime"],
  567. load_cache,
  568. )
  569. except ValueError:
  570. continue
  571. sample_count = len(samples)
  572. if not sample_count:
  573. continue
  574. sample_indices_for_file = samples[:, 0].astype(np.int64)
  575. file_base_index = int(sample_indices_for_file[0])
  576. file_span = max(sample_count, 1)
  577. file_required = {0, sample_count - 1}
  578. if file_id == source_id:
  579. file_required.update(required)
  580. if no_sampling:
  581. target_per_file = sample_count
  582. else:
  583. target_per_file = max(256, int(np.ceil(max_points / max(len(points), 1))))
  584. chosen = downsample_indices(samples[:, 1], target_per_file, file_required)
  585. for offset in chosen:
  586. x = slot + (int(sample_indices_for_file[offset]) - file_base_index) / file_span
  587. second = _safe_float(samples[offset, 2])
  588. raw_value = float(samples[offset, 1])
  589. series_data[measurement_type].append(
  590. {
  591. "value": [x, raw_value],
  592. "x": x,
  593. "rawValue": raw_value,
  594. "sampleIndex": int(sample_indices_for_file[offset]),
  595. "waveFileId": file_id,
  596. "sampleTime": point["sampleTime"],
  597. "secondValue": second,
  598. "volume": (
  599. _safe_float(current_volume[offset])
  600. if file_id == source_id
  601. else None
  602. ),
  603. "angle360": (
  604. _safe_float(full_angle_vector[offset])
  605. if file_id == source_id
  606. else None
  607. ),
  608. },
  609. )
  610. if file_id == source_id:
  611. second_chosen = downsample_indices(samples[:, 2], target_per_file, file_required)
  612. for offset in second_chosen:
  613. second_value = _safe_float(samples[offset, 2])
  614. if second_value is None:
  615. continue
  616. x = slot + (int(sample_indices_for_file[offset]) - file_base_index) / file_span
  617. second_series_data.append(
  618. {
  619. "value": [x, second_value],
  620. "x": x,
  621. "rawValue": second_value,
  622. "sampleIndex": int(sample_indices_for_file[offset]),
  623. "waveFileId": file_id,
  624. "sampleTime": point["sampleTime"],
  625. },
  626. )
  627. angle_chosen = downsample_indices(angle_vector, target_per_file, file_required)
  628. for offset in angle_chosen:
  629. value = _safe_float(angle_vector[offset])
  630. if value is None:
  631. continue
  632. x = slot + (int(sample_indices_for_file[offset]) - file_base_index) / file_span
  633. angle_data.append(
  634. {
  635. "value": [x, value],
  636. "x": x,
  637. "angle": value,
  638. "sampleIndex": int(sample_indices_for_file[offset]),
  639. "waveFileId": file_id,
  640. "sampleTime": point["sampleTime"],
  641. },
  642. )
  643. volume_chosen = downsample_indices(current_volume, target_per_file, file_required)
  644. for offset in volume_chosen:
  645. value = _safe_float(current_volume[offset])
  646. if value is None:
  647. continue
  648. x = slot + (int(sample_indices_for_file[offset]) - file_base_index) / file_span
  649. volume_data.append(
  650. {
  651. "value": [x, value],
  652. "x": x,
  653. "volume": value,
  654. "sampleIndex": int(sample_indices_for_file[offset]),
  655. "waveFileId": file_id,
  656. "sampleTime": point["sampleTime"],
  657. },
  658. )
  659. files.append(
  660. {
  661. "id": file_id,
  662. "pointIndex": slot,
  663. "sampleTime": point["sampleTime"],
  664. "measurementType": measurement_type,
  665. "sampleCount": int(metadata.get("sample_count") or sample_count),
  666. "sampleFrequencyHz": int(metadata.get("sample_frequency_hz") or 0),
  667. },
  668. )
  669. # Keep at most the current time point's raw arrays resident. The
  670. # response retains only downsampled values and period metadata.
  671. load_cache.clear()
  672. for measurement_type in series_data:
  673. series_data[measurement_type].sort(key=lambda item: item["x"])
  674. second_series_data.sort(key=lambda item: item["x"])
  675. angle_data.sort(key=lambda item: item["x"])
  676. volume_data.sort(key=lambda item: item["x"])
  677. return {
  678. "pointName": point_name,
  679. "measurementTypes": types,
  680. "points": points,
  681. "xMin": 0,
  682. "xMax": len(points),
  683. "series": [
  684. {
  685. "measurementType": measurement_type,
  686. "color": MEASUREMENT_COLORS[measurement_type],
  687. "data": series_data[measurement_type],
  688. }
  689. for measurement_type in types
  690. ],
  691. "secondSeries": {
  692. "name": "周期数据",
  693. "color": "#f56c6c",
  694. "sourceMeasurementType": source_type,
  695. "data": second_series_data,
  696. "finiteCount": second_finite_count,
  697. "nonZeroCount": second_non_zero_count,
  698. "min": second_min,
  699. "max": second_max,
  700. },
  701. "angleSeries": {
  702. "color": "#d59b2b",
  703. "data": angle_data,
  704. },
  705. "volumeSeries": {
  706. "color": "#4d9e6f",
  707. "data": volume_data,
  708. "info": volume_info,
  709. },
  710. "cycles": cycles,
  711. "triggerXs": sorted(set(triggers)),
  712. "files": files,
  713. "diagnostics": diagnostics,
  714. }
  715. @staticmethod
  716. def _build_volume_vector(
  717. sample_count: int,
  718. cycles: list[DetectedCycle],
  719. point_name: str,
  720. ) -> tuple[np.ndarray, dict[str, Any] | None]:
  721. volume = np.full(sample_count, np.nan, dtype=float)
  722. cylinder_name = next(
  723. (name for name in CYLINDER_BORE_MM if name in point_name),
  724. None,
  725. )
  726. if cylinder_name is None or not cycles:
  727. return volume, None
  728. bore_mm = CYLINDER_BORE_MM[cylinder_name]
  729. clearance = CLEARANCE_VOLUME_L_BY_BORE[bore_mm]
  730. crank_radius = PISTON_STROKE_MM / 2.0
  731. piston_area = np.pi * (bore_mm / 2.0) ** 2
  732. for cycle in cycles:
  733. angle_rad = np.deg2rad(cycle.angle)
  734. travel = (
  735. crank_radius * (1.0 - np.cos(angle_rad))
  736. + CONNECTING_ROD_LENGTH_MM
  737. - np.sqrt(
  738. CONNECTING_ROD_LENGTH_MM**2
  739. - (crank_radius * np.sin(angle_rad)) ** 2,
  740. )
  741. )
  742. volume[cycle.start_offset : cycle.end_offset] = (
  743. clearance + piston_area * travel / 1_000_000.0
  744. )
  745. finite = volume[np.isfinite(volume)]
  746. return volume, {
  747. "cylinder": cylinder_name,
  748. "boreMm": bore_mm,
  749. "clearanceVolumeL": clearance,
  750. "minVolumeL": float(np.min(finite)) if len(finite) else None,
  751. "maxVolumeL": float(np.max(finite)) if len(finite) else None,
  752. }
  753. @staticmethod
  754. def _build_period_detail(
  755. metadata: dict[str, Any],
  756. samples: np.ndarray,
  757. period_number: int,
  758. ) -> dict[str, Any]:
  759. detected, diagnostics = detect_cycles(samples)
  760. cycle = next((item for item in detected if item.number == period_number), None)
  761. if cycle is None:
  762. raise ValueError(f"没有找到周期 {period_number}")
  763. angles360 = np.linspace(0.0, 359.0, 360)
  764. pressure = np.interp(angles360, cycle.angle, cycle.signal)
  765. display_angles = np.where(angles360 <= 180.0, angles360, 360.0 - angles360)
  766. point_name = str(metadata.get("point_name") or "")
  767. cylinder_name = next(
  768. (name for name in CYLINDER_BORE_MM if name in point_name),
  769. None,
  770. )
  771. volume: np.ndarray | None = None
  772. volume_info: dict[str, Any] | None = None
  773. if cylinder_name:
  774. bore_mm = CYLINDER_BORE_MM[cylinder_name]
  775. clearance_volume = CLEARANCE_VOLUME_L_BY_BORE[bore_mm]
  776. angle_rad = np.deg2rad(angles360)
  777. crank_radius = PISTON_STROKE_MM / 2.0
  778. piston_travel = (
  779. crank_radius * (1.0 - np.cos(angle_rad))
  780. + CONNECTING_ROD_LENGTH_MM
  781. - np.sqrt(
  782. CONNECTING_ROD_LENGTH_MM**2
  783. - (crank_radius * np.sin(angle_rad)) ** 2,
  784. )
  785. )
  786. piston_area = np.pi * (bore_mm / 2.0) ** 2
  787. volume = clearance_volume + piston_area * piston_travel / 1_000_000.0
  788. volume_info = {
  789. "cylinder": cylinder_name,
  790. "boreMm": bore_mm,
  791. "clearanceVolumeL": clearance_volume,
  792. "minVolumeL": float(np.min(volume)),
  793. "maxVolumeL": float(np.max(volume)),
  794. }
  795. start_index = int(samples[cycle.start_offset, 0])
  796. end_offset = min(cycle.end_offset, len(samples) - 1)
  797. end_index = int(samples[max(cycle.end_offset - 1, cycle.start_offset), 0])
  798. return {
  799. "waveFile": {
  800. "id": int(metadata["id"]),
  801. "pointName": point_name,
  802. "measurementType": metadata.get("measurement_type"),
  803. "sampleTime": _time_string(metadata.get("sample_time")),
  804. "sampleFrequencyHz": int(metadata.get("sample_frequency_hz") or 0),
  805. "sampleCount": int(metadata.get("sample_count") or len(samples)),
  806. },
  807. "period": {
  808. "periodNo": cycle.number,
  809. "startSampleIndex": start_index,
  810. "endSampleIndex": end_index,
  811. "sampleCount": int(cycle.end_offset - cycle.start_offset),
  812. "triggerSampleIndices": [
  813. int(samples[offset, 0])
  814. for offset in cycle.trigger_offsets
  815. if 0 <= offset < len(samples)
  816. ],
  817. },
  818. "angles": display_angles.tolist(),
  819. "angles360": angles360.tolist(),
  820. "pressure": pressure.tolist(),
  821. "volume": volume.tolist() if volume is not None else None,
  822. "volumeInfo": volume_info,
  823. "phases": [
  824. {
  825. "name": name,
  826. "color": color,
  827. "start": start,
  828. "end": end,
  829. }
  830. for name, color, start, end in PHASES
  831. ],
  832. "diagnostics": diagnostics,
  833. }
  834. @staticmethod
  835. def _load_for_window(
  836. loader: Callable[..., tuple[dict[str, Any], np.ndarray]],
  837. file_id: int,
  838. measurement_type: str,
  839. point_name: str,
  840. sample_time: str,
  841. load_cache: dict[int, tuple[dict[str, Any], np.ndarray]],
  842. ) -> tuple[dict[str, Any], np.ndarray]:
  843. if file_id not in load_cache:
  844. if loader.__name__ == "_load_demo_wave":
  845. load_cache[file_id] = loader(file_id, measurement_type, point_name, sample_time)
  846. else:
  847. load_cache[file_id] = loader(file_id)
  848. return load_cache[file_id]
  849. def _load_db_wave(self, file_id: int) -> tuple[dict[str, Any], np.ndarray]:
  850. with get_connection() as connection:
  851. with connection.cursor() as cursor:
  852. cursor.execute(
  853. """
  854. SELECT id, point_name, measurement_type, sample_frequency_hz,
  855. sample_count, sample_time
  856. FROM wave_file
  857. WHERE id = %s
  858. """,
  859. (file_id,),
  860. )
  861. metadata = cursor.fetchone()
  862. if metadata is None:
  863. raise ValueError(f"wave_file.id={file_id} 不存在")
  864. cursor.execute(
  865. """
  866. SELECT sample_index, signal_value, second_value
  867. FROM wave_sample
  868. WHERE wave_file_id = %s
  869. ORDER BY sample_index ASC
  870. """,
  871. (file_id,),
  872. )
  873. rows = cursor.fetchall()
  874. if not rows:
  875. raise ValueError(f"wave_file.id={file_id} 没有采样数据")
  876. samples = np.asarray(
  877. [
  878. (
  879. float(row["sample_index"]),
  880. float(row["signal_value"]),
  881. float(row["second_value"]) if row["second_value"] is not None else np.nan,
  882. )
  883. for row in rows
  884. ],
  885. dtype=float,
  886. )
  887. return metadata, samples
  888. @staticmethod
  889. @lru_cache(maxsize=24)
  890. def _demo_samples(file_id: int, measurement_type: str) -> np.ndarray:
  891. count = DEMO_SAMPLE_COUNT
  892. index = np.arange(count, dtype=float)
  893. revolution = DEMO_REVOLUTION_SAMPLES
  894. phase = (index % revolution) / revolution * 2 * np.pi
  895. second = np.zeros(count, dtype=float)
  896. for revolution_start in range(0, count, revolution):
  897. for pulse in range(PULSES_PER_REVOLUTION):
  898. pulse_start = revolution_start + int(round(pulse * revolution / PULSES_PER_REVOLUTION))
  899. width = 22 if pulse == 0 else 8
  900. pulse_end = min(count, pulse_start + width)
  901. second[pulse_start:pulse_end] = 40.0
  902. variation = (file_id % 17) / 17.0
  903. if measurement_type == "压力":
  904. signal = (
  905. 4.2
  906. + 1.8 * np.sin(phase - 0.4)
  907. + 0.55 * np.sin(2 * phase + variation)
  908. + 0.22 * np.sin(7 * phase)
  909. )
  910. signal += 0.2 * np.maximum(np.sin(phase - 0.2), 0) ** 5
  911. elif measurement_type == "位移":
  912. signal = 0.5 + 0.18 * np.cos(phase) + 0.035 * np.sin(3 * phase + variation)
  913. else:
  914. signal = 0.15 * np.sin(phase * 2 + variation) + 0.04 * np.sin(11 * phase)
  915. signal += 0.018 * np.cos(index / 37.0)
  916. return np.column_stack((index, signal, second))
  917. def _load_demo_wave(
  918. self,
  919. file_id: int,
  920. measurement_type: str,
  921. point_name: str,
  922. sample_time: str,
  923. ) -> tuple[dict[str, Any], np.ndarray]:
  924. samples = self._demo_samples(file_id, measurement_type)
  925. metadata = {
  926. "id": file_id,
  927. "point_name": point_name,
  928. "measurement_type": measurement_type,
  929. "sample_frequency_hz": 25600,
  930. "sample_count": len(samples),
  931. "sample_time": sample_time,
  932. }
  933. return metadata, samples
  934. @staticmethod
  935. def _demo_options() -> list[dict[str, Any]]:
  936. end = DEMO_START + timedelta(minutes=5 * (DEMO_POINT_COUNT - 1))
  937. return [
  938. {
  939. "pointName": DEMO_POINT_NAME,
  940. "measurementType": measurement_type,
  941. "minTime": _time_string(DEMO_START),
  942. "maxTime": _time_string(end),
  943. "fileCount": DEMO_POINT_COUNT,
  944. }
  945. for measurement_type in MEASUREMENT_TYPES
  946. ]
  947. @staticmethod
  948. def _demo_time_points(
  949. point_name: str,
  950. types: list[str],
  951. start: datetime | None,
  952. end: datetime | None,
  953. ) -> list[dict[str, Any]]:
  954. points = []
  955. for index in range(DEMO_POINT_COUNT):
  956. timestamp = DEMO_START + timedelta(minutes=5 * index)
  957. if start and timestamp < start:
  958. continue
  959. if end and timestamp > end:
  960. continue
  961. files = {
  962. measurement_type: {
  963. "id": DEMO_ID_BY_TYPE[measurement_type] + index,
  964. "sampleCount": DEMO_SAMPLE_COUNT,
  965. "sampleFrequencyHz": 25600,
  966. "rpm": 998.0,
  967. }
  968. for measurement_type in types
  969. }
  970. points.append(
  971. {
  972. "index": len(points),
  973. "sampleTime": _time_string(timestamp),
  974. "files": files,
  975. },
  976. )
  977. return points
  978. data_service = DataService()