data_service.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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. "pointName": str(metadata.get("point_name") or point_name),
  668. "rpm": float(metadata.get("rpm") or 0),
  669. "fileName": str(metadata.get("file_name") or ""),
  670. },
  671. )
  672. # Keep at most the current time point's raw arrays resident. The
  673. # response retains only downsampled values and period metadata.
  674. load_cache.clear()
  675. for measurement_type in series_data:
  676. series_data[measurement_type].sort(key=lambda item: item["x"])
  677. second_series_data.sort(key=lambda item: item["x"])
  678. angle_data.sort(key=lambda item: item["x"])
  679. volume_data.sort(key=lambda item: item["x"])
  680. return {
  681. "pointName": point_name,
  682. "measurementTypes": types,
  683. "points": points,
  684. "xMin": 0,
  685. "xMax": len(points),
  686. "series": [
  687. {
  688. "measurementType": measurement_type,
  689. "color": MEASUREMENT_COLORS[measurement_type],
  690. "data": series_data[measurement_type],
  691. }
  692. for measurement_type in types
  693. ],
  694. "secondSeries": {
  695. "name": "周期数据",
  696. "color": "#f56c6c",
  697. "sourceMeasurementType": source_type,
  698. "data": second_series_data,
  699. "finiteCount": second_finite_count,
  700. "nonZeroCount": second_non_zero_count,
  701. "min": second_min,
  702. "max": second_max,
  703. },
  704. "angleSeries": {
  705. "color": "#d59b2b",
  706. "data": angle_data,
  707. },
  708. "volumeSeries": {
  709. "color": "#4d9e6f",
  710. "data": volume_data,
  711. "info": volume_info,
  712. },
  713. "cycles": cycles,
  714. "triggerXs": sorted(set(triggers)),
  715. "files": files,
  716. "diagnostics": diagnostics,
  717. }
  718. @staticmethod
  719. def _build_volume_vector(
  720. sample_count: int,
  721. cycles: list[DetectedCycle],
  722. point_name: str,
  723. ) -> tuple[np.ndarray, dict[str, Any] | None]:
  724. volume = np.full(sample_count, np.nan, dtype=float)
  725. cylinder_name = next(
  726. (name for name in CYLINDER_BORE_MM if name in point_name),
  727. None,
  728. )
  729. if cylinder_name is None or not cycles:
  730. return volume, None
  731. bore_mm = CYLINDER_BORE_MM[cylinder_name]
  732. clearance = CLEARANCE_VOLUME_L_BY_BORE[bore_mm]
  733. crank_radius = PISTON_STROKE_MM / 2.0
  734. piston_area = np.pi * (bore_mm / 2.0) ** 2
  735. for cycle in cycles:
  736. angle_rad = np.deg2rad(cycle.angle)
  737. travel = (
  738. crank_radius * (1.0 - np.cos(angle_rad))
  739. + CONNECTING_ROD_LENGTH_MM
  740. - np.sqrt(
  741. CONNECTING_ROD_LENGTH_MM**2
  742. - (crank_radius * np.sin(angle_rad)) ** 2,
  743. )
  744. )
  745. volume[cycle.start_offset : cycle.end_offset] = (
  746. clearance + piston_area * travel / 1_000_000.0
  747. )
  748. finite = volume[np.isfinite(volume)]
  749. return volume, {
  750. "cylinder": cylinder_name,
  751. "boreMm": bore_mm,
  752. "clearanceVolumeL": clearance,
  753. "minVolumeL": float(np.min(finite)) if len(finite) else None,
  754. "maxVolumeL": float(np.max(finite)) if len(finite) else None,
  755. }
  756. @staticmethod
  757. def _build_period_detail(
  758. metadata: dict[str, Any],
  759. samples: np.ndarray,
  760. period_number: int,
  761. ) -> dict[str, Any]:
  762. detected, diagnostics = detect_cycles(samples)
  763. cycle = next((item for item in detected if item.number == period_number), None)
  764. if cycle is None:
  765. raise ValueError(f"没有找到周期 {period_number}")
  766. angles360 = np.linspace(0.0, 359.0, 360)
  767. pressure = np.interp(angles360, cycle.angle, cycle.signal)
  768. display_angles = np.where(angles360 <= 180.0, angles360, 360.0 - angles360)
  769. point_name = str(metadata.get("point_name") or "")
  770. cylinder_name = next(
  771. (name for name in CYLINDER_BORE_MM if name in point_name),
  772. None,
  773. )
  774. volume: np.ndarray | None = None
  775. volume_info: dict[str, Any] | None = None
  776. if cylinder_name:
  777. bore_mm = CYLINDER_BORE_MM[cylinder_name]
  778. clearance_volume = CLEARANCE_VOLUME_L_BY_BORE[bore_mm]
  779. angle_rad = np.deg2rad(angles360)
  780. crank_radius = PISTON_STROKE_MM / 2.0
  781. piston_travel = (
  782. crank_radius * (1.0 - np.cos(angle_rad))
  783. + CONNECTING_ROD_LENGTH_MM
  784. - np.sqrt(
  785. CONNECTING_ROD_LENGTH_MM**2
  786. - (crank_radius * np.sin(angle_rad)) ** 2,
  787. )
  788. )
  789. piston_area = np.pi * (bore_mm / 2.0) ** 2
  790. volume = clearance_volume + piston_area * piston_travel / 1_000_000.0
  791. volume_info = {
  792. "cylinder": cylinder_name,
  793. "boreMm": bore_mm,
  794. "clearanceVolumeL": clearance_volume,
  795. "minVolumeL": float(np.min(volume)),
  796. "maxVolumeL": float(np.max(volume)),
  797. }
  798. start_index = int(samples[cycle.start_offset, 0])
  799. end_offset = min(cycle.end_offset, len(samples) - 1)
  800. end_index = int(samples[max(cycle.end_offset - 1, cycle.start_offset), 0])
  801. return {
  802. "waveFile": {
  803. "id": int(metadata["id"]),
  804. "pointName": point_name,
  805. "measurementType": metadata.get("measurement_type"),
  806. "sampleTime": _time_string(metadata.get("sample_time")),
  807. "sampleFrequencyHz": int(metadata.get("sample_frequency_hz") or 0),
  808. "sampleCount": int(metadata.get("sample_count") or len(samples)),
  809. },
  810. "period": {
  811. "periodNo": cycle.number,
  812. "startSampleIndex": start_index,
  813. "endSampleIndex": end_index,
  814. "sampleCount": int(cycle.end_offset - cycle.start_offset),
  815. "triggerSampleIndices": [
  816. int(samples[offset, 0])
  817. for offset in cycle.trigger_offsets
  818. if 0 <= offset < len(samples)
  819. ],
  820. },
  821. "angles": display_angles.tolist(),
  822. "angles360": angles360.tolist(),
  823. "pressure": pressure.tolist(),
  824. "volume": volume.tolist() if volume is not None else None,
  825. "volumeInfo": volume_info,
  826. "phases": [
  827. {
  828. "name": name,
  829. "color": color,
  830. "start": start,
  831. "end": end,
  832. }
  833. for name, color, start, end in PHASES
  834. ],
  835. "diagnostics": diagnostics,
  836. }
  837. @staticmethod
  838. def _load_for_window(
  839. loader: Callable[..., tuple[dict[str, Any], np.ndarray]],
  840. file_id: int,
  841. measurement_type: str,
  842. point_name: str,
  843. sample_time: str,
  844. load_cache: dict[int, tuple[dict[str, Any], np.ndarray]],
  845. ) -> tuple[dict[str, Any], np.ndarray]:
  846. if file_id not in load_cache:
  847. if loader.__name__ == "_load_demo_wave":
  848. load_cache[file_id] = loader(file_id, measurement_type, point_name, sample_time)
  849. else:
  850. load_cache[file_id] = loader(file_id)
  851. return load_cache[file_id]
  852. def _load_db_wave(self, file_id: int) -> tuple[dict[str, Any], np.ndarray]:
  853. with get_connection() as connection:
  854. with connection.cursor() as cursor:
  855. cursor.execute(
  856. """
  857. SELECT id, point_name, measurement_type, sample_frequency_hz,
  858. sample_count, sample_time, rpm, file_name
  859. FROM wave_file
  860. WHERE id = %s
  861. """,
  862. (file_id,),
  863. )
  864. metadata = cursor.fetchone()
  865. if metadata is None:
  866. raise ValueError(f"wave_file.id={file_id} 不存在")
  867. cursor.execute(
  868. """
  869. SELECT sample_index, signal_value, second_value
  870. FROM wave_sample
  871. WHERE wave_file_id = %s
  872. ORDER BY sample_index ASC
  873. """,
  874. (file_id,),
  875. )
  876. rows = cursor.fetchall()
  877. if not rows:
  878. raise ValueError(f"wave_file.id={file_id} 没有采样数据")
  879. samples = np.asarray(
  880. [
  881. (
  882. float(row["sample_index"]),
  883. float(row["signal_value"]),
  884. float(row["second_value"]) if row["second_value"] is not None else np.nan,
  885. )
  886. for row in rows
  887. ],
  888. dtype=float,
  889. )
  890. return metadata, samples
  891. @staticmethod
  892. @lru_cache(maxsize=24)
  893. def _demo_samples(file_id: int, measurement_type: str) -> np.ndarray:
  894. count = DEMO_SAMPLE_COUNT
  895. index = np.arange(count, dtype=float)
  896. revolution = DEMO_REVOLUTION_SAMPLES
  897. phase = (index % revolution) / revolution * 2 * np.pi
  898. second = np.zeros(count, dtype=float)
  899. for revolution_start in range(0, count, revolution):
  900. for pulse in range(PULSES_PER_REVOLUTION):
  901. pulse_start = revolution_start + int(round(pulse * revolution / PULSES_PER_REVOLUTION))
  902. width = 22 if pulse == 0 else 8
  903. pulse_end = min(count, pulse_start + width)
  904. second[pulse_start:pulse_end] = 40.0
  905. variation = (file_id % 17) / 17.0
  906. if measurement_type == "压力":
  907. signal = (
  908. 4.2
  909. + 1.8 * np.sin(phase - 0.4)
  910. + 0.55 * np.sin(2 * phase + variation)
  911. + 0.22 * np.sin(7 * phase)
  912. )
  913. signal += 0.2 * np.maximum(np.sin(phase - 0.2), 0) ** 5
  914. elif measurement_type == "位移":
  915. signal = 0.5 + 0.18 * np.cos(phase) + 0.035 * np.sin(3 * phase + variation)
  916. else:
  917. signal = 0.15 * np.sin(phase * 2 + variation) + 0.04 * np.sin(11 * phase)
  918. signal += 0.018 * np.cos(index / 37.0)
  919. return np.column_stack((index, signal, second))
  920. def _load_demo_wave(
  921. self,
  922. file_id: int,
  923. measurement_type: str,
  924. point_name: str,
  925. sample_time: str,
  926. ) -> tuple[dict[str, Any], np.ndarray]:
  927. samples = self._demo_samples(file_id, measurement_type)
  928. metadata = {
  929. "id": file_id,
  930. "point_name": point_name,
  931. "measurement_type": measurement_type,
  932. "sample_frequency_hz": 25600,
  933. "sample_count": len(samples),
  934. "sample_time": sample_time,
  935. "rpm": 998.0,
  936. "file_name": f"demo-{file_id}.dat",
  937. }
  938. return metadata, samples
  939. @staticmethod
  940. def _demo_options() -> list[dict[str, Any]]:
  941. end = DEMO_START + timedelta(minutes=5 * (DEMO_POINT_COUNT - 1))
  942. return [
  943. {
  944. "pointName": DEMO_POINT_NAME,
  945. "measurementType": measurement_type,
  946. "minTime": _time_string(DEMO_START),
  947. "maxTime": _time_string(end),
  948. "fileCount": DEMO_POINT_COUNT,
  949. }
  950. for measurement_type in MEASUREMENT_TYPES
  951. ]
  952. @staticmethod
  953. def _demo_time_points(
  954. point_name: str,
  955. types: list[str],
  956. start: datetime | None,
  957. end: datetime | None,
  958. ) -> list[dict[str, Any]]:
  959. points = []
  960. for index in range(DEMO_POINT_COUNT):
  961. timestamp = DEMO_START + timedelta(minutes=5 * index)
  962. if start and timestamp < start:
  963. continue
  964. if end and timestamp > end:
  965. continue
  966. files = {
  967. measurement_type: {
  968. "id": DEMO_ID_BY_TYPE[measurement_type] + index,
  969. "sampleCount": DEMO_SAMPLE_COUNT,
  970. "sampleFrequencyHz": 25600,
  971. "rpm": 998.0,
  972. }
  973. for measurement_type in types
  974. }
  975. points.append(
  976. {
  977. "index": len(points),
  978. "sampleTime": _time_string(timestamp),
  979. "files": files,
  980. },
  981. )
  982. return points
  983. data_service = DataService()