tsrTrendAnalyst.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import os
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import seaborn as sns
  6. from .analyst import Analyst
  7. from .utils.directoryUtil import DirectoryUtil as dir
  8. from confBusiness import ConfBusiness
  9. class TSRTrendAnalyst(Analyst):
  10. """
  11. 风电机组叶尖速比时序分析
  12. """
  13. def typeAnalyst(self):
  14. return "tsr_trend"
  15. def turbineAnalysis(self,
  16. dataFrame,
  17. outputAnalysisDir,
  18. outputFilePath,
  19. confData: ConfBusiness,
  20. turbineName):
  21. self.tsr_trend(dataFrame, outputFilePath,
  22. confData.field_turbine_time, confData.field_wind_speed, confData.field_rotor_speed, confData.field_power, confData.field_pitch_angle1,
  23. confData.rotor_diameter)
  24. def tsr_trend(self, dataFrame, output_path, field_time, field_wind_speed, field_rotor_speed, field_power_active, field_angle_pitch, rotor_diameter):
  25. # Convert time column to datetime and extract date
  26. dataFrame[field_time] = pd.to_datetime(
  27. dataFrame[field_time], format='%Y-%m-%d %H:%M:%S')
  28. dataFrame['time_day'] = dataFrame[field_time].dt.date
  29. # Calculate 'tsr'
  30. dataFrame['wind_speed'] = dataFrame[field_wind_speed].astype(float)
  31. dataFrame['rotor_speed'] = dataFrame[field_rotor_speed].astype(float)
  32. rotor_diameter = pd.to_numeric(rotor_diameter, errors='coerce')
  33. dataFrame['tsr'] = (dataFrame['rotor_speed'] * 0.104667 *
  34. (rotor_diameter / 2)) / dataFrame['wind_speed']
  35. # Group by day and aggregate
  36. grouped = dataFrame.groupby('time_day').agg({
  37. field_time: 'min',
  38. 'wind_speed': 'mean',
  39. 'rotor_speed': 'mean',
  40. 'tsr': ['mean', 'max', 'min']
  41. }).reset_index()
  42. # Rename columns post-aggregation
  43. grouped.columns = ['time_day', 'time_', 'wind_speed',
  44. 'rotor_speed', 'tsr', 'tsr_max', 'tsr_min']
  45. # Sort by day
  46. grouped.sort_values('time_day', inplace=True)
  47. # Write to CSV
  48. grouped.to_csv(output_path, index=False)
  49. def turbinesAnalysis(self, dataFrameMerge, outputAnalysisDir, confData: ConfBusiness):
  50. self.plot_tsr_trend(outputAnalysisDir, confData.farm_name)
  51. def plot_tsr_trend(self, csvFileDirOfCp, farm_name, encoding='utf-8'):
  52. """
  53. Plot TSR trend from CSV files in a given input path and save the plots to an output path.
  54. Parameters:
  55. - csvFileDirOfCp: str, path to the directory containing input CSV files.
  56. - farm_name: str, name of the wind farm.
  57. - encoding: str, encoding of the input CSV files. Defaults to 'utf-8'.
  58. """
  59. field_Name_Turbine = "turbine_name"
  60. file_time = 'time_day'
  61. y_name = 'tsr'
  62. y_min = 'tsr_min'
  63. y_max = 'tsr_max'
  64. split_way = '_tsr_trend.csv'
  65. # Set seaborn palette
  66. sns.set_palette('deep')
  67. # Iterate over the files in the input directory
  68. for root, dir_names, file_names in dir.list_directory(csvFileDirOfCp):
  69. for file_name in file_names:
  70. if not file_name.endswith(".csv"):
  71. continue
  72. try:
  73. print(os.path.join(root, file_name))
  74. data = pd.read_csv(os.path.join(
  75. root, file_name), encoding=encoding)
  76. # Convert the time column to datetime
  77. data.loc[:, file_time] = pd.to_datetime(
  78. data.loc[:, file_time])
  79. # Calculate min and max TSR values
  80. data[y_min] = data[y_name] - data[y_min]
  81. data[y_max] = data[y_max] - data[y_name]
  82. # Split the file name to get the output name
  83. turbine_name = file_name.split(split_way)[0]
  84. # 添加设备名作为新列
  85. data[field_Name_Turbine] = turbine_name
  86. # Plot the TSR trend with error bars
  87. fig, ax = plt.subplots()
  88. ax.errorbar(x=data[file_time], y=data[y_name], yerr=[data[y_min], data[y_max]],
  89. fmt='o', capsize=4, elinewidth=2, ecolor='lightgrey', mfc='dodgerblue')
  90. # Set axis labels, limits, and title
  91. ax.set_xlabel('time')
  92. ax.set_ylabel('TSR')
  93. # ax.set_ylim(0, 16)
  94. ax.set_title('turbine_name={}'.format(turbine_name))
  95. # Save the plot to the output path
  96. plt.savefig(os.path.join(csvFileDirOfCp, "{}.png".format(
  97. turbine_name)), bbox_inches='tight', dpi=120)
  98. plt.close(fig)
  99. except Exception as e:
  100. print(f"An error occurred while processing file {file_name}: {e}")