data_clean.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. import os
  2. import json
  3. import pandas as pd
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. from typing import Tuple, List
  7. import warnings
  8. import sys
  9. import frequency_filter as ff
  10. from datetime import datetime
  11. warnings.filterwarnings("ignore", category=FutureWarning)
  12. plt.rcParams['font.sans-serif'] = ['SimHei']
  13. plt.rcParams['axes.unicode_minus'] = False
  14. def result_main():
  15. python_interpreter_path = sys.executable
  16. project_directory = os.path.dirname(python_interpreter_path)
  17. data_folder = os.path.join(project_directory, 'data')
  18. if not os.path.exists(data_folder):
  19. os.makedirs(data_folder)
  20. csv_file_path = os.path.join(data_folder, 'history_data.csv')
  21. if not os.path.exists(csv_file_path):
  22. pd.DataFrame(columns=['时间', '场站', '风机编号', '采样频率',
  23. '叶片1角度偏差', '叶片2角度偏差', '叶片3角度偏差', '相对角度偏差',
  24. '叶片1净空值', '叶片2净空值', '叶片3净空值',
  25. '叶片1扭转', '叶片2扭转', '叶片3扭转', '平均扭转',
  26. '振动幅值', '振动主频']).to_csv(csv_file_path, index=False)
  27. return csv_file_path
  28. def delete_data(name):
  29. python_interpreter_path = sys.executable
  30. project_directory = os.path.dirname(python_interpreter_path)
  31. data_folder = os.path.join(project_directory, 'data')
  32. csv_file_path = os.path.join(data_folder, 'history_data.csv')
  33. df = pd.read_csv(csv_file_path)
  34. condition = ((df['时间'].astype(str).str.contains(name[0])) &
  35. (df['场站'].astype(str).str.contains(name[1])) &
  36. (df['风机编号'].astype(str).str.contains(name[2])))
  37. df = df[~condition]
  38. df.to_csv(csv_file_path, index=False)
  39. return csv_file_path
  40. def history_data(name):
  41. time_code = name[0]
  42. wind_name = name[1]
  43. turbine_code = name[2]
  44. python_interpreter_path = sys.executable
  45. project_directory = os.path.dirname(python_interpreter_path)
  46. data_folder = os.path.join(project_directory, 'data')
  47. time_code_cleaned = time_code.replace("-", "").replace(":", "").replace(" ", "")
  48. json_filename = f"{wind_name}_{turbine_code}_{time_code_cleaned}.json"
  49. json_file_path = os.path.join(data_folder, json_filename)
  50. if not os.path.exists(json_file_path):
  51. raise ValueError("文件不存在")
  52. with open(json_file_path, 'r') as f:
  53. data = json.load(f)
  54. return data
  55. def data_analyse(path: List[str]):
  56. locate_file = path[0]
  57. measure_file = path[1]
  58. noise_reduction = 0.000001
  59. min_difference = 1.5
  60. angle_cone = float(path[2])
  61. axial_inclination = float(path[3])
  62. return_list = []
  63. wind_name, turbine_code, time_code, sampling_fq, angle_nan, angle_cen = find_param(locate_file)
  64. wind_name_1, turbine_code_1, time_code_1, sampling_fq_1, angle_tip, angle_root = find_param(measure_file)
  65. sampling_fq_1 = sampling_fq_1 * 1000
  66. sampling_fq = sampling_fq * 1000
  67. data_nan, data_cen = process_data(locate_file)
  68. data_tip, data_root = process_data(measure_file)
  69. start_tip, end_tip, filtered_data_tip = cycle_calculate(data_tip, noise_reduction, min_difference)
  70. start_root, end_root, filtered_data_root = cycle_calculate(data_root, noise_reduction, min_difference)
  71. start_nan, end_nan, filtered_data_nan = cycle_calculate(data_nan, noise_reduction, min_difference)
  72. filtered_data_cen = tower_filter(data_cen, noise_reduction)
  73. dist_cen = np.mean(filtered_data_cen.iloc[:, 1].tolist())
  74. filtered_data_cen.iloc[:, 1] = filtered_data_cen.iloc[:, 1] * np.cos(np.deg2rad(angle_cen))
  75. if end_tip.iloc[0, 0] < start_root.iloc[0, 0]:
  76. start_tip = start_tip.drop(start_tip.index[0])
  77. end_tip = end_tip.drop(end_tip.index[0])
  78. if start_root.iloc[0, 0] < start_tip.iloc[0, 0] < end_tip.iloc[0, 0] < end_root.iloc[0, 0]:
  79. pass
  80. else:
  81. raise ValueError("The elements are not in the expected order.")
  82. tower_dist_tip = ff.tower_cal(filtered_data_tip, start_tip, end_tip, sampling_fq_1)
  83. tower_dist_root = ff.tower_cal(filtered_data_root, start_root, end_root, sampling_fq_1)
  84. tower_dist_nan = ff.tower_cal(filtered_data_nan, start_nan, end_nan, sampling_fq)
  85. lowpass_data, fft_x, fft_y, tower_freq, tower_max = ff.process_fft(filtered_data_cen, sampling_fq)
  86. result_line_tip, result_scatter_tip, border_rows_tip, cycle_len_tip, min_tip \
  87. = data_normalize(filtered_data_tip, start_tip, end_tip)
  88. result_line_root, result_scatter_root, border_rows_root, cycle_len_root, min_root \
  89. = data_normalize(filtered_data_root, start_root, end_root)
  90. result_line_nan, result_scatter_nan, border_rows_nan, cycle_len_nan, min_nan \
  91. = data_normalize(filtered_data_nan, start_nan, end_nan)
  92. result_avg_tip, result_diff_tip = blade_shape(result_line_tip)
  93. result_avg_root, result_diff_root = blade_shape(result_line_root)
  94. border_rows_tip_new, angle_tip_new = coordinate_normalize(border_rows_tip, angle_tip)
  95. border_rows_nan_new, angle_nan_new = coordinate_normalize(border_rows_nan, angle_nan)
  96. tip_r = radius_cal(border_rows_tip_new, angle_tip_new, dist_cen, angle_cen, axial_inclination, angle_cone)
  97. root_r = radius_cal(border_rows_root, angle_root, dist_cen, angle_cen, axial_inclination, angle_cone)
  98. nan_r = radius_cal(border_rows_nan_new, angle_nan_new, dist_cen, angle_cen, axial_inclination, angle_cone)
  99. pitch_angle_tip, aero_dist_tip, v_speed_tip, cen_blade_tip = (
  100. blade_angle_aero_dist(border_rows_tip, tip_r, cycle_len_tip, tower_dist_tip, angle_tip_new))
  101. pitch_angle_root, aero_dist_root, v_speed_root, cen_blade_root = (
  102. blade_angle_aero_dist(border_rows_root, root_r, cycle_len_root, tower_dist_root, angle_root))
  103. pitch_angle_nan, aero_dist_nan, v_speed_nan, cen_blade_nan = (
  104. blade_angle_aero_dist(border_rows_nan_new, nan_r, cycle_len_nan, tower_dist_nan, angle_nan_new))
  105. cen_blade_tip_array = np.array(cen_blade_tip)
  106. cen_blade_nan_array = np.array(cen_blade_nan)
  107. min_tip_array = np.array(min_tip)
  108. min_nan_array = np.array(min_nan)
  109. abs_diff = np.abs(cen_blade_tip_array - min_tip_array)
  110. abs_diff_nan = np.abs(cen_blade_nan_array - min_nan_array)
  111. blade_dist_tip = abs_diff * np.cos(np.deg2rad(angle_tip_new))
  112. blade_dist_nan = abs_diff_nan * np.cos(np.deg2rad(angle_nan_new))
  113. blade_dist_tip.tolist()
  114. blade_dist_nan.tolist()
  115. dist_distribute_nan = blade_dist_distribute_cal(filtered_data_nan, start_nan, end_nan,
  116. tower_dist_nan, angle_nan_new, blade_dist_nan)
  117. dist_distribute = [df.round(5) for df in dist_distribute_nan]
  118. min_values = []
  119. min_keys = []
  120. max_values = []
  121. max_keys = []
  122. mean_values = []
  123. for df in dist_distribute:
  124. second_col_min = df[df.columns[1]].min()
  125. second_col_max = df[df.columns[1]].max()
  126. min_row = df[df[df.columns[1]] == second_col_min]
  127. max_row = df[df[df.columns[1]] == second_col_max]
  128. min_values.append(round(second_col_min, 2))
  129. min_keys.append(round(min_row.iloc[0][df.columns[0]], 2))
  130. max_values.append(round(second_col_max, 2))
  131. max_keys.append(round(max_row.iloc[0][df.columns[0]], 2))
  132. for i in range(3):
  133. mean_values.append(round((max_values[i] + min_values[i]) / 2, 2))
  134. for df in result_line_tip:
  135. first_column = df.iloc[:, 0]
  136. sec_column = df.iloc[:, 1]
  137. df.iloc[:, 0] = first_column * v_speed_tip
  138. df.iloc[:, 1] = sec_column * np.cos(np.deg2rad(angle_tip_new))
  139. for df in result_line_root:
  140. first_column = df.iloc[:, 0]
  141. sec_column = df.iloc[:, 1]
  142. df.iloc[:, 0] = first_column * v_speed_root
  143. df.iloc[:, 1] = sec_column * np.cos(np.deg2rad(angle_root))
  144. avg_tip = result_avg_tip.iloc[:, 0]
  145. result_avg_tip.iloc[:, 0] = avg_tip * v_speed_tip
  146. avg_root = result_avg_root.iloc[:, 0]
  147. result_avg_root.iloc[:, 0] = avg_root * v_speed_root
  148. twist_1 = round(np.abs(pitch_angle_root[0] - pitch_angle_tip[0]), 2)
  149. twist_2 = round(np.abs(pitch_angle_root[1] - pitch_angle_tip[1]), 2)
  150. twist_3 = round(np.abs(pitch_angle_root[2] - pitch_angle_tip[2]), 2)
  151. twist_avg = round((twist_1 + twist_2 + twist_3) / 3, 2)
  152. sampling_num = int(0.015 * sampling_fq_1)
  153. data_tip.iloc[:, 0] = data_tip.iloc[:, 0] / 5000000
  154. data_root.iloc[:, 0] = data_root.iloc[:, 0] / 5000000
  155. lowpass_data.iloc[:, 0] = lowpass_data.iloc[:, 0] / 5000000
  156. return_list.append(str(time_code))
  157. return_list.append(str(wind_name))
  158. return_list.append(str(turbine_code))
  159. return_list.append(sampling_fq_1)
  160. return_list.append(pitch_angle_root[0])
  161. return_list.append(pitch_angle_root[1])
  162. return_list.append(pitch_angle_root[2])
  163. return_list.append(pitch_angle_root[3])
  164. return_list.append(mean_values[0])
  165. return_list.append(mean_values[1])
  166. return_list.append(mean_values[2])
  167. return_list.append(twist_1)
  168. return_list.append(twist_2)
  169. return_list.append(twist_3)
  170. return_list.append(twist_avg)
  171. return_list.append(tower_max)
  172. return_list.append(tower_freq)
  173. df_new_row = pd.DataFrame([return_list],
  174. columns=['时间', '场站', '风机编号', '采样频率',
  175. '叶片1角度偏差', '叶片2角度偏差', '叶片3角度偏差', '相对角度偏差',
  176. '叶片1净空值', '叶片2净空值', '叶片3净空值',
  177. '叶片1扭转', '叶片2扭转', '叶片3扭转', '平均扭转',
  178. '振动幅值', '振动主频'])
  179. json_output = {
  180. 'original_plot': {
  181. 'blade_tip': {
  182. 'xdata': data_tip.iloc[:, 0].tolist()[::sampling_num],
  183. 'ydata': data_tip.iloc[:, 1].tolist()[::sampling_num]
  184. },
  185. 'blade_root': {
  186. 'xdata': data_root.iloc[:, 0].tolist()[::sampling_num],
  187. 'ydata': data_root.iloc[:, 1].tolist()[::sampling_num]
  188. }
  189. },
  190. 'fft_plot': {
  191. 'lowpass': {
  192. 'xdata': lowpass_data['time'].tolist()[::sampling_num],
  193. 'ydata': lowpass_data['distance_filtered'].tolist()[::sampling_num],
  194. 'xmax': max(lowpass_data['time'].tolist()),
  195. 'xmin': min(lowpass_data['time'].tolist()),
  196. 'ymax': max(lowpass_data['distance_filtered'].tolist()) + 0.02,
  197. 'ymin': min(lowpass_data['distance_filtered'].tolist()) - 0.02
  198. },
  199. 'fft': {
  200. 'xdata': fft_x,
  201. 'ydata': fft_y,
  202. 'xmax': max(fft_x),
  203. 'xmin': min(fft_x),
  204. 'ymax': max(fft_y) + 0.02,
  205. 'ymin': 0
  206. }
  207. },
  208. 'blade_tip': {
  209. 'first_blade': {
  210. 'xdata': result_line_tip[0].iloc[:, 0].tolist(),
  211. 'ydata': result_line_tip[0].iloc[:, 1].tolist()
  212. },
  213. 'second_blade': {
  214. 'xdata': result_line_tip[1].iloc[:, 0].tolist(),
  215. 'ydata': result_line_tip[1].iloc[:, 1].tolist()
  216. },
  217. 'third_blade': {
  218. 'xdata': result_line_tip[2].iloc[:, 0].tolist(),
  219. 'ydata': result_line_tip[2].iloc[:, 1].tolist()
  220. },
  221. 'avg_blade': {
  222. 'xdata': result_avg_tip.iloc[:, 0].tolist(),
  223. 'ydata': result_avg_tip.iloc[:, 1].tolist()
  224. }
  225. },
  226. 'blade_root': {
  227. 'first_blade': {
  228. 'xdata': result_line_root[0].iloc[:, 0].tolist(),
  229. 'ydata': result_line_root[0].iloc[:, 1].tolist()
  230. },
  231. 'second_blade': {
  232. 'xdata': result_line_root[1].iloc[:, 0].tolist(),
  233. 'ydata': result_line_root[1].iloc[:, 1].tolist()
  234. },
  235. 'third_blade': {
  236. 'xdata': result_line_root[2].iloc[:, 0].tolist(),
  237. 'ydata': result_line_root[2].iloc[:, 1].tolist()
  238. },
  239. 'avg_blade': {
  240. 'xdata': result_avg_root.iloc[:, 0].tolist(),
  241. 'ydata': result_avg_root.iloc[:, 1].tolist()
  242. }
  243. },
  244. 'dist_distribution': {
  245. 'first_blade': {
  246. 'xdata': dist_distribute[0].iloc[:, 0].tolist(),
  247. 'ydata': dist_distribute[0].iloc[:, 1].tolist()
  248. },
  249. 'second_blade': {
  250. 'xdata': dist_distribute[1].iloc[:, 0].tolist(),
  251. 'ydata': dist_distribute[1].iloc[:, 1].tolist()
  252. },
  253. 'third_blade': {
  254. 'xdata': dist_distribute[2].iloc[:, 0].tolist(),
  255. 'ydata': dist_distribute[2].iloc[:, 1].tolist()
  256. }
  257. },
  258. 'analyse_table': {
  259. 'pitch_angle_diff': {
  260. 'blade_1': pitch_angle_root[0],
  261. 'blade_2': pitch_angle_root[1],
  262. 'blade_3': pitch_angle_root[2],
  263. 'blade_relate': pitch_angle_root[3]
  264. },
  265. 'aero_dist': {
  266. 'first_blade': {
  267. 'x_min': min_keys[0],
  268. 'y_min': min_values[0],
  269. 'x_max': max_keys[0],
  270. 'y_max': max_values[0],
  271. 'y_diff': np.abs(max_values[0] - min_values[0]),
  272. 'y_ava': mean_values[0]
  273. },
  274. 'second_blade': {
  275. 'x_min': min_keys[1],
  276. 'y_min': min_values[1],
  277. 'x_max': max_keys[1],
  278. 'y_max': max_values[1],
  279. 'y_diff': np.abs(max_values[1] - min_values[1]),
  280. 'y_ava': mean_values[1]
  281. },
  282. 'third_blade': {
  283. 'x_min': min_keys[2],
  284. 'y_min': min_values[2],
  285. 'x_max': max_keys[2],
  286. 'y_max': max_values[2],
  287. 'y_diff': np.abs(max_values[2] - min_values[2]),
  288. 'y_ava': mean_values[2]
  289. }
  290. },
  291. 'blade_twist': {
  292. 'blade_1': twist_1,
  293. 'blade_2': twist_2,
  294. 'blade_3': twist_3,
  295. 'blade_avg': twist_avg
  296. },
  297. 'tower_vibration': {
  298. 'max_vibration': tower_max,
  299. 'main_vibration_freq': tower_freq
  300. }
  301. }
  302. }
  303. python_interpreter_path = sys.executable
  304. project_directory = os.path.dirname(python_interpreter_path)
  305. data_folder = os.path.join(project_directory, 'data')
  306. if not os.path.exists(data_folder):
  307. os.makedirs(data_folder)
  308. csv_file_path = os.path.join(data_folder, 'history_data.csv')
  309. if not os.path.exists(csv_file_path):
  310. pd.DataFrame(columns=['时间', '场站', '风机编号', '采样频率',
  311. '叶片1角度偏差', '叶片2角度偏差', '叶片3角度偏差', '相对角度偏差',
  312. '叶片1净空值', '叶片2净空值', '叶片3净空值',
  313. '叶片1扭转', '叶片2扭转', '叶片3扭转', '平均扭转',
  314. '振动幅值', '振动主频']).to_csv(csv_file_path, index=False)
  315. df_new_row.to_csv(csv_file_path, mode='a', header=False, index=False)
  316. time_code_cleaned = time_code.replace("-", "").replace(":", "").replace(" ", "")
  317. json_filename = f"{wind_name}_{turbine_code}_{time_code_cleaned}.json"
  318. json_file_path = os.path.join(data_folder, json_filename)
  319. with open(json_file_path, 'w') as json_file:
  320. json.dump(json_output, json_file, indent=4)
  321. return json_output
  322. def process_data(file_path):
  323. data = pd.read_csv(file_path, usecols=[1, 3, 8], header=None, engine='c')
  324. data = data.head(int(len(data) * 0.95))
  325. max_value = data.iloc[:, 0].max()
  326. max_index = data.iloc[:, 0].idxmax()
  327. min_index = data.iloc[:, 0].idxmin()
  328. if min_index == max_index + 1:
  329. data.iloc[min_index:, 0] += max_value
  330. last_time = data.iloc[-1, 0]
  331. first_time = data.iloc[0, 0]
  332. data = data[data.iloc[:, 0] >= first_time]
  333. data = data[data.iloc[:, 0] <= last_time]
  334. data.reset_index(drop=True, inplace=True)
  335. min_time = data.iloc[:, 0].min()
  336. data.iloc[:, 0] -= min_time
  337. data_1 = data.iloc[:, [0, 1]]
  338. data_2 = data.iloc[:, [0, 2]]
  339. data_1.columns = ['time', 'distance']
  340. data_2.columns = ['time', 'distance']
  341. return data_1, data_2
  342. def tower_filter(data_group: pd.DataFrame, noise_threshold: float):
  343. distance_counts = data_group['distance'].value_counts(normalize=True)
  344. noise_distance_threshold = distance_counts[distance_counts < noise_threshold].index
  345. noise_indices = data_group[data_group['distance'].isin(noise_distance_threshold)].index
  346. data_group.loc[noise_indices, 'distance'] = np.nan
  347. top_5_distances = distance_counts.head(5).index
  348. mean_values = data_group[data_group['distance'].isin(top_5_distances)]['distance'].mean()
  349. data_group.loc[(data_group['distance'] < mean_values - 20) | (
  350. data_group['distance'] > mean_values * 1.1), 'distance'] = np.nan
  351. data_group['distance'] = data_group['distance'].fillna(method='ffill')
  352. filtered_data = data_group
  353. return filtered_data
  354. def cycle_calculate(data_group: pd.DataFrame, noise_threshold: float, min_distance: float):
  355. distance_counts = data_group['distance'].value_counts(normalize=True)
  356. noise_distance_threshold = distance_counts[distance_counts < noise_threshold].index
  357. noise_indices = data_group[data_group['distance'].isin(noise_distance_threshold)].index
  358. data_group.loc[noise_indices, 'distance'] = np.nan
  359. top_5_distances = distance_counts.head(5).index
  360. mean_values = data_group[data_group['distance'].isin(top_5_distances)]['distance'].mean()
  361. data_group.loc[(data_group['distance'] < mean_values - 31) | (
  362. data_group['distance'] > mean_values * 1.1), 'distance'] = np.nan
  363. data_group['distance'] = data_group['distance'].fillna(method='ffill')
  364. filtered_data = data_group
  365. filtered_data['distance_diff'] = filtered_data['distance'].diff()
  366. large_diff_indices = filtered_data[filtered_data['distance_diff'] > min_distance].index
  367. small_diff_indices = filtered_data[filtered_data['distance_diff'] < -min_distance].index
  368. filtered_data = filtered_data.drop(columns=['distance_diff'])
  369. start_points = pd.DataFrame()
  370. end_points = pd.DataFrame()
  371. for idx in large_diff_indices:
  372. current_distance = filtered_data.loc[idx, 'distance']
  373. next_rows_large = filtered_data.loc[idx - 201: idx - 1]
  374. if next_rows_large['distance'].le(current_distance - min_distance).all():
  375. end_points = pd.concat([end_points, filtered_data.loc[[idx - 1]]])
  376. for idx in small_diff_indices:
  377. current_distance = filtered_data.loc[idx - 1, 'distance']
  378. next_rows_small = filtered_data.iloc[idx: idx + 201]
  379. if next_rows_small['distance'].le(current_distance - min_distance).all():
  380. start_points = pd.concat([start_points, filtered_data.loc[[idx]]])
  381. if end_points.iloc[0, 0] < start_points.iloc[0, 0]:
  382. end_points = end_points.drop(end_points.index[0])
  383. if end_points.iloc[-1, 0] < start_points.iloc[-1, 0]:
  384. start_points = start_points.drop(start_points.index[-1])
  385. else:
  386. pass
  387. return start_points, end_points, filtered_data
  388. def data_normalize(data_group: pd.DataFrame, start_points: pd.DataFrame, end_points: pd.DataFrame) \
  389. -> Tuple[List[pd.DataFrame], List[pd.DataFrame], List[pd.DataFrame], int, list]:
  390. combined_df_sorted = pd.concat([start_points, end_points]).sort_values(by='time')
  391. if combined_df_sorted.iloc[0].equals(end_points.iloc[0]):
  392. combined_df_sorted = combined_df_sorted.iloc[1:]
  393. if combined_df_sorted.iloc[-1].equals(start_points.iloc[-1]):
  394. combined_df_sorted = combined_df_sorted.iloc[:-1]
  395. combined_df_sorted.reset_index(drop=True, inplace=True)
  396. start_times = combined_df_sorted['time'].tolist()
  397. normalize_cycle = start_times[1] - start_times[0]
  398. full_cycle = int((start_times[2] - start_times[0]) * 3)
  399. turbines = [pd.DataFrame() for _ in range(3)]
  400. for i in range(0, len(start_times), 2):
  401. start_time = start_times[i]
  402. end_time = start_times[i + 1]
  403. segment = data_group[(data_group['time'] > start_time) & (data_group['time'] <= end_time)]
  404. if segment is None:
  405. pass
  406. else:
  407. ratio = (end_time - start_time) / normalize_cycle
  408. segment.loc[:, 'time'] = (segment['time'] - start_time) / ratio
  409. turbines[i % 3] = pd.concat([turbines[i % 3], segment])
  410. turbines_processed = []
  411. turbines_scattered = []
  412. min_list = []
  413. sd_time = [-1, -1]
  414. time_list = list(range(0, normalize_cycle, 9001))
  415. for turbine in turbines:
  416. turbine_sorted = turbine.sort_values(by='time').reset_index(drop=True)
  417. first_time = turbine_sorted['time'].iloc[0]
  418. bins = list(range(int(first_time), int(turbine_sorted['time'].max()), 9001))
  419. grouped = turbine_sorted.groupby(pd.cut(turbine_sorted['time'], bins=bins, right=False))
  420. processed_df = pd.DataFrame()
  421. scattered_df = pd.DataFrame()
  422. mean_points = []
  423. diff_points = []
  424. for _, group in grouped:
  425. quantile_5 = group['distance'].quantile(0.05)
  426. quantile_95 = group['distance'].quantile(0.95)
  427. filtered_group = group[(group['distance'] > quantile_5) & (group['distance'] < quantile_95)]
  428. mean_point = filtered_group['distance'].mean()
  429. mean_points.append(mean_point)
  430. for i in range(len(mean_points) - 1):
  431. diff = abs(mean_points[i + 1] - mean_points[i])
  432. diff_points.append(diff)
  433. start_index = int(len(diff_points) * 0.05)
  434. end_index = int(len(diff_points) * 0.95)
  435. subset1 = diff_points[start_index:end_index]
  436. sdr_diff = np.max(subset1) * 1.1
  437. min_list.append(min(mean_points))
  438. first_index = np.where(diff_points < sdr_diff)[0][0]
  439. last_index = np.where(diff_points < sdr_diff)[0][-1]
  440. for index, (bin, group) in enumerate(grouped):
  441. quantile_5 = group['distance'].quantile(0.05)
  442. quantile_95 = group['distance'].quantile(0.95)
  443. filtered_group = group[(group['distance'] > quantile_5) & (group['distance'] < quantile_95)]
  444. if first_index <= index < last_index:
  445. mid_point = filtered_group.mean()
  446. mid_point_df = pd.DataFrame([mid_point])
  447. mid_point_df.iloc[0, 0] = time_list[index]
  448. processed_df = pd.concat([processed_df, mid_point_df], ignore_index=True)
  449. scattered_df = pd.concat([scattered_df, filtered_group], ignore_index=True)
  450. else:
  451. pass
  452. min_time = processed_df['time'].min()
  453. max_time = processed_df['time'].max()
  454. if sd_time == [-1, -1]:
  455. sd_time = [min_time, max_time]
  456. elif sd_time[0] < min_time:
  457. sd_time[0] = min_time
  458. elif sd_time[1] > max_time:
  459. sd_time[1] = max_time
  460. turbines_processed.append(processed_df)
  461. turbines_scattered.append(scattered_df)
  462. border_rows = []
  463. for i, turbine in enumerate(turbines_processed):
  464. closest_index_0 = (turbine['time'] - sd_time[0]).abs().idxmin()
  465. turbine.at[closest_index_0, 'time'] = sd_time[0]
  466. sd_time_row_0 = turbine.loc[closest_index_0]
  467. closest_index_1 = (turbine['time'] - sd_time[1]).abs().idxmin()
  468. turbine.at[closest_index_1, 'time'] = sd_time[1]
  469. sd_time_row_1 = turbine.loc[closest_index_1]
  470. turbines_processed[i] = turbine.iloc[closest_index_0:closest_index_1 + 1].reset_index(drop=True)
  471. sd_time_rows_turbine = pd.concat([pd.DataFrame([sd_time_row_0]), pd.DataFrame([sd_time_row_1])]
  472. , ignore_index=True)
  473. border_rows.append(sd_time_rows_turbine)
  474. return turbines_processed, turbines_scattered, border_rows, full_cycle, min_list
  475. def blade_shape(turbines_processed: List[pd.DataFrame]):
  476. row_counts = [df.shape[0] for df in turbines_processed]
  477. num_rows = min(row_counts)
  478. turbine_avg = pd.DataFrame(index=range(num_rows), columns=['time', 'distance'])
  479. turbine_diff = [pd.DataFrame(index=range(num_rows), columns=['time', 'distance']) for _ in turbines_processed]
  480. for i in range(num_rows):
  481. distances = [df.loc[i, 'distance'] for df in turbines_processed]
  482. avg_distance = sum(distances) / len(distances)
  483. time_value = turbines_processed[0].loc[i, 'time']
  484. turbine_avg.loc[i, 'time'] = time_value
  485. turbine_avg.loc[i, 'distance'] = avg_distance
  486. for j in range(len(distances)):
  487. distances[j] = distances[j] - avg_distance
  488. turbine_diff[j].loc[i, 'time'] = time_value
  489. turbine_diff[j].loc[i, 'distance'] = distances[j]
  490. return turbine_avg, turbine_diff
  491. def coordinate_normalize(tip_border_rows: List[pd.DataFrame], tip_angle):
  492. tip_angle1 = np.deg2rad(tip_angle)
  493. tip_angle_list = []
  494. for turbine in tip_border_rows:
  495. tip_angle_cal0 = ((np.sin(tip_angle1) * turbine['distance'] - 0.07608) /
  496. (np.cos(tip_angle1) * turbine['distance']))
  497. tip_angle_cal = np.arctan(tip_angle_cal0)
  498. turbine['distance'] = (turbine['distance'] ** 2 + 0.0057881664 -
  499. 0.15216 * turbine['distance'] * np.sin(tip_angle1)) ** 0.5
  500. tip_angle_list.append(tip_angle_cal)
  501. tip_angle_new = float(np.mean(tip_angle_list))
  502. tip_angle_new1 = np.rad2deg(tip_angle_new)
  503. return tip_border_rows, tip_angle_new1
  504. def radius_cal(border_rows, meas_angle, cen_dist, cen_angle, angle_main, angle_rotate):
  505. aero_dist = (pd.concat([df['distance'] for df in border_rows]).mean())
  506. cen_x = np.cos(np.deg2rad(cen_angle)) * cen_dist
  507. cen_y = np.sin(np.deg2rad(cen_angle)) * cen_dist
  508. aero_x = np.cos(np.deg2rad(meas_angle)) * aero_dist
  509. aero_y = np.sin(np.deg2rad(meas_angle)) * aero_dist
  510. theta_4 = np.tan(np.pi - np.deg2rad(angle_main))
  511. theta_5 = np.tan(np.pi / 2 - np.deg2rad(angle_main) - np.deg2rad(angle_rotate))
  512. if theta_5 > 1000:
  513. radius = np.abs((cen_y - aero_y) - theta_4 * (cen_x - aero_x))
  514. else:
  515. radius = (np.abs((theta_4 * (cen_x - aero_x) - (cen_y - aero_y)) / (theta_4 - theta_5))
  516. * (1 + theta_5 ** 2) ** 0.5)
  517. return radius
  518. def blade_angle_aero_dist(border_rows: List[pd.DataFrame], radius: float, full_cycle: int,
  519. tower_dist: float, v_angle: float):
  520. v_speed = 2 * np.pi * radius / full_cycle
  521. pitch_angle_list = []
  522. aero_dist_list = []
  523. cen_blade = []
  524. for turbine in border_rows:
  525. diff_time = turbine.iloc[1, 0] - turbine.iloc[0, 0]
  526. diff_len = (turbine.iloc[1, 1] - turbine.iloc[0, 1]) * np.cos(np.deg2rad(v_angle))
  527. mean_col2 = (turbine.iloc[1, 1] + turbine.iloc[0, 1]) / 2
  528. aero_dist = abs(mean_col2 - tower_dist) * np.cos(np.deg2rad(v_angle))
  529. pitch_angle = np.degrees(np.arctan(diff_len / (diff_time * v_speed)))
  530. pitch_angle_list.append(pitch_angle)
  531. aero_dist_list.append(aero_dist)
  532. cen_blade.append(mean_col2)
  533. pitch_mean = np.mean(pitch_angle_list)
  534. pitch_angle_list = [angle - pitch_mean for angle in pitch_angle_list]
  535. pitch_angle_list.append(max(pitch_angle_list) - min(pitch_angle_list))
  536. aero_dist_list.append(np.mean(aero_dist_list))
  537. pitch_angle_list = [round(num, 2) for num in pitch_angle_list]
  538. aero_dist_list = [round(num, 2) for num in aero_dist_list]
  539. return pitch_angle_list, aero_dist_list, v_speed, cen_blade
  540. def find_param(path: str):
  541. path = path.replace('\\', '/')
  542. last_slash_index = path.rfind('/')
  543. result = path[last_slash_index + 1:]
  544. underscore_indices = []
  545. start = 0
  546. while True:
  547. index = result.find('_', start)
  548. if index == -1:
  549. break
  550. underscore_indices.append(index)
  551. start = index + 1
  552. wind_name = result[: underscore_indices[0]]
  553. turbine_code = result[underscore_indices[0] + 1: underscore_indices[1]]
  554. time_code = result[underscore_indices[1] + 1: underscore_indices[2]]
  555. sampling_fq = int(result[underscore_indices[2] + 1: underscore_indices[3]])
  556. tunnel_1 = float(result[underscore_indices[3] + 1: underscore_indices[4]])
  557. tunnel_2 = float(result[underscore_indices[4] + 1: -4])
  558. dt = datetime.strptime(time_code, "%Y%m%d%H%M%S")
  559. standard_time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
  560. return wind_name, turbine_code, standard_time_str, sampling_fq, tunnel_1, tunnel_2
  561. def blade_dist_distribute_cal(data_group: pd.DataFrame, start_points: pd.DataFrame, end_points: pd.DataFrame,
  562. tower_dist: float, v_angle: float, blade_cen_dist: list):
  563. combined_df_sorted = pd.concat([start_points, end_points]).sort_values(by='time')
  564. if combined_df_sorted.iloc[0].equals(end_points.iloc[0]):
  565. combined_df_sorted = combined_df_sorted.iloc[1:]
  566. if combined_df_sorted.iloc[-1].equals(start_points.iloc[-1]):
  567. combined_df_sorted = combined_df_sorted.iloc[:-1]
  568. combined_df_sorted.reset_index(drop=True, inplace=True)
  569. start_times = combined_df_sorted['time'].tolist()
  570. normalize_cycle = start_times[1] - start_times[0]
  571. tower_clearance = [pd.DataFrame() for _ in range(3)]
  572. for i in range(0, len(start_times) - 2, 2):
  573. start_time = start_times[i]
  574. end_time = start_times[i + 1]
  575. segment = data_group[(data_group['time'] > start_time) & (data_group['time'] <= end_time)]
  576. min_distance = segment['distance'].min()
  577. clearance = np.abs(tower_dist - min_distance - blade_cen_dist[i % 3]) * np.cos(np.deg2rad(v_angle))
  578. r_speed = round(60 / ((start_times[i + 2] - start_times[i]) * 3 / 5000000), 2)
  579. ratio = (end_time - start_time) / normalize_cycle
  580. segment.loc[:, 'time'] = (segment['time'] - start_time) / ratio
  581. new_df = pd.DataFrame({
  582. 'r_speed': [r_speed],
  583. 'clearance': [clearance]
  584. })
  585. tower_clearance[i % 3] = pd.concat([tower_clearance[i % 3], new_df])
  586. tower_clearance = [df.sort_values(by='r_speed') for df in tower_clearance]
  587. return tower_clearance