main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import pandas as pd
  2. import pymysql
  3. from LIB.BACKEND import DBManager, Log
  4. from apscheduler.schedulers.blocking import BlockingScheduler
  5. import time, datetime
  6. from sqlalchemy import create_engine
  7. from urllib import parse
  8. from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload
  9. from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import log
  10. import CBMSBatInterShort
  11. import CBMSBatUniform
  12. import VoltStray
  13. import CBMSSafetyWarning
  14. #电池热安全预警核心算法函数......................................................................................................................
  15. def saftywarning_cal():
  16. global SNnums
  17. global df_warning_ram
  18. global df_warning_ram1
  19. global df_warning_ram2
  20. global df_warning_ram3
  21. global df_warning_ram4
  22. global df_lfp_ram
  23. global df_lfp_ram1
  24. global now_time
  25. # pd.set_option('display.width', 300) # 设置字符显示宽度
  26. # pd.set_option('display.max_rows', None) # 设置显示最大行
  27. # pd.set_option('display.max_columns', None) # 设置显示最大列,None为显示所有列
  28. start=time.time()
  29. now_time=datetime.datetime.now()
  30. start_time=now_time-datetime.timedelta(hours=6)
  31. start_time1=now_time-datetime.timedelta(days=7)
  32. start_time2=now_time-datetime.timedelta(days=3)
  33. start_time3=now_time-datetime.timedelta(days=1)
  34. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  35. start_time1=start_time1.strftime('%Y-%m-%d %H:%M:%S')
  36. start_time2=start_time2.strftime('%Y-%m-%d %H:%M:%S')
  37. start_time3=start_time3.strftime('%Y-%m-%d %H:%M:%S')
  38. end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
  39. # now_time=now_time+datetime.timedelta(hours=6)
  40. # start_time=now_time-datetime.timedelta(hours=6)
  41. # start_time1=now_time-datetime.timedelta(days=7)
  42. # start_time2=now_time-datetime.timedelta(days=3)
  43. # start_time3=now_time-datetime.timedelta(days=1)
  44. # start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  45. # start_time1=start_time1.strftime('%Y-%m-%d %H:%M:%S')
  46. # start_time2=start_time2.strftime('%Y-%m-%d %H:%M:%S')
  47. # start_time3=start_time3.strftime('%Y-%m-%d %H:%M:%S')
  48. # end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
  49. #数据库配置
  50. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  51. port=3306
  52. user='qx_algo_rw'
  53. password='qx@123456'
  54. #读取故障结果库中code==110且end_time='0000-00-00 00:00:00'...............................
  55. db='safety_platform'
  56. mysql = pymysql.connect (host=host, user=user, password=password, port=port, database=db)
  57. cursor = mysql.cursor()
  58. param='start_time,end_time,product_id,code,level,info,advice'
  59. tablename='all_fault_info_copy'
  60. sql = "select %s from %s where end_time='0000-00-00 00:00:00' and level=4" %(param,tablename)
  61. cursor.execute(sql)
  62. res = cursor.fetchall()
  63. df_fault_ram= pd.DataFrame(res,columns=param.split(','))
  64. db_res_engine1 = create_engine(
  65. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  66. user, parse.quote_plus(password), host, port, db
  67. ))
  68. db='qx_cas'
  69. db_res_engine2 = create_engine(
  70. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  71. user, parse.quote_plus(password), host, port, db
  72. ))
  73. for sn in SNnums:
  74. try:
  75. if 'PK500' in sn:
  76. celltype=1 #6040三元电芯
  77. elif 'PK502' in sn:
  78. celltype=2 #4840三元电芯
  79. elif 'K504B' in sn:
  80. celltype=99 #60ah林磷酸铁锂电芯
  81. elif 'MGMLXN750' in sn:
  82. celltype=3 #力信50ah三元电芯
  83. elif ('MGMCLN750' in sn) or ('UD' in sn):
  84. celltype=4 #CATL 50ah三元电芯
  85. elif 'TJMCL'in sn:
  86. celltype=100 #重卡换电
  87. else:
  88. print('SN:{},未找到对应电池类型!!!'.format(sn))
  89. continue
  90. # sys.exit()
  91. #读取原始数据库数据........................................................................................................................................................
  92. dbManager = DBManager.DBManager()
  93. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
  94. df_bms = df_data['bms']
  95. df_bms=df_bms.dropna(axis=0,subset=['总电流[A]','SOH[%]','SOC[%]']) #去除有空值的行
  96. df_bms.reset_index(inplace=True,drop=True) #重置索引
  97. # print(df_bms)
  98. # df_bms.to_csv(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\98Download\\'+sn+'_BMS_'+'.csv',encoding='GB18030')
  99. #读取结果数据库数据........................................................................................................................................................
  100. db='qx_cas'
  101. mode=1
  102. DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
  103. with DBRead as DBRead:
  104. df_soh=DBRead.getdata('time_st,sn,soh,cellsoh', tablename='cellstateestimation_soh', sn=sn, timename='time_sp', st=start_time, sp=end_time)
  105. df_uniform=DBRead.getdata('time,sn,cellsoc_diff,cellvolt_diff,cellmin_num,cellmax_num,cellvolt_rank', tablename='cellstateestimation_uniform_socvoltdiff', sn=sn, timename='time', st=start_time1, sp=end_time)
  106. if not df_bms.empty:
  107. #ram处理...............................................................................................................
  108. df_warning_ram_sn=df_warning_ram[df_warning_ram['sn']==sn]
  109. df_warning_ram_sn1=df_warning_ram1[df_warning_ram1['sn']==sn]
  110. df_warning_ram_sn2=df_warning_ram2[df_warning_ram2['sn']==sn]
  111. df_warning_ram_sn3=df_warning_ram3[df_warning_ram3['sn']==sn]
  112. df_warning_ram_sn4=df_warning_ram4[df_warning_ram4['sn']==sn]
  113. df_warning_ram_sn.reset_index(inplace=True,drop=True) #重置索引
  114. df_warning_ram_sn1.reset_index(inplace=True,drop=True) #重置索引
  115. df_warning_ram_sn2.reset_index(inplace=True,drop=True) #重置索引
  116. df_warning_ram_sn3.reset_index(inplace=True,drop=True) #重置索引
  117. df_warning_ram_sn4.reset_index(inplace=True,drop=True) #重置索引
  118. if celltype>50 and (not df_lfp_ram.empty):
  119. df_lfp_ram_sn=df_lfp_ram[df_lfp_ram['sn']==sn]
  120. df_lfp_ram_sn.reset_index(inplace=True,drop=True) #重置索引
  121. else:
  122. df_lfp_ram_sn=pd.DataFrame()
  123. df_lfp_ram=pd.DataFrame(columns=df_bms.columns.tolist()+['sn'])
  124. if celltype>50 and (not df_lfp_ram1.empty):
  125. df_lfp_ram_sn1=df_lfp_ram1[df_lfp_ram1['sn']==sn]
  126. df_lfp_ram_sn1.reset_index(inplace=True,drop=True) #重置索引
  127. else:
  128. df_lfp_ram_sn1=pd.DataFrame()
  129. df_lfp_ram1=pd.DataFrame(columns=df_bms.columns.tolist()+['sn'])
  130. #内短路计算..................................................................................................................................................
  131. BatShort=CBMSBatInterShort.BatInterShort(sn,celltype,df_bms,df_soh,df_warning_ram_sn,df_warning_ram_sn1,df_warning_ram_sn2,df_warning_ram_sn3,df_lfp_ram_sn)
  132. df_short_res, df_ram_res, df_ram_res1, df_ram_res2, df_ram_res3, df_ram_res5=BatShort.intershort()
  133. if not df_short_res.empty:
  134. df_short_res.to_sql("cellstateestimation_intershort",con=db_res_engine2, if_exists="append",index=False)
  135. #静置电压排名..................................................................................................................................................
  136. BatUniform=CBMSBatUniform.BatUniform(sn,celltype,df_bms,df_uniform,df_ram_res3,df_lfp_ram_sn1)
  137. df_rank_res, df_ram_res3, df_ram_res6=BatUniform.batuniform()
  138. if not df_rank_res.empty:
  139. df_uniform=df_rank_res
  140. df_uniform.to_sql("cellstateestimation_uniform_socvoltdiff",con=db_res_engine2, if_exists="append",index=False)
  141. #电压离群.....................................................................................................................................................
  142. df_voltsigma,df_ram_res4=VoltStray.main(sn,df_bms,df_soh,celltype,df_warning_ram_sn4)
  143. if not df_voltsigma.empty:
  144. df_voltsigma.to_sql("outlier_voltchangeratio",con=db_res_engine2, if_exists="append",index=False)
  145. #ram处理................................................................................................................
  146. df_warning_ram=df_warning_ram.drop(df_warning_ram[df_warning_ram.sn==sn].index)
  147. df_warning_ram1=df_warning_ram1.drop(df_warning_ram1[df_warning_ram1.sn==sn].index)
  148. df_warning_ram2=df_warning_ram2.drop(df_warning_ram2[df_warning_ram2.sn==sn].index)
  149. df_warning_ram3=df_warning_ram3.drop(df_warning_ram3[df_warning_ram3.sn==sn].index)
  150. df_warning_ram4=df_warning_ram4.drop(df_warning_ram4[df_warning_ram4.sn==sn].index)
  151. df_warning_ram=pd.concat([df_warning_ram,df_ram_res],ignore_index=True)
  152. df_warning_ram1=pd.concat([df_warning_ram1,df_ram_res1],ignore_index=True)
  153. df_warning_ram2=pd.concat([df_warning_ram2,df_ram_res2],ignore_index=True)
  154. df_warning_ram3=pd.concat([df_warning_ram3,df_ram_res3],ignore_index=True)
  155. df_warning_ram4=pd.concat([df_warning_ram4,df_ram_res4],ignore_index=True)
  156. if celltype>50:
  157. df_lfp_ram=df_lfp_ram.drop(df_lfp_ram[df_lfp_ram.sn==sn].index)
  158. df_lfp_ram=pd.concat([df_lfp_ram,df_ram_res5],ignore_index=True)
  159. df_lfp_ram1=df_lfp_ram1.drop(df_lfp_ram1[df_lfp_ram1.sn==sn].index)
  160. df_lfp_ram1=pd.concat([df_lfp_ram1,df_ram_res6],ignore_index=True)
  161. else:
  162. df_voltsigma=pd.DataFrame()
  163. #电池热安全预警..............................................................................................................................................................
  164. #读取内短路、析锂和一致性结果数据库数据
  165. db='qx_cas'
  166. mode=2
  167. tablename1='cellstateestimation_intershort'
  168. tablename3='cellstateestimation_uniform_socvoltdiff'
  169. tablename4='outlier_voltchangeratio' #电压离群表单
  170. DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
  171. with DBRead as DBRead:
  172. df_short=DBRead.getdata('time_sp,sn,short_current', tablename=tablename1, sn=sn, timename='time_sp', st=start_time1, sp=end_time)
  173. # df_liplated=DBRead.getdata('time,sn,liplated,liplated_amount', tablename=tablename2, sn=sn, timename='time', st=start_time2, sp=end_time)
  174. df_uniform=DBRead.getdata('time,sn,cellsoc_diff,cellvolt_diff,cellmin_num,cellmax_num,cellvolt_rank', tablename=tablename3, sn=sn, timename='time', st=start_time2, sp=end_time)
  175. df_voltsigma=DBRead.getdata('time,sn,VolOl_Uni,VolChng_Uni', tablename=tablename4, sn=sn, timename='time', st=start_time3, sp=end_time)
  176. df_uniform=df_uniform.dropna(axis=0,how='any')
  177. #获取sn的故障RAM
  178. df_fault_ram_sn=df_fault_ram[df_fault_ram['product_id']==sn]
  179. df_fault_ram_sn.reset_index(inplace=True,drop=True) #重置索引
  180. #热安全预警
  181. BatWarning=CBMSSafetyWarning.SafetyWarning(sn,celltype,df_short,df_uniform,df_voltsigma,df_soh,df_fault_ram_sn)
  182. df_warning_res=BatWarning.diag()
  183. if not df_warning_res.empty:
  184. df_warning_new = pd.concat([df_warning_res,df_fault_ram_sn,df_fault_ram_sn]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
  185. df_warning_new.reset_index(inplace=True,drop=True) #重置索引
  186. df_warning_end=pd.concat([df_warning_res,df_warning_new,df_warning_new]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
  187. df_warning_end=df_warning_end[df_warning_end['end_time'] != '0000-00-00 00:00:00']
  188. df_warning_end.reset_index(inplace=True,drop=True) #重置索引
  189. #新增热失控预警写入数据库
  190. if not df_warning_new.empty:
  191. df_warning_new.to_sql("all_fault_info_copy",con=db_res_engine1, if_exists="append",index=False)
  192. #结束热失控预警更新数据库
  193. if not df_warning_end.empty:
  194. for j in range(len(df_warning_end)):
  195. cursor.execute('''
  196. update all_fault_info_copy set update_time='{}',end_time='{}', Batpos={} where product_id='{}' and end_time='0000-00-00 00:00:00' and code='{}'
  197. '''.format(datetime.datetime.now(), df_warning_end.loc[j,'end_time'], 1 ,sn, df_warning_end.loc[j,'code']))
  198. mysql.commit()
  199. end=time.time()
  200. print(end-start)
  201. except Exception as e:
  202. print(repr(e))
  203. mylog.logopt(sn+str(e))
  204. mysql.close()
  205. cursor.close()
  206. #...............................................主函数起定时作用.......................................................................................................................
  207. if __name__ == "__main__":
  208. excelpath=r'D:\Develop\User\Songpengfei\data_analyze_platform\WORK\01qixiang\sn-20210903.xlsx'
  209. SNdata_6060 = pd.read_excel(excelpath, sheet_name='科易6060')
  210. SNdata_6040 = pd.read_excel(excelpath, sheet_name='科易6040')
  211. SNdata_4840 = pd.read_excel(excelpath, sheet_name='科易4840')
  212. SNdata_L7255 = pd.read_excel(excelpath, sheet_name='格林美-力信7255')
  213. SNdata_C7255 = pd.read_excel(excelpath, sheet_name='格林美-CATL7255')
  214. SNdata_U7255 = pd.read_excel(excelpath, sheet_name='优旦7255')
  215. SNnums_6060=SNdata_6060['SN号'].tolist()
  216. SNnums_6040=SNdata_6040['SN号'].tolist()
  217. SNnums_4840=SNdata_4840['SN号'].tolist()
  218. SNnums_L7255=SNdata_L7255['SN号'].tolist()
  219. SNnums_C7255=SNdata_C7255['SN号'].tolist()
  220. SNnums_U7255=SNdata_U7255['SN号'].tolist()
  221. SNnums=SNnums_6060 + SNnums_6040 + SNnums_4840 + SNnums_L7255 + SNnums_C7255 + SNnums_U7255
  222. # SNnums=['MGMCLN750N215N044']
  223. mylog=log.Mylog('log_warning.txt','error')
  224. mylog.logcfg()
  225. #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取...................................
  226. df_warning_ram=pd.DataFrame(columns=['sn','time','deltsoc','cellsoc'])
  227. df_warning_ram1=pd.DataFrame(columns=['sn','time1','deltsoc1'])
  228. df_warning_ram2=pd.DataFrame(columns=['sn','time2','deltAs2'])
  229. df_warning_ram3=pd.DataFrame(columns=['sn','time3','standingtime','standingtime1','standingtime2'])
  230. df_warning_ram4=pd.DataFrame(columns=['sn','time4','cellsoc'])
  231. df_lfp_ram=pd.DataFrame()
  232. df_lfp_ram1=pd.DataFrame()
  233. now_time='2022-2-15 10:00:56'
  234. now_time=datetime.datetime.strptime(now_time,'%Y-%m-%d %H:%M:%S')
  235. #定时任务.......................................................................................................................................................................
  236. saftywarning_cal()
  237. scheduler = BlockingScheduler()
  238. scheduler.add_job(saftywarning_cal, 'interval', hours=6)
  239. try:
  240. scheduler.start()
  241. except Exception as e:
  242. scheduler.shutdown()
  243. print(repr(e))
  244. mylog.logopt(e)