data_service.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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. current_volume, current_volume_info = self._build_volume_vector(
  491. len(source_samples),
  492. detected,
  493. point_name,
  494. )
  495. if current_volume_info is not None:
  496. volume_info = current_volume_info
  497. sample_indices = source_samples[:, 0].astype(np.int64)
  498. sample_span = max(len(source_samples), 1)
  499. finite_second = source_samples[:, 2][np.isfinite(source_samples[:, 2])]
  500. if len(finite_second):
  501. second_finite_count += int(len(finite_second))
  502. second_non_zero_count += int(np.count_nonzero(finite_second != 0))
  503. current_min = float(np.min(finite_second))
  504. current_max = float(np.max(finite_second))
  505. second_min = current_min if second_min is None else min(second_min, current_min)
  506. second_max = current_max if second_max is None else max(second_max, current_max)
  507. required = {0, len(source_samples) - 1}
  508. for cycle in detected:
  509. required.update(
  510. {
  511. cycle.start_offset,
  512. max(cycle.end_offset - 1, cycle.start_offset),
  513. *cycle.trigger_offsets,
  514. },
  515. )
  516. start_x = slot + cycle.start_offset / sample_span
  517. end_x = slot + cycle.end_offset / sample_span
  518. start_sample_index = int(sample_indices[cycle.start_offset])
  519. end_sample_index = int(sample_indices[max(cycle.end_offset - 1, cycle.start_offset)])
  520. cycles.append(
  521. {
  522. "id": f"{source_id}:{cycle.number}",
  523. "waveFileId": source_id,
  524. "periodNo": cycle.number,
  525. "pointIndex": slot,
  526. "sampleTime": point["sampleTime"],
  527. "startX": start_x,
  528. "endX": end_x,
  529. "startSampleIndex": start_sample_index,
  530. "endSampleIndex": end_sample_index,
  531. "sourceType": source_measurement_type,
  532. },
  533. )
  534. for trigger_offset in sorted(required):
  535. if trigger_offset in required and any(
  536. trigger_offset == run_offset
  537. for cycle in detected
  538. for run_offset in cycle.trigger_offsets
  539. ):
  540. triggers.append(slot + trigger_offset / sample_span)
  541. diagnostics.append(
  542. {
  543. "waveFileId": source_id,
  544. "measurementType": source_measurement_type,
  545. "sampleTime": point["sampleTime"],
  546. **diagnostic,
  547. },
  548. )
  549. for measurement_type in types:
  550. file_info = point.get("files", {}).get(measurement_type)
  551. if not file_info:
  552. continue
  553. file_id = int(file_info["id"] if isinstance(file_info, dict) else file_info)
  554. if file_id == source_id:
  555. metadata, samples = source_metadata, source_samples
  556. else:
  557. try:
  558. metadata, samples = self._load_for_window(
  559. loader,
  560. file_id,
  561. measurement_type,
  562. point_name,
  563. point["sampleTime"],
  564. load_cache,
  565. )
  566. except ValueError:
  567. continue
  568. sample_count = len(samples)
  569. if not sample_count:
  570. continue
  571. sample_indices_for_file = samples[:, 0].astype(np.int64)
  572. file_base_index = int(sample_indices_for_file[0])
  573. file_span = max(sample_count, 1)
  574. file_required = {0, sample_count - 1}
  575. if file_id == source_id:
  576. file_required.update(required)
  577. if no_sampling:
  578. target_per_file = sample_count
  579. else:
  580. target_per_file = max(256, int(np.ceil(max_points / max(len(points), 1))))
  581. chosen = downsample_indices(samples[:, 1], target_per_file, file_required)
  582. for offset in chosen:
  583. x = slot + (int(sample_indices_for_file[offset]) - file_base_index) / file_span
  584. second = _safe_float(samples[offset, 2])
  585. raw_value = float(samples[offset, 1])
  586. series_data[measurement_type].append(
  587. {
  588. "value": [x, raw_value],
  589. "x": x,
  590. "rawValue": raw_value,
  591. "sampleIndex": int(sample_indices_for_file[offset]),
  592. "waveFileId": file_id,
  593. "sampleTime": point["sampleTime"],
  594. "secondValue": second,
  595. },
  596. )
  597. if file_id == source_id:
  598. second_chosen = downsample_indices(samples[:, 2], target_per_file, file_required)
  599. for offset in second_chosen:
  600. second_value = _safe_float(samples[offset, 2])
  601. if second_value is None:
  602. continue
  603. x = slot + (int(sample_indices_for_file[offset]) - file_base_index) / file_span
  604. second_series_data.append(
  605. {
  606. "value": [x, second_value],
  607. "x": x,
  608. "rawValue": second_value,
  609. "sampleIndex": int(sample_indices_for_file[offset]),
  610. "waveFileId": file_id,
  611. "sampleTime": point["sampleTime"],
  612. },
  613. )
  614. angle_chosen = downsample_indices(angle_vector, target_per_file, file_required)
  615. for offset in angle_chosen:
  616. value = _safe_float(angle_vector[offset])
  617. if value is None:
  618. continue
  619. x = slot + (int(sample_indices_for_file[offset]) - file_base_index) / file_span
  620. angle_data.append(
  621. {
  622. "value": [x, value],
  623. "x": x,
  624. "angle": value,
  625. "sampleIndex": int(sample_indices_for_file[offset]),
  626. "waveFileId": file_id,
  627. "sampleTime": point["sampleTime"],
  628. },
  629. )
  630. volume_chosen = downsample_indices(current_volume, target_per_file, file_required)
  631. for offset in volume_chosen:
  632. value = _safe_float(current_volume[offset])
  633. if value is None:
  634. continue
  635. x = slot + (int(sample_indices_for_file[offset]) - file_base_index) / file_span
  636. volume_data.append(
  637. {
  638. "value": [x, value],
  639. "x": x,
  640. "volume": value,
  641. "sampleIndex": int(sample_indices_for_file[offset]),
  642. "waveFileId": file_id,
  643. "sampleTime": point["sampleTime"],
  644. },
  645. )
  646. files.append(
  647. {
  648. "id": file_id,
  649. "pointIndex": slot,
  650. "sampleTime": point["sampleTime"],
  651. "measurementType": measurement_type,
  652. "sampleCount": int(metadata.get("sample_count") or sample_count),
  653. "sampleFrequencyHz": int(metadata.get("sample_frequency_hz") or 0),
  654. },
  655. )
  656. # Keep at most the current time point's raw arrays resident. The
  657. # response retains only downsampled values and period metadata.
  658. load_cache.clear()
  659. for measurement_type in series_data:
  660. series_data[measurement_type].sort(key=lambda item: item["x"])
  661. second_series_data.sort(key=lambda item: item["x"])
  662. angle_data.sort(key=lambda item: item["x"])
  663. volume_data.sort(key=lambda item: item["x"])
  664. return {
  665. "pointName": point_name,
  666. "measurementTypes": types,
  667. "points": points,
  668. "xMin": 0,
  669. "xMax": len(points),
  670. "series": [
  671. {
  672. "measurementType": measurement_type,
  673. "color": MEASUREMENT_COLORS[measurement_type],
  674. "data": series_data[measurement_type],
  675. }
  676. for measurement_type in types
  677. ],
  678. "secondSeries": {
  679. "name": "周期数据",
  680. "color": "#f56c6c",
  681. "sourceMeasurementType": source_type,
  682. "data": second_series_data,
  683. "finiteCount": second_finite_count,
  684. "nonZeroCount": second_non_zero_count,
  685. "min": second_min,
  686. "max": second_max,
  687. },
  688. "angleSeries": {
  689. "color": "#d59b2b",
  690. "data": angle_data,
  691. },
  692. "volumeSeries": {
  693. "color": "#4d9e6f",
  694. "data": volume_data,
  695. "info": volume_info,
  696. },
  697. "cycles": cycles,
  698. "triggerXs": sorted(set(triggers)),
  699. "files": files,
  700. "diagnostics": diagnostics,
  701. }
  702. @staticmethod
  703. def _build_volume_vector(
  704. sample_count: int,
  705. cycles: list[DetectedCycle],
  706. point_name: str,
  707. ) -> tuple[np.ndarray, dict[str, Any] | None]:
  708. volume = np.full(sample_count, np.nan, dtype=float)
  709. cylinder_name = next(
  710. (name for name in CYLINDER_BORE_MM if name in point_name),
  711. None,
  712. )
  713. if cylinder_name is None or not cycles:
  714. return volume, None
  715. bore_mm = CYLINDER_BORE_MM[cylinder_name]
  716. clearance = CLEARANCE_VOLUME_L_BY_BORE[bore_mm]
  717. crank_radius = PISTON_STROKE_MM / 2.0
  718. piston_area = np.pi * (bore_mm / 2.0) ** 2
  719. for cycle in cycles:
  720. angle_rad = np.deg2rad(cycle.angle)
  721. travel = (
  722. crank_radius * (1.0 - np.cos(angle_rad))
  723. + CONNECTING_ROD_LENGTH_MM
  724. - np.sqrt(
  725. CONNECTING_ROD_LENGTH_MM**2
  726. - (crank_radius * np.sin(angle_rad)) ** 2,
  727. )
  728. )
  729. volume[cycle.start_offset : cycle.end_offset] = (
  730. clearance + piston_area * travel / 1_000_000.0
  731. )
  732. finite = volume[np.isfinite(volume)]
  733. return volume, {
  734. "cylinder": cylinder_name,
  735. "boreMm": bore_mm,
  736. "clearanceVolumeL": clearance,
  737. "minVolumeL": float(np.min(finite)) if len(finite) else None,
  738. "maxVolumeL": float(np.max(finite)) if len(finite) else None,
  739. }
  740. @staticmethod
  741. def _build_period_detail(
  742. metadata: dict[str, Any],
  743. samples: np.ndarray,
  744. period_number: int,
  745. ) -> dict[str, Any]:
  746. detected, diagnostics = detect_cycles(samples)
  747. cycle = next((item for item in detected if item.number == period_number), None)
  748. if cycle is None:
  749. raise ValueError(f"没有找到周期 {period_number}")
  750. angles360 = np.linspace(0.0, 359.0, 360)
  751. pressure = np.interp(angles360, cycle.angle, cycle.signal)
  752. display_angles = np.where(angles360 <= 180.0, angles360, 360.0 - angles360)
  753. point_name = str(metadata.get("point_name") or "")
  754. cylinder_name = next(
  755. (name for name in CYLINDER_BORE_MM if name in point_name),
  756. None,
  757. )
  758. volume: np.ndarray | None = None
  759. volume_info: dict[str, Any] | None = None
  760. if cylinder_name:
  761. bore_mm = CYLINDER_BORE_MM[cylinder_name]
  762. clearance_volume = CLEARANCE_VOLUME_L_BY_BORE[bore_mm]
  763. angle_rad = np.deg2rad(angles360)
  764. crank_radius = PISTON_STROKE_MM / 2.0
  765. piston_travel = (
  766. crank_radius * (1.0 - np.cos(angle_rad))
  767. + CONNECTING_ROD_LENGTH_MM
  768. - np.sqrt(
  769. CONNECTING_ROD_LENGTH_MM**2
  770. - (crank_radius * np.sin(angle_rad)) ** 2,
  771. )
  772. )
  773. piston_area = np.pi * (bore_mm / 2.0) ** 2
  774. volume = clearance_volume + piston_area * piston_travel / 1_000_000.0
  775. volume_info = {
  776. "cylinder": cylinder_name,
  777. "boreMm": bore_mm,
  778. "clearanceVolumeL": clearance_volume,
  779. "minVolumeL": float(np.min(volume)),
  780. "maxVolumeL": float(np.max(volume)),
  781. }
  782. start_index = int(samples[cycle.start_offset, 0])
  783. end_offset = min(cycle.end_offset, len(samples) - 1)
  784. end_index = int(samples[max(cycle.end_offset - 1, cycle.start_offset), 0])
  785. return {
  786. "waveFile": {
  787. "id": int(metadata["id"]),
  788. "pointName": point_name,
  789. "measurementType": metadata.get("measurement_type"),
  790. "sampleTime": _time_string(metadata.get("sample_time")),
  791. "sampleFrequencyHz": int(metadata.get("sample_frequency_hz") or 0),
  792. "sampleCount": int(metadata.get("sample_count") or len(samples)),
  793. },
  794. "period": {
  795. "periodNo": cycle.number,
  796. "startSampleIndex": start_index,
  797. "endSampleIndex": end_index,
  798. "sampleCount": int(cycle.end_offset - cycle.start_offset),
  799. "triggerSampleIndices": [
  800. int(samples[offset, 0])
  801. for offset in cycle.trigger_offsets
  802. if 0 <= offset < len(samples)
  803. ],
  804. },
  805. "angles": display_angles.tolist(),
  806. "angles360": angles360.tolist(),
  807. "pressure": pressure.tolist(),
  808. "volume": volume.tolist() if volume is not None else None,
  809. "volumeInfo": volume_info,
  810. "phases": [
  811. {
  812. "name": name,
  813. "color": color,
  814. "start": start,
  815. "end": end,
  816. }
  817. for name, color, start, end in PHASES
  818. ],
  819. "diagnostics": diagnostics,
  820. }
  821. @staticmethod
  822. def _load_for_window(
  823. loader: Callable[..., tuple[dict[str, Any], np.ndarray]],
  824. file_id: int,
  825. measurement_type: str,
  826. point_name: str,
  827. sample_time: str,
  828. load_cache: dict[int, tuple[dict[str, Any], np.ndarray]],
  829. ) -> tuple[dict[str, Any], np.ndarray]:
  830. if file_id not in load_cache:
  831. if loader.__name__ == "_load_demo_wave":
  832. load_cache[file_id] = loader(file_id, measurement_type, point_name, sample_time)
  833. else:
  834. load_cache[file_id] = loader(file_id)
  835. return load_cache[file_id]
  836. def _load_db_wave(self, file_id: int) -> tuple[dict[str, Any], np.ndarray]:
  837. with get_connection() as connection:
  838. with connection.cursor() as cursor:
  839. cursor.execute(
  840. """
  841. SELECT id, point_name, measurement_type, sample_frequency_hz,
  842. sample_count, sample_time
  843. FROM wave_file
  844. WHERE id = %s
  845. """,
  846. (file_id,),
  847. )
  848. metadata = cursor.fetchone()
  849. if metadata is None:
  850. raise ValueError(f"wave_file.id={file_id} 不存在")
  851. cursor.execute(
  852. """
  853. SELECT sample_index, signal_value, second_value
  854. FROM wave_sample
  855. WHERE wave_file_id = %s
  856. ORDER BY sample_index ASC
  857. """,
  858. (file_id,),
  859. )
  860. rows = cursor.fetchall()
  861. if not rows:
  862. raise ValueError(f"wave_file.id={file_id} 没有采样数据")
  863. samples = np.asarray(
  864. [
  865. (
  866. float(row["sample_index"]),
  867. float(row["signal_value"]),
  868. float(row["second_value"]) if row["second_value"] is not None else np.nan,
  869. )
  870. for row in rows
  871. ],
  872. dtype=float,
  873. )
  874. return metadata, samples
  875. @staticmethod
  876. @lru_cache(maxsize=24)
  877. def _demo_samples(file_id: int, measurement_type: str) -> np.ndarray:
  878. count = DEMO_SAMPLE_COUNT
  879. index = np.arange(count, dtype=float)
  880. revolution = DEMO_REVOLUTION_SAMPLES
  881. phase = (index % revolution) / revolution * 2 * np.pi
  882. second = np.zeros(count, dtype=float)
  883. for revolution_start in range(0, count, revolution):
  884. for pulse in range(PULSES_PER_REVOLUTION):
  885. pulse_start = revolution_start + int(round(pulse * revolution / PULSES_PER_REVOLUTION))
  886. width = 22 if pulse == 0 else 8
  887. pulse_end = min(count, pulse_start + width)
  888. second[pulse_start:pulse_end] = 40.0
  889. variation = (file_id % 17) / 17.0
  890. if measurement_type == "压力":
  891. signal = (
  892. 4.2
  893. + 1.8 * np.sin(phase - 0.4)
  894. + 0.55 * np.sin(2 * phase + variation)
  895. + 0.22 * np.sin(7 * phase)
  896. )
  897. signal += 0.2 * np.maximum(np.sin(phase - 0.2), 0) ** 5
  898. elif measurement_type == "位移":
  899. signal = 0.5 + 0.18 * np.cos(phase) + 0.035 * np.sin(3 * phase + variation)
  900. else:
  901. signal = 0.15 * np.sin(phase * 2 + variation) + 0.04 * np.sin(11 * phase)
  902. signal += 0.018 * np.cos(index / 37.0)
  903. return np.column_stack((index, signal, second))
  904. def _load_demo_wave(
  905. self,
  906. file_id: int,
  907. measurement_type: str,
  908. point_name: str,
  909. sample_time: str,
  910. ) -> tuple[dict[str, Any], np.ndarray]:
  911. samples = self._demo_samples(file_id, measurement_type)
  912. metadata = {
  913. "id": file_id,
  914. "point_name": point_name,
  915. "measurement_type": measurement_type,
  916. "sample_frequency_hz": 25600,
  917. "sample_count": len(samples),
  918. "sample_time": sample_time,
  919. }
  920. return metadata, samples
  921. @staticmethod
  922. def _demo_options() -> list[dict[str, Any]]:
  923. end = DEMO_START + timedelta(minutes=5 * (DEMO_POINT_COUNT - 1))
  924. return [
  925. {
  926. "pointName": DEMO_POINT_NAME,
  927. "measurementType": measurement_type,
  928. "minTime": _time_string(DEMO_START),
  929. "maxTime": _time_string(end),
  930. "fileCount": DEMO_POINT_COUNT,
  931. }
  932. for measurement_type in MEASUREMENT_TYPES
  933. ]
  934. @staticmethod
  935. def _demo_time_points(
  936. point_name: str,
  937. types: list[str],
  938. start: datetime | None,
  939. end: datetime | None,
  940. ) -> list[dict[str, Any]]:
  941. points = []
  942. for index in range(DEMO_POINT_COUNT):
  943. timestamp = DEMO_START + timedelta(minutes=5 * index)
  944. if start and timestamp < start:
  945. continue
  946. if end and timestamp > end:
  947. continue
  948. files = {
  949. measurement_type: {
  950. "id": DEMO_ID_BY_TYPE[measurement_type] + index,
  951. "sampleCount": DEMO_SAMPLE_COUNT,
  952. "sampleFrequencyHz": 25600,
  953. "rpm": 998.0,
  954. }
  955. for measurement_type in types
  956. }
  957. points.append(
  958. {
  959. "index": len(points),
  960. "sampleTime": _time_string(timestamp),
  961. "files": files,
  962. },
  963. )
  964. return points
  965. data_service = DataService()