temperatureEnvironmentAnalyst.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import os
  2. import numpy as np
  3. import pandas as pd
  4. import plotly.graph_objects as go
  5. from algorithmContract.confBusiness import *
  6. from algorithmContract.contract import Contract
  7. from behavior.analystWithGoodBadLimitPoint import AnalystWithGoodBadLimitPoint
  8. from geopy.distance import geodesic
  9. from plotly.subplots import make_subplots
  10. class TemperatureEnvironmentAnalyst(AnalystWithGoodBadLimitPoint):
  11. """
  12. 风电机组大部件温升分析
  13. """
  14. def typeAnalyst(self):
  15. return "temperature_environment"
  16. def turbinesAnalysis(self, outputAnalysisDir, conf: Contract, turbineCodes):
  17. dictionary = self.processTurbineData(turbineCodes, conf, [
  18. Field_DeviceCode, Field_Time,Field_EnvTemp, Field_WindSpeed, Field_ActiverPower])
  19. dataFrameOfTurbines = self.userDataFrame(
  20. dictionary, conf.dataContract.configAnalysis, self)
  21. # 检查所需列是否存在
  22. required_columns = {Field_CodeOfTurbine,Field_EnvTemp}
  23. if not required_columns.issubset(dataFrameOfTurbines.columns):
  24. raise ValueError(f"DataFrame缺少必要的列。需要的列有: {required_columns}")
  25. # 环境温度分析
  26. turbineEnvTempData = dataFrameOfTurbines.groupby(Field_CodeOfTurbine).agg(
  27. {Field_EnvTemp: 'median'})
  28. turbineEnvTempData = turbineEnvTempData.reset_index()
  29. mergeData = self.mergeData(self.turbineInfo, turbineEnvTempData)
  30. return self.draw(mergeData, outputAnalysisDir, conf)
  31. def mergeData(self, turbineInfos: pd.DataFrame, turbineEnvTempData):
  32. """
  33. 将每台机组的环境温度均值数据与机组信息,按机组合并
  34. 参数:
  35. turbineInfos (pandas.DataFrame): 机组信息数据
  36. turbineEnvTempData (pandas.DataFrame): 每台机组的环境温度均值数据
  37. 返回:
  38. pandas.DataFrame: 每台机组的环境温度均值数据与机组信息合并数据
  39. """
  40. """
  41. 合并类型how的选项包括:
  42. 'inner': 内连接,只保留两个DataFrame中都有的键的行。
  43. 'outer': 外连接,保留两个DataFrame中任一或两者都有的键的行。
  44. 'left': 左连接,保留左边DataFrame的所有键,以及右边DataFrame中匹配的键的行。
  45. 'right': 右连接,保留右边DataFrame的所有键,以及左边DataFrame中匹配的键的行。
  46. """
  47. # turbineInfos[fieldTurbineName]=turbineInfos[fieldTurbineName].astype(str).apply(confData.add_W_if_starts_with_digit)
  48. # turbineEnvTempData[Field_NameOfTurbine] = turbineEnvTempData[Field_NameOfTurbine].astype(
  49. # str)
  50. tempDataFrame = pd.merge(turbineInfos, turbineEnvTempData, on=[
  51. Field_CodeOfTurbine], how='inner')
  52. # 保留指定字段,例如 'Key' 和 'Value1'
  53. mergeDataFrame = tempDataFrame[[Field_CodeOfTurbine, Field_NameOfTurbine, Field_Latitude,Field_Longitude, Field_EnvTemp]]
  54. return mergeDataFrame
  55. # 定义查找给定半径内点的函数
  56. def find_points_within_radius(self, data, center, field_temperature_env, radius):
  57. points_within_radius = []
  58. for index, row in data.iterrows():
  59. distance = geodesic(
  60. (center[2], center[1]), (row[Field_Latitude], row[Field_Longitude])).meters
  61. if distance <= radius:
  62. points_within_radius.append(
  63. (row[Field_NameOfTurbine], row[field_temperature_env]))
  64. return points_within_radius
  65. fieldTemperatureDiff = "temperature_diff"
  66. def draw(self, dataFrame: pd.DataFrame, outputAnalysisDir, conf: Contract, charset=charset_unify):
  67. # 处理数据
  68. dataFrame['new'] = dataFrame.loc[:, [Field_NameOfTurbine,
  69. Field_Longitude, Field_Latitude, Field_EnvTemp]].apply(tuple, axis=1)
  70. coordinates = dataFrame['new'].tolist()
  71. # df = pd.DataFrame(coordinates, columns=[Field_NameOfTurbine, Field_Longitude, Field_Latitude, confData.field_env_temp])
  72. # 查找半径内的点
  73. points_within_radius = {coord: self.find_points_within_radius(
  74. dataFrame, coord, Field_EnvTemp, self.turbineModelInfo[Field_RotorDiameter].iloc[0]*10) for coord in coordinates}
  75. res = []
  76. for center, nearby_points in points_within_radius.items():
  77. current_temp = dataFrame[dataFrame[Field_NameOfTurbine]
  78. == center[0]][Field_EnvTemp].iloc[0]
  79. target_tuple = (center[0], current_temp)
  80. if target_tuple in nearby_points:
  81. nearby_points.remove(target_tuple)
  82. median_temp = np.median(
  83. [i[1] for i in nearby_points]) if nearby_points else current_temp
  84. res.append((center[0], nearby_points, median_temp, current_temp))
  85. res = pd.DataFrame(
  86. res, columns=[Field_NameOfTurbine, '周边机组', '周边机组温度', '当前机组温度'])
  87. res[self.fieldTemperatureDiff] = res['当前机组温度'] - res['周边机组温度']
  88. # 使用plotly进行数据可视化
  89. fig1 = make_subplots(rows=1, cols=1)
  90. # 温度差异条形图
  91. fig1.add_trace(
  92. go.Bar(x=res[Field_NameOfTurbine],
  93. y=res[self.fieldTemperatureDiff], marker_color='dodgerblue'),
  94. row=1, col=1
  95. )
  96. fig1.update_layout(
  97. title={'text': f'温度偏差-{self.turbineModelInfo[Field_MachineTypeCode].iloc[0]}', 'x': 0.5},
  98. xaxis_title='机组名称',
  99. yaxis_title='温度偏差',
  100. shapes=[
  101. {'type': 'line', 'x0': 0, 'x1': 1, 'xref': 'paper', 'y0': 5,
  102. 'y1': 5, 'line': {'color': 'red', 'dash': 'dot'}},
  103. {'type': 'line', 'x0': 0, 'x1': 1, 'xref': 'paper', 'y0': -
  104. 5, 'y1': -5, 'line': {'color': 'red', 'dash': 'dot'}}
  105. ],
  106. xaxis=dict(tickangle=-45) # 设置x轴刻度旋转角度为45度
  107. )
  108. result_rows = []
  109. # 保存图像
  110. pngFileName = '{}环境温差Bias.png'.format(
  111. self.powerFarmInfo[Field_PowerFarmName].iloc[0])
  112. pngFilePath = os.path.join(outputAnalysisDir, pngFileName)
  113. fig1.write_image(pngFilePath, scale=3)
  114. # 保存HTML
  115. htmlFileName = '{}环境温差Bias.html'.format(
  116. self.powerFarmInfo[Field_PowerFarmName].iloc[0])
  117. htmlFilePath = os.path.join(outputAnalysisDir, htmlFileName)
  118. fig1.write_html(htmlFilePath)
  119. result_rows.append({
  120. Field_Return_TypeAnalyst: self.typeAnalyst(),
  121. Field_PowerFarmCode: conf.dataContract.dataFilter.powerFarmID,
  122. Field_Return_BatchCode: conf.dataContract.dataFilter.dataBatchNum,
  123. Field_CodeOfTurbine: Const_Output_Total,
  124. Field_Return_FilePath: pngFilePath,
  125. Field_Return_IsSaveDatabase: False
  126. })
  127. result_rows.append({
  128. Field_Return_TypeAnalyst: self.typeAnalyst(),
  129. Field_PowerFarmCode: conf.dataContract.dataFilter.powerFarmID,
  130. Field_Return_BatchCode: conf.dataContract.dataFilter.dataBatchNum,
  131. Field_CodeOfTurbine: Const_Output_Total,
  132. Field_Return_FilePath: htmlFilePath,
  133. Field_Return_IsSaveDatabase: True
  134. })
  135. # 环境温度中位数条形图
  136. fig2 = make_subplots(rows=1, cols=1)
  137. fig2.add_trace(
  138. go.Bar(x=res[Field_NameOfTurbine],
  139. y=res['当前机组温度'], marker_color='dodgerblue'),
  140. row=1, col=1
  141. )
  142. fig2.update_layout(
  143. title={'text': f'平均温度-{self.turbineModelInfo[Field_MachineTypeCode].iloc[0]}', 'x': 0.5},
  144. xaxis_title='机组名称',
  145. yaxis_title=' 温度',
  146. xaxis=dict(tickangle=-45) # 为x轴也设置旋转角度
  147. )
  148. # 保存图像
  149. pngFileName = '{}环境温度中位数.png'.format(
  150. self.powerFarmInfo[Field_PowerFarmName].iloc[0])
  151. pngFilePath = os.path.join(outputAnalysisDir, pngFileName)
  152. fig2.write_image(pngFilePath, scale=3)
  153. # 保存HTML
  154. htmlFileName = '{}环境温度中位数.html'.format(
  155. self.powerFarmInfo[Field_PowerFarmName].iloc[0])
  156. htmlFilePath = os.path.join(outputAnalysisDir, htmlFileName)
  157. fig2.write_html(htmlFilePath)
  158. result_rows.append({
  159. Field_Return_TypeAnalyst: self.typeAnalyst(),
  160. Field_PowerFarmCode: conf.dataContract.dataFilter.powerFarmID,
  161. Field_Return_BatchCode: conf.dataContract.dataFilter.dataBatchNum,
  162. Field_CodeOfTurbine: Const_Output_Total,
  163. Field_Return_FilePath: pngFilePath,
  164. Field_Return_IsSaveDatabase: False
  165. })
  166. result_rows.append({
  167. Field_Return_TypeAnalyst: self.typeAnalyst(),
  168. Field_PowerFarmCode: conf.dataContract.dataFilter.powerFarmID,
  169. Field_Return_BatchCode: conf.dataContract.dataFilter.dataBatchNum,
  170. Field_CodeOfTurbine: Const_Output_Total,
  171. Field_Return_FilePath: htmlFilePath,
  172. Field_Return_IsSaveDatabase: True
  173. })
  174. result_df = pd.DataFrame(result_rows)
  175. return result_df
  176. """
  177. fig, ax = plt.subplots(figsize=(16,8),dpi=96)
  178. # 设置x轴刻度值旋转角度为45度
  179. plt.tick_params(axis='x', rotation=45)
  180. sns.barplot(x=Field_NameOfTurbine,y=self.fieldTemperatureDiff,data=res,ax=ax,color='dodgerblue')
  181. plt.axhline(y=5,ls=":",c="red")#添加水平直线
  182. plt.axhline(y=-5,ls=":",c="red")#添加水平直线
  183. ax.set_ylabel('temperature_difference')
  184. ax.set_title('temperature Bias')
  185. plt.savefig(outputAnalysisDir +'//'+ "{}环境温差Bias.png".format(confData.farm_name),bbox_inches='tight',dpi=120)
  186. fig2, ax2 = plt.subplots(figsize=(16,8),dpi=96)
  187. # 设置x轴刻度值旋转角度为45度
  188. plt.tick_params(axis='x', rotation=45)
  189. sns.barplot(x=Field_NameOfTurbine ,y='当前机组温度',data=res,ax=ax2,color='dodgerblue')
  190. ax2.set_ylabel('temperature')
  191. ax2.set_title('temperature median')
  192. plt.savefig(outputAnalysisDir +'//'+ "{}环境温度均值.png".format(confData.farm_name),bbox_inches='tight',dpi=120)
  193. """