main_pred.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. from LIB.MIDDLE.ThermoRunaway.V1_0_2.Trunaway 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. start=time.time()
  22. now_time=datetime.datetime.now()
  23. start_time=now_time-datetime.timedelta(hours=6)
  24. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  25. end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
  26. #数据库配置
  27. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  28. port=3306
  29. db='safety_platform'
  30. user='qx_read'
  31. password='Qx@123456'
  32. #读取结果库数据......................................................
  33. param='product_id,start_time,end_time,diff_min,SOC,loss_sum,loss_max,diffV,downV,diffdownV'
  34. tablename='thermo_runaway'
  35. mysql = pymysql.connect (host=host, user=user, password=password, port=port, database=db)
  36. cursor = mysql.cursor()
  37. sql = "select {} from {} where end_time='0000-00-00 00:00:00'".format(param,tablename)
  38. cursor.execute(sql)
  39. res = cursor.fetchall()
  40. df_diag_ram= pd.DataFrame(res,columns=param.split(','))
  41. db_res_engine = create_engine(
  42. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  43. user, parse.quote_plus(password), host, port, db
  44. ))
  45. #调用主函数................................................................................................................................................................
  46. for sn in SNnums:
  47. try:
  48. group=sn[:5]
  49. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
  50. data_bms = df_data['bms']
  51. data_bms['sn']=sn
  52. if len(data_bms)>0:
  53. logger.info("SN: {} 数据开始预处理".format(sn))
  54. data_bms=delete(data_bms)
  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. #读取训练产出的模型状态空间:电压模型&温度模型
  63. model = model_dict[group]
  64. res,diff=res_output(df_stand,scaler,model,group,end_time)
  65. df_diag_ram_sn=df_diag_ram[df_diag_ram['product_id']==sn]
  66. if not df_diag_ram_sn.empty: #该sn相关结果非空
  67. new_res,update_res=arrange(res,df_diag_ram_sn,start_time,diff)
  68. if len(update_res)>0:
  69. cursor.execute("DELETE FROM thermo_runaway WHERE end_time = '0000-00-00 00:00:00' and product_id='{}'".format(sn))
  70. mysql.commit()
  71. update_res.to_sql("thermo_runaway",con=db_res_engine, if_exists="append",index=False)
  72. #新增结果存入结果库................................................................
  73. if len(new_res)>0:
  74. new_res.to_sql("thermo_runaway",con=db_res_engine, if_exists="append",index=False)
  75. else:
  76. res.to_sql("thermo_runaway",con=db_res_engine, if_exists="append",index=False)
  77. # end=time.time()
  78. # print(end-start)
  79. except Exception as e:
  80. logger.error(str(e))
  81. logger.error(traceback.format_exc())
  82. cursor.close()
  83. mysql.close()
  84. #...............................................主函数起定时作用.......................................................................................................................
  85. if __name__ == "__main__":
  86. # 日志
  87. log_path = 'log/'
  88. if not os.path.exists(log_path):
  89. os.makedirs(log_path)
  90. logger = logging.getLogger("main")
  91. logger.setLevel(logging.DEBUG)
  92. # 根据日期滚动(每天产生1个文件)
  93. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_info.log'.format(log_path), when="D", interval=1, backupCount=30,
  94. encoding="utf-8")
  95. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  96. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  97. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  98. fh.setFormatter(formatter)
  99. fh.setLevel(logging.INFO)
  100. logger.addHandler(fh)
  101. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_error.log'.format(log_path), when="D", interval=1, backupCount=30,
  102. encoding="utf-8")
  103. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  104. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  105. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  106. fh.setFormatter(formatter)
  107. fh.setLevel(logging.ERROR)
  108. logger.addHandler(fh)
  109. logger.info("pid is {}".format(os.getpid()))
  110. # # 更新sn列表
  111. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  112. port=3306
  113. db='qixiang_oss'
  114. user='qixiang_oss'
  115. password='Qixiang2021'
  116. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  117. cursor = conn.cursor()
  118. cursor.execute("select sn, imei, add_time from app_device where status in (1,2,3)")
  119. res = cursor.fetchall()
  120. df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  121. df_sn = df_sn.reset_index(drop=True)
  122. conn.close();
  123. SNnums = list(df_sn['sn'])
  124. scaler_list=[]
  125. model_list=[]
  126. for group in ['PK504','MGMCL','PK500']:
  127. scaler=pickle.load(open('D:/deploy/python_platform/data_analyze_platform/LIB/MIDDLE/ThermoRunaway/V1_0_2/train_out/scaler_'+group+'_05.pkl', 'rb'))
  128. model=load_model('D:/deploy/python_platform/data_analyze_platform/LIB/MIDDLE/ThermoRunaway/V1_0_2/train_out/model_'+group+'_05.h5')
  129. scaler_list.append(scaler)
  130. model_list.append(model)
  131. scaler_dict={'PK504':scaler_list[0],'MGMCL':scaler_list[1],'PK500':scaler_list[2]}
  132. model_dict={'PK504':model_list[0],'MGMCL':model_list[1],'PK500':model_list[2]}
  133. diag_cal()
  134. #定时任务.......................................................................................................................................................................
  135. scheduler = BlockingScheduler()
  136. scheduler.add_job(diag_cal, 'interval', hours=6)
  137. try:
  138. scheduler.start()
  139. except Exception as e:
  140. scheduler.shutdown()
  141. logger.error(str(e))
  142. logger.error(traceback.format_exc())