fault_frequency.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. ratio = self._speed_ratio(cur, mill_type)
  43. ref = self._component(cur, mill_type)
  44. if ref is None:
  45. return self._unsupported([], "该测点未映射到主轴承/齿轮箱/发电机")
  46. if not ref.brand or not ref.model:
  47. return self._unsupported(["brand", "model"], "部件品牌或型号缺失")
  48. spec = self._spec(cur, ref.brand, ref.model)
  49. if spec is None:
  50. return self._unsupported(["brand/model"], f"故障参数库无 {ref.brand}/{ref.model}")
  51. missing = [k for k in BEARING_FIELDS if spec.get(k) is None]
  52. if missing:
  53. return self._unsupported(missing, "轴承几何参数不完整,无法计算故障频率")
  54. shaft_rpm, speed_note = self._shaft_rpm(ref, ratio)
  55. if shaft_rpm <= 0:
  56. return self._unsupported(["rpm"], "转速为 0,无法计算")
  57. fr = shaft_rpm / 60.0
  58. n = float(spec["n_rolls"])
  59. d = float(spec["roller_diameter"])
  60. D = float(spec["pitch_diameter"])
  61. theta = math.radians(float(spec["contact_angle"]))
  62. ratio_d = d / D
  63. bpfi = (n / 2) * (1 + ratio_d * math.cos(theta)) * fr
  64. bpfo = (n / 2) * (1 - ratio_d * math.cos(theta)) * fr
  65. bsf = (D / (2 * d)) * (1 - (ratio_d * math.cos(theta)) ** 2) * fr
  66. ftf = 0.5 * (1 - ratio_d * math.cos(theta)) * fr
  67. freqs = {
  68. "BPFI": round(bpfi, 3),
  69. "BPFO": round(bpfo, 3),
  70. "BSF": round(bsf, 3),
  71. "FTF": round(ftf, 3),
  72. }
  73. if ref.teeth:
  74. freqs["GMF"] = round(float(ref.teeth) * fr, 3)
  75. return {
  76. "code": 200,
  77. "supported": True,
  78. "engineCode": self.engine_code,
  79. "millTypeCode": mill_type,
  80. "componentType": ref.component_type,
  81. "position": ref.position,
  82. "stage": ref.stage,
  83. "brand": ref.brand,
  84. "model": ref.model,
  85. "nRolls": n,
  86. "rollerDiameter": d,
  87. "pitchDiameter": D,
  88. "contactAngle": float(spec["contact_angle"]),
  89. "rpm": round(self.rpm, 3),
  90. "shaftRpm": round(shaft_rpm, 3),
  91. "speedRatio": round(ratio, 4),
  92. "frequencies": freqs,
  93. "source": spec.get("source") or "component_fault_spec",
  94. "confidence": float(spec.get("confidence") or 0),
  95. "missing": [],
  96. "warnings": ref.warnings + ([speed_note] if speed_note else []),
  97. }
  98. finally:
  99. conn.close()
  100. def _mill_type(self, cur) -> Optional[str]:
  101. if self.mill_type_code:
  102. return self.mill_type_code
  103. row = _one(cur, "SELECT mill_type_code FROM wind_engine_group WHERE engine_code=%s", (self.engine_code,))
  104. return row["mill_type_code"] if row else None
  105. def _speed_ratio(self, cur, mill_type: str) -> float:
  106. row = _one(cur, "SELECT rotational_speed_ratio FROM wind_engine_mill WHERE mill_type_code=%s", (mill_type,))
  107. try:
  108. value = float(row["rotational_speed_ratio"]) if row and row.get("rotational_speed_ratio") else 1.0
  109. except (TypeError, ValueError):
  110. value = 1.0
  111. return value if value > 0 else 1.0
  112. def _component(self, cur, mill_type: str) -> Optional[ComponentRef]:
  113. map_row = _one(cur, "SELECT component_type, position, stage FROM measurement_point_component WHERE point_name=%s",
  114. (self.point_name,))
  115. if map_row:
  116. ctype, pos, stage = map_row["component_type"], map_row["position"] or "", int(map_row["stage"] or 0)
  117. else:
  118. ctype, pos, stage = self._infer(self.point_name)
  119. if not ctype:
  120. return None
  121. if ctype == "main_bearing":
  122. row = _one(cur, "SELECT * FROM unit_bearings WHERE mill_type_code=%s LIMIT 1", (mill_type,))
  123. if not row:
  124. return None
  125. if pos == "front":
  126. brand, model = row.get("front_bearing_brand"), row.get("front_bearing_model")
  127. elif pos == "rear":
  128. brand, model = row.get("rear_bearing_brand"), row.get("rear_bearing_model")
  129. else:
  130. brand, model = row.get("front_bearing_brand"), row.get("front_bearing_model")
  131. pos = "front"
  132. return ComponentRef(ctype, pos, 0, brand, model)
  133. if ctype == "generator":
  134. row = _one(cur, "SELECT * FROM unit_dynamo WHERE mill_type_code=%s LIMIT 1", (mill_type,))
  135. if not row:
  136. return None
  137. if pos == "non_drive_end":
  138. brand, model = row.get("non_drive_end_bearing_brand"), row.get("non_drive_end_bearing_model")
  139. else:
  140. brand, model = row.get("drive_end_bearing_brand"), row.get("drive_end_bearing_model")
  141. pos = pos or "drive_end"
  142. return ComponentRef(ctype, pos, 0, brand, model)
  143. gear = _one(cur, "SELECT code FROM unit_gearbox WHERE mill_type_code=%s LIMIT 1", (mill_type,))
  144. if not gear:
  145. return None
  146. code = gear["code"]
  147. if ctype == "gearbox_gear":
  148. row = _one(cur, """SELECT * FROM unit_gearbox_structure
  149. WHERE gearbox_code=%s AND gearbox_structure=1 AND planetary_gear_grade=%s LIMIT 1""",
  150. (code, stage or 1))
  151. if not row:
  152. return None
  153. return ComponentRef(ctype, pos or "planet", stage or 1,
  154. row.get("bearing_brand"), row.get("bearing_model"),
  155. row.get("gear_ring_teeth_count"))
  156. if ctype == "gearbox_bearing":
  157. grade = 3 if pos == "high_speed" else 2 if pos in ("intermediate", "low_speed_intermediate") else 1
  158. row = _one(cur, """SELECT * FROM unit_gearbox_bearings
  159. WHERE gearbox_code=%s AND parallel_wheel_grade=%s LIMIT 1""", (code, grade))
  160. if not row:
  161. return None
  162. brand = row.get("bearing_rs_brand") or row.get("bearing_brand")
  163. model = row.get("bearing_rs_model") or row.get("bearing_model")
  164. return ComponentRef(ctype, pos, 0, brand, model)
  165. return None
  166. @staticmethod
  167. def _infer(point: str) -> Tuple[Optional[str], str, int]:
  168. p = (point or "").lower()
  169. stage = 1 if "first" in p else 2 if "second" in p else 3 if "third" in p else 0
  170. if "main_bearing" in p:
  171. pos = "front" if "front" in p else "rear" if "rear" in p else "main"
  172. return "main_bearing", pos, 0
  173. if "generator" in p or "stator" in p:
  174. pos = "non_drive_end" if "non_drive" in p else "drive_end"
  175. return "generator", pos, 0
  176. if "gearbox" in p:
  177. if "planet" in p or "sun" in p:
  178. return "gearbox_gear", "planet", stage or 1
  179. return "gearbox_bearing", "high_speed" if "high_speed" in p else "low_speed", 0
  180. return None, "", 0
  181. def _spec(self, cur, brand: str, model: str) -> Optional[Dict[str, Any]]:
  182. row = _one(cur, """SELECT * FROM component_fault_spec
  183. WHERE component_type IN ('bearing','main_bearing','generator','gearbox_bearing')
  184. AND brand=%s AND model=%s LIMIT 1""", (brand, model))
  185. if row:
  186. return row
  187. row = _one(cur, """SELECT * FROM unit_dict_brand_model
  188. WHERE unit_type=1 AND manufacture=%s AND model_number=%s LIMIT 1""", (brand, model))
  189. if row:
  190. return {
  191. "n_rolls": row.get("rolls_number"),
  192. "roller_diameter": row.get("rolls_diameter"),
  193. "pitch_diameter": row.get("circle_diameter"),
  194. "contact_angle": row.get("theta_deg"),
  195. "source": "unit_dict_brand_model",
  196. "confidence": 0.9,
  197. }
  198. return None
  199. def _shaft_rpm(self, ref: ComponentRef, ratio: float) -> Tuple[float, str]:
  200. if self.rpm <= 0:
  201. return 0.0, ""
  202. if ref.component_type in ("main_bearing", "gearbox_gear", "gearbox_bearing") and ratio > 1:
  203. if ref.component_type == "gearbox_bearing" and ref.position == "high_speed":
  204. return self.rpm, ""
  205. note = "按机型传动比折算到低速轴" if ref.component_type == "main_bearing" else "按机型传动比折算,级间转速为近似值"
  206. return self.rpm / ratio, note
  207. return self.rpm, ""
  208. def _unsupported(self, missing: List[str], message: str) -> Dict[str, Any]:
  209. return {
  210. "code": 200,
  211. "supported": False,
  212. "engineCode": self.engine_code,
  213. "millTypeCode": self.mill_type_code,
  214. "componentType": None,
  215. "frequencies": {},
  216. "missing": missing,
  217. "message": message,
  218. "warnings": [],
  219. }