cms_class_20241201.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. import numpy as np
  2. from scipy.signal import hilbert
  3. from scipy.fft import ifft
  4. import plotly.graph_objs as go
  5. import pandas as pd
  6. from sqlalchemy import create_engine, text
  7. import sqlalchemy
  8. import json
  9. import ast
  10. import math
  11. '''
  12. # 输入:
  13. {
  14. "ids":[12345,121212],
  15. "windCode":"xxxx",
  16. "analysisType":"xxxxx",
  17. "fmin":int(xxxx) (None),
  18. "fmax":"int(xxxx) (None),
  19. }
  20. [{id:xxxx,"time":xxx},{}]
  21. id[123456]
  22. # 通过id,读取mysql,获取数据
  23. engine = create_engine('mysql+pymysql://root:admin123456@192.168.50.235:30306/energy_data')
  24. def get_by_id(table_name,id):
  25. lastday_df_sql = f"SELECT * FROM {table_name} where id = {id} "
  26. # print(lastday_df_sql)
  27. df = pd.read_sql(lastday_df_sql, engine)
  28. return df
  29. select distinct id, timeStamp from table_name group by ids
  30. ids time
  31. 1 xxx
  32. 2 xxxx
  33. df_data = []
  34. # for id in ids:
  35. # sql_data = get_by_id('SKF001_wave',id)
  36. # df_data.append(sql_data)
  37. # print(sql_data)
  38. [df1,df2]
  39. '''
  40. '''
  41. 数据库字段:
  42. "samplingFrequency"
  43. "timeStamp"
  44. "mesureData"
  45. '''
  46. # %%
  47. # %%
  48. # 主要的类
  49. class CMSAnalyst:
  50. def __init__(self, fmin, fmax, table_name, ids):
  51. # envelope_spectrum_analysis
  52. # datas是[df1,df2,.....]
  53. #从数据库获取原始数据
  54. self.datas = self._get_by_id(table_name,ids)
  55. self.datas = [df[['mesure_data','time_stamp','sampling_frequency','wind_turbine_number','rotational_speed','mesure_point_name']] for df in self.datas]
  56. # 只输入一个id,返回一个[df],所以拿到self.data[0]
  57. self.data_filter = self.datas[0]
  58. # print(self.data_filter)
  59. # 取数据列
  60. self.data = np.array(ast.literal_eval(self.data_filter['mesure_data'][0]))
  61. self.envelope_spectrum_m = self.data.shape[0]
  62. self.envelope_spectrum_n = 1
  63. #设置分析参数
  64. self.fs = int(self.data_filter['sampling_frequency'].iloc[0])
  65. self.envelope_spectrum_t = np.arange(self.envelope_spectrum_m) / self.fs
  66. self.fmin = fmin if fmin is not None else 0
  67. self.fmax = fmax if fmax is not None else float('inf')
  68. self.envelope_spectrum_y = self._bandpass_filter(self.data)
  69. self.f, self.HP = self._calculate_envelope_spectrum(self.envelope_spectrum_y)
  70. #设备信息
  71. self.wind_code = self.data_filter['wind_turbine_number'].iloc[0]
  72. self.rpm_Gen = self.data_filter['rotational_speed'].iloc[0]
  73. self.mesure_point_name = self.data_filter['mesure_point_name'].iloc[0]
  74. self.fn_Gen = round(self.rpm_Gen/60,2)
  75. self.CF = self.Characteristic_Frequency()
  76. print(self.CF)
  77. self.CF = pd.DataFrame(self.CF,index=[0])
  78. print(self.CF)
  79. print(self.rpm_Gen)
  80. #if self.CF['type'].iloc[0] == 'bearing':
  81. n_rolls_m = self.CF['n_rolls'].iloc[0]
  82. d_rolls_m = self.CF['d_rolls'].iloc[0]
  83. D_diameter_m = self.CF['D_diameter'].iloc[0]
  84. theta_deg_m = self.CF['theta_deg'].iloc[0]
  85. print(n_rolls_m)
  86. print(d_rolls_m)
  87. print(D_diameter_m)
  88. print(theta_deg_m)
  89. self.bearing_frequencies = self.calculate_bearing_frequencies(n_rolls_m, d_rolls_m, D_diameter_m, theta_deg_m, self.rpm_Gen)
  90. print(self.bearing_frequencies)
  91. self.bearing_frequencies = pd.DataFrame(self.bearing_frequencies,index=[0])
  92. print(self.bearing_frequencies)
  93. # frequency_domain_analysis
  94. (
  95. self.frequency_domain_analysis_t,
  96. self.frequency_domain_analysis_f,
  97. self.frequency_domain_analysis_m,
  98. self.frequency_domain_analysis_mag,
  99. self.frequency_domain_analysis_Xrms,
  100. ) = self._calculate_spectrum(self.data)
  101. # time_domain_analysis
  102. self.time_domain_analysis_t = np.arange(self.data.shape[0]) / self.fs
  103. def _get_by_id(self, windcode, ids):
  104. df_res = []
  105. engine = create_engine('mysql+pymysql://root:admin123456@192.168.50.235:30306/energy_data_prod')
  106. # engine = create_engine('mysql+pymysql://root:admin123456@106.120.102.238:10336/energy_data_prod')
  107. for id in ids:
  108. table_name=windcode+'_wave'
  109. lastday_df_sql = f"SELECT * FROM {table_name} where id = {id} "
  110. # print(lastday_df_sql)
  111. df = pd.read_sql(lastday_df_sql, engine)
  112. df_res.append(df)
  113. return df_res
  114. # envelope_spectrum_analysis 包络谱分析
  115. def _bandpass_filter(self, data):
  116. """带通滤波"""
  117. m= data.shape[0]
  118. ni = round(self.fmin * self.envelope_spectrum_m / self.fs + 1)
  119. # na = round(self.fmax * self.envelope_spectrum_m / self.fs + 1)
  120. if self.fmax == float('inf'):
  121. na = m
  122. else:
  123. na = round(self.fmax * m / self.fs + 1)
  124. col = 1
  125. y = np.zeros((self.envelope_spectrum_m, col))
  126. # for p in range(col):
  127. # print(data.shape,p)
  128. z = np.fft.fft(data)
  129. a = np.zeros(self.envelope_spectrum_m, dtype=complex)
  130. a[ni:na] = z[ni:na]
  131. a[self.envelope_spectrum_m - na + 1 : self.envelope_spectrum_m - ni + 1] = z[
  132. self.envelope_spectrum_m - na + 1 : self.envelope_spectrum_m - ni + 1
  133. ]
  134. z = np.fft.ifft(a)
  135. y[:, 0] = np.real(z)
  136. return y
  137. def _calculate_envelope_spectrum(self, y):
  138. """计算包络谱"""
  139. m, n = y.shape
  140. HP = np.zeros((m, n))
  141. col = 1
  142. for p in range(col):
  143. H = np.abs(hilbert(y[:, p] - np.mean(y[:, p])))
  144. HP[:, p] = np.abs(np.fft.fft(H - np.mean(H))) * 2 / m
  145. f = np.fft.fftfreq(m, d=1 / self.fs)
  146. return f, HP
  147. def envelope_spectrum(self):
  148. """绘制包络谱"""
  149. # 只取正频率部分
  150. positive_frequencies = self.f[: self.envelope_spectrum_m // 2]
  151. positive_HP = self.HP[: self.envelope_spectrum_m // 2, 0]
  152. x = positive_frequencies
  153. y = positive_HP
  154. title = "包络谱"
  155. xaxis = "频率(Hz)"
  156. yaxis = "加速度(m/s^2)"
  157. Xrms = np.sqrt(np.mean(y**2)) # 加速度均方根值(有效值)
  158. rpm_Gen = round(self.rpm_Gen, 2)
  159. BPFI_1X = round(self.bearing_frequencies['BPFI'].iloc[0], 2)
  160. BPFO_1X = round(self.bearing_frequencies['BPFO'].iloc[0], 2)
  161. BSF_1X = round(self.bearing_frequencies['BSF'].iloc[0], 2)
  162. FTF_1X = round(self.bearing_frequencies['FTF'].iloc[0], 2)
  163. fn_Gen = round(self.fn_Gen, 2)
  164. _3P_1X = round(self.fn_Gen, 2) * 3
  165. # if self.CF['type'].iloc[0] == 'bearing':
  166. result = {
  167. "fs":self.fs,
  168. "Xrms":round(Xrms, 2),
  169. "x":list(x),
  170. "y":list(y),
  171. "title":title,
  172. "xaxis":xaxis,
  173. "yaxis":yaxis,
  174. "rpm_Gen": round(rpm_Gen, 2), # 转速r/min
  175. "BPFI": [{"Xaxis": BPFI_1X ,"val": "1BPFI"},{"Xaxis": BPFI_1X*2 ,"val": "2BPFI"},
  176. {"Xaxis": BPFI_1X*3, "val": "3BPFI"}, {"Xaxis": BPFI_1X*4, "val": "4BPFI"},
  177. {"Xaxis": BPFI_1X*5, "val": "5BPFI"}, {"Xaxis": BPFI_1X*6, "val": "6BPFI"}],
  178. "BPFO": [{"Xaxis": BPFO_1X ,"val": "1BPFO"},{"Xaxis": BPFO_1X*2 ,"val": "2BPFO"},
  179. {"Xaxis": BPFO_1X*3, "val": "3BPFO"}, {"Xaxis": BPFO_1X*4, "val": "4BPFO"},
  180. {"Xaxis": BPFO_1X*5, "val": "5BPFO"}, {"Xaxis": BPFO_1X*6, "val": "6BPFO"}],
  181. "BSF": [{"Xaxis": BSF_1X ,"val": "1BSF"},{"Xaxis": BSF_1X*2 ,"val": "2BSF"},
  182. {"Xaxis": BSF_1X*3, "val": "3BSF"}, {"Xaxis": BSF_1X*4, "val": "4BSF"},
  183. {"Xaxis": BSF_1X*5, "val": "5BSF"}, {"Xaxis": BSF_1X*6, "val": "6BSF"}],
  184. "FTF": [{"Xaxis": FTF_1X ,"val": "1FTF"},{"Xaxis": FTF_1X*2 ,"val": "2FTF"},
  185. {"Xaxis": FTF_1X*3, "val": "3FTF"}, {"Xaxis": FTF_1X*4, "val": "4FTF"},
  186. {"Xaxis": FTF_1X*5, "val": "5FTF"}, {"Xaxis": FTF_1X*6, "val": "6FTF"}],
  187. "fn_Gen":[{"Xaxis": fn_Gen ,"val": "1X"},{"Xaxis": fn_Gen*2 ,"val": "2X"},
  188. {"Xaxis": fn_Gen*3, "val": "3X"}, {"Xaxis": fn_Gen*4, "val": "4X"},
  189. {"Xaxis": fn_Gen*5, "val": "5X"}, {"Xaxis": fn_Gen*6, "val": "6X"}],
  190. "B3P":_3P_1X,
  191. }
  192. # result = json.dumps(result, ensure_ascii=False)
  193. return result
  194. # frequency_domain_analysis 频谱分析
  195. def _calculate_spectrum(self, data):
  196. """计算频谱"""
  197. m = data.shape[0]
  198. n = 1
  199. t = np.arange(m) / self.fs
  200. mag = np.zeros((m, n))
  201. Xrms = np.sqrt(np.mean(data**2)) # 加速度均方根值(有效值)
  202. # col=1
  203. # for p in range(col):
  204. mag = np.abs(np.fft.fft(data - np.mean(data))) * 2 / m
  205. f = np.fft.fftfreq(m, d=1 / self.fs)
  206. return t, f, m, mag, Xrms
  207. def frequency_domain(self):
  208. """绘制频域波形参数"""
  209. # 只取正频率部分
  210. positive_frequencies = self.frequency_domain_analysis_f[
  211. : self.frequency_domain_analysis_m // 2
  212. ]
  213. positive_mag = self.frequency_domain_analysis_mag[
  214. : self.frequency_domain_analysis_m // 2
  215. ]
  216. x = positive_frequencies
  217. y = positive_mag
  218. title = "频域信号"
  219. xaxis = "频率(Hz)"
  220. yaxis = "加速度(m/s^2)"
  221. Xrms = self.frequency_domain_analysis_Xrms
  222. rpm_Gen = round(self.rpm_Gen, 2)
  223. BPFI_1X = round(self.bearing_frequencies['BPFI'].iloc[0], 2)
  224. BPFO_1X = round(self.bearing_frequencies['BPFO'].iloc[0], 2)
  225. BSF_1X = round(self.bearing_frequencies['BSF'].iloc[0], 2)
  226. FTF_1X = round(self.bearing_frequencies['FTF'].iloc[0], 2)
  227. fn_Gen = round(self.fn_Gen, 2)
  228. _3P_1X = round(self.fn_Gen, 2) * 3
  229. # if self.CF['type'].iloc[0] == 'bearing':
  230. result = {
  231. "fs":self.fs,
  232. "Xrms":round(Xrms, 2),
  233. "x":list(x),
  234. "y":list(y),
  235. "title":title,
  236. "xaxis":xaxis,
  237. "yaxis":yaxis,
  238. "rpm_Gen": round(rpm_Gen, 2), # 转速r/min
  239. "BPFI": [{"Xaxis": BPFI_1X ,"val": "1BPFI"},{"Xaxis": BPFI_1X*2 ,"val": "2BPFI"},
  240. {"Xaxis": BPFI_1X*3, "val": "3BPFI"}, {"Xaxis": BPFI_1X*4, "val": "4BPFI"},
  241. {"Xaxis": BPFI_1X*5, "val": "5BPFI"}, {"Xaxis": BPFI_1X*6, "val": "6BPFI"}],
  242. "BPFO": [{"Xaxis": BPFO_1X ,"val": "1BPFO"},{"Xaxis": BPFO_1X*2 ,"val": "2BPFO"},
  243. {"Xaxis": BPFO_1X*3, "val": "3BPFO"}, {"Xaxis": BPFO_1X*4, "val": "4BPFO"},
  244. {"Xaxis": BPFO_1X*5, "val": "5BPFO"}, {"Xaxis": BPFO_1X*6, "val": "6BPFO"}],
  245. "BSF": [{"Xaxis": BSF_1X ,"val": "1BSF"},{"Xaxis": BSF_1X*2 ,"val": "2BSF"},
  246. {"Xaxis": BSF_1X*3, "val": "3BSF"}, {"Xaxis": BSF_1X*4, "val": "4BSF"},
  247. {"Xaxis": BSF_1X*5, "val": "5BSF"}, {"Xaxis": BSF_1X*6, "val": "6BSF"}],
  248. "FTF": [{"Xaxis": FTF_1X ,"val": "1FTF"},{"Xaxis": FTF_1X*2 ,"val": "2FTF"},
  249. {"Xaxis": FTF_1X*3, "val": "3FTF"}, {"Xaxis": FTF_1X*4, "val": "4FTF"},
  250. {"Xaxis": FTF_1X*5, "val": "5FTF"}, {"Xaxis": FTF_1X*6, "val": "6FTF"}],
  251. "fn_Gen":[{"Xaxis": fn_Gen ,"val": "1X"},{"Xaxis": fn_Gen*2 ,"val": "2X"},
  252. {"Xaxis": fn_Gen*3, "val": "3X"}, {"Xaxis": fn_Gen*4, "val": "4X"},
  253. {"Xaxis": fn_Gen*5, "val": "5X"}, {"Xaxis": fn_Gen*6, "val": "6X"}],
  254. "B3P":_3P_1X,
  255. }
  256. result = json.dumps(result, ensure_ascii=False)
  257. return result
  258. # time_domain_analysis 时域分析
  259. def time_domain(self):
  260. """绘制时域波形参数"""
  261. x = self.time_domain_analysis_t
  262. y = self.data
  263. rpm_Gen =self.rpm_Gen
  264. title = "时间域信号"
  265. xaxis = "时间(s)"
  266. yaxis = "加速度(m/s^2)"
  267. # 图片右侧统计量
  268. mean_value = np.mean(y)#平均值
  269. max_value = np.max(y)#最大值
  270. min_value = np.min(y)#最小值
  271. Xrms = np.sqrt(np.mean(y**2)) # 加速度均方根值(有效值)
  272. Xp = (max_value - min_value) / 2 # 峰值(单峰最大值) # 峰值
  273. Xpp=max_value-min_value#峰峰值
  274. Cf = Xp / Xrms # 峰值指标
  275. Sf = Xrms / mean_value # 波形指标
  276. If = Xp / np.mean(np.abs(y)) # 脉冲指标
  277. Xr = np.mean(np.sqrt(np.abs(y))) ** 2 # 方根幅值
  278. Ce = Xp / Xr # 裕度指标
  279. # 计算每个数据点的绝对值减去均值后的三次方,并求和
  280. sum_abs_diff_cubed_3 = np.mean((np.abs(y) - mean_value) ** 3)
  281. # 计算偏度指标
  282. Cw = sum_abs_diff_cubed_3 / (Xrms**3)
  283. # 计算每个数据点的绝对值减去均值后的四次方,并求和
  284. sum_abs_diff_cubed_4 = np.mean((np.abs(y) - mean_value) ** 4)
  285. # 计算峭度指标
  286. Cq = sum_abs_diff_cubed_4 / (Xrms**4)
  287. result = {
  288. "x":list(x),
  289. "y":list(y),
  290. "title":title,
  291. "xaxis":xaxis,
  292. "yaxis":yaxis,
  293. "fs":self.fs,
  294. "Xrms":round(Xrms, 2),#有效值
  295. "mean_value":round(mean_value, 2),# 均值
  296. "max_value":round(max_value, 2),# 最大值
  297. "min_value":round(min_value, 2), # 最小值
  298. "Xp":round(Xp, 2),# 峰值
  299. "Xpp":round(Xpp, 2),# 峰峰值
  300. "Cf":round(Cf, 2),# 峰值指标
  301. "Sf":round(Sf, 2),# 波形因子
  302. "If":round(If, 2),# 脉冲指标
  303. "Ce":round(Ce, 2),# 裕度指标
  304. "Cw":round(Cw, 2) ,# 偏度指标
  305. "Cq":round(Cq, 2) ,# 峭度指标
  306. "rpm_Gen": round(rpm_Gen, 2), # 转速r/min
  307. }
  308. result = json.dumps(result, ensure_ascii=False)
  309. return result
  310. # trend_analysis 趋势图
  311. def trend_analysis(self):
  312. all_stats = []
  313. # 定义积分函数
  314. def _integrate(data, dt):
  315. return np.cumsum(data) * dt
  316. # 定义计算统计指标的函数
  317. def _calculate_stats(data):
  318. mean_value = np.mean(data)
  319. max_value = np.max(data)
  320. min_value = np.min(data)
  321. Xrms = np.sqrt(np.mean(data**2)) # 加速度均方根值(有效值)
  322. # Xrms = filtered_acceleration_rms # 加速度均方根值(有效值)
  323. Xp = (max_value - min_value) / 2 # 峰值(单峰最大值) # 峰值
  324. Cf = Xp / Xrms # 峰值指标
  325. Sf = Xrms / mean_value # 波形指标
  326. If = Xp / np.mean(np.abs(data)) # 脉冲指标
  327. Xr = np.mean(np.sqrt(np.abs(data))) ** 2 # 方根幅值
  328. Ce = Xp / Xr # 裕度指标
  329. # 计算每个数据点的绝对值减去均值后的三次方,并求和
  330. sum_abs_diff_cubed_3 = np.mean((np.abs(data) - mean_value) ** 3)
  331. # 计算偏度指标
  332. Cw = sum_abs_diff_cubed_3 / (Xrms**3)
  333. # 计算每个数据点的绝对值减去均值后的四次方,并求和
  334. sum_abs_diff_cubed_4 = np.mean((np.abs(data) - mean_value) ** 4)
  335. # 计算峭度指标
  336. Cq = sum_abs_diff_cubed_4 / (Xrms**4)
  337. #
  338. return {
  339. "fs":self.fs,#采样频率
  340. "Mean": round(mean_value, 2),#平均值
  341. "Max": round(max_value, 2),#最大值
  342. "Min": round(min_value, 2),#最小值
  343. "Xrms": round(Xrms, 2),#有效值
  344. "Xp": round(Xp, 2),#峰值
  345. "If": round(If, 2), # 脉冲指标
  346. "Cf": round(Cf, 2),#峰值指标
  347. "Sf": round(Sf, 2),#波形指标
  348. "Ce": round(Ce, 2),#裕度指标
  349. "Cw": round(Cw, 2) ,#偏度指标
  350. "Cq": round(Cq, 2),#峭度指标
  351. #velocity_rms :速度有效值
  352. #time_stamp:时间戳
  353. }
  354. for data in self.datas:
  355. fs=int(self.data_filter['sampling_frequency'].iloc[0])
  356. dt = 1 / fs
  357. time_stamp=data['time_stamp'][0]
  358. print(time_stamp)
  359. data=np.array(ast.literal_eval(data['mesure_data'][0]))
  360. velocity = _integrate(data, dt)
  361. velocity_rms = np.sqrt(np.mean(velocity**2))
  362. stats = _calculate_stats(data)
  363. stats["velocity_rms"] = round(velocity_rms, 2)#速度有效值
  364. stats["time_stamp"] = str(time_stamp)#时间戳
  365. all_stats.append(stats)
  366. # df = pd.DataFrame(all_stats)
  367. all_stats = json.dumps(all_stats, ensure_ascii=False)
  368. return all_stats
  369. # def Characteristic_Frequency(self):
  370. # """提取轴承、齿轮等参数"""
  371. # # 1、从测点名称中提取部件名称(计算特征频率的部件)
  372. # str1 = self.mesure_point_name
  373. # # str2 = ["main_bearing", "front_main_bearing", "rear_main_bearing", "generator_non_drive_end"]
  374. # str2 = ["main_bearing", "front_main_bearing", "rear_main_bearing", "generator","stator","gearbox"]
  375. # for str in str2:
  376. # if str in str1:
  377. # parts = str
  378. # if parts == "front_main_bearing":
  379. # parts = "front_bearing"
  380. # elif parts == "rear_main_bearing":
  381. # parts = "rear_bearing"
  382. # print(parts)
  383. def Characteristic_Frequency(self):
  384. """提取轴承、齿轮等参数"""
  385. # 1、从测点名称中提取部件名称(计算特征频率的部件)
  386. str1 = self.mesure_point_name
  387. # str2 = ["main_bearing", "front_main_bearing", "rear_main_bearing", "generator_non_drive_end"]
  388. # str2 = ["main_bearing", "front_main_bearing", "rear_main_bearing", "generator","stator","gearbox"]
  389. # for str in str2:
  390. # if str in str1:
  391. # parts = str
  392. # # if parts == "front_main_bearing":
  393. # # parts = "front_bearing"
  394. # # elif parts == "rear_main_bearing":
  395. # # parts = "rear_bearing"
  396. print(str1)
  397. # 2、连接233的数据库'energy_show',从表'wind_engine_group'查找风机编号'engine_code'对应的机型编号'mill_type_code'
  398. engine_code = self.wind_code
  399. print(engine_code)
  400. Engine2 = create_engine('mysql+pymysql://admin:admin123456@192.168.50.233:3306/energy_show')
  401. #Engine2 = create_engine('mysql+pymysql://admin:admin123456@106.120.102.238:16306/energy_show')
  402. # df_sql2 = f"SELECT * FROM {'wind_engine_group'} where engine_code = {'engine_code'} "
  403. df_sql2 = f"SELECT * FROM wind_engine_group WHERE engine_code = '{engine_code}'"
  404. df2 = pd.read_sql(df_sql2, Engine2)
  405. mill_type_code = df2['mill_type_code'].iloc[0]
  406. print(mill_type_code)
  407. # # 3、从表'unit_bearings'中通过机型编号'mill_type_code'查找部件'brand'、'model'的参数信息
  408. # Engine3 = create_engine('mysql+pymysql://admin:admin123456@106.120.102.238:16306/energy_show')
  409. # #unit_bearings是主轴承的参数
  410. # df_sql3 = f"SELECT * FROM {'unit_bearings'} where mill_type_code = {'mill_type_code'} "
  411. # df3 = pd.read_sql(df_sql3, Engine3)
  412. # brand = 'front_bearing' + '_brand' # parts代替'front_bearing'
  413. # model = 'front_bearing' + '_model' # parts代替'front_bearing'
  414. # print(brand)
  415. # _brand = df3[brand].iloc[0]
  416. # _model = df3[model].iloc[0]
  417. # print(_brand)
  418. # print(_model)
  419. # 3、从相关的表中通过机型编号'mill_type_code'或者齿轮箱编号gearbox_code查找部件'brand'、'model'的参数信息
  420. Engine3 = create_engine('mysql+pymysql://admin:admin123456@192.168.50.233:3306/energy_show')
  421. # Engine3 = create_engine('mysql+pymysql://admin:admin123456@106.120.102.238:16306/energy_show')
  422. #unit_bearings主轴承参数表 关键词"main_bearing"
  423. if 'main_bearing' in str1:
  424. print("main_bearing")
  425. # df_sql3 = f"SELECT * FROM {'unit_bearings'} where mill_type_code = {'mill_type_code'} "
  426. df_sql3 = f"SELECT * FROM unit_bearings WHERE mill_type_code = '{mill_type_code}' "
  427. df3 = pd.read_sql(df_sql3, Engine3)
  428. if df3.empty:
  429. print("警告: 没有找到有效的机型信息")
  430. if 'front' in str1:
  431. brand = 'front_bearing' + '_brand'
  432. model = 'front_bearing' + '_model'
  433. front_has_value = not pd.isna(df3[brand].iloc[0]) and not pd.isna(df3[model].iloc[0])
  434. if not front_has_value:
  435. print("警告: 没有找到有效的品牌信息")
  436. elif 'rear' in str1:
  437. brand = 'rear_bearing' + '_brand'
  438. model = 'rear_bearing' + '_model'
  439. end_has_value = not pd.isna(df3[brand].iloc[0]) and not pd.isna(df3[model].iloc[0])
  440. if not end_has_value:
  441. print("警告: 没有找到有效的品牌信息")
  442. else:
  443. # 当没有指定 front 或 end 时,自动选择有值的轴承信息
  444. front_brand_col = 'front_bearing_brand'
  445. front_model_col = 'front_bearing_model'
  446. rear_brand_col = 'rear_bearing_brand'
  447. rear_model_col = 'rear_bearing_model'
  448. # 检查 front_bearing 是否有值
  449. front_has_value = not pd.isna(df3[front_brand_col].iloc[0]) and not pd.isna(df3[front_model_col].iloc[0])
  450. # 检查 end_bearing 是否有值
  451. end_has_value = not pd.isna(df3[rear_brand_col].iloc[0]) and not pd.isna(df3[rear_model_col].iloc[0])
  452. # 根据检查结果选择合适的列
  453. if front_has_value and end_has_value:
  454. # 如果两者都有值,默认选择 front
  455. brand = front_brand_col
  456. model = front_model_col
  457. elif front_has_value:
  458. brand = front_brand_col
  459. model = front_model_col
  460. elif end_has_value:
  461. brand = rear_brand_col
  462. model = rear_model_col
  463. else:
  464. # 如果两者都没有有效值,设置默认值或抛出异常
  465. print("警告: 没有找到有效的轴承信息")
  466. brand = front_brand_col # 默认使用 front
  467. model = front_model_col # 默认使用 front
  468. print(brand)
  469. _brand = df3[brand].iloc[0]
  470. _model = df3[model].iloc[0]
  471. print(_brand)
  472. print(_model)
  473. #unit_dynamo 发电机参数表 关键词generator stator
  474. elif 'generator'in str1 or 'stator' in str1:
  475. print("generator or 'stator'")
  476. # df_sql3 = f"SELECT * FROM {'unit_dynamo'} where mill_type_code = {'mill_type_code'} "
  477. df_sql3 = f"SELECT * FROM unit_dynamo WHERE mill_type_code = '{mill_type_code}' "
  478. df3 = pd.read_sql(df_sql3, Engine3)
  479. if 'non' in str1:
  480. brand = 'non_drive_end_bearing' + '_brand'
  481. model = 'non_drive_end_bearing' + '_model'
  482. else:
  483. brand = 'drive_end_bearing' + '_brand'
  484. model = 'drive_end_bearing' + '_model'
  485. print(brand)
  486. _brand = df3[brand].iloc[0]
  487. _model = df3[model].iloc[0]
  488. print(_brand)
  489. print(_model)
  490. #齿轮箱区分行星轮/平行轮 和 轴承两个表
  491. elif 'gearbox' in str1:
  492. print("gearbox")
  493. #根据mill_type_code从unit_gearbox表中获得gearbox_code
  494. df_sql3 = f"SELECT * FROM unit_gearbox WHERE mill_type_code = '{mill_type_code}' "
  495. df3 = pd.read_sql(df_sql3, Engine3)
  496. gearbox_code =df3['code'].iloc[0]
  497. print(gearbox_code)
  498. Engine33 = create_engine('mysql+pymysql://admin:admin123456@192.168.50.233:3306/energy_show')
  499. #Engine33 = create_engine('mysql+pymysql://admin:admin123456@106.120.102.238:16306/energy_show')
  500. #如果是行星轮/平行轮 则从unit_gearbox_structure 表中取数据
  501. if 'planet'in str1 or 'sun' in str1:
  502. print("'planet' or 'sun' ")
  503. gearbox_structure =1 if 'planet'in str1 else 2
  504. planetary_gear_grade =1
  505. if 'first' in str1:
  506. planetary_gear_grade =1
  507. elif 'second'in str1:
  508. planetary_gear_grade =2
  509. elif 'third'in str1:
  510. planetary_gear_grade =3
  511. # df_sql33 = f"SELECT * FROM unit_gearbox_structure WHERE gearbox_code = '{gearbox_code}' "
  512. df_sql33 = f"""
  513. SELECT bearing_brand, bearing_model
  514. FROM unit_gearbox_structure
  515. WHERE gearbox_code = '{gearbox_code}'
  516. AND gearbox_structure = '{gearbox_structure}'
  517. AND planetary_gear_grade = '{planetary_gear_grade}'
  518. """
  519. df33 = pd.read_sql(df_sql33, Engine33)
  520. if df33.empty:
  521. print("unit_gearbox_structure没有该测点的参数")
  522. else:
  523. brand = 'bearing' + '_brand'
  524. model = 'bearing' + '_model'
  525. print(brand)
  526. _brand = df33[brand].iloc[0]
  527. _model = df33[model].iloc[0]
  528. has_value = not pd.isna(df33[brand].iloc[0]) and not pd.isna(df33[model].iloc[0])
  529. if has_value:
  530. print(_brand)
  531. print(_model)
  532. else:
  533. print("警告: 没有找到有效的轴承信息")
  534. #如果是齿轮箱轴承 则从unit_gearbox_bearings 表中取数据
  535. elif 'shaft' in str1 or'input' in str1:
  536. print("'shaft'or'input'")
  537. # df_sql33 = f"SELECT * FROM unit_gearbox_bearings WHERE gearbox_code = '{gearbox_code}' "
  538. # df33 = pd.read_sql(df_sql33, Engine33)
  539. #高速轴 低速中间轴 取bearing_rs/gs均可
  540. parallel_wheel_grade=1
  541. if 'low_speed' in str1:
  542. parallel_wheel_grade =1
  543. elif 'low_speed_intermediate' in str1:
  544. parallel_wheel_grade =2
  545. elif 'high_speed' in str1:
  546. parallel_wheel_grade =3
  547. # df_sql33 = f"SELECT * FROM unit_gearbox_bearings WHERE gearbox_code = '{gearbox_code}' "
  548. df_sql33 = f"""
  549. SELECT bearing_rs_brand, bearing_rs_model, bearing_gs_brand, bearing_gs_model
  550. FROM unit_gearbox_bearings
  551. WHERE gearbox_code = '{gearbox_code}'
  552. AND parallel_wheel_grade = '{parallel_wheel_grade}'
  553. """
  554. df33 = pd.read_sql(df_sql33, Engine33)
  555. if not df33.empty:
  556. if 'high_speed' in str1 or 'low_speed_intermediate' in str1:
  557. rs_brand = 'bearing_rs' + '_brand'
  558. rs_model = 'bearing_rs' + '_model'
  559. gs_brand = 'bearing_gs' + '_brand'
  560. gs_model = 'bearing_gs' + '_model'
  561. rs_has_value = not pd.isna(df33[rs_brand].iloc[0]) and not pd.isna(df33[rs_model].iloc[0])
  562. gs_has_value = not pd.isna(df33[gs_brand].iloc[0]) and not pd.isna(df33[gs_model].iloc[0])
  563. if rs_has_value and gs_has_value:
  564. brand = rs_brand
  565. model = rs_model
  566. elif rs_has_value:
  567. brand = rs_brand
  568. model = rs_model
  569. elif gs_has_value:
  570. brand = gs_brand
  571. model = gs_model
  572. else:
  573. print("警告: 没有找到有效的品牌信息")
  574. brand = rs_brand
  575. model = rs_model
  576. #低速轴 取bearing_model
  577. elif 'low_speed'in str1:
  578. brand = 'bearing' + '_brand'
  579. model = 'bearing' + '_model'
  580. else:
  581. print("警告: 没有找到有效的轴承信息")
  582. print(brand)
  583. _brand = df33[brand].iloc[0]
  584. _model = df33[model].iloc[0]
  585. print(_brand)
  586. print(_model)
  587. # # 4、从表'unit_dict_brand_model'中通过'_brand'、'_model'查找部件的参数信息
  588. # Engine4 = create_engine('mysql+pymysql://admin:admin123456@106.120.102.238:16306/energy_show')
  589. # df_sql4 = f"SELECT * FROM unit_dict_brand_model where manufacture = %s AND model_number = %s"
  590. # params = [(_brand, _model)]
  591. # df4 = pd.read_sql(df_sql4, Engine4, params=params)
  592. # if 'bearing' in parts:
  593. # n_rolls = df4['rolls_number'].iloc[0]
  594. # d_rolls = df4['rolls_diameter'].iloc[0]
  595. # D_diameter = df4['circle_diameter'].iloc[0]
  596. # theta_deg = df4['theta_deg'].iloc[0]
  597. # result = {
  598. # "type":'bearing',
  599. # "n_rolls":round(n_rolls, 2),
  600. # "d_rolls":round(d_rolls, 2),
  601. # "D_diameter":round(D_diameter, 2),
  602. # "theta_deg":round(theta_deg, 2),
  603. # }
  604. # # result = json.dumps(result, ensure_ascii=False)
  605. # return result
  606. # 4、从表'unit_dict_brand_model'中通过'_brand'、'_model'查找部件的参数信息
  607. Engine4 = create_engine('mysql+pymysql://admin:admin123456@192.168.50.233:3306/energy_show')
  608. # Engine4 = create_engine('mysql+pymysql://admin:admin123456@106.120.102.238:16306/energy_show')
  609. df_sql4 = f"SELECT * FROM unit_dict_brand_model where manufacture = %s AND model_number = %s"
  610. params = [(_brand, _model)]
  611. df4 = pd.read_sql(df_sql4, Engine4, params=params)
  612. n_rolls = df4['rolls_number'].iloc[0]
  613. d_rolls = df4['rolls_diameter'].iloc[0]
  614. D_diameter = df4['circle_diameter'].iloc[0]
  615. theta_deg = df4['theta_deg'].iloc[0]
  616. result = {
  617. "type":'bearing',
  618. "n_rolls":round(n_rolls, 2),
  619. "d_rolls":round(d_rolls, 2),
  620. "D_diameter":round(D_diameter, 2),
  621. "theta_deg":round(theta_deg, 2),
  622. }
  623. # result = json.dumps(result, ensure_ascii=False)
  624. return result
  625. def calculate_bearing_frequencies(self, n, d, D, theta_deg, rpm):
  626. """
  627. 计算轴承各部件特征频率
  628. 参数:
  629. n (int): 滚动体数量
  630. d (float): 滚动体直径(单位:mm)
  631. D (float): 轴承节圆直径(滚动体中心圆直径,单位:mm)
  632. theta_deg (float): 接触角(单位:度)
  633. rpm (float): 转速(转/分钟)
  634. 返回:
  635. dict: 包含各特征频率的字典(单位:Hz)
  636. """
  637. # 转换角度为弧度
  638. theta = math.radians(theta_deg)
  639. # 转换直径单位为米(保持单位一致性,实际计算中比值抵消单位影响)
  640. # 注意:由于公式中使用的是比值,单位可以保持mm不需要转换
  641. ratio = d / D
  642. # 基础频率计算(转/秒)
  643. f_r = rpm / 60.0
  644. # 计算各特征频率
  645. BPFI = n / 2 * (1 + ratio * math.cos(theta)) * f_r # 内圈故障频率
  646. BPFO = n / 2 * (1 - ratio * math.cos(theta)) * f_r # 外圈故障频率
  647. BSF = (D / (2 * d)) * (1 - (ratio ** 2) * (math.cos(theta) ** 2)) * f_r # 滚动体故障频率
  648. FTF = 0.5 * (1 - ratio * math.cos(theta)) * f_r # 保持架故障频率
  649. return {
  650. "BPFI": round(BPFI, 2),
  651. "BPFO": round(BPFO, 2),
  652. "BSF": round(BSF, 2),
  653. "FTF": round(FTF, 2),
  654. }
  655. if __name__ == "__main__":
  656. # table_name = "SKF001_wave"
  657. # ids = [67803,67804]
  658. # fmin, fmax = None, None
  659. cms = CMSAnalyst(fmin, fmax,table_name,ids)
  660. time_domain = cms.time_domain()
  661. # print(time_domain)
  662. '''
  663. trace = go.Scatter(
  664. x=time_domain['x'],
  665. y=time_domain['y'],
  666. mode="lines",
  667. name=time_domain['title'],
  668. )
  669. layout = go.Layout(
  670. title= time_domain['title'],
  671. xaxis=dict(title=time_domain["xaxis"]),
  672. yaxis=dict(title=time_domain["yaxis"]),
  673. )
  674. fig = go.Figure(data=[trace], layout=layout)
  675. fig.show()
  676. '''
  677. # data_path_lsit = ["test1.csv", "test2.csv"]
  678. # trend_analysis_test = cms.trend_analysis(data_path_lsit, fmin, fmax)
  679. # print(trend_analysis_test)