inputData.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import pandas as pd
  2. import datetime, time
  3. import yaml
  4. import os
  5. import pymysql
  6. from sqlalchemy import create_engine
  7. import pytz
  8. from getdata.data_cleaning import cleaning, rm_duplicated
  9. current_path = os.path.dirname(__file__)
  10. dataloc = current_path + '/data/'
  11. weatherloc = [1]
  12. def readData(name):
  13. """
  14. 读取数据
  15. :param name: 名字
  16. :return:
  17. """
  18. path = dataloc + r"/" + name
  19. return pd.read_csv(path)
  20. def saveData(name, data):
  21. """
  22. 存放数据
  23. :param name: 名字
  24. :param data: 数据
  25. :return:
  26. """
  27. path = dataloc + r"/" + name
  28. os.makedirs(os.path.dirname(path), exist_ok=True)
  29. data.to_csv(path, index=False)
  30. def timestamp_to_datetime(ts):
  31. local_timezone = pytz.timezone('Asia/Shanghai')
  32. if type(ts) is not int:
  33. raise ValueError("timestamp-时间格式必须是整型")
  34. if len(str(ts)) == 13:
  35. dt = datetime.datetime.fromtimestamp(ts/1000, tz=pytz.utc).astimezone(local_timezone)
  36. return dt
  37. elif len(str(ts)) == 10:
  38. dt = datetime.datetime.fromtimestamp(ts, tz=pytz.utc).astimezone(local_timezone)
  39. return dt
  40. else:
  41. raise ValueError("timestamp-时间格式错误")
  42. def timestr_to_timestamp(time_str):
  43. """
  44. 将时间戳或时间字符串转换为datetime.datetime类型
  45. :param time_data: int or str
  46. :return:datetime.datetime
  47. """
  48. if isinstance(time_str, str):
  49. if len(time_str) == 10:
  50. dt = datetime.datetime.strptime(time_str, '%Y-%m-%d')
  51. return int(round(time.mktime(dt.timetuple())) * 1000)
  52. elif len(time_str) in {17, 18, 19}:
  53. dt = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') # strptime字符串解析必须严格按照字符串中的格式
  54. return int(round(time.mktime(dt.timetuple())) * 1000) # 转换成毫秒级的时间戳
  55. else:
  56. raise ValueError("时间字符串长度不满足要求!")
  57. else:
  58. return time_str
  59. class DataBase(object):
  60. def __init__(self, begin, end, database):
  61. self.begin = begin
  62. self.end = end - pd.Timedelta(minutes=15)
  63. self.begin_stamp = timestr_to_timestamp(str(begin))
  64. self.end_stamp = timestr_to_timestamp(str(self.end))
  65. self.database = database
  66. def clear_data(self):
  67. """
  68. 删除所有csv
  69. :return:
  70. """
  71. # 设置文件夹路径
  72. import glob
  73. import os
  74. folder_path = dataloc
  75. # 使用 glob 获取所有的 .csv 文件路径
  76. csv_files = glob.glob(os.path.join(folder_path, '**/*.csv'), recursive=True)
  77. # 遍历所有 .csv 文件并删除
  78. for file_path in csv_files:
  79. os.remove(file_path)
  80. # self.logger.info("清除所有csv文件")
  81. def create_database(self):
  82. """
  83. 创建数据库连接
  84. :param database: 数据库地址
  85. :return:
  86. """
  87. engine = create_engine(self.database)
  88. return engine
  89. def exec_sql(self, sql, engine):
  90. """
  91. 从数据库获取数据
  92. :param sql: sql语句
  93. :param engine: 数据库对象
  94. :return:
  95. """
  96. df = pd.read_sql_query(sql, engine)
  97. return df
  98. def split_time(self, data):
  99. data['C_TIME'] = pd.to_datetime(data["C_TIME"])
  100. data.set_index('C_TIME', inplace=True)
  101. data = data.sort_index().loc[self.begin: self.end]
  102. data.reset_index(drop=False, inplace=True)
  103. return data
  104. def get_process_NWP(self):
  105. """
  106. 从数据库中获取NWP数据,并进行简单处理
  107. :param database:
  108. :return:
  109. """
  110. # NPW数据
  111. engine = self.create_database()
  112. sql_NWP = "select C_PRE_TIME,C_T,C_RH,C_PRESSURE, C_SWR," \
  113. "C_DIFFUSE_RADIATION, C_DIRECT_RADIATION, " \
  114. "C_WD10,C_WD30,C_WD50,C_WD70,C_WD80,C_WD90,C_WD100,C_WD170," \
  115. "C_WS10,C_WS30,C_WS50,C_WS70,C_WS80,C_WS90,C_WS100,C_WS170 from t_nwp " \
  116. " where C_PRE_TIME between {} and {}".format(self.begin_stamp, self.end_stamp) # 光的NWP字段
  117. NWP = self.exec_sql(sql_NWP, engine)
  118. NWP['C_PRE_TIME'] = NWP['C_PRE_TIME'].apply(timestamp_to_datetime)
  119. NWP = NWP.rename(columns={'C_PRE_TIME': 'C_TIME'})
  120. NWP = cleaning(NWP, 'NWP')
  121. # NWP = self.split_time(NWP)
  122. NWP['C_TIME'] = NWP['C_TIME'].dt.strftime('%Y-%m-%d %H:%M:%S')
  123. saveData("NWP.csv", NWP)
  124. print("导出nwp数据")
  125. return NWP
  126. def get_process_weather(self):
  127. """
  128. 获取环境检测仪数据
  129. :param database:
  130. :return:
  131. """
  132. engine = self.create_database()
  133. print("现有环境监测仪:{}".format(weatherloc))
  134. for i in weatherloc:
  135. # 删除没用的列
  136. drop_colmns = ["C_ID", "C_EQUIPMENT_NO", "C_DATA1","C_DATA2","C_DATA3","C_DATA4","C_DATA5","C_DATA6","C_DATA7","C_DATA8","C_DATA9","C_DATA10", "C_STATUS", "C_IS_GENERATED","C_ABNORMAL_CODE"]
  137. get_colmns = []
  138. # 查询表的所有列名
  139. result_set = self.exec_sql("SHOW COLUMNS FROM t_weather_station_status_data", engine)
  140. for name in result_set.iloc[:,0]:
  141. if name not in drop_colmns:
  142. get_colmns.append(name)
  143. all_columns_str = ", ".join([f'{col}' for col in get_colmns])
  144. weather_sql = "select " + all_columns_str + " from t_weather_station_status_data where C_EQUIPMENT_NO="+ str(i) + " and C_TIME between '{}' and '{}'".format(self.begin, self.end)
  145. weather = self.exec_sql(weather_sql, engine)
  146. weather['C_TIME'] = pd.to_datetime(weather['C_TIME'])
  147. # weather = self.split_time(weather)
  148. saveData("/weather-{}.csv".format(i), weather)
  149. print("环境监测仪{}导出数据".format(i))
  150. def get_process_power(self):
  151. """
  152. 获取整体功率数据
  153. :param database:
  154. :return:
  155. """
  156. engine = self.create_database()
  157. sql_cap = "select C_CAPACITY from t_electric_field"
  158. cap = self.exec_sql(sql_cap, engine)['C_CAPACITY']
  159. sql_power = "select C_TIME, C_REAL_VALUE, C_ABLE_VALUE, C_IS_RATIONING_BY_MANUAL_CONTROL, C_IS_RATIONING_BY_AUTO_CONTROL" \
  160. " from t_power_station_status_data where C_TIME between '{}' and '{}'".format(self.begin, self.end)
  161. # if self.opt.usable_power["clean_power_by_signal"]:
  162. # sql_power += " and C_IS_RATIONING_BY_MANUAL_CONTROL=0 and C_IS_RATIONING_BY_AUTO_CONTROL=0"
  163. powers = self.exec_sql(sql_power, engine)
  164. mask1 = powers.loc[:, 'C_REAL_VALUE'].astype(float) > float(cap)
  165. mask = powers['C_REAL_VALUE'] == -99
  166. mask = mask | mask1
  167. print("实际功率共{}条,要剔除功率有{}条".format(len(powers), mask.sum()))
  168. powers = powers[~mask]
  169. print("剔除完后还剩{}条".format(len(powers)))
  170. powers.reset_index(drop=True, inplace=True)
  171. binary_map = {b'\x00': 0, b'\x01': 1}
  172. powers['C_IS_RATIONING_BY_AUTO_CONTROL'] = powers['C_IS_RATIONING_BY_AUTO_CONTROL'].map(binary_map)
  173. powers = rm_duplicated(powers)
  174. saveData("power.csv", powers)
  175. def get_process_dq(self):
  176. """
  177. 获取短期预测结果
  178. :param database:
  179. :return:
  180. """
  181. engine = self.create_database()
  182. sql_dq = "select C_FORECAST_TIME AS C_TIME, C_FP_VALUE from t_forecast_power_short_term " \
  183. "where C_FORECAST_TIME between {} and {}".format(self.begin_stamp, self.end_stamp)
  184. dq = self.exec_sql(sql_dq, engine)
  185. # dq['C_TIME'] = pd.to_datetime(dq['C_TIME'], unit='ms')
  186. dq['C_TIME'] = dq['C_TIME'].apply(timestamp_to_datetime)
  187. # dq = dq[dq['C_FORECAST_HOW_LONG_AGO'] == 1]
  188. # dq.drop('C_FORECAST_HOW_LONG_AGO', axis=1, inplace=True)
  189. dq = cleaning(dq, 'dq', cols=['C_FP_VALUE'])
  190. dq['C_TIME'] = dq['C_TIME'].dt.strftime('%Y-%m-%d %H:%M:%S')
  191. saveData("dq.csv", dq)
  192. print("导出dq数据")
  193. def get_process_cdq(self):
  194. """
  195. 获取超短期预测结果
  196. :param database:
  197. :return:
  198. """
  199. engine = self.create_database()
  200. sql_cdq = "select C_FORECAST_TIME AS C_TIME, C_ABLE_VALUE, C_FORECAST_HOW_LONG_AGO from " \
  201. "t_forecast_power_ultra_short_term_his" \
  202. " where C_FORECAST_TIME between {} and {}".format(self.begin_stamp, self.end_stamp)
  203. cdq = self.exec_sql(sql_cdq, engine)
  204. cdq['C_TIME'] = cdq['C_TIME'].apply(timestamp_to_datetime)
  205. cdq = cleaning(cdq, 'cdq', cols=['C_ABLE_VALUE'], dup=False)
  206. # cdq = cdq[cdq['C_FORECAST_HOW_LONG_AGO'] == int(str(self.opt.predict_point)[1:])]
  207. cdq['C_TIME'] = cdq['C_TIME'].dt.strftime('%Y-%m-%d %H:%M:%S')
  208. saveData("cdq.csv", cdq)
  209. def indep_process(self):
  210. """
  211. 进一步数据处理:时间统一处理等
  212. :return:
  213. """
  214. # 环境监测仪数据处理
  215. for i in weatherloc:
  216. weather = readData("/weather-{}.csv".format(i))
  217. weather = cleaning(weather, 'weather', cols=['C_GLOBALR', 'C_DIRECTR', 'C_DIFFUSER', 'C_RH', 'C_AIRT', 'C_P', 'C_WS', 'C_WD'])
  218. saveData("/weather-{}-process.csv".format(i), weather)
  219. def data_process(self):
  220. """
  221. 数据导出+初步处理的总操控代码
  222. :param database:
  223. :return:
  224. """
  225. self.clear_data()
  226. try:
  227. self.get_process_power()
  228. self.get_process_dq()
  229. # self.get_process_cdq()
  230. self.get_process_NWP()
  231. self.get_process_weather()
  232. self.indep_process()
  233. except Exception as e:
  234. print("导出数据出错:{}".format(e.args))