windSpeedFrequencyAnalyst.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import os
  2. import pandas as pd
  3. import numpy as np
  4. import plotly.graph_objects as go
  5. import plotly.express as px
  6. from plotly.subplots import make_subplots
  7. from behavior.analyst import Analyst
  8. from utils.directoryUtil import DirectoryUtil as dir
  9. import matplotlib.pyplot as plt
  10. from algorithmContract.confBusiness import *
  11. class WindSpeedFrequencyAnalyst(Analyst):
  12. def typeAnalyst(self):
  13. return "wind_speed_frequency"
  14. def filterCommon(self,dataFrame:pd.DataFrame, confData:ConfBusiness):
  15. return dataFrame
  16. def turbinesAnalysis(self, dataFrameMerge, outputAnalysisDir, confData: ConfBusiness):
  17. self.windRoseAnalysis(dataFrameMerge, outputAnalysisDir, confData)
  18. def windRoseAnalysis(self, dataFrameMerge: pd.DataFrame, outputAnalysisDir, confData: ConfBusiness):
  19. # 检查所需列是否存在
  20. required_columns = {Field_NameOfTurbine, confData.field_wind_speed}
  21. if not required_columns.issubset(dataFrameMerge.columns):
  22. raise ValueError(f"DataFrame缺少必要的列。需要的列有: {required_columns}")
  23. wind_speed_bins = np.arange(0, 26, 0.5) # x轴风速范围 ,间隔0.5
  24. # 按设备名分组数据
  25. grouped = dataFrameMerge.groupby(Field_NameOfTurbine)
  26. for name, group in grouped:
  27. # 2. 计算风速频率
  28. # 首先,我们需要确定风速的范围并计算每个风速的频数
  29. wind_speeds = group[confData.field_wind_speed].unique()
  30. # 计算风速频率,确保频率没有零值(用很小的数代替零)
  31. wind_speed_freq = np.histogram(wind_speeds, bins=wind_speed_bins)[0] / len(wind_speeds) * 100
  32. # 3. & 4. 确定y轴风速频率的范围和间隔(这里直接计算了频率,所以不需要手动设置间隔)
  33. # 我们已经计算了风速频率,因此不需要再手动设置y轴的间隔和范围
  34. # 5. 使用plotly绘制风速频率分布柱状图
  35. # 为了使用plotly绘制柱状图,我们需要将风速范围的中点作为x轴的值
  36. x_values = (wind_speed_bins[:-1] + wind_speed_bins[1:]) / 2
  37. # 创建柱状图
  38. fig = px.bar(x=x_values, y=wind_speed_freq)
  39. # 更新图形的布局
  40. fig.update_layout(
  41. title={
  42. 'text': f'Wind Speed Frequency {name}',
  43. # 'y': 0.95,
  44. 'x': 0.5,
  45. 'xanchor': 'center',
  46. 'yanchor': 'top'
  47. },
  48. xaxis=dict(
  49. title='Wind Speed (m/s)',
  50. showgrid=True,
  51. range=[0, 26],
  52. dtick=1,
  53. tickangle=-45
  54. ),
  55. yaxis=dict(
  56. title='Frequency (%)',
  57. showgrid=True,
  58. # range=[0, 1],
  59. ),
  60. margin=dict(t=50, b=10) # t为顶部(top)间距,b为底部(bottom)间距
  61. )
  62. # # 更新x轴和y轴的范围和标签
  63. # fig.update_yaxes(range=[0, max(wind_speed_freq) * 1.1 if max(wind_speed_freq) > 0 else 0.2], title='Frequency')
  64. # # 保存html
  65. outputFileHtml = os.path.join(outputAnalysisDir, f"{name}.html")
  66. fig.write_html(outputFileHtml)
  67. # 保存图像
  68. # output_file = os.path.join(outputAnalysisDir, f"{name}.png")
  69. # fig.write_image(output_file, scale=2)