fault_frequency.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. """故障频率解析与计算。
  2. 目标:按“风机/测点/转速”解析部件,读取轴承几何或齿轮齿数,输出特征频率,
  3. 并明确返回缺失参数,避免用猜测参数生成诊断结论。
  4. """
  5. from __future__ import annotations
  6. import math
  7. import re
  8. from dataclasses import dataclass, field
  9. from typing import Any, Dict, List, Optional, Tuple
  10. from app.report.collector import platform_conn
  11. BEARING_FIELDS = ("n_rolls", "roller_diameter", "pitch_diameter", "contact_angle")
  12. @dataclass
  13. class ComponentRef:
  14. component_type: str
  15. position: str = ""
  16. stage: int = 0
  17. brand: Optional[str] = None
  18. model: Optional[str] = None
  19. teeth: Optional[int] = None
  20. warnings: List[str] = field(default_factory=list)
  21. def _safe_engine(value: str) -> str:
  22. if not re.fullmatch(r"[A-Za-z0-9_]+", value or ""):
  23. raise ValueError("非法的风机编号")
  24. return value
  25. def _one(cur, sql: str, params: Tuple[Any, ...] = ()) -> Optional[Dict[str, Any]]:
  26. cur.execute(sql, params)
  27. return cur.fetchone()
  28. class FaultFrequencyService:
  29. def __init__(self, engine_code: str, point_name: str, rpm: float,
  30. mill_type_code: Optional[str] = None):
  31. self.engine_code = _safe_engine(engine_code)
  32. self.point_name = (point_name or "").strip()
  33. self.rpm = float(rpm or 0)
  34. self.mill_type_code = (mill_type_code or "").strip() or None
  35. def resolve(self) -> Dict[str, Any]:
  36. conn = platform_conn()
  37. try:
  38. with conn.cursor() as cur:
  39. mill_type = self._mill_type(cur)
  40. if not mill_type:
  41. return self._unsupported([], "风机未关联机型(wind_engine_group.mill_type_code 为空)")
  42. machine_row = _one(
  43. cur,
  44. "SELECT machine_type_code FROM wind_engine_mill WHERE mill_type_code=%s",
  45. (mill_type,),
  46. )
  47. machine_type = machine_row.get("machine_type_code") if machine_row else None
  48. ratio = self._speed_ratio(cur, mill_type)
  49. ref = self._component(cur, mill_type)
  50. if ref is None:
  51. return self._unsupported([], "该测点未映射到主轴承/齿轮箱/发电机")
  52. if not ref.brand or not ref.model:
  53. return self._unsupported(["brand", "model"], "部件品牌或型号缺失")
  54. spec = self._spec(cur, ref.brand, ref.model)
  55. if spec is None:
  56. return self._unsupported(["brand/model"], f"故障参数库无 {ref.brand}/{ref.model}")
  57. missing = [k for k in BEARING_FIELDS if spec.get(k) is None]
  58. if missing:
  59. return self._unsupported(missing, "轴承几何参数不完整,无法计算故障频率")
  60. shaft_rpm, speed_note = self._shaft_rpm(ref, ratio)
  61. if shaft_rpm <= 0:
  62. return self._unsupported(["rpm"], "转速为 0,无法计算")
  63. fr = shaft_rpm / 60.0
  64. n = float(spec["n_rolls"])
  65. d = float(spec["roller_diameter"])
  66. D = float(spec["pitch_diameter"])
  67. theta = math.radians(float(spec["contact_angle"]))
  68. ratio_d = d / D
  69. bpfi = (n / 2) * (1 + ratio_d * math.cos(theta)) * fr
  70. bpfo = (n / 2) * (1 - ratio_d * math.cos(theta)) * fr
  71. bsf = (D / (2 * d)) * (1 - (ratio_d * math.cos(theta)) ** 2) * fr
  72. ftf = 0.5 * (1 - ratio_d * math.cos(theta)) * fr
  73. freqs = {
  74. "BPFI": round(bpfi, 3),
  75. "BPFO": round(bpfo, 3),
  76. "BSF": round(bsf, 3),
  77. "FTF": round(ftf, 3),
  78. }
  79. if ref.teeth:
  80. freqs["GMF"] = round(float(ref.teeth) * fr, 3)
  81. return {
  82. "code": 200,
  83. "supported": True,
  84. "engineCode": self.engine_code,
  85. "millTypeCode": mill_type,
  86. "machineTypeCode": machine_type,
  87. "componentType": ref.component_type,
  88. "position": ref.position,
  89. "stage": ref.stage,
  90. "brand": ref.brand,
  91. "model": ref.model,
  92. "nRolls": n,
  93. "rollerDiameter": d,
  94. "pitchDiameter": D,
  95. "contactAngle": float(spec["contact_angle"]),
  96. "rpm": round(self.rpm, 3),
  97. "shaftRpm": round(shaft_rpm, 3),
  98. "speedRatio": round(ratio, 4),
  99. "frequencies": freqs,
  100. "source": spec.get("source") or "component_fault_spec",
  101. "confidence": float(spec.get("confidence") or 0),
  102. "missing": [],
  103. "warnings": ref.warnings + ([speed_note] if speed_note else []),
  104. }
  105. finally:
  106. conn.close()
  107. def _mill_type(self, cur) -> Optional[str]:
  108. if self.mill_type_code:
  109. return self.mill_type_code
  110. row = _one(cur, "SELECT mill_type_code FROM wind_engine_group WHERE engine_code=%s", (self.engine_code,))
  111. return row["mill_type_code"] if row else None
  112. def _speed_ratio(self, cur, mill_type: str) -> float:
  113. row = _one(cur, "SELECT rotational_speed_ratio FROM wind_engine_mill WHERE mill_type_code=%s", (mill_type,))
  114. try:
  115. value = float(row["rotational_speed_ratio"]) if row and row.get("rotational_speed_ratio") else 1.0
  116. except (TypeError, ValueError):
  117. value = 1.0
  118. return value if value > 0 else 1.0
  119. def _component(self, cur, mill_type: str) -> Optional[ComponentRef]:
  120. map_row = _one(cur, "SELECT component_type, position, stage FROM measurement_point_component WHERE point_name=%s",
  121. (self.point_name,))
  122. if map_row:
  123. ctype, pos, stage = map_row["component_type"], map_row["position"] or "", int(map_row["stage"] or 0)
  124. else:
  125. ctype, pos, stage = self._infer(self.point_name)
  126. if not ctype:
  127. return None
  128. if ctype == "main_bearing":
  129. row = _one(cur, "SELECT * FROM unit_bearings WHERE mill_type_code=%s LIMIT 1", (mill_type,))
  130. if not row:
  131. return None
  132. if pos == "front":
  133. brand, model = row.get("front_bearing_brand"), row.get("front_bearing_model")
  134. elif pos == "rear":
  135. brand, model = row.get("rear_bearing_brand"), row.get("rear_bearing_model")
  136. else:
  137. brand, model = row.get("front_bearing_brand"), row.get("front_bearing_model")
  138. pos = "front"
  139. return ComponentRef(ctype, pos, 0, brand, model)
  140. if ctype == "generator":
  141. row = _one(cur, "SELECT * FROM unit_dynamo WHERE mill_type_code=%s LIMIT 1", (mill_type,))
  142. if not row:
  143. return None
  144. if pos == "non_drive_end":
  145. brand, model = row.get("non_drive_end_bearing_brand"), row.get("non_drive_end_bearing_model")
  146. else:
  147. brand, model = row.get("drive_end_bearing_brand"), row.get("drive_end_bearing_model")
  148. pos = pos or "drive_end"
  149. return ComponentRef(ctype, pos, 0, brand, model)
  150. gear = _one(cur, "SELECT code FROM unit_gearbox WHERE mill_type_code=%s LIMIT 1", (mill_type,))
  151. if not gear:
  152. return None
  153. code = gear["code"]
  154. if ctype == "gearbox_gear":
  155. row = _one(cur, """SELECT * FROM unit_gearbox_structure
  156. WHERE gearbox_code=%s AND gearbox_structure=1 AND planetary_gear_grade=%s LIMIT 1""",
  157. (code, stage or 1))
  158. if not row:
  159. return None
  160. return ComponentRef(ctype, pos or "planet", stage or 1,
  161. row.get("bearing_brand"), row.get("bearing_model"),
  162. row.get("gear_ring_teeth_count"))
  163. if ctype == "gearbox_bearing":
  164. grade = 3 if pos == "high_speed" else 2 if pos in ("intermediate", "low_speed_intermediate") else 1
  165. row = _one(cur, """SELECT * FROM unit_gearbox_bearings
  166. WHERE gearbox_code=%s AND parallel_wheel_grade=%s LIMIT 1""", (code, grade))
  167. if not row:
  168. return None
  169. brand = row.get("bearing_rs_brand") or row.get("bearing_brand")
  170. model = row.get("bearing_rs_model") or row.get("bearing_model")
  171. return ComponentRef(ctype, pos, 0, brand, model)
  172. return None
  173. @staticmethod
  174. def _infer(point: str) -> Tuple[Optional[str], str, int]:
  175. p = (point or "").lower()
  176. stage = 1 if "first" in p else 2 if "second" in p else 3 if "third" in p else 0
  177. if "main_bearing" in p:
  178. pos = "front" if "front" in p else "rear" if "rear" in p else "main"
  179. return "main_bearing", pos, 0
  180. if "generator" in p or "stator" in p:
  181. pos = "non_drive_end" if "non_drive" in p else "drive_end"
  182. return "generator", pos, 0
  183. if "gearbox" in p:
  184. if "planet" in p or "sun" in p:
  185. return "gearbox_gear", "planet", stage or 1
  186. return "gearbox_bearing", "high_speed" if "high_speed" in p else "low_speed", 0
  187. return None, "", 0
  188. def _spec(self, cur, brand: str, model: str) -> Optional[Dict[str, Any]]:
  189. row = _one(cur, """SELECT * FROM component_fault_spec
  190. WHERE component_type IN ('bearing','main_bearing','generator','gearbox_bearing')
  191. AND brand=%s AND model=%s LIMIT 1""", (brand, model))
  192. if row:
  193. return row
  194. row = _one(cur, """SELECT * FROM unit_dict_brand_model
  195. WHERE unit_type=1 AND manufacture=%s AND model_number=%s LIMIT 1""", (brand, model))
  196. if row:
  197. return {
  198. "n_rolls": row.get("rolls_number"),
  199. "roller_diameter": row.get("rolls_diameter"),
  200. "pitch_diameter": row.get("circle_diameter"),
  201. "contact_angle": row.get("theta_deg"),
  202. "source": "unit_dict_brand_model",
  203. "confidence": 0.9,
  204. }
  205. return None
  206. def _shaft_rpm(self, ref: ComponentRef, ratio: float) -> Tuple[float, str]:
  207. if self.rpm <= 0:
  208. return 0.0, ""
  209. if ref.component_type in ("main_bearing", "gearbox_gear", "gearbox_bearing") and ratio > 1:
  210. if ref.component_type == "gearbox_bearing" and ref.position == "high_speed":
  211. return self.rpm, ""
  212. note = "按机型传动比折算到低速轴" if ref.component_type == "main_bearing" else "按机型传动比折算,级间转速为近似值"
  213. return self.rpm / ratio, note
  214. return self.rpm, ""
  215. def _unsupported(self, missing: List[str], message: str) -> Dict[str, Any]:
  216. return {
  217. "code": 200,
  218. "supported": False,
  219. "engineCode": self.engine_code,
  220. "millTypeCode": self.mill_type_code,
  221. "componentType": None,
  222. "frequencies": {},
  223. "missing": missing,
  224. "message": message,
  225. "warnings": [],
  226. }