main_pred.py 8.3 KB

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