trans_service.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2024/6/7
  3. # @Author : 魏志亮
  4. import os
  5. import traceback
  6. import pandas as pd
  7. from utils.db.ConnectMysql import ConnectMysql
  8. from utils.log.trans_log import trans_print
  9. trans = ConnectMysql("trans")
  10. def get_min_sec_conf(field_code, trans_type) -> dict:
  11. query_sql = "SELECT * FROM trans_conf where wind_code = %s and type = %s and status = 1"
  12. res = trans.execute(query_sql, (field_code, trans_type))
  13. print(res)
  14. if type(res) == tuple:
  15. return None
  16. return res[0]
  17. def get_fault_warn_conf(field_code, trans_type) -> dict:
  18. types = list()
  19. if trans_type == 'fault':
  20. types.append(1)
  21. elif trans_type == 'warn':
  22. types.append(2)
  23. else:
  24. trans_print(f"未找到{trans_type}告警/故障的配置")
  25. raise ValueError(f"未找到{trans_type}告警/故障的配置")
  26. types.append(3)
  27. query_sql = "SELECT * FROM warn_fault_conf where wind_code = %s and type in %s and status = 1"
  28. res = trans.execute(query_sql, (field_code, types))
  29. print(res)
  30. if type(res) == tuple:
  31. return None
  32. return res[0]
  33. def creat_min_sec_table(table_name, win_names, read_type):
  34. create_sql = f"""
  35. CREATE TABLE
  36. IF NOT EXISTS `{table_name}` (
  37. `wind_turbine_number` VARCHAR (20) DEFAULT NULL COMMENT '风机编号',
  38. `wind_turbine_name` VARCHAR(20) DEFAULT NULL COMMENT '风机原始名称',
  39. `time_stamp` datetime NOT NULL COMMENT '时间戳',
  40. `active_power` DOUBLE DEFAULT NULL COMMENT '有功功率',
  41. `rotor_speed` DOUBLE DEFAULT NULL COMMENT '风轮转速',
  42. `generator_speed` DOUBLE DEFAULT NULL COMMENT '发电机转速',
  43. `wind_velocity` DOUBLE DEFAULT NULL COMMENT '风速',
  44. `pitch_angle_blade_1` DOUBLE DEFAULT NULL COMMENT '桨距角1',
  45. `pitch_angle_blade_2` DOUBLE DEFAULT NULL COMMENT '桨距角2',
  46. `pitch_angle_blade_3` DOUBLE DEFAULT NULL COMMENT '桨距角3',
  47. `cabin_position` DOUBLE DEFAULT NULL COMMENT '机舱位置',
  48. `true_wind_direction` DOUBLE DEFAULT NULL COMMENT '绝对风向',
  49. `yaw_error1` DOUBLE DEFAULT NULL COMMENT '对风角度',
  50. `set_value_of_active_power` DOUBLE DEFAULT NULL COMMENT '有功功率设定值',
  51. `gearbox_oil_temperature` DOUBLE DEFAULT NULL COMMENT '齿轮箱油温',
  52. `generatordrive_end_bearing_temperature` DOUBLE DEFAULT NULL COMMENT '发电机驱动端轴承温度',
  53. `generatornon_drive_end_bearing_temperature` DOUBLE DEFAULT NULL COMMENT '发电机非驱动端轴承温度',
  54. `cabin_temperature` DOUBLE DEFAULT NULL COMMENT '机舱内温度',
  55. `twisted_cable_angle` DOUBLE DEFAULT NULL COMMENT '扭缆角度',
  56. `front_back_vibration_of_the_cabin` DOUBLE DEFAULT NULL COMMENT '机舱前后振动',
  57. `side_to_side_vibration_of_the_cabin` DOUBLE DEFAULT NULL COMMENT '机舱左右振动',
  58. `actual_torque` DOUBLE DEFAULT NULL COMMENT '实际力矩',
  59. `given_torque` DOUBLE DEFAULT NULL COMMENT '给定力矩',
  60. `clockwise_yaw_count` DOUBLE DEFAULT NULL COMMENT '顺时针偏航次数',
  61. `counterclockwise_yaw_count` DOUBLE DEFAULT NULL COMMENT '逆时针偏航次数',
  62. `unusable` DOUBLE DEFAULT NULL COMMENT '不可利用',
  63. `power_curve_available` DOUBLE DEFAULT NULL COMMENT '功率曲线可用',
  64. `required_gearbox_speed` DOUBLE DEFAULT NULL COMMENT '齿轮箱转速',
  65. `inverter_speed_master_control` DOUBLE DEFAULT NULL COMMENT '变频器转速(主控)',
  66. `outside_cabin_temperature` DOUBLE DEFAULT NULL COMMENT '环境温度',
  67. `main_bearing_temperature` DOUBLE DEFAULT NULL COMMENT '主轴承轴承温度',
  68. `gearbox_high_speed_shaft_bearing_temperature` DOUBLE DEFAULT NULL COMMENT '齿轮箱高速轴轴承温度',
  69. `gearboxmedium_speed_shaftbearing_temperature` DOUBLE DEFAULT NULL COMMENT '齿轮箱中速轴轴承温度',
  70. `gearbox_low_speed_shaft_bearing_temperature` DOUBLE DEFAULT NULL COMMENT '齿轮箱低速轴轴承温度',
  71. `generator_winding1_temperature` DOUBLE DEFAULT NULL COMMENT '发电机绕组1温度',
  72. `generator_winding2_temperature` DOUBLE DEFAULT NULL COMMENT '发电机绕组2温度',
  73. `generator_winding3_temperature` DOUBLE DEFAULT NULL COMMENT '发电机绕组3温度',
  74. `wind_turbine_status` DOUBLE DEFAULT NULL COMMENT '风机状态1',
  75. `wind_turbine_status2` DOUBLE DEFAULT NULL COMMENT '风机状态2',
  76. `turbulence_intensity` DOUBLE DEFAULT NULL COMMENT '湍流强度',
  77. `lab` int DEFAULT NULL COMMENT '-1:停机 0:好点 1:欠发功率点;2:超发功率点;3:额定风速以上的超发功率点 4: 限电',
  78. `year` INT (4) DEFAULT NULL COMMENT '年',
  79. `month` INT (2) DEFAULT NULL COMMENT '月',
  80. `day` INT (2) DEFAULT NULL COMMENT '日',
  81. `param1` DOUBLE DEFAULT NULL COMMENT '预留1',
  82. `param2` DOUBLE DEFAULT NULL COMMENT '预留2',
  83. `param3` DOUBLE DEFAULT NULL COMMENT '预留3',
  84. `param4` DOUBLE DEFAULT NULL COMMENT '预留4',
  85. `param5` DOUBLE DEFAULT NULL COMMENT '预留5',
  86. `param6` VARCHAR (20) DEFAULT NULL COMMENT '预留6',
  87. `param7` VARCHAR (20) DEFAULT NULL COMMENT '预留7',
  88. `param8` VARCHAR (20) DEFAULT NULL COMMENT '预留8',
  89. `param9` VARCHAR (20) DEFAULT NULL COMMENT '预留9',
  90. `param10` VARCHAR (20) DEFAULT NULL COMMENT '预留10',
  91. KEY `time_stamp` (`time_stamp`),
  92. KEY `wind_turbine_number` (`wind_turbine_number`)
  93. ) ENGINE = myisam DEFAULT CHARSET = utf8mb4
  94. """
  95. if read_type == 'second' and win_names and len(win_names) > 1:
  96. create_sql = create_sql + f" PARTITION BY LIST COLUMNS(`wind_turbine_number`) ("
  97. partition_strs = list()
  98. for wind_name in win_names:
  99. partition_strs.append(f" PARTITION p{wind_name} VALUES IN('{wind_name}')")
  100. create_sql = create_sql + ",".join(partition_strs) + ")"
  101. trans.execute(create_sql)
  102. def rename_table(table_name, renamed_table_name, save_db=True):
  103. if save_db:
  104. rename_sql = f"RENAME TABLE {table_name} TO {renamed_table_name}"
  105. try:
  106. trans.execute(rename_sql)
  107. except:
  108. trans_print(traceback.format_exc())
  109. def drop_table(table_name, save_db=True):
  110. if save_db:
  111. rename_sql = f"drop TABLE `{table_name}`"
  112. try:
  113. trans.execute(rename_sql)
  114. except:
  115. trans_print(traceback.format_exc())
  116. def save_file_to_db(table_name: str, file: str, batch_count=100000):
  117. base_name = os.path.basename(file)
  118. try:
  119. for i, df in enumerate(pd.read_csv(file, chunksize=batch_count)):
  120. # df.to_sql(table_name, engine, if_exists='append', index=False)
  121. trans.execute_df_save(df, table_name)
  122. count = (i + 1) * batch_count
  123. trans_print(base_name, f"Chunk {count} written to MySQL.")
  124. except Exception as e:
  125. trans_print(traceback.format_exc())
  126. message = base_name + str(e)
  127. raise Exception(message)
  128. def batch_statistics(table_name):
  129. query_sql = f"select count(1) as total_count ,min(t.time_stamp) as min_date ,max(t.time_stamp) as max_date from `{table_name}` t "
  130. try:
  131. res = trans.execute(query_sql)
  132. return res[0]
  133. except:
  134. trans_print(traceback.format_exc())
  135. return None
  136. def create_warn_fault_table(table_name):
  137. sql = f"""
  138. CREATE TABLE `{table_name}` (
  139. `wind_turbine_number` varchar(20) DEFAULT NULL COMMENT '风机编号',
  140. `wind_turbine_name` varchar(20) DEFAULT NULL COMMENT '原始风机编号',
  141. `begin_time` datetime DEFAULT NULL COMMENT '开始时间',
  142. `end_time` datetime DEFAULT NULL COMMENT '结束时间',
  143. `time_diff` int DEFAULT NULL COMMENT '处理耗时,单位秒',
  144. `fault_id` varchar(20) DEFAULT NULL COMMENT '报警或者故障ID',
  145. `fault_code` varchar(50) DEFAULT NULL COMMENT '报警或者故障CODE',
  146. `fault_detail` varchar(255) DEFAULT NULL COMMENT '错误描述',
  147. `fault_level` varchar(20) DEFAULT NULL COMMENT '报警等级',
  148. `fault_type` varchar(20) DEFAULT NULL COMMENT '报警类型',
  149. `stop_status` varchar(20) DEFAULT NULL COMMENT '刹车状态',
  150. KEY `wind_turbine_number` (`wind_turbine_number`),
  151. KEY `begin_time` (`begin_time`),
  152. KEY `end_time` (`end_time`)
  153. ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4
  154. """
  155. trans.execute(sql)
  156. if __name__ == '__main__':
  157. # path_prix = r"/data/download/collection_data/2完成/招远风电场-山东-大唐/清理数据/WOF063100040-WOB00013/second"
  158. # files = ["WOG00030.csv", "WOG00034.csv"]
  159. # for path in files:
  160. # save_file_to_db("WOF063100040-WOB00013_second", path_prix + os.sep + path, batch_count=100000)
  161. # sql = """
  162. # SELECT wind_turbine_number, time_stamp, wind_velocity, active_power
  163. # FROM `WOF085500002-WOB000001_second`
  164. # WHERE time_stamp >= '2024-02-17 00:00:00' AND time_stamp <= '2024-05-14 00:00:00' AND lab = 0
  165. # """
  166. #
  167. # begin = datetime.datetime.now()
  168. # df = trans.read_sql_to_df(sql)
  169. # end = datetime.datetime.now()
  170. # print(df.shape)
  171. # print(df.info())
  172. # print("Time used:", (end - begin).seconds)
  173. get_fault_warn_conf("test", "fault")