main_pred.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. from LIB.MIDDLE.FaultDetection.V1_0_2.aelstm import *
  2. import pymysql
  3. import datetime
  4. import pandas as pd
  5. from LIB.BACKEND import DBManager
  6. dbManager = DBManager.DBManager()
  7. from sqlalchemy import create_engine
  8. from urllib import parse
  9. import datetime, time
  10. from apscheduler.schedulers.blocking import BlockingScheduler
  11. import traceback
  12. import pickle
  13. from keras.models import load_model
  14. import logging
  15. import logging.handlers
  16. import os
  17. import re
  18. #...................................故障检测函数......................................................................................................................
  19. def diag_cal():
  20. global SNnums
  21. global scaler_dict, scaler2_dict, model_dict, model2_dict
  22. start=time.time()
  23. now_time=datetime.datetime.now()
  24. start_time=now_time-datetime.timedelta(hours=3)
  25. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  26. end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
  27. #数据库配置
  28. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  29. port=3306
  30. db='safety_platform'
  31. user='qx_read'
  32. password='Qx@123456'
  33. #读取结果库数据......................................................
  34. param='product_id,start_time,end_time,diff_min,SOC,AnoScoreV_sum_max,AnoScoreV_max_max,AnoScoreT_sum_max,AnoScoreT_max_max'
  35. tablename='fault_detection'
  36. mysql = pymysql.connect (host=host, user=user, password=password, port=port, database=db)
  37. cursor = mysql.cursor()
  38. sql = "select {} from {} where end_time='0000-00-00 00:00:00'".format(param,tablename)
  39. cursor.execute(sql)
  40. res = cursor.fetchall()
  41. df_diag_ram= pd.DataFrame(res,columns=param.split(','))
  42. db_res_engine = create_engine(
  43. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  44. user, parse.quote_plus(password), host, port, db
  45. ))
  46. #调用主函数................................................................................................................................................................
  47. for sn in SNnums:
  48. try:
  49. group=sn[:5]
  50. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
  51. data_bms = df_data['bms']
  52. data_bms['sn']=sn
  53. if len(data_bms)>0:
  54. logger.info("SN: {} 数据开始预处理".format(sn))
  55. data_stand=data_groups(data_bms,sn,start_time,end_time)
  56. df_stand=split(data_stand)
  57. res=pd.DataFrame()
  58. if len(df_stand)>0:
  59. #读取训练产出的缩放指标:均值&方差
  60. logger.info("SN: {} 数据开始模型预测".format(sn))
  61. scaler = scaler_dict[group]
  62. scaler2 = scaler2_dict[group]
  63. #读取训练产出的模型状态空间:电压模型&温度模型
  64. model = model_dict[group]
  65. model2 = model2_dict[group]
  66. res=prediction(df_stand,scaler,scaler2,model,model2)
  67. if len(res)>0:
  68. df_res2,diff=threshold(res,group,end_time)
  69. df_diag_ram_sn=df_diag_ram[df_diag_ram['product_id']==sn]
  70. if not df_diag_ram_sn.empty: #该sn相关结果非空
  71. new_res,update_res=arrange(df_res2,df_diag_ram_sn,start_time,diff)
  72. if len(update_res)>0:
  73. cursor.execute("DELETE FROM fault_detection WHERE end_time = '0000-00-00 00:00:00' and product_id='{}'".format(sn))
  74. mysql.commit()
  75. update_res.to_sql("fault_detection",con=db_res_engine, if_exists="append",index=False)
  76. #新增结果存入结果库................................................................
  77. if len(new_res)>0:
  78. new_res.to_sql("fault_detection",con=db_res_engine, if_exists="append",index=False)
  79. else:
  80. df_res2.to_sql("fault_detection",con=db_res_engine, if_exists="append",index=False)
  81. # end=time.time()
  82. # print(end-start)
  83. except Exception as e:
  84. logger.error(str(e))
  85. logger.error(traceback.format_exc())
  86. cursor.close()
  87. mysql.close()
  88. #...............................................主函数起定时作用.......................................................................................................................
  89. if __name__ == "__main__":
  90. # 日志
  91. log_path = 'log/'
  92. if not os.path.exists(log_path):
  93. os.makedirs(log_path)
  94. logger = logging.getLogger("main")
  95. logger.setLevel(logging.DEBUG)
  96. # 根据日期滚动(每天产生1个文件)
  97. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_info.log'.format(log_path), when="D", interval=1, backupCount=30,
  98. encoding="utf-8")
  99. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  100. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  101. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  102. fh.setFormatter(formatter)
  103. fh.setLevel(logging.INFO)
  104. logger.addHandler(fh)
  105. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_error.log'.format(log_path), when="D", interval=1, backupCount=30,
  106. encoding="utf-8")
  107. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  108. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  109. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  110. fh.setFormatter(formatter)
  111. fh.setLevel(logging.ERROR)
  112. logger.addHandler(fh)
  113. logger.info("pid is {}".format(os.getpid()))
  114. # # 更新sn列表
  115. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  116. port=3306
  117. db='qixiang_oss'
  118. user='qixiang_oss'
  119. password='Qixiang2021'
  120. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  121. cursor = conn.cursor()
  122. cursor.execute("select sn, imei, add_time from app_device where status in (1,2,3)")
  123. res = cursor.fetchall()
  124. df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  125. df_sn = df_sn.reset_index(drop=True)
  126. conn.close();
  127. SNnums = list(df_sn['sn'])
  128. scaler_list=[]
  129. scaler2_list=[]
  130. model_list=[]
  131. model2_list=[]
  132. for group in ['MGMLX','PK504','PK502','PK500','MGMCL']:
  133. scaler = pickle.load(open('D:/deploy/python_platform/data_analyze_platform/LIB/MIDDLE/FaultDetection/V1_0_2/train_out/scalerV_'+group+'_10.pkl', 'rb'))
  134. scaler2 = pickle.load(open('D:/deploy/python_platform/data_analyze_platform/LIB/MIDDLE/FaultDetection/V1_0_2/train_out/scalerT_'+group+'_10.pkl', 'rb'))
  135. model = load_model('D:/deploy/python_platform/data_analyze_platform/LIB/MIDDLE/FaultDetection/V1_0_2/train_out/modelV_'+group+'_10.h5')
  136. model2 = load_model('D:/deploy/python_platform/data_analyze_platform/LIB/MIDDLE/FaultDetection/V1_0_2/train_out/modelT_'+group+'_10.h5')
  137. scaler_list.append(scaler)
  138. scaler2_list.append(scaler2)
  139. model_list.append(model)
  140. model2_list.append(model2)
  141. scaler_dict={'MGMLX':scaler_list[0],'PK504':scaler_list[1],'PK502':scaler_list[2],'PK500':scaler_list[3],'MGMCL':scaler_list[4]}
  142. scaler2_dict={'MGMLX':scaler2_list[0],'PK504':scaler2_list[1],'PK502':scaler2_list[2],'PK500':scaler2_list[3],'MGMCL':scaler2_list[4]}
  143. model_dict={'MGMLX':model_list[0],'PK504':model_list[1],'PK502':model_list[2],'PK500':model_list[3],'MGMCL':model_list[4]}
  144. model2_dict={'MGMLX':model2_list[0],'PK504':model2_list[1],'PK502':model2_list[2],'PK500':model2_list[3],'MGMCL':model2_list[4]}
  145. logger.info("模型加载完成")
  146. diag_cal()
  147. #定时任务.......................................................................................................................................................................
  148. scheduler = BlockingScheduler()
  149. scheduler.add_job(diag_cal, 'interval', hours=3)
  150. try:
  151. scheduler.start()
  152. except Exception as e:
  153. scheduler.shutdown()
  154. logger.error(str(e))
  155. logger.error(traceback.format_exc())