inputData.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import pandas as pd
  2. import datetime, time
  3. import pytz
  4. import os
  5. import pymysql
  6. from sqlalchemy import create_engine
  7. import pytz
  8. from cache.data_cleaning import cleaning, rm_duplicated
  9. current_path = os.path.dirname(__file__)
  10. dataloc = current_path + '/data/'
  11. def readData(name):
  12. """
  13. 读取数据
  14. :param name: 名字
  15. :return:
  16. """
  17. path = dataloc + r"/" + name
  18. return pd.read_csv(path)
  19. def saveData(name, data):
  20. """
  21. 存放数据
  22. :param name: 名字
  23. :param data: 数据
  24. :return:
  25. """
  26. path = dataloc + r"/" + name
  27. os.makedirs(os.path.dirname(path), exist_ok=True)
  28. data.to_csv(path, index=False)
  29. def timestamp_to_datetime(ts):
  30. local_timezone = pytz.timezone('Asia/Shanghai')
  31. if type(ts) is not int:
  32. raise ValueError("timestamp-时间格式必须是整型")
  33. if len(str(ts)) == 13:
  34. dt = datetime.datetime.fromtimestamp(ts/1000, tz=pytz.utc).astimezone(local_timezone)
  35. return dt
  36. elif len(str(ts)) == 10:
  37. dt = datetime.datetime.fromtimestamp(ts, tz=pytz.utc).astimezone(local_timezone)
  38. return dt
  39. else:
  40. raise ValueError("timestamp-时间格式错误")
  41. def dt_tag(dt):
  42. date = dt.replace(hour=0, minute=0, second=0)
  43. delta = (dt - date) / pd.Timedelta(minutes=15)
  44. return delta + 1
  45. def timestr_to_timestamp(time_str):
  46. """
  47. 将时间戳或时间字符串转换为datetime.datetime类型
  48. :param time_data: int or str
  49. :return:datetime.datetime
  50. """
  51. if isinstance(time_str, str):
  52. if len(time_str) == 10:
  53. dt = datetime.datetime.strptime(time_str, '%Y-%m-%d')
  54. return int(round(time.mktime(dt.timetuple())) * 1000)
  55. elif len(time_str) in {17, 18, 19}:
  56. dt = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') # strptime字符串解析必须严格按照字符串中的格式
  57. return int(round(time.mktime(dt.timetuple())) * 1000) # 转换成毫秒级的时间戳
  58. else:
  59. raise ValueError("时间字符串长度不满足要求!")
  60. else:
  61. return time_str
  62. class DataBase(object):
  63. def __init__(self, begin, end, opt, logger):
  64. self.begin = begin
  65. self.opt = opt
  66. self.his_begin = self.begin - pd.Timedelta(hours=self.opt.Model["his_points"]/4)
  67. self.end = end + pd.Timedelta(days=1) - pd.Timedelta(minutes=15)
  68. self.begin_stamp = timestr_to_timestamp(str(begin))
  69. self.his_begin_stamp = timestr_to_timestamp(str(self.his_begin))
  70. self.end_stamp = timestr_to_timestamp(str(self.end))
  71. self.database = opt.database
  72. self.logger = logger
  73. self.towerloc = self.opt.tower
  74. def clear_data(self):
  75. """
  76. 删除所有csv
  77. :return:
  78. """
  79. # 设置文件夹路径
  80. import glob
  81. import os
  82. folder_path = dataloc
  83. # 使用 glob 获取所有的 .csv 文件路径
  84. csv_files = glob.glob(os.path.join(folder_path, '**/*.csv'), recursive=True)
  85. # 遍历所有 .csv 文件并删除
  86. for file_path in csv_files:
  87. os.remove(file_path)
  88. self.logger.info("清除所有csv文件")
  89. def create_database(self):
  90. """
  91. 创建数据库连接
  92. :param database: 数据库地址
  93. :return:
  94. """
  95. engine = create_engine(self.database)
  96. return engine
  97. def exec_sql(self, sql, engine):
  98. """
  99. 从数据库获取数据
  100. :param sql: sql语句
  101. :param engine: 数据库对象
  102. :return:
  103. """
  104. df = pd.read_sql_query(sql, engine)
  105. return df
  106. def get_process_NWP(self):
  107. """
  108. 从数据库中获取NWP数据,并进行简单处理
  109. :param database:
  110. :return:
  111. """
  112. # NPW数据
  113. engine = self.create_database()
  114. if self.opt.new_field:
  115. sql_NWP = "select C_PRE_TIME,C_T,C_RH,C_PRESSURE, C_SWR, C_TPR," \
  116. "C_DIFFUSE_RADIATION, C_DIRECT_RADIATION, C_SOLAR_ZENITH," \
  117. "C_LCC, C_MCC, C_HCC, C_TCC, C_CLEARSKY_GHI, C_DNI_CALCD," \
  118. "C_WD10,C_WD30,C_WD50,C_WD70,C_WD80,C_WD90,C_WD100,C_WD170," \
  119. "C_WS10,C_WS30,C_WS50,C_WS70,C_WS80,C_WS90,C_WS100,C_WS170 from t_nwp " \
  120. " where C_PRE_TIME between {} and {}".format(self.begin_stamp, self.end_stamp) # 新NWP字段
  121. else:
  122. sql_NWP = "select C_PRE_TIME,C_T,C_RH,C_PRESSURE, C_SWR," \
  123. "C_DIFFUSE_RADIATION, C_DIRECT_RADIATION, " \
  124. "C_WD10,C_WD30,C_WD50,C_WD70,C_WD80,C_WD90,C_WD100,C_WD170," \
  125. "C_WS10,C_WS30,C_WS50,C_WS70,C_WS80,C_WS90,C_WS100,C_WS170 from t_nwp " \
  126. " where C_PRE_TIME between {} and {}".format(self.begin_stamp, self.end_stamp) # 老NWP字段
  127. NWP = self.exec_sql(sql_NWP, engine)
  128. NWP['C_PRE_TIME'] = NWP['C_PRE_TIME'].apply(timestamp_to_datetime)
  129. NWP = NWP.rename(columns={'C_PRE_TIME': 'C_TIME'})
  130. # NWP['DT_TAG'] = NWP.apply(lambda x: dt_tag(x['C_TIME']), axis=1)
  131. NWP = cleaning(NWP, 'NWP', self.logger)
  132. # NWP = self.split_time(NWP)
  133. NWP['C_TIME'] = NWP['C_TIME'].dt.strftime('%Y-%m-%d %H:%M:%S')
  134. saveData("NWP.csv", NWP)
  135. self.logger.info("导出nwp数据")
  136. return NWP
  137. def get_process_tower(self):
  138. """
  139. 获取环境检测仪数据
  140. :param database:
  141. :return:
  142. """
  143. engine = self.create_database()
  144. self.logger.info("提取测风塔:{}".format(self.towerloc))
  145. for i in self.towerloc:
  146. # 删除没用的列
  147. drop_colmns = ["C_ID","C_DATA1","C_DATA2","C_DATA3","C_DATA4","C_DATA5","C_DATA6","C_DATA7","C_DATA8","C_DATA9","C_DATA10","C_IS_GENERATED","C_ABNORMAL_CODE"]
  148. get_colmns = []
  149. # 查询表的所有列名
  150. result_set = self.exec_sql("SHOW COLUMNS FROM t_wind_tower_status_data", engine)
  151. for name in result_set.iloc[:,0]:
  152. if name not in drop_colmns:
  153. get_colmns.append(name)
  154. all_columns_str = ", ".join([f'{col}' for col in get_colmns])
  155. tower_sql = "select " + all_columns_str + " from t_wind_tower_status_data where C_EQUIPMENT_NO="+str(i) + " and C_TIME between '{}' and '{}'".format(self.his_begin, self.end)
  156. tower = self.exec_sql(tower_sql, engine)
  157. tower['C_TIME'] = pd.to_datetime(tower['C_TIME'])
  158. saveData("/tower-{}.csv".format(i), tower)
  159. self.logger.info("测风塔{}导出数据".format(i))
  160. def get_process_power(self):
  161. """
  162. 获取整体功率数据
  163. :param database:
  164. :return:
  165. """
  166. engine = self.create_database()
  167. sql_cap = "select C_CAPACITY from t_electric_field"
  168. cap = self.exec_sql(sql_cap, engine)['C_CAPACITY']
  169. self.opt.cap = float(cap)
  170. sql_power = "select C_TIME,C_REAL_VALUE, C_ABLE_VALUE, C_REFERENCE_POWER_BY_SAMPLE," \
  171. "C_IS_RATIONING_BY_MANUAL_CONTROL, C_IS_RATIONING_BY_AUTO_CONTROL from t_power_station_status_data " \
  172. "where C_TIME between '{}' and '{}'".format(self.his_begin, self.end)
  173. powers = self.exec_sql(sql_power, engine)
  174. powers['C_TIME'] = pd.to_datetime(powers['C_TIME'])
  175. mask2 = powers[self.opt.predict] < 0
  176. mask1 = powers['C_REAL_VALUE'].astype(float) > float(cap)
  177. mask = powers['C_REAL_VALUE'] == -99
  178. mask = mask | mask1 | mask2
  179. self.logger.info("实际功率共{}条,要剔除功率有{}条".format(len(powers), mask.sum()))
  180. powers = powers[~mask]
  181. self.logger.info("剔除完后还剩{}条".format(len(powers)))
  182. binary_map = {b'\x00': 0, b'\x01': 1}
  183. powers['C_IS_RATIONING_BY_AUTO_CONTROL'] = powers['C_IS_RATIONING_BY_AUTO_CONTROL'].map(binary_map)
  184. powers = rm_duplicated(powers, self.logger)
  185. saveData("power.csv", powers)
  186. def get_process_dq(self):
  187. """
  188. 获取短期预测结果
  189. :param database:
  190. :return:
  191. """
  192. engine = self.create_database()
  193. sql_dq = "select C_FORECAST_TIME AS C_TIME, C_FP_VALUE from t_forecast_power_short_term " \
  194. "where C_FORECAST_TIME between {} and {}".format(self.his_begin_stamp, self.end_stamp)
  195. dq = self.exec_sql(sql_dq, engine)
  196. # dq['C_TIME'] = pd.to_datetime(dq['C_TIME'], unit='ms')
  197. dq['C_TIME'] = dq['C_TIME'].apply(timestamp_to_datetime)
  198. # dq = dq[dq['C_FORECAST_HOW_LONG_AGO'] == 1]
  199. # dq.drop('C_FORECAST_HOW_LONG_AGO', axis=1, inplace=True)
  200. dq = cleaning(dq, 'dq', self.logger, cols=['C_FP_VALUE'])
  201. dq['C_TIME'] = dq['C_TIME'].dt.strftime('%Y-%m-%d %H:%M:%S')
  202. saveData("dq.csv", dq)
  203. def indep_process(self):
  204. """
  205. 进一步数据处理:时间统一处理等
  206. :return:
  207. """
  208. # 测风塔数据处理
  209. for i in self.towerloc:
  210. tower = readData("/tower-{}.csv".format(i))
  211. tower['C_TIME'] = pd.to_datetime(tower['C_TIME'])
  212. tower = cleaning(tower, 'tower', self.logger, [self.opt.usable_power['env']])
  213. tower_ave = tower.resample('15T', on='C_TIME').mean().reset_index()
  214. tower_ave = tower_ave.dropna(subset=[self.opt.usable_power['env']])
  215. tower_ave.set_index('C_TIME', inplace=True)
  216. tower_ave = tower_ave.interpolate(method='linear')
  217. tower_ave = tower_ave.fillna(method='ffill')
  218. tower_ave = tower_ave.fillna(method='bfill')
  219. tower_ave.reset_index(drop=False, inplace=True)
  220. tower_ave = tower_ave.dropna(subset=[self.opt.usable_power['env']]).round(2)
  221. tower_ave.iloc[:, 1:] = tower_ave.iloc[:, 1:].round(2)
  222. saveData("/tower-{}-process.csv".format(i), tower_ave)
  223. def get_process_cdq(self):
  224. """
  225. 获取超短期预测结果
  226. :param database:
  227. :return:
  228. """
  229. engine = self.create_database()
  230. sql_cdq = "select C_FORECAST_TIME AS C_TIME, C_ABLE_VALUE, C_FORECAST_HOW_LONG_AGO from t_forecast_power_ultra_short_term_his" \
  231. " where C_FORECAST_TIME between {} and {}".format(self.begin_stamp, self.end_stamp)
  232. cdq = self.exec_sql(sql_cdq, engine)
  233. cdq['C_TIME'] = cdq['C_TIME'].apply(timestamp_to_datetime)
  234. cdq = cleaning(cdq, 'cdq', self.logger, cols=['C_ABLE_VALUE'], dup=False)
  235. # cdq = cdq[cdq['C_FORECAST_HOW_LONG_AGO'] == int(str(self.opt.predict_point)[1:])]
  236. cdq['C_TIME'] = cdq['C_TIME'].dt.strftime('%Y-%m-%d %H:%M:%S')
  237. saveData("cdq.csv", cdq)
  238. def get_process_turbine(self):
  239. """
  240. 从数据库中获取风头数据,并进行简单处理
  241. :param database:
  242. :return:
  243. """
  244. for number in self.opt.turbineloc:
  245. # number = self.opt.usable_power['turbine_id']
  246. # 机头数据
  247. engine = self.create_database()
  248. self.logger.info("导出风机{}的数据".format(number))
  249. sql_turbine = "select C_TIME, C_WS, C_WD, C_ACTIVE_POWER from t_wind_turbine_status_data " \
  250. "WHERE C_EQUIPMENT_NO=" + str(number) + " and C_TIME between '{}' and '{}'".format(self.begin, self.end) # + " and C_WS>0 and C_ACTIVE_POWER>0"
  251. turbine = self.exec_sql(sql_turbine, engine)
  252. turbine = cleaning(turbine, 'turbine-'+str(number), self.logger, cols=['C_WS', 'C_ACTIVE_POWER'], dup=False)
  253. turbine = turbine[turbine['C_TIME'].dt.strftime('%M').isin(['00', '15', '30', '45'])]
  254. # 直接导出所有数据
  255. saveData("turbine-{}.csv".format(number), turbine)
  256. def process_csv_files(self, input_dir, output_dir, M, N): # MBD:没有考虑时间重复
  257. if not os.path.exists(output_dir):
  258. os.makedirs(output_dir)
  259. for i in self.opt.turbineloc:
  260. input_file = os.path.join(input_dir, f"turbine-{i}.csv")
  261. output_file = os.path.join(output_dir, f"turbine-{i}.csv")
  262. # 读取csv文件
  263. df = pd.read_csv(input_file)
  264. # 剔除异常值,并获取异常值统计信息
  265. df_clean, count_abnormal1, count_abnormal2, total_removed, removed_continuous_values = self.remove_abnormal_values(df, N)
  266. # 输出异常值统计信息
  267. self.logger.info(f"处理文件:{input_file}")
  268. self.logger.info(f"剔除 -99 点异常值数量:{count_abnormal1}")
  269. self.logger.info(f"剔除连续异常值数量:{count_abnormal2}")
  270. self.logger.info(f"总共剔除数据量:{total_removed}")
  271. self.logger.info(f"剔除的连续异常值具体数值:{removed_continuous_values}\n")
  272. # 保存处理过的CSV文件
  273. df_clean.to_csv(output_file, index=False)
  274. def remove_abnormal_values(self,df, N):
  275. # 标记C_ACTIVE_POWER为-99的行为异常值
  276. abnormal_mask1 = df['C_ACTIVE_POWER'] == -99
  277. count_abnormal1 = abnormal_mask1.sum()
  278. # 标记C_WS, A, B连续5行不变的行为异常值
  279. columns = ['C_WS', 'C_WD', 'C_ACTIVE_POWER']
  280. abnormal_mask2 = self.mark_abnormal_streaks(df, columns, N)
  281. count_abnormal2 = abnormal_mask2.sum()
  282. # 获得所有异常值的布尔掩码
  283. abnormal_mask = abnormal_mask1 | abnormal_mask2
  284. # 获取连续异常值具体数值
  285. removed_continuous_values = {column: df.loc[abnormal_mask2, column].unique() for column in columns}
  286. # 剔除异常值
  287. df_clean = df[~abnormal_mask]
  288. total_removed = abnormal_mask.sum()
  289. return df_clean, count_abnormal1, count_abnormal2, total_removed, removed_continuous_values
  290. # ——————————————————————————对分区的风机进行发电功率累加——————————————————————————————
  291. def zone_powers(self, input_dir):
  292. z_power = {}
  293. for zone, turbines in self.opt.zone.items():
  294. dfs = [pd.read_csv(os.path.join(input_dir, f"turbine-{z}.csv")) for z in self.opt.turbineloc if z in turbines]
  295. z_power['C_TIME'] = dfs[0]['C_TIME']
  296. sum_power = pd.concat([df['C_ACTIVE_POWER'] for df in dfs], ignore_index=True, axis=1).sum(axis=1)
  297. z_power[zone] = sum_power
  298. z_power = pd.DataFrame(z_power)
  299. z_power.iloc[:, 1:] = z_power.iloc[:, 1:].round(2)
  300. saveData("z-power.csv", z_power)
  301. # ——————————————————————————机头风速-99和连续异常值清洗代码——————————————————————————————
  302. def mark_abnormal_streaks(self, df, columns, min_streak):
  303. abnormal_mask = pd.Series(False, index=df.index)
  304. streak_start = None
  305. for i in range(len(df)):
  306. if i == 0 or any(df.at[i - 1, col] != df.at[i, col] for col in columns):
  307. streak_start = i
  308. if i - streak_start >= min_streak - 1:
  309. abnormal_mask[i - min_streak + 1:i + 1] = True
  310. return abnormal_mask
  311. # ——————————————————————————风机单机时间对齐——————————————————————————————
  312. def TimeMerge(self, input_dir, output_dir, M):
  313. # 读取所有CSV文件
  314. files = [os.path.join(input_dir, f"turbine-{i}.csv") for i in self.opt.turbineloc]
  315. dataframes = [pd.read_csv(f) for f in files]
  316. # 获取C_TIME列的交集
  317. c_time_intersection = set(dataframes[0]["C_TIME"])
  318. for df in dataframes[1:]:
  319. c_time_intersection.intersection_update(df["C_TIME"])
  320. # 只保留C_TIME交集中的数据
  321. filtered_dataframes = [df[df["C_TIME"].isin(c_time_intersection)] for df in dataframes]
  322. # 将每个过滤后的DataFrame写入新的CSV文件
  323. os.makedirs(output_dir, exist_ok=True)
  324. for (filtered_df, i) in zip(filtered_dataframes, self.opt.turbineloc):
  325. if i == 144:
  326. filtered_df['C_ACTIVE_POWER'] /= 1000
  327. filtered_df.to_csv(os.path.join(output_dir, f"turbine-{i}.csv"), index=False)
  328. def data_process(self):
  329. """
  330. 数据导出+初步处理的总操控代码
  331. :param database:
  332. :return:
  333. """
  334. self.clear_data()
  335. self.get_process_power()
  336. self.get_process_dq()
  337. self.get_process_cdq()
  338. self.get_process_NWP()
  339. self.get_process_tower()
  340. self.indep_process()
  341. self.get_process_turbine()
  342. self.process_csv_files('./cache/data', './cache/data', 50, 5)
  343. self.TimeMerge('./cache/data', './cache/data', 50)
  344. self.zone_powers('./cache/data')