detect_cycle_index.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. """Backfill the first detected cycle's sample_index range into wave_file.
  2. The original full re-run encoded the first complete cycle of every file but
  3. never wrote back where that cycle starts and ends. This script re-detects the
  4. first complete cycle for every pressure file (rpm > 0) and records the real
  5. ``sample_index`` bounds into two columns:
  6. * ``cycle_start`` / ``cycle_end`` >= 0 : first complete cycle, half-open
  7. ``[cycle_start, cycle_end)`` in actual sample_index values;
  8. * ``-1`` : no complete cycle found (matches the
  9. ``tspluse_status = -1`` convention);
  10. * ``NULL`` : not yet processed.
  11. It reuses predict.py's adaptive multi-stage batch reading (STAGE_LIMITS =
  12. 3500 -> 7000 -> 14000, parallel reader connections, tuple watermark) but needs
  13. no model: only the trigger channel is used, so it runs on CPU only. The fetch
  14. also keeps the real ``sample_index`` per row because ``detect_cycles`` returns
  15. array offsets, which differ from database indices for sparse columns.
  16. Only rows still holding ``cycle_start IS NULL`` are selected, so the
  17. ``(sample_time, id)`` watermark is naturally idempotent: a file already
  18. written (0/-1) is never re-selected on resume. Writes are flushed in one
  19. ``CASE id`` UPDATE per ``--write-batch`` rows.
  20. Usage:
  21. conda activate tspulse
  22. python detect_cycle_index.py [--start-time ""] [--start-id 0]
  23. [--batch 100] [--read-workers 4] [--limit 0]
  24. [--report-every 100] [--write-batch 100]
  25. [--dry-run]
  26. """
  27. import argparse
  28. import sys
  29. from concurrent.futures import ThreadPoolExecutor
  30. from pathlib import Path
  31. import numpy as np
  32. BACKEND = Path(__file__).resolve().parents[1]
  33. sys.path.insert(0, str(BACKEND))
  34. from app.algorithms.cycles import detect_cycles # noqa: E402
  35. import predict # noqa: E402
  36. from predict import MEASUREMENT_TYPE, STAGE_LIMITS # noqa: E402
  37. def _fetch_chunk(connection, file_ids: list[int], limit: int) -> dict[int, np.ndarray]:
  38. """Fetch the first ``limit`` rows of a chunk of files in one query.
  39. Returns {file_id: (n, 4) array} with columns
  40. [array_offset(0..n-1), signal_value, second_value, sample_index].
  41. """
  42. if not file_ids:
  43. return {}
  44. placeholders = ",".join(["%s"] * len(file_ids))
  45. with connection.cursor() as cursor:
  46. cursor.execute(
  47. f"""
  48. SELECT wave_file_id,
  49. CAST(signal_value AS FLOAT) AS sig,
  50. CAST(second_value AS FLOAT) AS sec,
  51. sample_index
  52. FROM wave_sample
  53. WHERE wave_file_id IN ({placeholders}) AND sample_index < %s
  54. ORDER BY wave_file_id, sample_index
  55. """,
  56. (*file_ids, limit),
  57. )
  58. rows = cursor.fetchall()
  59. grouped: dict[int, tuple[list[float], list[float], list[int]]] = {}
  60. for row in rows:
  61. signal, second, index = grouped.setdefault(row["wave_file_id"], ([], [], []))
  62. signal.append(float(row["sig"]))
  63. second.append(float(row["sec"]) if row["sec"] is not None else np.nan)
  64. index.append(int(row["sample_index"]))
  65. out: dict[int, np.ndarray] = {}
  66. for file_id, (signal, second, index) in grouped.items():
  67. count = len(signal)
  68. out[file_id] = np.column_stack(
  69. [
  70. np.arange(count, dtype=float),
  71. np.asarray(signal),
  72. np.asarray(second),
  73. np.asarray(index, dtype=float),
  74. ]
  75. )
  76. return out
  77. def read_batch_samples(
  78. reader_connections: list,
  79. file_ids: list[int],
  80. workers: int,
  81. limit: int,
  82. ) -> dict[int, np.ndarray]:
  83. """Fetch the first ``limit`` rows of every file in one round-trip."""
  84. if not file_ids:
  85. return {}
  86. if workers <= 1 or len(file_ids) <= workers:
  87. return _fetch_chunk(reader_connections[0], file_ids, limit)
  88. chunks = np.array_split(file_ids, min(workers, len(file_ids)))
  89. with ThreadPoolExecutor(max_workers=len(chunks)) as executor:
  90. futures = [
  91. executor.submit(_fetch_chunk, reader_connections[i], chunk.tolist(), limit)
  92. for i, chunk in enumerate(chunks)
  93. ]
  94. merged: dict[int, np.ndarray] = {}
  95. for future in futures:
  96. merged.update(future.result())
  97. return merged
  98. def first_cycle_bounds(samples: np.ndarray) -> tuple[int, int] | None:
  99. """Return ``(cycle_start, cycle_end)`` in real sample_index, half-open."""
  100. cycles, _ = detect_cycles(samples)
  101. if not cycles:
  102. return None
  103. cycle = cycles[0]
  104. return (int(samples[cycle.start_offset, 3]), int(samples[cycle.end_offset, 3]))
  105. def resolve_batch_bounds(
  106. rows: list[dict],
  107. reader_connections: list,
  108. workers: int,
  109. first_stage: int = 0,
  110. ) -> tuple[dict[int, tuple[int, int] | None], int]:
  111. """Adaptively detect the first cycle per file, escalating window sizes.
  112. Returns (``{file_id: (start, end) | None}``, error_count). None means no
  113. complete cycle was found at any window (-> -1).
  114. """
  115. errors = 0
  116. resolved: dict[int, tuple[int, int] | None] = {}
  117. stage_files: dict[int, dict] = {int(row["id"]): row for row in rows}
  118. for stage in range(first_stage, len(STAGE_LIMITS)):
  119. if not stage_files:
  120. break
  121. limit = STAGE_LIMITS[stage]
  122. samples_map = read_batch_samples(reader_connections, list(stage_files), workers, limit)
  123. next_pending: dict[int, dict] = {}
  124. for file_id, row in stage_files.items():
  125. samples = samples_map.get(file_id)
  126. if samples is None or len(samples) == 0:
  127. resolved[file_id] = None
  128. continue
  129. try:
  130. bounds = first_cycle_bounds(samples)
  131. except Exception:
  132. errors += 1
  133. resolved[file_id] = None
  134. continue
  135. if bounds is None and int(row.get("sample_count") or 0) > limit:
  136. next_pending[file_id] = row
  137. else:
  138. resolved[file_id] = bounds
  139. stage_files = next_pending
  140. for file_id in stage_files:
  141. resolved[file_id] = None
  142. return resolved, errors
  143. def flush_bounds(connection, buffer: list[tuple[int, int, int]]) -> None:
  144. """Write pending (file_id, cycle_start, cycle_end) rows in one UPDATE."""
  145. if not buffer:
  146. return
  147. case_start = " ".join("WHEN %s THEN %s" for _ in buffer)
  148. case_end = " ".join("WHEN %s THEN %s" for _ in buffer)
  149. placeholders = ",".join(["%s"] * len(buffer))
  150. params_start: list[int] = []
  151. params_end: list[int] = []
  152. for file_id, start, end in buffer:
  153. params_start.extend([file_id, start])
  154. params_end.extend([file_id, end])
  155. with connection.cursor() as cursor:
  156. cursor.execute(
  157. f"UPDATE wave_file SET cycle_start = CASE id {case_start} END, "
  158. f"cycle_end = CASE id {case_end} END "
  159. f"WHERE id IN ({placeholders})",
  160. tuple(params_start + params_end + [file_id for file_id, _, _ in buffer]),
  161. )
  162. buffer.clear()
  163. def fetch_batch(
  164. connection,
  165. watermark_time: object | None,
  166. watermark_id: int,
  167. batch: int,
  168. ) -> list[dict]:
  169. with connection.cursor() as cursor:
  170. if watermark_time is None:
  171. cursor.execute(
  172. """
  173. SELECT id, point_name, measurement_type, sample_time, sample_count
  174. FROM wave_file
  175. WHERE rpm > 0 AND measurement_type = %s AND cycle_start IS NULL
  176. ORDER BY sample_time ASC, id ASC
  177. LIMIT %s
  178. """,
  179. (MEASUREMENT_TYPE, batch),
  180. )
  181. else:
  182. cursor.execute(
  183. """
  184. SELECT id, point_name, measurement_type, sample_time, sample_count
  185. FROM wave_file
  186. WHERE rpm > 0 AND measurement_type = %s AND cycle_start IS NULL
  187. AND (sample_time > %s OR (sample_time = %s AND id > %s))
  188. ORDER BY sample_time ASC, id ASC
  189. LIMIT %s
  190. """,
  191. (MEASUREMENT_TYPE, watermark_time, watermark_time, watermark_id, batch),
  192. )
  193. return cursor.fetchall()
  194. def main() -> int:
  195. parser = argparse.ArgumentParser(description="回写首个完整周期的 sample_index 边界")
  196. parser.add_argument("--start-time", type=str, default="",
  197. help="起始水位时间(含),留空从头开始")
  198. parser.add_argument("--start-id", type=int, default=0,
  199. help="起始水位 id(含)")
  200. parser.add_argument("--batch", type=int, default=100, help="每轮读取的文件数")
  201. parser.add_argument("--read-workers", type=int, default=4, help="并行读样本的连接数")
  202. parser.add_argument("--limit", type=int, default=0, help="最多处理文件数,0 表示不限")
  203. parser.add_argument("--report-every", type=int, default=100, help="每 N 个文件打印一次汇总")
  204. parser.add_argument("--write-batch", type=int, default=100,
  205. help="回写攒满 N 条才批量写一次")
  206. parser.add_argument("--dry-run", action="store_true", help="只检测不回写数据库")
  207. args = parser.parse_args()
  208. start_time = args.start_time.strip()
  209. watermark_time: object | None = start_time or None
  210. watermark_id = args.start_id
  211. total = 0
  212. stats = {"有周期": 0, "无周期": 0}
  213. errors = 0
  214. last_reported = 0
  215. write_buffer: list[tuple[int, int, int]] = []
  216. read_workers = max(1, min(args.read_workers, args.batch))
  217. reader_connections = [predict.get_connection() for _ in range(read_workers)]
  218. def flush(connection) -> None:
  219. if args.dry_run:
  220. write_buffer.clear()
  221. else:
  222. flush_bounds(connection, write_buffer)
  223. def summary_text() -> str:
  224. return (
  225. f"已处理 {total}, 有周期 {stats['有周期']}, 无周期 {stats['无周期']}, "
  226. f"错误 {errors}, 水位 sample_time={watermark_time} id={watermark_id}"
  227. )
  228. print(f"水位起点: sample_time={start_time or '从头'}, id={args.start_id}, "
  229. f"批大小: {args.batch}, 读并行: {read_workers} 连接, 窗口: {STAGE_LIMITS}"
  230. + (", 干跑(不回写)" if args.dry_run else ""))
  231. try:
  232. while True:
  233. connection = predict.get_connection()
  234. try:
  235. rows = fetch_batch(connection, watermark_time, watermark_id, args.batch)
  236. if not rows:
  237. flush(connection)
  238. connection.close()
  239. print(f"无待处理文件,完成 [{summary_text()}]")
  240. return 0
  241. resolved, batch_errors = resolve_batch_bounds(
  242. rows, reader_connections, read_workers,
  243. )
  244. errors += batch_errors
  245. for row in rows:
  246. file_id = int(row["id"])
  247. total += 1
  248. bounds = resolved[file_id]
  249. if bounds is None:
  250. stats["无周期"] += 1
  251. write_buffer.append((file_id, -1, -1))
  252. else:
  253. stats["有周期"] += 1
  254. write_buffer.append((file_id, bounds[0], bounds[1]))
  255. if len(write_buffer) >= args.write_batch:
  256. flush(connection)
  257. if total // args.report_every > last_reported:
  258. last_reported = total // args.report_every
  259. print(f" 汇总: {summary_text()}", flush=True)
  260. if args.limit and total >= args.limit:
  261. flush(connection)
  262. watermark_time = rows[-1]["sample_time"]
  263. watermark_id = int(rows[-1]["id"])
  264. connection.close()
  265. print(f"已达 --limit={args.limit},退出")
  266. print(f" 汇总: {summary_text()}")
  267. return 0
  268. flush(connection)
  269. watermark_time = rows[-1]["sample_time"]
  270. watermark_id = int(rows[-1]["id"])
  271. finally:
  272. try:
  273. connection.close()
  274. except Exception:
  275. pass
  276. except KeyboardInterrupt:
  277. if write_buffer and not args.dry_run:
  278. try:
  279. with predict.get_connection() as connection:
  280. flush_bounds(connection, write_buffer)
  281. except Exception:
  282. pass
  283. for connection in reader_connections:
  284. try:
  285. connection.close()
  286. except Exception:
  287. pass
  288. print(f"\n已中断。{summary_text()}")
  289. if watermark_time is not None:
  290. print(f"续跑命令: python detect_cycle_index.py --start-time \"{watermark_time}\" "
  291. f"--start-id {watermark_id}")
  292. return 0
  293. for connection in reader_connections:
  294. try:
  295. connection.close()
  296. except Exception:
  297. pass
  298. return 0
  299. if __name__ == "__main__":
  300. sys.exit(main())