qingfeng 2 роки тому
батько
коміт
f291778ca9

BIN
LIB/BACKEND/__pycache__/DBManager.cpython-38.pyc


BIN
LIB/BACKEND/__pycache__/Log.cpython-38.pyc


BIN
LIB/MIDDLE/CellStateEstimation/Common/V1_0_1/__pycache__/BatParam.cpython-38.pyc


BIN
LIB/MIDDLE/CellStateEstimation/Common/V1_0_1/__pycache__/log.cpython-38.pyc


BIN
USER/SPF/01qixiang/06BatSafetyAlarm/__pycache__/CBMSSafetyAlarm.cpython-38.pyc


+ 0 - 248
USER/SPF/01qixiang/06BatSafetyAlarm/deploy - 副本.py

@@ -1,248 +0,0 @@
-
-__author__ = 'lmstack'
-#coding=utf-8
-import os
-import datetime
-import pandas as pd
-from LIB.BACKEND import DBManager, Log
-from sqlalchemy import create_engine
-from sqlalchemy.orm import sessionmaker
-import time, datetime
-import traceback
-from LIB.MIDDLE.CellStateEstimation.Common import log
-import CBMSSafetyAlarm
-
-from LIB.MIDDLE.CellStateEstimation.Common import DBDownload
-from urllib import parse
-import pymysql
-import pdb
-from apscheduler.schedulers.blocking import BlockingScheduler
-import datacompy
-import logging
-import multiprocessing
-#...................................电池包电芯安全诊断函数......................................................................................................................
-def diag_cal(df_sn, df_bms_ram, log_name):
-    
-    # 日志
-    logger = logging.getLogger()
-    fh = logging.FileHandler(log_name + ".log", encoding="utf-8",mode="a")
-    formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
-    fh.setFormatter(formatter)
-    logger.addHandler(fh)
-    logger.setLevel(logging.INFO)
-    logger.info("pid is {}".format(os.getpid()))
-    
-    # 读取结果数据库
-    host2='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
-    port2=3306
-    db2='safety_platform'
-    user2='qx_algo_rw'
-    password2='qx@123456'
-    
-    db_res_engine = create_engine(
-        "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
-            user2, parse.quote_plus(password2), host2, port2, db2
-        ))
-    
-    conn = pymysql.connect(host=host2, port=port2, user=user2, password=password2, database=db2)
-    cursor = conn.cursor()
-    
-    result=pd.read_sql("select start_time, end_time, product_id, code, level, info, advice from all_fault_info where factory = '{}'".format('骑享'), db_res_engine)
-    result = result[['start_time', 'end_time', 'product_id', 'code', 'level', 'info', 'advice']]
-    df_diag_ram=result[(result['end_time']=='0000-00-00 00:00:00') & (result['code']==119)]
-    df_bms_ram=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])
-    
-    start=time.time()
-    now_time=datetime.datetime.now()
-    start_time=now_time-datetime.timedelta(seconds=70)
-    start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
-    end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
-
-    for i in range(0, len(df_sn)):
-        try:
-            sn = df_sn.loc[i, 'sn']
-            if 'PK500' in sn:
-                celltype=1 #6040三元电芯
-            elif 'PK502' in sn:
-                celltype=2 #4840三元电芯
-            elif 'K504B' in sn:
-                celltype=99    #60ah林磷酸铁锂电芯
-            elif 'MGMLXN750' in sn:
-                celltype=3 #力信50ah三元电芯
-            elif 'MGMCLN750' or 'UD' in sn: 
-                celltype=4 #CATL 50ah三元电芯
-            else:
-                print('SN:{},未找到对应电池类型!!!'.format(sn))
-                continue
-            
-            logger.info("pid-{} celltype-{} SN: {} START!".format(os.getpid(), celltype, sn))
-
-            #读取原始数据库数据........................................................................................................................................................
-            dbManager = DBManager.DBManager()
-            df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
-            df_bms = df_data['bms']
-            # print(df_bms)
-
-            #电池诊断................................................................................................................................................................
-            df_diag_ram_sn=df_diag_ram[df_diag_ram['product_id']==sn]
-            df_bms_ram_sn=df_bms_ram[df_bms_ram['sn']==sn]
-            if df_diag_ram_sn.empty:   
-                if not df_bms.empty:
-                    SafetyAlarm=CBMSSafetyAlarm.SafetyAlarm(sn,celltype,df_bms, df_bms_ram_sn)
-                    df_diag_res, df_bms_res=SafetyAlarm.diag() 
-
-                    #更新bms的ram数据
-                    sn_index=df_bms_ram.loc[df_bms_ram['sn']==sn].index
-                    df_bms_ram=df_bms_ram.drop(index=sn_index)
-                    df_bms_ram=df_bms_ram.append(df_bms_res)
-                    # sn_index=df_diag_ram.loc[df_diag_ram['product_id']==sn].index
-                    # df_diag_ram=df_diag_ram.drop(index=sn_index)
-                    # df_diag_ram=df_diag_ram.append(df_diag_res)
-                    # df_diag_ram.reset_index(inplace=True,drop=True)     #重置索引
-
-                    #当前热失控故障写入数据库
-                    if not df_diag_res.empty:
-                        df_diag_res.columns = ['start_time', 'end_time', 'product_id', 'code', 'level', 'info', 'advice']
-                        df_diag_res['add_time'] = datetime.datetime.now()
-                        df_diag_res['factory'] = '骑享'
-                        df_diag_res.to_sql("all_fault_info",con=db_res_engine, if_exists="append",index=False)
-
-                    
-                #当前热失控已超过1天变为历史故障并写入数据库,并删除原有数据库中的当前故障和ram中的当前故障
-            else:
-                fault_time=datetime.datetime.strptime(df_diag_ram_sn.iloc[-1]['start_time'], '%Y-%m-%d %H:%M:%S')
-                if (now_time-fault_time).total_seconds()>24*3600:
-                    df_diag_ram_sn['end_time']=end_time
-                    df_diag_ram_sn['Batpos']=1
-                
-                    try:
-
-                        cursor.execute('''
-                                    update all_fault_info set update_time='{}',end_time='{}', Batpos={} where product_id='{}' and end_time='0000-00-00 00:00:00' and code={} and factory='骑享'
-                                    '''.format(datetime.datetime.now(), end_time, 1,sn, 119))
-                        conn.commit()
-                        conn.close();
-                    except:
-                        logger.error(traceback.format_exc)
-                        logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
-                        conn.close();
-        except:
-            logger.error(traceback.format_exc)
-            logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
-    cursor.close()
-    conn.close()
-    db_res_engine.dispose()
-    logger.info("pid-{} Done!".format(os.getpid()))
-
-#...................................................主进程...........................................................................................................
-def mainprocess():
-    global df_bms_ram
-    global log_path
-    # 更新sn列表
-    # host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
-    # port=3306
-    # db='qixiang_oss'
-    # user='qixiang_oss'
-    # password='Qixiang2021'
-    # conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
-    # cursor = conn.cursor()
-    # cursor.execute("select sn, imei, add_time from app_device")
-    # res = cursor.fetchall()
-    # df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
-    # df_sn = df_sn.reset_index(drop=True)
-    # cursor.close()
-    # conn.close();
-    df_sn=pd.DataFrame(columns=['sn'])
-    df_sn['sn']=['PK504B10100004434', 'MGMCLN750N215N205', 'PK504B10100004447', 'PK504B10100004379', 'PK504B10100004483']
-    process = 2
-    pool = multiprocessing.Pool(processes = process)
-
-    for i in range(process):
-        sn_list = df_sn[int(len(df_sn)*i/process):int(len(df_sn)*(i+1)/process)]
-        sn_list = sn_list.reset_index(drop=True)
-        log_name = log_path + '/log_' + str(i)
-        pool.apply_async(diag_cal, (sn_list,df_bms_ram,log_name))
-
-    pool.close()
-    pool.join()
-if __name__ == "__main__":
-    
-    # 时间设置
-    # now_time = datetime.datetime.now()
-    # pre_time = now_time + dateutil.relativedelta.relativedelta(days=-1)# 前一日
-    # end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d 00:00:00")
-    # start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d 00:00:00")
-    
-    history_run_flag = False # 历史数据运行标志
-    
-
-    # # 更新sn列表
-    # host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
-    # port=3306
-    # db='qixiang_oss'
-    # user='qixiang_oss'
-    # password='Qixiang2021'
-    # conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
-    # cursor = conn.cursor()
-    # cursor.execute("select sn, imei, add_time from app_device")
-    # res = cursor.fetchall()
-    # df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
-    # df_sn = df_sn.reset_index(drop=True)
-    # conn.close();
-    
-    # 数据库配置
-    host = 'rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
-    port = 3306
-    user = 'qx_cas'
-    password = parse.quote_plus('Qx@123456')
-    database = 'qx_cas'
-
-    db_engine = create_engine(
-        "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
-            user, password, host, port, database
-        ))
-    DbSession = sessionmaker(bind=db_engine)
-    
-    # 运行历史数据配置
-    
-    df_first_data_time = pd.read_sql("select * from bat_first_data_time", db_engine)
-
-    
-    # 日志配置
-    now_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).replace(":","_")
-    log_path = 'log/' + now_str
-    if not os.path.exists(log_path):
-        os.makedirs(log_path)
-    log = Log.Mylog(log_name='batsafetyAlarm', log_level = 'info')
-    log.set_file_hl(file_name='{}/info.log'.format(log_path), log_level='info', size=1024* 1024 * 100)
-    log.set_file_hl(file_name='{}/error.log'.format(log_path), log_level='error', size=1024* 1024 * 100)
-    logger = log.get_logger()
-
-    logger.info("pid is {}".format(os.getpid()))
-    
-    # 算法参数
-    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
-    port=3306
-    db='safety_platform'
-    user='qx_read'
-    password=parse.quote_plus('Qx@123456')
-    tablename='all_fault_info'
-    db_res_engine = create_engine(
-        "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
-            user, password, host, port, db
-        ))
-
-        
-    #ram参数初始化........................................................................................................
-    df_bms_ram=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])
-
-    #定时任务.......................................................................................................................................................................
-    scheduler = BlockingScheduler()
-    scheduler.add_job(mainprocess, 'interval', seconds=60, id='diag_job')
-
-    try:  
-        scheduler.start()
-    except Exception as e:
-        scheduler.shutdown()
-        logger.error(str(e))
-    

+ 0 - 906
USER/SPF/01qixiang/07BatSafetyWarning copy/CBMSBatInterShort.py

@@ -1,906 +0,0 @@
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-import datetime
-# from pymysql import paramstyle
-from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import BatParam
-
-class BatInterShort():
-    def __init__(self,sn,celltype,df_bms,df_soh,df_last,df_last1,df_last2,df_last3,df_lfp):  #参数初始化
-
-        if (not df_lfp.empty) and celltype>50:
-            df_lfp.drop(['sn'],axis=1)
-            df_bms=pd.concat([df_lfp, df_bms], ignore_index=True)
-        else:
-            pass
-
-        self.sn=sn
-        self.celltype=celltype
-        self.param=BatParam.BatParam(celltype)
-        self.packcrnt=df_bms['总电流[A]']*self.param.PackCrntDec
-        self.packvolt=df_bms['总电压[V]']
-        self.bms_soc=df_bms['SOC[%]']
-        df_bms['time']=pd.to_datetime(df_bms['时间戳'], format='%Y-%m-%d %H:%M:%S')
-        self.bmstime= df_bms['time']
-
-        self.df_bms=df_bms
-        self.df_soh=df_soh
-        self.df_last=df_last
-        self.df_last1=df_last1
-        self.df_last2=df_last2
-        self.df_last3=df_last3
-        self.df_lfp=df_lfp
-
-        self.cellvolt_name=['单体电压'+str(x) for x in range(1,self.param.CellVoltNums+1)]
-        self.celltemp_name=['单体温度'+str(x) for x in range(1,self.param.CellTempNums+1)]
-    
-    def intershort(self):
-        if self.celltype<=50:
-            df_res, df_ram_last, df_ram_last1, df_ram_last3=self._ncm_intershort()
-            return df_res, df_ram_last, df_ram_last1,self.df_last2, df_ram_last3,self.df_lfp
-            
-        else:
-            df_res, df_ram_last, df_ram_last1, df_ram_last2, df_ram_last3, df_ram_lfp=self._lfp_intershort()
-            return df_res, df_ram_last, df_ram_last1, df_ram_last2, df_ram_last3, df_ram_lfp
-
-
-    #定义滑动滤波函数....................................................................................
-    def _np_move_avg(self,a, n, mode="same"): 
-        return (np.convolve(a, np.ones((n,)) / n, mode=mode))
-    
-    #寻找当前行数据的最小温度值.............................................................................
-    def _celltemp_weight(self,num):   
-        celltemp = list(self.df_bms.loc[num,self.celltemp_name])
-        celltemp=min(celltemp)
-        self.celltemp=celltemp
-        if self.celltype==99:
-            if celltemp>=25:
-                self.tempweight=1
-                self.StandardStandingTime=4800
-            elif celltemp>=15:
-                self.tempweight=0.6
-                self.StandardStandingTime=7200
-            elif celltemp>=5:
-                self.tempweight=0.
-                self.StandardStandingTime=10800
-            else:
-                self.tempweight=0.1
-                self.StandardStandingTime=10800
-        else:
-            if celltemp>=25:
-                self.tempweight=1
-                self.StandardStandingTime=4800
-            elif celltemp>=15:
-                self.tempweight=0.8
-                self.StandardStandingTime=7200
-            elif celltemp>=5:
-                self.tempweight=0.6
-                self.StandardStandingTime=7200
-            else:
-                self.tempweight=0.2
-                self.StandardStandingTime=10800
-
-    #获取前半个小时每个电压的平均值........................................................................................
-    def _avgvolt_get(self,num): 
-        time_now=self.df_bms.loc[num, 'time']
-        time_last=time_now-datetime.timedelta(seconds=1800)
-        df_volt=self.df_bms[(self.df_bms['time']>=time_last) & (self.df_bms['time']<=time_now)]
-        df_volt=df_volt[self.cellvolt_name]
-        cellvolt_std=df_volt.std(axis=0)
-        if len(df_volt)>2 and max(cellvolt_std)<1.5:
-            cellvolt_sum=df_volt.sum(0)-df_volt.max(0)-df_volt.min(0)
-            cellvolt_mean=cellvolt_sum/(len(df_volt)-2)
-            cellvolt=cellvolt_mean/1000
-        elif len(df_volt)==2:
-            # df_volt=pd.DataFrame(df_volt,dtype=np.float)
-            if max(abs(df_volt.iloc[1]-df_volt.iloc[0]))<3:
-                cellvolt=df_volt.mean(0)/1000
-            else:
-                cellvolt=pd.DataFrame()
-        else:
-            cellvolt=pd.DataFrame()
-        return cellvolt
-    
-    #获取单个电压值.................................................................................................
-    def _singlevolt_get(self,num,series,mode):  #mode==1取当前行单体电压值,mode==2取某个单体所有电压值
-        s=str(series)
-        if mode==1:
-            singlevolt=self.df_bms.loc[num,'单体电压' + s]/1000
-            return singlevolt
-        else:
-            singlevolt=self.df_bms['单体电压' + s]/1000
-            return singlevolt
-
-    #获取当前行所有电压数据........................................................................................
-    def _cellvolt_get(self,num):
-        cellvolt = np.array(self.df_bms.loc[num,self.cellvolt_name])/1000
-        return cellvolt
-
-    #获取当前行所有soc差...........................................................................................
-    def _celldeltsoc_get(self,cellvolt_list,dict_baltime,capacity): 
-        cellsoc=[]
-        celldeltsoc=[]
-        for j in range(self.param.CellVoltNums):   #获取每个电芯电压对应的SOC值
-            cellvolt=cellvolt_list[j]
-            ocv_soc=np.interp(cellvolt,self.param.LookTab_OCV,self.param.LookTab_SOC)
-            if j+1 in dict_baltime.keys():
-                ocv_soc=ocv_soc+dict_baltime[j+1]*self.param.BalCurrent/(capacity*3600)   #补偿均衡电流
-            else:
-                pass
-            cellsoc.append(ocv_soc)
-        
-        if self.celltype==1 or self.celltype==2:
-            consum_num=7
-            cellsoc1=cellsoc[:self.param.CellVoltNums-consum_num]    #切片,将bms耗电的电芯和非耗电的电芯分离开
-            cellsocmean1=(sum(cellsoc1)-max(cellsoc1)-min(cellsoc1))/(len(cellsoc1)-2)
-            cellsoc2=cellsoc[self.param.CellVoltNums-consum_num:]
-            cellsocmean2=(sum(cellsoc2)-max(cellsoc2)-min(cellsoc2))/(len(cellsoc2)-2)
-            
-            for j in range(len(cellsoc)):   #计算每个电芯的soc差
-                if j<self.param.CellVoltNums-consum_num:
-                    celldeltsoc.append(cellsoc[j]-cellsocmean1)
-                else:
-                    celldeltsoc.append(cellsoc[j]-cellsocmean2)
-            return np.array(celldeltsoc), np.array(cellsoc)
-        
-        elif self.celltype==99:
-            consum_num=10
-            cellsoc1=cellsoc[:self.param.CellVoltNums-consum_num]    #切片,将bms耗电的电芯和非耗电的电芯分离开
-            cellsocmean1=(sum(cellsoc1)-max(cellsoc1)-min(cellsoc1))/(len(cellsoc1)-2)
-            cellsoc2=cellsoc[self.param.CellVoltNums-consum_num:]
-            cellsocmean2=(sum(cellsoc2)-max(cellsoc2)-min(cellsoc2))/(len(cellsoc2)-2)
-            
-            for j in range(len(cellsoc)):   #计算每个电芯的soc差
-                if j<self.param.CellVoltNums-consum_num:
-                    celldeltsoc.append(cellsoc[j]-cellsocmean1)
-                else:
-                    celldeltsoc.append(cellsoc[j]-cellsocmean2)
-            return np.array(celldeltsoc), np.array(cellsoc)
-
-        else:
-            cellsocmean=(sum(cellsoc)-max(cellsoc)-min(cellsoc))/(len(cellsoc)-2)
-            for j in range(len(cellsoc)):   #计算每个电芯的soc差
-                celldeltsoc.append(cellsoc[j]-cellsocmean)
-            return np.array(celldeltsoc), np.array(cellsoc)
- 
-    #获取所有电芯的As差
-    def _cellDeltAs_get(self,chrg_st,chrg_end,dict_baltime):
-        cellAs=[]
-        celldeltAs=[]
-        for j in range(1, self.param.CellVoltNums+1):   #获取每个电芯电压>峰值电压的充入As数
-            if j in dict_baltime.keys():    #补偿均衡电流
-                As=-self.param.BalCurrent*dict_baltime[j]
-            else:    
-                As=0
-            As_tatol=0
-            symbol=0
-            for m in range(chrg_st+1,chrg_end):
-                As=As-self.packcrnt[m]*(self.bmstime[m]-self.bmstime[m-1]).total_seconds()
-                if symbol<5:
-                    if self.df_bms.loc[m,'单体电压'+str(j)]/1000>self.param.PeakCellVolt[symbol]:
-                        As_tatol=As_tatol+As
-                        symbol=symbol+1
-                    else:
-                        continue
-                else:
-                    cellAs.append(As_tatol/5)
-                    break
-        
-        if self.celltype==99:
-            consum_num=10
-            cellAs1=cellAs[:self.param.CellVoltNums-consum_num]    #切片,将bms耗电的电芯和非耗电的电芯分离开
-            cellAsmean1=(sum(cellAs1)-max(cellAs1)-min(cellAs1))/(len(cellAs1)-2)
-            cellAs2=cellAs[self.param.CellVoltNums-consum_num:]
-            cellAsmean2=(sum(cellAs2)-max(cellAs2)-min(cellAs2))/(len(cellAs2)-2)
-            
-            for j in range(len(cellAs)):   #计算每个电芯的soc差
-                if j<self.param.CellVoltNums-consum_num:
-                    celldeltAs.append(cellAs[j]-cellAsmean1)
-                else:
-                    celldeltAs.append(cellAs[j]-cellAsmean2)
-        else:
-            cellAsmean=(sum(cellAs)-max(cellAs)-min(cellAs))/(len(cellAs)-2)
-            for j in range(len(cellAs)):   #计算每个电芯的soc差
-                celldeltAs.append(cellAs[j]-cellAsmean)
-            
-        return np.array(celldeltAs)
-    
-    #寻找DVDQ的峰值点,并返回..........................................................................................................................
-    def _dvdq_peak(self, time, soc, cellvolt, packcrnt):
-        cellvolt = self._np_move_avg(cellvolt, 3, mode="same")
-        Soc = 0
-        Ah = 0
-        Volt = cellvolt[0]
-        DV_Volt = []
-        DQ_Ah = []
-        DVDQ = []
-        time1 = []
-        soc1 = []
-        soc2 = []
-        xvolt=[]
-
-        for m in range(1, len(time)):
-            Step = (time[m] - time[m - 1]).total_seconds()
-            Soc = Soc - packcrnt[m] * Step * 100 / (3600 * self.param.Capacity)
-            Ah = Ah - packcrnt[m] * Step / 3600
-            if (cellvolt[m]-Volt)>0.0015 and Ah>0:
-                DQ_Ah.append(Ah)
-                DV_Volt.append(cellvolt[m]-Volt)
-                DVDQ.append((DV_Volt[-1])/Ah)
-                xvolt.append(cellvolt[m])
-                Volt=cellvolt[m]
-                Ah = 0
-                soc1.append(Soc)
-                time1.append(time[m])
-                soc2.append(soc[m])
-
-        #切片,去除前后10min的数据
-        df_Data1 = pd.DataFrame({'time': time1,
-                                'SOC': soc2,
-                                'DVDQ': DVDQ,
-                                'AhSoc': soc1,
-                                'DQ_Ah':DQ_Ah,
-                                'DV_Volt':DV_Volt,
-                                'XVOLT':xvolt})
-        start_time=df_Data1.loc[0,'time']
-        start_time=start_time+datetime.timedelta(seconds=900)
-        end_time=df_Data1.loc[len(time1)-1,'time']
-        end_time=end_time-datetime.timedelta(seconds=1200)
-        if soc2[0]<36:
-            df_Data1=df_Data1[(df_Data1['SOC']>40) & (df_Data1['SOC']<80)]
-        else:
-            df_Data1=df_Data1[(df_Data1['time']>start_time) & (df_Data1['SOC']<80)]
-        df_Data1=df_Data1[(df_Data1['XVOLT']>self.param.PeakVoltLowLmt) & (df_Data1['XVOLT']<self.param.PeakVoltUpLmt)]
-
-        # print(packcrnt[int(len(time)/2)], min(self.celltemp))
-        # ax1 = plt.subplot(3, 1, 1)
-        # plt.plot(df_Data1['SOC'],df_Data1['DQ_Ah'],'g*-')
-        # plt.xlabel('SOC/%')
-        # plt.ylabel('DQ_Ah')
-        # plt.legend()
-        # ax1 = plt.subplot(3, 1, 2)
-        # plt.plot(df_Data1['SOC'],df_Data1['XVOLT'],'y*-')
-        # plt.xlabel('SOC/%')
-        # plt.ylabel('Volt/V')
-        # plt.legend()
-        # ax1 = plt.subplot(3, 1, 3)
-        # plt.plot(df_Data1['SOC'], df_Data1['DVDQ'], 'r*-')
-        # plt.xlabel('SOC/%')
-        # plt.ylabel('DV/DQ')
-        # plt.legend()
-        # # plt.show()
-
-        if len(df_Data1)>2:     #寻找峰值点,且峰值点个数>2
-            PeakIndex = df_Data1['DVDQ'].idxmax()
-            df_Data2 = df_Data1[(df_Data1['SOC'] > (df_Data1['SOC'][PeakIndex] - 0.5)) & (df_Data1['SOC'] < (df_Data1['SOC'][PeakIndex] + 0.5))]
-            if len(df_Data2) > 1 and df_Data1.loc[PeakIndex,'XVOLT']<self.param.PeakVoltUpLmt-0.015:
-                return df_Data1['AhSoc'][PeakIndex]
-            else:
-                df_Data1 = df_Data1.drop([PeakIndex])
-                PeakIndex = df_Data1['DVDQ'].idxmax()
-                df_Data2 = df_Data1[(df_Data1['SOC'] > (df_Data1['SOC'][PeakIndex] - 0.5)) & (df_Data1['SOC'] < (df_Data1['SOC'][PeakIndex] + 0.5))]
-                if len(df_Data2) > 1 and df_Data1.loc[PeakIndex,'XVOLT']<self.param.PeakVoltUpLmt-0.015:
-                    return df_Data1['AhSoc'][PeakIndex]
-                else:
-                    return 0
-        else:
-            return 0
-
-    #计算每个电芯的均衡时长..........................................................................................................................
-    def _bal_time(self,dict_bal):
-        dict_baltime={}
-        dict_baltime1={}
-        for key in dict_bal:
-            count=1
-            x=eval(key)
-            while x>0:
-                if x & 1==1:    #判断最后一位是否为1
-                    if count in dict_baltime.keys():
-                        dict_baltime[count] = dict_baltime[count] + dict_bal[key]
-                    else:
-                        dict_baltime[count] = dict_bal[key]
-                else:
-                    pass
-                count += 1
-                x >>= 1    #右移一位
-        
-        dict_baltime=dict(sorted(dict_baltime.items(),key=lambda dict_baltime:dict_baltime[0]))
-        for key in dict_baltime:    #解析均衡的电芯编号
-            if self.celltype==1:    #科易6040
-                if key<14:
-                    dict_baltime1[key]=dict_baltime[key]
-                elif key<18:
-                    dict_baltime1[key-1]=dict_baltime[key]
-                else:
-                    dict_baltime1[key-3]=dict_baltime[key]
-            elif self.celltype==1:    #科易4840
-                if key<4:
-                    dict_baltime1[key-1]=dict_baltime[key]
-                elif key<8:
-                    dict_baltime1[key-1]=dict_baltime[key]
-                elif key<14:
-                    dict_baltime1[key-3]=dict_baltime[key]
-                elif key<18:
-                    dict_baltime1[key-4]=dict_baltime[key]
-                else:
-                    dict_baltime1[key-6]=dict_baltime[key]
-            else:
-                dict_baltime1=dict_baltime
-        return dict_baltime1
-
-    #三元电池的内短路电流计算...........................................................................................................................................................
-    def _ncm_intershort(self):
-        df_res=pd.DataFrame(columns=['time_st', 'time_sp', 'sn', 'method','short_current','baltime'])
-        df_ram_last=self.df_last
-        df_ram_last1=self.df_last1
-        df_ram_last3=self.df_last3
-
-        #容量初始化
-        if self.df_soh.empty:
-            batsoh=(self.df_bms.loc[0,'SOH[%]'])
-            capacity=self.param.Capacity*batsoh/100
-        else:
-            batsoh=self.df_soh.loc[len(self.df_soh)-1,'soh']
-            capacity=self.param.Capacity*batsoh/100
-
-        #参数初始化
-        if df_ram_last.empty:  
-            firsttime=1
-            dict_bal={}
-        else:
-            deltsoc_last=df_ram_last.loc[0,'deltsoc']
-            cellsoc_last=df_ram_last.loc[0,'cellsoc']
-            time_last=df_ram_last.loc[0,'time']
-            firsttime=0
-            dict_bal={}
-        if df_ram_last1.empty:
-            firsttime1=1
-            dict_bal1={}
-        else:
-            deltsoc_last1=df_ram_last1.loc[0,'deltsoc1']
-            time_last1=df_ram_last1.loc[0,'time1']
-            firsttime1=0
-            dict_bal1={}
-        if df_ram_last3.empty:
-            standingtime=0
-            standingtime1=0
-            standingtime2=0
-        else:
-            standingtime=df_ram_last3.loc[0,'standingtime']
-            standingtime1=df_ram_last3.loc[0,'standingtime1']
-            standingtime2=df_ram_last3.loc[0,'standingtime2']
-            dict_bal1={}
-            if abs(self.packcrnt[0])<0.01 and standingtime>1 and standingtime1>1:
-                standingtime=standingtime+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
-                standingtime1=standingtime1+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
-            else:
-                pass
-
-        for i in range(1,len(self.df_bms)-1):
-
-            if firsttime1==0:   #满电静置算法--计算均衡状态对应的均衡时间
-                try:
-                    balstat=int(self.df_bms.loc[i,'单体均衡状态'])
-                    if balstat>0.5:
-                        bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
-                        bal_step=int(bal_step)
-                        if str(balstat) in dict_bal1.keys():
-                            dict_bal1[str(balstat)]=dict_bal1[str(balstat)]+bal_step
-                        else:
-                            dict_bal1[str(balstat)]=bal_step
-                    else:
-                        pass
-                except:
-                    dict_bal1={}
-            else:
-                pass
-
-            if abs(self.packcrnt[i]) < 0.1 and abs(self.packcrnt[i-1]) < 0.1 and abs(self.packcrnt[i+1]) < 0.1:     
-                delttime=(self.bmstime[i]-self.bmstime[i-1]).total_seconds()
-                standingtime=standingtime+delttime
-                standingtime1=standingtime1+delttime
-                self._celltemp_weight(i)
-
-                #长时间静置法计算内短路-开始.....................................................................................................................................
-                if firsttime==1:    
-                    if standingtime>self.StandardStandingTime*2:      #静置时间满足要求
-                        standingtime=0
-                        cellvolt_now=self._avgvolt_get(i)
-                        if not cellvolt_now.empty:
-                            cellvolt_min=min(cellvolt_now)
-                            cellvolt_max=max(cellvolt_now)
-                            # cellvolt_last=self._avgvolt_get(i-1)
-                            # deltvolt=max(abs(cellvolt_now-cellvolt_last))
-                            cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-
-                            if 2<cellvolt_min<4.5 and 2<cellvolt_max<4.5 and (45<cellsoc_max or cellsoc_max<30) and (45<cellsoc_min or cellsoc_min<30): 
-                                dict_baltime={}   #获取每个电芯的均衡时间
-                                deltsoc_last, cellsoc_last=self._celldeltsoc_get(cellvolt_now,dict_baltime,capacity)
-                                time_last=self.bmstime[i]
-                                firsttime=0
-                                df_ram_last.loc[0]=[self.sn,time_last,deltsoc_last,cellsoc_last]   #更新RAM信息
-                    else:
-                        pass                
-                elif standingtime>3600*12:
-                    standingtime=0
-                    cellvolt_now=self._avgvolt_get(i)
-                    if not cellvolt_now.empty:
-                        cellvolt_min=min(cellvolt_now)
-                        cellvolt_max=max(cellvolt_now)
-                        # cellvolt_last=self._avgvolt_get(i-1)
-                        # deltvolt=max(abs(cellvolt_now-cellvolt_last))
-                        cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                        cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                        
-                        if 2<cellvolt_min<4.5 and 2<cellvolt_max<4.5 and (45<cellsoc_max or cellsoc_max<30) and (45<cellsoc_min or cellsoc_min<30):
-                            dict_baltime=self._bal_time(dict_bal)   #获取每个电芯的均衡时间
-                            deltsoc_now, cellsoc_now=self._celldeltsoc_get(cellvolt_now,dict_baltime,capacity)
-                            time_now=self.bmstime[i]
-                            if -5<max(cellsoc_now-cellsoc_last)<5:
-                                df_ram_last.loc[0]=[self.sn,time_now,deltsoc_now,cellsoc_now] #更新RAM信息
-                                
-                                list_sub=deltsoc_now-deltsoc_last
-                                list_pud=(0.01*capacity*3600*1000)/(time_now-time_last).total_seconds()
-                                leak_current=list_sub*list_pud
-                                # leak_current=np.array(leak_current)
-                                leak_current=np.round(leak_current,3)
-                                leak_current=list(leak_current)
-                                
-                                df_res.loc[len(df_res)]=[time_last,time_now,self.sn,1,str(leak_current),str(dict_baltime)]  #计算结果存入Dataframe
-                                time_last=time_now  #更新时间
-                                deltsoc_last=deltsoc_now    #更新soc差
-                                dict_bal={}
-                            else:
-                                firsttime=1
-                else: 
-                    try:  
-                        balstat=int(self.df_bms.loc[i,'单体均衡状态'])
-                        if balstat>0.5:
-                            bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
-                            bal_step=int(bal_step)
-                            if str(balstat) in dict_bal.keys():
-                                dict_bal[str(balstat)]=dict_bal[str(balstat)]+bal_step
-                            else:
-                                dict_bal[str(balstat)]=bal_step
-                        else:
-                            pass
-                    except:
-                        dict_bal={}
-
-                #满电静置法计算内短路-开始.....................................................................................................................................................
-                if self.StandardStandingTime<standingtime1:  
-                    standingtime1=0
-                    cellvolt_now1=self._avgvolt_get(i)
-                    if not cellvolt_now1.empty:
-                        cellvolt_max1=max(cellvolt_now1)
-                        cellvolt_min1=min(cellvolt_now1)
-                        # cellvolt_last1=self._avgvolt_get(i-1)
-                        # deltvolt1=max(abs(cellvolt_now1-cellvolt_last1))
-                        cellsoc_now1=np.interp(cellvolt_max1,self.param.LookTab_OCV,self.param.LookTab_SOC)
-
-                        if cellsoc_now1>self.param.FullChrgSoc-10 and 2<cellvolt_min1<4.5 and 2<cellvolt_max1<4.5:
-                            if firsttime1==1:
-                                dict_baltime1={}   #获取每个电芯的均衡时间
-                                deltsoc_last1, cellsoc_last1=self._celldeltsoc_get(cellvolt_now1,dict_baltime1,capacity)
-                                time_last1=self.bmstime[i]
-                                firsttime1=0
-                                df_ram_last1.loc[0]=[self.sn,time_last1,deltsoc_last1]    #更新RAM信息
-                            else:
-                                dict_baltime1=self._bal_time(dict_bal1)   #获取每个电芯的均衡时间
-                                time_now1=self.bmstime[i]
-                                if (time_now1-time_last1).total_seconds()>3600*20:
-                                    deltsoc_now1, cellsoc_now1=self._celldeltsoc_get(cellvolt_now1,dict_baltime1,capacity)
-                                    df_ram_last1.loc[0]=[self.sn,time_now1,deltsoc_now1] #更新RAM信息
-
-                                    list_sub1=deltsoc_now1-deltsoc_last1
-                                    list_pud1=(0.01*capacity*3600*1000)/(time_now1-time_last1).total_seconds()
-                                    leak_current1=list_sub1*list_pud1
-                                    # leak_current1=np.array(leak_current1)
-                                    leak_current1=np.round(leak_current1,3)
-                                    leak_current1=list(leak_current1)
-                                    
-                                    df_res.loc[len(df_res)]=[time_last1,time_now1,self.sn,2,str(leak_current1),str(dict_baltime1)]  #计算结果存入Dataframe
-                                    time_last1=time_now1  #更新时间
-                                    deltsoc_last1=deltsoc_now1    #更新soc差
-                                    dict_bal1={}
-                                else:
-                                    pass
-                    else:
-                        pass
-                else:   
-                    pass
-
-            else:
-                df_ram_last=pd.DataFrame(columns=['sn','time','deltsoc','cellsoc'])   #电流>0,清空上次静置的SOC差
-                dict_bal={} 
-                firsttime=1
-                standingtime=0
-                standingtime1=0
-                pass
-        
-        #更新RAM的standingtime
-        df_ram_last3.loc[0]=[self.sn,self.bmstime[len(self.bmstime)-1],standingtime,standingtime1,standingtime2]
-
-        #返回计算结果
-        if df_res.empty:    
-            return pd.DataFrame(), df_ram_last, df_ram_last1, df_ram_last3
-        else:
-            return df_res, df_ram_last, df_ram_last1, df_ram_last3
-
-    #磷酸铁锂电池内短路计算程序.............................................................................................................................
-    def _lfp_intershort(self):
-        column_name=['time_st', 'time_sp', 'sn', 'method','short_current','baltime']
-        df_res=pd.DataFrame(columns=column_name)
-        df_ram_last=self.df_last
-        df_ram_last1=self.df_last1
-        df_ram_last2=self.df_last2
-        df_ram_last3=self.df_last3
-        df_ram_lfp=pd.DataFrame(columns=self.df_bms.columns.tolist())
-
-        #容量初始化
-        if self.df_soh.empty:
-            batsoh=(self.df_bms.loc[0,'SOH[%]'])
-            capacity=self.param.Capacity*batsoh/100
-        else:
-            batsoh=self.df_soh.loc[len(self.df_soh)-1,'soh']
-            capacity=self.param.Capacity*batsoh/100
-        #参数初始化
-        if df_ram_last.empty:  
-            firsttime=1
-            dict_bal={}
-        else:
-            deltsoc_last=df_ram_last.loc[0,'deltsoc']
-            cellsoc_last=df_ram_last.loc[0,'cellsoc']
-            time_last=df_ram_last.loc[0,'time']
-            firsttime=0
-            dict_bal={}
-        if df_ram_last1.empty:
-            firsttime1=1
-            dict_bal1={}
-        else:
-            deltsoc_last1=df_ram_last1.loc[0,'deltsoc1']
-            time_last1=df_ram_last1.loc[0,'time1']
-            firsttime1=0
-            dict_bal1={}
-        if df_ram_last2.empty:
-            firsttime2=1
-            charging=0
-            dict_bal2={}
-        else:
-            deltAs_last2=df_ram_last2.loc[0,'deltAs2']
-            time_last2=df_ram_last2.loc[0,'time2']
-            firsttime2=0
-            charging=0
-            dict_bal2={}
-        if df_ram_last3.empty:
-            standingtime=0
-            standingtime1=0
-            standingtime2=0
-        else:
-            standingtime=df_ram_last3.loc[0,'standingtime']
-            standingtime1=df_ram_last3.loc[0,'standingtime1']
-            standingtime2=df_ram_last3.loc[0,'standingtime2']
-            dict_bal1={}
-            if abs(self.packcrnt[0])<0.01 and standingtime>1 and standingtime1>1:
-                standingtime=standingtime+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
-                standingtime1=standingtime1+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
-            else:
-                pass
-
-        for i in range(1,len(self.df_bms)-1):
-
-            #静置法计算内短路..........................................................................................................................
-            if firsttime1==0:   #满电静置算法--计算均衡状态对应的均衡时间
-                try:
-                    balstat=int(self.df_bms.loc[i,'单体均衡状态'])
-                    if balstat>0.5:
-                        bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
-                        bal_step=int(bal_step)
-                        if str(balstat) in dict_bal1.keys():
-                            dict_bal1[str(balstat)]=dict_bal1[str(balstat)]+bal_step
-                        else:
-                            dict_bal1[str(balstat)]=bal_step
-                    else:
-                        pass
-                except:
-                    dict_bal1={}
-            else:
-                pass
-
-            if abs(self.packcrnt[i]) < 0.1 and abs(self.packcrnt[i-1]) < 0.1 and abs(self.packcrnt[i+1]) < 0.1:     
-                delttime=(self.bmstime[i]-self.bmstime[i-1]).total_seconds()
-                standingtime=standingtime+delttime
-                standingtime1=standingtime1+delttime
-                self._celltemp_weight(i)
-
-                #长时间静置法计算内短路-开始.....................................................................................................................................
-                if firsttime==1:    
-                    if standingtime>self.StandardStandingTime:      #静置时间满足要求
-                        standingtime=0
-                        cellvolt_now=self._avgvolt_get(i)
-                        if not cellvolt_now.empty:
-                            cellvolt_min=min(cellvolt_now)
-                            cellvolt_max=max(cellvolt_now)
-                            # cellvolt_last=self._avgvolt_get(i-1)
-                            # deltvolt=max(abs(cellvolt_now-cellvolt_last))
-                            cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-
-                            if cellsoc_max<self.param.SocInflexion1-2 and 12<cellsoc_min:
-                                dict_baltime={}  #获取每个电芯的均衡时间
-                                deltsoc_last, cellsoc_last=self._celldeltsoc_get(cellvolt_now,dict_baltime,capacity)
-                                time_last=self.bmstime[i]
-                                firsttime=0
-                                df_ram_last.loc[0]=[self.sn,time_last,deltsoc_last,cellsoc_last]   #更新RAM信息
-                            else:
-                                pass
-                    else:
-                        pass                
-                elif standingtime>3600*12:
-                    standingtime=0
-                    cellvolt_now=self._avgvolt_get(i)
-                    if not cellvolt_now.empty:
-                        cellvolt_min=min(cellvolt_now)
-                        cellvolt_max=max(cellvolt_now)
-                        # cellvolt_last=np.array(self._avgvolt_get(i-1))
-                        # deltvolt=max(abs(cellvolt_now-cellvolt_last))
-                        cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                        cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-
-                        if cellsoc_max<self.param.SocInflexion1-2 and 12<cellsoc_min:
-                            dict_baltime=self._bal_time(dict_bal)   #获取每个电芯的均衡时间
-                            deltsoc_now, cellsoc_now=self._celldeltsoc_get(cellvolt_now, dict_baltime,capacity)    #获取每个电芯的SOC差
-                            time_now=self.bmstime[i]
-                            if -5<max(cellsoc_now-cellsoc_last)<5:
-                                df_ram_last.loc[0]=[self.sn,time_now,deltsoc_now,cellsoc_now]   #更新RAM信息
-
-                                list_sub=deltsoc_now-deltsoc_last
-                                list_pud=(0.01*capacity*3600*1000)/(time_now-time_last).total_seconds()
-                                leak_current=list_sub*list_pud
-                                # leak_current=np.array(leak_current)
-                                leak_current=np.round(leak_current,3)
-                                leak_current=list(leak_current)
-                                
-                                df_res.loc[len(df_res)]=[time_last,time_now,self.sn,1,str(leak_current),str(dict_baltime)]  #计算结果存入Dataframe
-                                time_last=time_now  #更新时间
-                                deltsoc_last=deltsoc_now    #更新soc差
-                                dict_bal={}
-                            else:
-                                firsttime=1
-                        else:
-                            pass
-                else: 
-                    try:  
-                        balstat=int(self.df_bms.loc[i,'单体均衡状态'])
-                        if balstat>0.5:
-                            bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
-                            bal_step=int(bal_step)
-                            if str(balstat) in dict_bal.keys():
-                                dict_bal[str(balstat)]=dict_bal[str(balstat)]+bal_step
-                            else:
-                                dict_bal[str(balstat)]=bal_step
-                        else:
-                            pass
-                    except:
-                        dict_bal={}
-
-                #非平台区间静置法计算内短路-开始.....................................................................................................................................................
-                if standingtime1>self.StandardStandingTime: 
-                    standingtime1=0
-                    cellvolt_now1=self._avgvolt_get(i)
-                    if not cellvolt_now1.empty:
-                        cellvolt_max1=max(cellvolt_now1)
-                        cellvolt_min1=min(cellvolt_now1)
-                        # cellvolt_last1=self._avgvolt_get(i-1)
-                        # deltvolt1=max(abs(cellvolt_now1-cellvolt_last1))
-                        cellsoc_max1=np.interp(cellvolt_max1,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                        cellsoc_min1=np.interp(cellvolt_min1,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                    
-                        if cellsoc_max1<self.param.SocInflexion1-2 and 12<cellsoc_min1:
-                            if firsttime1==1:
-                                dict_baltime1=self._bal_time(dict_bal1)   #获取每个电芯的均衡时间
-                                deltsoc_last1, cellsoc_last1=self._celldeltsoc_get(cellvolt_now1,dict_baltime1,capacity)
-                                time_last1=self.bmstime[i]
-                                firsttime1=0
-                                df_ram_last1.loc[0]=[self.sn,time_last1,deltsoc_last1]    #更新RAM信息
-                            else:
-                                dict_baltime1=self._bal_time(dict_bal1)   #获取每个电芯的均衡时间
-                                deltsoc_now1, cellsoc_now1=self._celldeltsoc_get(cellvolt_now1,dict_baltime1,capacity)
-                                time_now1=self.bmstime[i]
-                                df_ram_last1.loc[0]=[self.sn,time_now1,deltsoc_now1]    #更新RAM信息
-
-                                if (time_now1-time_last1).total_seconds()>3600*24:
-                                    list_sub1=deltsoc_now1-deltsoc_last1
-                                    list_pud1=(0.01*capacity*3600*1000)/(time_now1-time_last1).total_seconds()
-                                    leak_current1=list_sub1*list_pud1
-                                    # leak_current1=np.array(leak_current1)
-                                    leak_current1=np.round(leak_current1,3)
-                                    leak_current1=list(leak_current1)
-                                    
-                                    df_res.loc[len(df_res)]=[time_last1,time_now1,self.sn,2,str(leak_current1),str(dict_baltime1)]  #计算结果存入Dataframe
-                                    time_last1=time_now1  #更新时间
-                                    deltsoc_last1=deltsoc_now1    #更新soc差
-                                    dict_bal1={}
-                                else:
-                                    pass
-                        else:
-                            pass
-                else:   
-                    pass
-
-            else:
-                df_ram_last=pd.DataFrame(columns=['sn','time','deltsoc','cellsoc'])   #电流>0,清空上次静置的SOC差
-                dict_bal={} 
-                firsttime=1
-                standingtime=0
-                standingtime1=0
-                pass
-
-            #获取充电数据——开始..............................................................................................................
-            try:
-                balstat=int(self.df_bms.loc[i,'单体均衡状态'])  #统计均衡状态
-                if balstat>0.5:
-                    bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
-                    bal_step=int(bal_step)
-                    if str(balstat) in dict_bal2.keys():
-                        dict_bal2[str(balstat)]=dict_bal2[str(balstat)]+bal_step
-                    else:
-                        dict_bal2[str(balstat)]=bal_step
-                else:
-                    pass
-            except:
-                dict_bal2={}
-
-            #判断充电状态
-            if self.packcrnt[i]<=-1 and self.packcrnt[i+1]<=-1 and self.packcrnt[i-1]<=-1:
-                if charging==0:
-                    if self.bms_soc[i]<41:
-                        cellvolt_now=self._cellvolt_get(i)
-                        if min(cellvolt_now)<self.param.CellFullChrgVolt-0.15:
-                            charging=1
-                            chrg_start=i
-                        else:
-                            pass
-                    else:
-                        pass
-
-                else: #充电中
-                    cellvolt_now=self._cellvolt_get(i)
-                    if (self.bmstime[i+1]-self.bmstime[i]).total_seconds()>180 or (self.packcrnt[i]>self.param.Capacity/2 and self.packcrnt[i+1]>self.param.Capacity/2):  #如果充电过程中时间间隔>180s,则舍弃该次充电
-                        charging=0
-                        continue
-                    elif min(cellvolt_now)>self.param.CellFullChrgVolt-0.13:   #电压>满充电压-0.13V,即3.37V
-                        self._celltemp_weight(i)
-                        if i-chrg_start>10 and self.celltemp>20:
-                            chrg_end=i+1
-                            charging=0
-
-                            #计算漏电流值...................................................................
-                            if firsttime2==1:
-                                firsttime2=0
-                                dict_baltime={}
-                                deltAs_last2=self._cellDeltAs_get(chrg_start,chrg_end,dict_baltime)
-                                time_last2=self.bmstime[chrg_end]
-                                df_ram_last2.loc[0]=[self.sn,time_last2,deltAs_last2]    #更新RAM信息
-                            else:
-                                dict_baltime=self._bal_time(dict_bal2)   #获取每个电芯的均衡时间
-                                deltAs_now2=self._cellDeltAs_get(chrg_start,chrg_end,dict_baltime)  #获取每个电芯的As差
-                                time_now2=self.bmstime[chrg_end]
-                                df_ram_last2.loc[0]=[self.sn,time_now2,deltAs_now2]    #更新RAM信息
-
-                                list_sub2=deltAs_now2-deltAs_last2
-                                list_pud2=-1000/(time_now2-time_last2).total_seconds()
-                                leak_current2=list_sub2*list_pud2
-                                # leak_current=np.array(leak_current)
-                                leak_current2=np.round(leak_current2,3)
-                                leak_current2=list(leak_current2)
-
-                                df_res.loc[len(df_res)]=[time_last2,time_now2,self.sn,3,str(leak_current2),str(dict_baltime)]  #计算结果存入Dataframe
-                                deltAs_last2=deltAs_now2
-                                time_last2=time_now2
-                                dict_bal2={}
-
-                        else:
-                            charging=0
-                            continue
-                    # elif min(cellvolt_now)>self.param.CellFullChrgVolt-0.1:   #电压>满充电压
-                    #     self._celltemp_weight(i)
-                    #     if i-chrg_start>10 and self.celltemp>10:
-                    #         chrg_end=i+1
-                    #         charging=0
-
-                    #         #计算漏电流值...................................................................
-                    #         if firsttime2==1:
-                    #             dict_baltime={}
-                    #             peaksoc_list=[]
-                    #             for j in range(1, self.param.CellVoltNums + 1):
-                    #                 cellvolt = self._singlevolt_get(i,j,2)  #取单体电压j的所有电压值
-                    #                 cellvolt = list(cellvolt[chrg_start:chrg_end])
-                    #                 time = list(self.bmstime[chrg_start:chrg_end])
-                    #                 packcrnt = list(self.packcrnt[chrg_start:chrg_end])
-                    #                 soc = list(self.bms_soc[chrg_start:chrg_end])
-                    #                 peaksoc = self._dvdq_peak(time, soc, cellvolt, packcrnt)
-                    #                 if peaksoc>1:
-                    #                     peaksoc_list.append(peaksoc)
-                    #                 else:
-                    #                     break
-                    #             if len(peaksoc_list)==self.param.CellVoltNums:
-                    #                 celldeltsoc=[]
-                    #                 consum_num=10
-                    #                 cellsoc1=peaksoc_list[:self.param.CellVoltNums-consum_num]    #切片,将bms耗电的电芯和非耗电的电芯分离开
-                    #                 cellsocmean1=(sum(cellsoc1)-max(cellsoc1)-min(cellsoc1))/(len(cellsoc1)-2)
-                    #                 cellsoc2=peaksoc_list[self.param.CellVoltNums-consum_num:]
-                    #                 cellsocmean2=(sum(cellsoc2)-max(cellsoc2)-min(cellsoc2))/(len(cellsoc2)-2)
-                                    
-                    #                 for j in range(len(peaksoc_list)):   #计算每个电芯的soc差
-                    #                     if j<self.param.CellVoltNums-consum_num:
-                    #                         celldeltsoc.append(peaksoc_list[j]-cellsocmean1)
-                    #                     else:
-                    #                         celldeltsoc.append(peaksoc_list[j]-cellsocmean2)
-                    #                 deltsoc_last2=celldeltsoc
-                    #                 time_last2=self.bmstime[chrg_end]
-                    #                 df_ram_last2.loc[0]=[self.sn,time_last2,deltsoc_last2]    #更新RAM信息
-                    #         else:
-                    #             dict_baltime=self._bal_time(dict_bal2)   #获取每个电芯的均衡时间
-                    #             peaksoc_list=[]
-                    #             for j in range(1, self.param.CellVoltNums + 1):
-                    #                 cellvolt = self._singlevolt_get(i,j,2)  #取单体电压j的所有电压值
-                    #                 cellvolt = list(cellvolt[chrg_start:chrg_end])
-                    #                 time = list(self.bmstime[chrg_start:chrg_end])
-                    #                 packcrnt = list(self.packcrnt[chrg_start:chrg_end])
-                    #                 soc = list(self.bms_soc[chrg_start:chrg_end])
-                    #                 peaksoc = self._dvdq_peak(time, soc, cellvolt, packcrnt)
-                    #                 if peaksoc>1:
-                    #                     peaksoc_list.append(peaksoc)
-                    #                 else:
-                    #                     break
-                    #             if len(peaksoc_list)==self.param.CellVoltNums:
-                    #                 celldeltsoc=[]
-                    #                 consum_num=10
-                    #                 cellsoc1=peaksoc_list[:self.param.CellVoltNums-consum_num]    #切片,将bms耗电的电芯和非耗电的电芯分离开
-                    #                 cellsocmean1=(sum(cellsoc1)-max(cellsoc1)-min(cellsoc1))/(len(cellsoc1)-2)
-                    #                 cellsoc2=peaksoc_list[self.param.CellVoltNums-consum_num:]
-                    #                 cellsocmean2=(sum(cellsoc2)-max(cellsoc2)-min(cellsoc2))/(len(cellsoc2)-2)
-                                    
-                    #                 for j in range(len(peaksoc_list)):   #计算每个电芯的soc差
-                    #                     if j<self.param.CellVoltNums-consum_num:
-                    #                         celldeltsoc.append(peaksoc_list[j]-cellsocmean1)
-                    #                     else:
-                    #                         celldeltsoc.append(peaksoc_list[j]-cellsocmean2)
-                    #                 deltsoc_now2=celldeltsoc
-                    #                 time_now2=self.bmstime[chrg_end]
-                    #                 df_ram_last2.loc[0]=[self.sn,time_now2,deltsoc_now2]    #更新RAM信息
-
-                    #                 list_sub2=deltsoc_now2-deltsoc_last2
-                    #                 list_pud2=(0.01*capacity*3600*1000)/(time_now2-time_last2).total_seconds()
-                    #                 leak_current2=list_sub2*list_pud2
-                    #                 leak_current2=np.round(leak_current2,3)
-                    #                 leak_current2=list(leak_current2)
-
-                    #                 df_res.loc[len(df_res)]=[time_last2,time_now2,self.sn,3,str(leak_current2),str(dict_baltime)]  #计算结果存入Dataframe
-                    #                 deltsoc_last2=deltsoc_now2
-                    #                 time_last2=time_now2
-                    #                 dict_bal2={}
-                        
-                    #     else:
-                    #         charging=0
-                    #         continue
-
-                    elif i==len(self.df_bms)-2:  #数据中断后仍在充电,将前段充电数据写入RAM
-                        df_ram_lfp=self.df_bms.iloc[chrg_start:]
-                        df_ram_lfp['sn']=self.sn
-                    else:
-                        pass
-            else:
-                pass
-
-    
-        #更新RAM
-        df_ram_last3.loc[0]=[self.sn,self.bmstime[len(self.bmstime)-1],standingtime,standingtime1,standingtime2]
-
-        #返回结果
-        if df_res.empty:    
-            return pd.DataFrame(), df_ram_last, df_ram_last1, df_ram_last2, df_ram_last3,df_ram_lfp
-        else:
-            return df_res, df_ram_last, df_ram_last1, df_ram_last2, df_ram_last3, df_ram_lfp

+ 0 - 506
USER/SPF/01qixiang/07BatSafetyWarning copy/CBMSBatUniform.py

@@ -1,506 +0,0 @@
-import pandas as pd
-import numpy as np
-import datetime
-from LIB.MIDDLE.CellStateEstimation.Common import BatParam
-
-class BatUniform():
-    def __init__(self,sn,celltype,df_bms,df_uniform,df_last3,df_lfp1):  #参数初始化
-
-        if (not df_lfp1.empty) and celltype>50:
-            df_lfp1.drop(['sn'],axis=1)
-            df_bms=pd.concat([df_lfp1, df_bms], ignore_index=True)
-        else:
-            pass
-        
-        self.sn=sn
-        self.celltype=celltype
-        self.param=BatParam.BatParam(celltype)
-        self.df_bms=df_bms
-        self.packcrnt=df_bms['总电流[A]']*self.param.PackCrntDec
-        self.packvolt=df_bms['总电压[V]']
-        self.bms_soc=df_bms['SOC[%]']
-        self.bmstime= pd.to_datetime(df_bms['时间戳'], format='%Y-%m-%d %H:%M:%S')
-        # df_uniform['time']=pd.to_datetime(df_uniform['time'], format='%Y-%m-%d %H:%M:%S')
-
-        self.df_uniform=df_uniform
-        self.df_last3=df_last3
-        self.df_lfp1=df_lfp1
-
-        self.cellvolt_name=['单体电压'+str(x) for x in range(1,self.param.CellVoltNums+1)]
-        self.celltemp_name=['单体温度'+str(x) for x in range(1,self.param.CellTempNums+1)]
-
-    def batuniform(self):
-        if self.celltype<50:
-            df_res, df_ram_last3=self._ncm_uniform()
-            return df_res, df_ram_last3, self.df_lfp1
-        else:
-            df_res, df_ram_last3, df_ram_lfp1=self._lfp_uniform()
-            return df_res, df_ram_last3, df_ram_lfp1
-    
-    #定义滑动滤波函数........................................................................................................................................
-    def _np_move_avg(self,a, n, mode="same"): 
-        return (np.convolve(a, np.ones((n,)) / n, mode=mode))
-    
-    #寻找当前行数据的最小温度值................................................................................................................................
-    def _celltemp_weight(self,num):   
-        celltemp = list(self.df_bms.loc[num,self.celltemp_name])
-        celltemp.remove(min(celltemp))
-        self.celltemp=celltemp
-        if self.celltype>50:
-            if min(celltemp)>=25:
-                self.tempweight=1
-                self.StandardStandingTime=2400
-            elif min(celltemp)>=15:
-                self.tempweight=0.6
-                self.StandardStandingTime=3600
-            elif min(celltemp)>=5:
-                self.tempweight=0.2
-                self.StandardStandingTime=4800
-            else:
-                self.tempweight=0.1
-                self.StandardStandingTime=7200
-        else:
-            if min(celltemp)>=25:
-                self.tempweight=1
-                self.StandardStandingTime=1800
-            elif min(celltemp)>=15:
-                self.tempweight=0.8
-                self.StandardStandingTime=2400
-            elif min(celltemp)>=5:
-                self.tempweight=0.6
-                self.StandardStandingTime=3600
-            else:
-                self.tempweight=0.2
-                self.StandardStandingTime=7200
-        
-    #获取当前行所有电压数据............................................................................................................................
-    def _cellvolt_get(self,num):
-        cellvolt = np.array(self.df_bms.loc[num,self.cellvolt_name])/1000
-        return cellvolt
-    
-    #获取单个电压值.................................................................................................
-    def _singlevolt_get(self,num,series,mode):  #mode==1取当前行单体电压值,mode==2取某个单体所有电压值
-        s=str(series)
-        if mode==1:
-            singlevolt=self.df_bms.loc[num,'单体电压' + s]/1000
-            return singlevolt
-        else:
-            singlevolt=self.df_bms['单体电压' + s]/1000
-            return singlevolt
-
-    #寻找DVDQ的峰值点,并返回..........................................................................................................................
-    def _dvdq_peak(self, time, soc, cellvolt, packcrnt):
-        cellvolt = self._np_move_avg(cellvolt, 3, mode="same")
-        Soc = 0
-        Ah = 0
-        Volt = cellvolt[0]
-        DV_Volt = []
-        DQ_Ah = []
-        DVDQ = []
-        time1 = []
-        soc1 = []
-        soc2 = []
-        xvolt=[]
-
-        for m in range(1, len(time)):
-            Step = (time[m] - time[m - 1]).total_seconds()
-            Soc = Soc - packcrnt[m] * Step * 100 / (3600 * self.param.Capacity)
-            Ah = Ah - packcrnt[m] * Step / 3600
-            if (cellvolt[m]-Volt)>0.0019 and Ah>0:
-                DQ_Ah.append(Ah)
-                DV_Volt.append(cellvolt[m]-Volt)
-                DVDQ.append((DV_Volt[-1])/Ah)
-                xvolt.append(cellvolt[m])
-                Volt=cellvolt[m]
-                Ah = 0
-                soc1.append(Soc)
-                time1.append(time[m])
-                soc2.append(soc[m])
-
-        #切片,去除前后10min的数据
-        df_Data1 = pd.DataFrame({'time': time1,
-                                'SOC': soc2,
-                                'DVDQ': DVDQ,
-                                'AhSoc': soc1,
-                                'DQ_Ah':DQ_Ah,
-                                'DV_Volt':DV_Volt,
-                                'XVOLT':xvolt})
-        start_time=df_Data1.loc[0,'time']
-        start_time=start_time+datetime.timedelta(seconds=900)
-        end_time=df_Data1.loc[len(time1)-1,'time']
-        end_time=end_time-datetime.timedelta(seconds=1200)
-        if soc2[0]<36:
-            df_Data1=df_Data1[(df_Data1['SOC']>40) & (df_Data1['SOC']<80)]
-        else:
-            df_Data1=df_Data1[(df_Data1['time']>start_time) & (df_Data1['SOC']<80)]
-        df_Data1=df_Data1[(df_Data1['XVOLT']>self.param.PeakVoltLowLmt) & (df_Data1['XVOLT']<self.param.PeakVoltUpLmt)]
-
-        # print(packcrnt[int(len(time)/2)], min(self.celltemp))
-        # ax1 = plt.subplot(3, 1, 1)
-        # plt.plot(df_Data1['SOC'],df_Data1['DQ_Ah'],'g*-')
-        # plt.xlabel('SOC/%')
-        # plt.ylabel('DQ_Ah')
-        # plt.legend()
-        # ax1 = plt.subplot(3, 1, 2)
-        # plt.plot(df_Data1['SOC'],df_Data1['XVOLT'],'y*-')
-        # plt.xlabel('SOC/%')
-        # plt.ylabel('Volt/V')
-        # plt.legend()
-        # ax1 = plt.subplot(3, 1, 3)
-        # plt.plot(df_Data1['SOC'], df_Data1['DVDQ'], 'r*-')
-        # plt.xlabel('SOC/%')
-        # plt.ylabel('DV/DQ')
-        # plt.legend()
-        # # plt.show()
-
-        if len(df_Data1)>2:     #寻找峰值点,且峰值点个数>2
-            PeakIndex = df_Data1['DVDQ'].idxmax()
-            df_Data2 = df_Data1[(df_Data1['SOC'] > (df_Data1['SOC'][PeakIndex] - 0.5)) & (df_Data1['SOC'] < (df_Data1['SOC'][PeakIndex] + 0.5))]
-            if len(df_Data2) > 2 and df_Data1.loc[PeakIndex,'XVOLT']<self.param.PeakVoltUpLmt-0.019:
-                return df_Data1['AhSoc'][PeakIndex]
-            else:
-                df_Data1 = df_Data1.drop([PeakIndex])
-                PeakIndex = df_Data1['DVDQ'].idxmax()
-                df_Data2 = df_Data1[(df_Data1['SOC'] > (df_Data1['SOC'][PeakIndex] - 0.5)) & (df_Data1['SOC'] < (df_Data1['SOC'][PeakIndex] + 0.5))]
-                if len(df_Data2) > 2 and df_Data1.loc[PeakIndex,'XVOLT']<self.param.PeakVoltUpLmt-0.019:
-                    return df_Data1['AhSoc'][PeakIndex]
-                else:
-                    return 0
-        else:
-            return 0
- 
-    #三元电池一致性计算.................................................................................................................................
-    def _ncm_uniform(self):
-        column_name=['time','sn','cellsoc_diff','cellvolt_diff','cellmin_num','cellmax_num','cellvolt_rank']
-        df_res=pd.DataFrame(columns=column_name)
-
-        df_ram_last3=self.df_last3
-        if df_ram_last3.empty:
-            standingtime=0
-            standingtime1=0
-            standingtime2=0
-        else:
-            standingtime=df_ram_last3.loc[0,'standingtime']
-            standingtime1=df_ram_last3.loc[0,'standingtime1']
-            standingtime2=df_ram_last3.loc[0,'standingtime2']
-            if abs(self.packcrnt[0])<0.01 and standingtime2>1:
-                standingtime2=standingtime2+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
-            else:
-                pass
-        
-
-        for i in range(1,len(self.df_bms)-2):
-
-            if abs(self.packcrnt[i]) < 0.1 and abs(self.packcrnt[i-1]) < 0.1 and abs(self.packcrnt[i+1]) < 0.1:     #电流为0
-                delttime=(self.bmstime[i]-self.bmstime[i-1]).total_seconds()
-                standingtime2=standingtime2+delttime
-                self._celltemp_weight(i)     #获取不同温度对应的静置时间
-
-                if standingtime2>self.StandardStandingTime:      #静置时间满足要求
-                    if abs(self.packcrnt[i+2]) >= 0.1:
-                        standingtime2=0  
-                        cellvolt_now=self._cellvolt_get(i)
-                        cellvolt_min=min(cellvolt_now)
-                        cellvolt_max=max(cellvolt_now)
-                        cellvolt_last=self._cellvolt_get(i-1)
-                        deltvolt=max(abs(cellvolt_now-cellvolt_last))                
-                        if 3<cellvolt_min<4.5 and 3<cellvolt_max<4.5 and deltvolt<0.005:
-                            cellvolt_sort=np.argsort(cellvolt_now)
-                            cellvolt_rank=list(np.argsort(cellvolt_sort)+1)
-                            cellmin_num=list(cellvolt_now).index(cellvolt_min)+1
-                            cellmax_num=list(cellvolt_now).index(cellvolt_max)+1
-                            cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellvolt_diff=(cellvolt_max-cellvolt_min)*1000
-                            cellsoc_diff=cellsoc_max-cellsoc_min
-                            cellsoc_diff=eval(format(cellsoc_diff,'.1f'))
-                            cellvolt_diff=eval(format(cellvolt_diff,'.0f'))
-                            df_res.loc[len(df_res)]=[self.bmstime[i], self.sn, cellsoc_diff, cellvolt_diff, cellmin_num, cellmax_num, str(cellvolt_rank)]
-                    elif standingtime2>3600*6:
-                        standingtime2=0
-                        cellvolt_now=self._cellvolt_get(i)
-                        cellvolt_min=min(cellvolt_now)
-                        cellvolt_max=max(cellvolt_now)
-                        cellvolt_last=self._cellvolt_get(i-1)
-                        deltvolt=max(abs(cellvolt_now-cellvolt_last))                  
-                        
-                        if 3<cellvolt_min<4.5 and 3<cellvolt_max<4.5 and deltvolt<0.005:
-                            cellvolt_sort=np.argsort(cellvolt_now)
-                            cellvolt_rank=list(np.argsort(cellvolt_sort)+1)
-                            cellmin_num=list(cellvolt_now).index(cellvolt_min)+1
-                            cellmax_num=list(cellvolt_now).index(cellvolt_max)+1
-                            cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellvolt_diff=(cellvolt_max-cellvolt_min)*1000
-                            cellsoc_diff=cellsoc_max-cellsoc_min
-                            cellsoc_diff=eval(format(cellsoc_diff,'.1f'))
-                            cellvolt_diff=eval(format(cellvolt_diff,'.0f'))
-                            df_res.loc[len(df_res)]=[self.bmstime[i], self.sn, cellsoc_diff, cellvolt_diff, cellmin_num, cellmax_num, str(cellvolt_rank)]
-                    elif i>=len(self.df_bms)-3:
-                        standingtime2=0
-                        cellvolt_now=self._cellvolt_get(i)
-                        cellvolt_min=min(cellvolt_now)
-                        cellvolt_max=max(cellvolt_now)
-                        cellvolt_last=self._cellvolt_get(i-1)
-                        deltvolt=max(abs(cellvolt_now-cellvolt_last))     
-                        
-                        if 3<cellvolt_min<4.5 and 3<cellvolt_max<4.5 and deltvolt<0.005:
-                            cellvolt_sort=np.argsort(cellvolt_now)
-                            cellvolt_rank=list(np.argsort(cellvolt_sort)+1)
-                            cellmin_num=list(cellvolt_now).index(cellvolt_min)+1
-                            cellmax_num=list(cellvolt_now).index(cellvolt_max)+1
-                            cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellvolt_diff=(cellvolt_max-cellvolt_min)*1000
-                            cellsoc_diff=cellsoc_max-cellsoc_min
-                            cellsoc_diff=eval(format(cellsoc_diff,'.1f'))
-                            cellvolt_diff=eval(format(cellvolt_diff,'.0f'))
-                            df_res.loc[len(df_res)]=[self.bmstime[i], self.sn, cellsoc_diff, cellvolt_diff, cellmin_num, cellmax_num, str(cellvolt_rank)]
-                        break
-                    else:
-                        continue
-                else:
-                    continue
-            else:
-                standingtime2=0
-                continue
-        
-        #更新RAM的standingtime
-        df_ram_last3.loc[0]=[self.sn,self.bmstime[len(self.bmstime)-1],standingtime,standingtime1,standingtime2]
-
-        if df_res.empty:    #返回计算结果
-            return pd.DataFrame(), df_ram_last3
-        else:
-            return df_res, df_ram_last3
-
-    #磷酸铁锂电池一致性计算.........................................................................................................................
-    def _lfp_uniform(self):
-        column_name=['time','sn','cellsoc_diff','cellvolt_diff','cellmin_num','cellmax_num','cellvolt_rank']
-        df_res=pd.DataFrame(columns=column_name)
-        df_ram_lfp1=pd.DataFrame(columns=self.df_bms.columns.tolist())
-        chrg_start=[]
-        chrg_end=[]
-        charging=0
-
-        df_ram_last3=self.df_last3
-        if df_ram_last3.empty:
-            standingtime=0
-            standingtime1=0
-            standingtime2=0
-        else:
-            standingtime=df_ram_last3.loc[0,'standingtime']
-            standingtime1=df_ram_last3.loc[0,'standingtime1']
-            standingtime2=df_ram_last3.loc[0,'standingtime2']
-            if abs(self.packcrnt[0])<0.01 and standingtime2>1:
-                standingtime2=standingtime2+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
-            else:
-                pass
-
-        for i in range(2,len(self.df_bms)-2):
-
-            #静置电压法计算电芯一致性
-            if abs(self.packcrnt[i]) < 0.1 and abs(self.packcrnt[i-1]) < 0.1 and abs(self.packcrnt[i+1]) < 0.1:     #电流为0
-                delttime=(self.bmstime[i]-self.bmstime[i-1]).total_seconds()
-                standingtime2=standingtime2+delttime
-                self._celltemp_weight(i)     #获取不同温度对应的静置时间
-
-                if standingtime2>self.StandardStandingTime:      #静置时间满足要求
-                    if abs(self.packcrnt[i+2]) >= 0.1:     
-                        standingtime2=0  
-                        cellvolt_now=self._cellvolt_get(i)
-                        cellvolt_min=min(cellvolt_now)
-                        cellvolt_max=max(cellvolt_now)
-                        cellvolt_last=self._cellvolt_get(i-1)
-                        deltvolt=max(abs(cellvolt_now-cellvolt_last))  
-        
-                        if 2 < cellvolt_max < self.param.OcvInflexionBelow-0.002 and 2<cellvolt_min<4.5 and deltvolt<0.005: 
-                            cellvolt_sort=np.argsort(cellvolt_now)
-                            cellvolt_rank=list(np.argsort(cellvolt_sort)+1)               
-                            cellmin_num=list(cellvolt_now).index(cellvolt_min)+1
-                            cellmax_num=list(cellvolt_now).index(cellvolt_max)+1
-                            cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellvolt_diff=(cellvolt_max-cellvolt_min)*1000
-                            cellsoc_diff=cellsoc_max-cellsoc_min
-                            cellsoc_diff=eval(format(cellsoc_diff,'.1f'))
-                            cellvolt_diff=eval(format(cellvolt_diff,'.0f'))
-                            df_res.loc[len(df_res)]=[self.bmstime[i], self.sn, cellsoc_diff, cellvolt_diff, cellmin_num, cellmax_num, str(cellvolt_rank)]
-                        # elif 2<cellvolt_max<4.5 and 2<cellvolt_min<4.5 and deltvolt<0.005: 
-                        #     cellvolt_sort=np.argsort(cellvolt_now)
-                        #     cellvolt_rank=list(np.argsort(cellvolt_sort)+1)
-                        #     if not df_res.empty:
-                        #         df_res.loc[len(df_res)]=df_res.loc[len(df_res)-1]
-                        #         df_res.loc[len(df_res)-1,'cellvolt_rank']=str(cellvolt_rank)
-                        #         df_res.loc[len(df_res)-1,'time']=self.bmstime[i]
-                        #     elif not self.df_uniform.empty:
-                        #         df_res.loc[len(df_res)]=self.df_uniform.iloc[-1]
-                        #         df_res.loc[len(df_res)-1,'cellvolt_rank']=str(cellvolt_rank)
-                        #         df_res.loc[len(df_res)-1,'time']=self.bmstime[i]
-                        #     else:
-                        #         pass
-                    elif standingtime2>3600*6:
-                        standingtime2=0
-                        cellvolt_now=self._cellvolt_get(i)
-                        cellvolt_min=min(cellvolt_now)
-                        cellvolt_max=max(cellvolt_now)
-                        cellvolt_last=self._cellvolt_get(i-1)
-                        deltvolt=max(abs(cellvolt_now-cellvolt_last))                  
-                        
-                        if 2 < cellvolt_max < self.param.OcvInflexionBelow-0.002 and 2<cellvolt_min<4.5 and deltvolt<0.005: 
-                            cellvolt_sort=np.argsort(cellvolt_now)
-                            cellvolt_rank=list(np.argsort(cellvolt_sort)+1)
-                            cellmin_num=list(cellvolt_now).index(cellvolt_min)+1
-                            cellmax_num=list(cellvolt_now).index(cellvolt_max)+1
-                            cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellvolt_diff=(cellvolt_max-cellvolt_min)*1000
-                            cellsoc_diff=cellsoc_max-cellsoc_min
-                            cellsoc_diff=eval(format(cellsoc_diff,'.1f'))
-                            cellvolt_diff=eval(format(cellvolt_diff,'.0f'))
-                            df_res.loc[len(df_res)]=[self.bmstime[i], self.sn, cellsoc_diff, cellvolt_diff, cellmin_num, cellmax_num, str(cellvolt_rank)]
-                        # elif 2<cellvolt_max<4.5 and 2<cellvolt_min<4.5 and deltvolt<0.005: 
-                        #     cellvolt_sort=np.argsort(cellvolt_now)
-                        #     cellvolt_rank=list(np.argsort(cellvolt_sort)+1)
-                        #     if not df_res.empty:
-                        #         df_res.loc[len(df_res)]=df_res.loc[len(df_res)-1]
-                        #         df_res.loc[len(df_res)-1,'cellvolt_rank']=str(cellvolt_rank)
-                        #         df_res.loc[len(df_res)-1,'time']=self.bmstime[i]
-                        #     elif not self.df_uniform.empty:
-                        #         df_res.loc[len(df_res)]=self.df_uniform.iloc[-1]
-                        #         df_res.loc[len(df_res)-1,'cellvolt_rank']=str(cellvolt_rank)
-                        #         df_res.loc[len(df_res)-1,'time']=self.bmstime[i]
-                        #     else:
-                        #         pass
-                    
-                    elif i>=len(self.df_bms)-3:
-                        standingtime2=0
-                        cellvolt_now=self._cellvolt_get(i)
-                        cellvolt_min=min(cellvolt_now)
-                        cellvolt_max=max(cellvolt_now)
-                        cellvolt_last=self._cellvolt_get(i-1)
-                        deltvolt=max(abs(cellvolt_now-cellvolt_last)) 
-                        if 2 < cellvolt_max < self.param.OcvInflexionBelow-0.002 and 2<cellvolt_min<4.5 and deltvolt<0.003:
-                            cellvolt_sort=np.argsort(cellvolt_now)
-                            cellvolt_rank=list(np.argsort(cellvolt_sort)+1) 
-                            cellmin_num=list(cellvolt_now).index(cellvolt_min)+1
-                            cellmax_num=list(cellvolt_now).index(cellvolt_max)+1
-                            cellsoc_min=np.interp(cellvolt_min,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellsoc_max=np.interp(cellvolt_max,self.param.LookTab_OCV,self.param.LookTab_SOC)
-                            cellvolt_diff=(cellvolt_max-cellvolt_min)*1000
-                            cellsoc_diff=cellsoc_max-cellsoc_min
-                            cellsoc_diff=eval(format(cellsoc_diff,'.1f'))
-                            cellvolt_diff=eval(format(cellvolt_diff,'.0f'))
-                            df_res.loc[len(df_res)]=[self.bmstime[i], self.sn, cellsoc_diff, cellvolt_diff, cellmin_num, cellmax_num, str(cellvolt_rank)]
-                        # elif 2<cellvolt_max<4.5 and 2<cellvolt_min<4.5 and deltvolt<0.005: 
-                        #     cellvolt_sort=np.argsort(cellvolt_now)
-                        #     cellvolt_rank=list(np.argsort(cellvolt_sort)+1)
-                        #     if not df_res.empty:
-                        #         df_res.loc[len(df_res)]=df_res.loc[len(df_res)-1]
-                        #         df_res.loc[len(df_res)-1,'cellvolt_rank']=str(cellvolt_rank)
-                        #         df_res.loc[len(df_res)-1,'time']=self.bmstime[i]
-                        #     elif not self.df_uniform.empty:
-                        #         df_res.loc[len(df_res)]=self.df_uniform.iloc[-1]
-                        #         df_res.loc[len(df_res)-1,'cellvolt_rank']=str(cellvolt_rank)
-                        #         df_res.loc[len(df_res)-1,'time']=self.bmstime[i]
-                        #     else:
-                        #         pass
-                    else:
-                        pass
-                else:
-                    pass
-            else:
-                standingtime2=0
-                pass   
-
-            #获取DVDQ算法所需数据——开始............................................................................................................
-            if charging==0: #判断充电开始
-                if self.packcrnt[i]<=-1 and self.packcrnt[i+1]<=-1 and self.packcrnt[i+2]<=-1 and self.bms_soc[i]<40:     #充电开始
-                    charging=1
-                    if len(chrg_start)>len(chrg_end):
-                        chrg_start[-1]=i
-                    else:
-                        chrg_start.append(i)
-                else:
-                    pass
-
-            else: #充电中
-                if (self.bmstime[i+1]-self.bmstime[i]).total_seconds()>180 or (self.packcrnt[i]<-self.param.Capacity/2 and self.packcrnt[i+1]<-self.param.Capacity/2):  #如果充电过程中时间间隔>180s,则舍弃该次充电
-                    chrg_start.remove(chrg_start[-1])
-                    charging=0
-                    continue
-                elif self.packcrnt[i]<=-1 and self.packcrnt[i+1]<=-1 and  self.packcrnt[i+2]>-1:  #判断电流波动时刻
-                    cellvolt_now=self._cellvolt_get(i+1)
-                    if max(cellvolt_now)>self.param.CellFullChrgVolt:   #电压>满充电压
-                        chrg_end.append(i+1)
-                        charging=0
-                        continue
-                    else:
-                        pass
-                elif self.packcrnt[i+1]>-0.1 and self.packcrnt[i+2]>-0.1:   #判断充电结束
-                    charging=0
-                    if len(chrg_start)>len(chrg_end):
-                        if self.bms_soc[i]>90:
-                            chrg_end.append(i)
-                        else:
-                            chrg_start.remove(chrg_start[-1])
-                            continue
-                    else:
-                        continue
-                elif i==len(self.packcrnt)-3 and self.packcrnt[i+1]<-1 and self.packcrnt[i+2]<-1:
-                    charging=0
-                    if len(chrg_start)>len(chrg_end) and self.bms_soc[i]>90:   #soc>90
-                        chrg_end.append(i)
-                        continue
-                    else:
-                        df_ram_lfp1=self.df_bms.iloc[chrg_start[-1]:]
-                        df_ram_lfp1['sn']=self.sn
-                        chrg_start.remove(chrg_start[-1])
-                        continue
-                else:
-                    continue   
-
-        if chrg_end:    #DVDQ方法计算soc差
-            peaksoc_list=[]
-            for i in range(len(chrg_end)):
-                peaksoc_list = []
-                self._celltemp_weight(chrg_start[i])
-                if min(self.celltemp)>10:
-                    for j in range(1, self.param.CellVoltNums + 1):
-                        cellvolt = self._singlevolt_get(i,j,2)  #取单体电压j的所有电压值
-                        cellvolt = list(cellvolt[chrg_start[i]:chrg_end[i]])
-                        time = list(self.bmstime[chrg_start[i]:chrg_end[i]])
-                        packcrnt = list(self.packcrnt[chrg_start[i]:chrg_end[i]])
-                        soc = list(self.bms_soc[chrg_start[i]:chrg_end[i]])
-                        peaksoc = self._dvdq_peak(time, soc, cellvolt, packcrnt)
-                        if peaksoc>1:
-                            peaksoc_list.append(peaksoc)    #计算到达峰值点的累计Soc
-                        else:
-                            pass
-                    if len(peaksoc_list)>self.param.CellVoltNums/2:
-                        peaksoc_max=max(peaksoc_list)
-                        peaksoc_min=min(peaksoc_list)
-                        peaksoc_maxnum=peaksoc_list.index(peaksoc_min)+1
-                        peaksoc_minnum=peaksoc_list.index(peaksoc_max)+1
-                        cellsoc_diff=peaksoc_max-peaksoc_min
-                        cellsoc_diff=eval(format(cellsoc_diff,'.1f'))
-                        if not df_res.empty:
-                            cellvolt_rank=df_res.iloc[-1]['cellvolt_rank']
-                            df_res.loc[len(df_res)]=[self.bmstime[chrg_start[i]], self.sn, cellsoc_diff, 0, peaksoc_minnum, peaksoc_maxnum, cellvolt_rank]
-                        elif not self.df_uniform.empty:
-                            cellvolt_rank=self.df_uniform.iloc[-1]['cellvolt_rank']
-                            df_res.loc[len(df_res)]=[self.bmstime[chrg_start[i]], self.sn, cellsoc_diff, 0, peaksoc_minnum, peaksoc_maxnum, cellvolt_rank]
-                        else:
-                            pass
-                    else:
-                        pass
-                else:
-                    pass
-
-        #更新RAM的standingtime
-        df_ram_last3.loc[0]=[self.sn,self.bmstime[len(self.bmstime)-1],standingtime,standingtime1,standingtime2]
-        
-        if df_res.empty:
-            return pd.DataFrame(), df_ram_last3, df_ram_lfp1
-        else:
-            df_res.sort_values(by='time', ascending=True, inplace=True)
-            return df_res, df_ram_last3, df_ram_lfp1

+ 0 - 265
USER/SPF/01qixiang/07BatSafetyWarning copy/CBMSSafetyWarning.py

@@ -1,265 +0,0 @@
-import pandas as pd
-import numpy as np
-import datetime
-import time
-from matplotlib import pyplot as plt
-import pymannkendall as mk
-from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import BatParam
-
-class SafetyWarning:
-    def __init__(self,sn,celltype,df_short,df_uniform,OutLineVol_Rate,df_soh,df_fault_ram_sn):  #参数初始化
-
-        self.sn=sn
-        self.celltype=celltype
-        self.param=BatParam.BatParam(celltype)
-        self.df_short=df_short
-        self.df_uniform=df_uniform
-        self.OutLineVol_Rate=OutLineVol_Rate
-        self.df_soh=df_soh
-        self.df_alarm_ram=df_fault_ram_sn.copy()
-    
-    def diag(self):
-        if self.celltype<=50:
-            df_res=self._warning_diag()
-            return df_res    
-        else:
-            df_res=self._warning_diag()
-            return df_res
-        
-
-    #电池热安全预警诊断功能.................................................................................................
-    def _warning_diag(self):
-
-        df_res=pd.DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
-
-        time_now=datetime.datetime.now()
-        time_now=time_now.strftime('%Y-%m-%d %H:%M:%S')
-        time_sp='0000-00-00 00:00:00'
-
-        #参数初始化.......................................
-        voltsigmafault=0
-        uniformfault=0
-        cellshortfault=0
-        cellshortfault=[]
-        volt_rate=[]
-        R2_list=[]
-        voltsigmafault_list=[]
-        uniformfault_list=[]
-        mk_trend_list=[]
-        mk_p_list=[]
-        mk_z_list=[]
-        mk_Tau_list=[]
-        mk_slope_list=[]
-        mk_s_list=[]
-        mk_svar_list=[]
-
-        if not self.df_short.empty:
-            short_current=self.df_short['short_current']
-            short_current=short_current.str.replace("[", '')
-            short_current=short_current.str.replace("]", '')
-        
-        if not self.OutLineVol_Rate.empty:
-            volt_column = ['单体电压'+str(i) for i in range(1,self.param.CellVoltNums+1)]
-            self.OutLineVol_Rate['VolChng_Uni']=self.OutLineVol_Rate['VolChng_Uni'].str.replace("[","")
-            self.OutLineVol_Rate['VolChng_Uni']=self.OutLineVol_Rate['VolChng_Uni'].str.replace("]","")
-            self.OutLineVol_Rate['VolOl_Uni']=self.OutLineVol_Rate['VolOl_Uni'].str.replace("[","")
-            self.OutLineVol_Rate['VolOl_Uni']=self.OutLineVol_Rate['VolOl_Uni'].str.replace("]","")
-            Volt_3Sigma=self.OutLineVol_Rate['VolOl_Uni'].str.split(',',expand=True)
-            Volt_3Sigma.columns=volt_column
-
-            #电压变化率
-            VoltChange=self.OutLineVol_Rate['VolChng_Uni'].str.split(',',expand=True)
-            VoltChange.columns=volt_column
-            VoltChange['time']=self.OutLineVol_Rate['time']
-            VoltChange = VoltChange.reset_index(drop=True)
-            xtime1=VoltChange['time']
-            time0=time.mktime(VoltChange.loc[0,'time'].timetuple())
-            for i in range(0,len(VoltChange)):
-                VoltChange.loc[i,'time']=(time.mktime(VoltChange.loc[i,'time'].timetuple())-time0)/36000
-            
-        #计算漏电流离群度
-        if not self.df_short.empty:
-            self.df_short['cellshort_sigma']=0
-            for i in range(len(self.df_short)):
-                cellshort=eval(self.df_short.loc[i,'short_current'])
-                cellshort_std=np.std(cellshort)
-                cellshort_mean=np.mean(cellshort)
-                self.df_short.loc[i,'cellshort_sigma']=str(list((cellshort-cellshort_mean)/cellshort_std))
-            
-    
-        if not self.df_uniform.empty:
-            cellvolt_rank=self.df_uniform['cellvolt_rank']
-            cellvolt_rank=cellvolt_rank.str.replace("[", '')
-            cellvolt_rank=cellvolt_rank.str.replace("]", '')
-    
-        for i in range(self.param.CellVoltNums):
-            #漏电流故障判断...........................................................................
-            if not self.df_short.empty:
-                self.df_short['cellshort'+str(i+1)]=short_current.map(lambda x:eval(x.split(',')[i]))
-                cellshort=self.df_short['cellshort'+str(i+1)]
-                index_list=cellshort[cellshort<self.param.LeakCurrentLv2].index
-                if len(index_list)>1:
-                    for j in range(1,len(index_list)):
-                        if index_list[j]-index_list[j-1]==1:
-                            cellshort_sigma1=eval(self.df_short.loc[index_list[j],'cellshort_sigma'])
-                            cellshort_sigma2=eval(self.df_short.loc[index_list[j-1],'cellshort_sigma'])
-                            if cellshort_sigma1[i]<-3 or cellshort_sigma2[i]<-3:
-                                cellshortfault.append(1)
-                            else:
-                                cellshortfault.append(0)                    
-                        else:
-                            cellshortfault.append(0)  
-                else:
-                    pass
-            
-            #电压变化率及电压离群度.................................................................................
-            if not self.OutLineVol_Rate.empty and VoltChange.iloc[-1]['time']*36000>18*3600 and len(VoltChange)>5:
-
-                VoltChange[volt_column[i]]=VoltChange[volt_column[i]].map(lambda x:eval(x))
-                y=VoltChange[volt_column[i]]
-                volt3sigma=np.array(Volt_3Sigma[volt_column[i]].map(lambda x:eval(x)))
-                volt3sigma_sum=np.sum(volt3sigma<-3)
-                #电压变化率
-                a1,b1=np.polyfit(VoltChange['time'].tolist(),y.tolist(),1)
-                y1=a1*VoltChange['time']+b1
-                y_mean=y.mean()
-                R2=1-(np.sum((y1-y)**2))/(np.sum((y-y_mean)**2))
-                R2_list.append(R2)
-                
-                volt_rate.append(a1)
-                plt.plot(xtime1,y1,label='单体'+str(i+1))
-                plt.xlabel('时间', fontsize=25)
-                plt.ylabel('SOC差', fontsize=25)
-                plt.xticks(fontsize=20)
-                plt.yticks(fontsize=20)
-                plt.scatter( xtime1,VoltChange[volt_column[i]],marker='o')
-                plt.legend(bbox_to_anchor=(1, 0), loc=3, fontsize=13)
-                plt.title(self.sn)
-                plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
-                plt.rcParams['axes.unicode_minus']=False #用来正常显示负号  
-                # plt.show()
-                
-                if volt3sigma_sum>len(volt3sigma)/2:
-                    voltsigmafault=1
-                else:
-                    voltsigmafault=0
-                voltsigmafault_list.append(voltsigmafault)
-                
-                #mana-kendell趋势检验
-                mk_res=mk.regional_test(np.array(y)) 
-                mk_trend_list.append(mk_res.trend)
-                mk_p_list.append(mk_res.p)
-                mk_z_list.append(mk_res.z)
-                mk_Tau_list.append(mk_res.Tau)
-                mk_slope_list.append(mk_res.slope)
-                mk_s_list.append(mk_res.s)
-                mk_svar_list.append(mk_res.var_s)
-                """
-                trend:趋势;
-                h:有无趋势;
-                p:趋势的显著水平,越小趋势越明显;
-                z:检验统计量,正代表随时间增大趋势,负代表随时间减小趋势;
-                Tau:反映两个序列的相关性,接近1的值表示强烈的正相关,接近-1的值表示强烈的负相关;
-                s:Mann-Kendal的分数,如果S是一个正数,那么后一部分的观测值相比之前的观测值会趋向于变大;如果S是一个负数,那么后一部分的观测值相比之前的观测值会趋向于变小
-                slope:趋势斜率
-                """
-                # print('单体电压{}:\n'.format(i+1), mk_res)
-
-            else:
-                volt_rate.append(0)
-                R2_list.append(0)
-                voltsigmafault_list.append(0)
-                mk_trend_list.append(0)
-                mk_p_list.append(0)
-                mk_z_list.append(0)
-                mk_Tau_list.append(0)
-                mk_slope_list.append(0)
-                mk_s_list.append(0)
-                mk_svar_list.append(0)
-
-            #电芯SOC排名判断.............................................................................
-            if not self.df_uniform.empty:
-                self.df_uniform['cellvolt_rank'+str(i+1)]=cellvolt_rank.map(lambda x:eval(x.split(',')[i]))
-                
-                if max(self.df_uniform['cellvolt_rank'+str(i+1)])<5:
-                    uniformfault=1
-                else:
-                    uniformfault=0
-            else:
-                uniformfault=0
-            uniformfault_list.append(uniformfault)
-        
-        plt.show()  
- 
-        #电池电压变化率离群度计算...............................................................................
-        volt_rate_std=np.std(volt_rate)
-        volt_rate_mean=np.mean(volt_rate)
-        volt_rate_3sigma=(np.array(volt_rate)-volt_rate_mean)/volt_rate_std
-        
-        #mk离群度计算
-        mk_slope_std=np.std(mk_slope_list)
-        mk_slope_mean=np.mean(mk_slope_list)
-        mk_slope_3sigma=(np.array(mk_slope_list)-mk_slope_mean)/mk_slope_std
-
-        mk_z_std=np.std(mk_z_list)
-        mk_z_mean=np.mean(mk_z_list)
-        mk_z_3sigma=(np.array(mk_z_list)-mk_z_mean)/mk_z_std  
-
-        if not self.df_soh.empty and self.celltype<50:
-            cellsoh=eval(self.df_soh.loc[0,'cellsoh'])
-            cellsoh_std=np.std(cellsoh)
-            cellsoh_mean=np.mean(cellsoh)
-            cellsoh_3sigma=((np.array(cellsoh)-cellsoh_mean)/cellsoh_std)
-        else:
-            cellsoh_3sigma=[0]*self.param.CellVoltNums
-        
-        #漏电流热失控预警确认.......................................................................................
-        if len(cellshortfault)>1:
-            if not 'C490' in list(self.df_alarm_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
-                if max(cellshortfault)==1:
-                    faultcode='C490'
-                    faultlv=4
-                    faultinfo='电芯{}发生热失控安全预警'.format(cellshortfault.index(1)+1)
-                    faultadvice='请于24h内联系技术人员确认故障'
-                    self.df_alarm_ram.loc[len(self.df_alarm_ram)]=[time_now, time_sp, self.sn, faultcode, faultlv, faultinfo, faultadvice]
-                else:
-                    pass
-            else:
-                if max(cellshortfault)==1:
-                    pass
-                else:
-                    self.df_alarm_ram.loc[self.df_alarm_ram[self.df_alarm_ram['code']=='C490'].index, 'end_time'] = time_now
-        else:
-            pass
-        #mana-kendall趋势检测
-        mk_fault_list=[]
-        for i in range(len(mk_p_list)):
-            #适用动态工况判断
-            if mk_trend_list[i]=='decreasing' and mk_p_list[i]<self.param.mk_p and mk_z_list[i]<self.param.mk_z and mk_Tau_list[i]<self.param.mk_Tau and mk_s_list[i]<self.param.mk_s and mk_svar_list[i]<self.param.mk_svar and mk_slope_3sigma[i]<-3 and mk_slope_list[i]<self.param.mk_slope and volt_rate_3sigma[i]<-3:
-                mk_fault_list.append(1)
-            #适用静态工况判断
-            elif self.celltype<=50 and mk_trend_list[i]=='decreasing' and mk_p_list[i]<self.param.mk_p and mk_z_list[i]<-6 and (mk_Tau_list[i]<-0.9 or mk_z_3sigma[i]<-3) and mk_s_list[i]<self.param.mk_s and mk_svar_list[i]<self.param.mk_svar and mk_slope_3sigma[i]<-3.5 and mk_slope_list[i]<-0.03 and volt_rate_3sigma[i]<-3:
-                mk_fault_list.append(1)
-            elif self.celltype>50 and mk_trend_list[i]=='decreasing' and mk_p_list[i]<self.param.mk_p and mk_z_list[i]<-6 and (mk_Tau_list[i]<-0.95 or mk_z_3sigma[i]<-3) and mk_s_list[i]<self.param.mk_s and mk_svar_list[i]<self.param.mk_svar and mk_slope_3sigma[i]<-3.5 and mk_slope_list[i]<-0.4 and volt_rate_3sigma[i]<-3:
-                mk_fault_list.append(1)
-            else:
-                mk_fault_list.append(0)
-        
-        if len(mk_fault_list)>1:
-            if not 'C491' in list(self.df_alarm_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
-                if max(mk_fault_list)==1:
-                    faultcode='C491'
-                    faultlv=4
-                    faultinfo='电芯{}发生热失控安全预警'.format(mk_fault_list.index(1)+1)
-                    faultadvice='请于24h内联系技术人员确认故障'
-                    self.df_alarm_ram.loc[len(self.df_alarm_ram)]=[time_now, time_sp, self.sn, faultcode, faultlv, faultinfo, faultadvice]
-                else:
-                    pass
-            else:
-                if max(mk_fault_list)==1:
-                    pass
-                else:
-                    self.df_alarm_ram.loc[self.df_alarm_ram[self.df_alarm_ram['code']=='C491'].index, 'end_time'] = time_now
-        else:
-            pass
-        return self.df_alarm_ram

+ 0 - 266
USER/SPF/01qixiang/07BatSafetyWarning copy/VoltStray.py

@@ -1,266 +0,0 @@
-from re import X
-import pandas as pd
-import numpy as np
-from pandas.core.frame import DataFrame
-from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import BatParam
-import pandas as pd
-# 计算充电过程
-def preprocess(df):
-    # 滤除前后电压存在一增一减的情况(采样异常)
-    pass
-
-# 计算SOC变化率  
-def cal_volt_change(dfin, volt_column):
-    
-    df = dfin.copy()
-    df_volt_rolling = df[volt_column] 
-
-    df_volt_rolling_sum=df_volt_rolling.sum(1)-df_volt_rolling.max(1)
-    df_volt_rolling_sum=df_volt_rolling_sum-df_volt_rolling.min(1)
-    mean1 = df_volt_rolling_sum/(len(volt_column)-2)
-    df_volt_rolling_norm = df_volt_rolling.sub(mean1, axis=0)#.div(std,axis=0)
-    df_volt_rolling_norm = df_volt_rolling_norm.reset_index(drop=True)#和均值的距离
-
-    return df_volt_rolling_norm
-
-# 计算电压离群  
-def cal_volt_sigma(dfin, volt_column):
-    
-    df = dfin.copy()
-    df_volt_rolling = df[volt_column] 
-    
-    mean1=df_volt_rolling.mean(axis=1)
-    std = df_volt_rolling.std(axis=1)
-    std = std.replace(0,0.000001)
-    df_volt_rolling = df_volt_rolling.sub(mean1, axis=0).div(std,axis=0)
-    df_volt_rolling = df_volt_rolling.reset_index(drop=True)#分布
-
-    return df_volt_rolling
-
-
-# # 计算电压变化量的偏离度    
-# def cal_voltdiff_uniform(dfin, volt_column, window=10, step=5, window2=10, step2=5,threshold=3):
-    
-#     df = dfin.copy()
-#     time_list = dfin['time'].tolist()
-
-#     # 电压滤波
-#     df_volt = df[volt_column] 
-#     df_volt_rolling = df_volt.rolling(window).mean()[window-1::step]  # 滑动平均值
-#     time_list = time_list[window-1::step] 
-
-#     # 计算电压变化量的绝对值(# 计算前后的差值的绝对值,  时间列-1)
-#     df_volt_diff = abs(df_volt_rolling.diff()[1:])
-#     df_volt_diff = df_volt_diff.reset_index(drop=True)
-#     time_list = time_list[1:]
-
-#     # 压差归一化(偏离度)
-#     # mean = df_volt_diff.mean(axis=1)
-#     # std = df_volt_diff.std(axis=1)
-#     # df_voltdiff_norm = df_volt_diff.sub(mean, axis=0).div(std,axis=0)
-#     df_voltdiff_norm = df_volt_diff.copy()
-
-#     # 压差偏离度滑动平均滤波
-#     df_voltdiff_rolling = df_voltdiff_norm.rolling(window2).mean()[window2-1::step2]  # 滑动平均值
-#     time_list = time_list[window2-1::step2]
-#     df_voltdiff_rolling_sum=df_voltdiff_rolling.sum(1)-df_voltdiff_rolling.max(1)
-#     df_voltdiff_rolling_sum=df_voltdiff_rolling_sum-df_voltdiff_rolling.min(1)
-#     mean = df_voltdiff_rolling_sum/(len(volt_column)-2)
-#     std = df_voltdiff_rolling.std(axis=1)
-#     # mean = [np.array(sorted(x)[1:-1]).mean() for x in df_voltdiff_rolling.values]
-#     # std = [np.array(sorted(x)[1:-1]).std() for x in df_voltdiff_rolling.values]
-#     df_voltdiff_rolling_norm = df_voltdiff_rolling.sub(mean, axis=0)#.div(std,axis=0)
-#     df_voltdiff_rolling_norm = df_voltdiff_rolling_norm.reset_index(drop=True)
-#     return df_voltdiff_rolling_norm, time_list
-def main(sn,df_bms,df_soh,celltype,df_last):
-    df_ram=pd.DataFrame(columns=['sn','time4','cellsoc'])
-    param=BatParam.BatParam(celltype)
-    df_bms['总电流[A]']=df_bms['总电流[A]']*param.PackCrntDec
-    df_bms.rename(columns = {'总电流[A]':'PackCrnt'}, inplace=True)
-    df_bms['time']=pd.to_datetime(df_bms['时间戳'], format='%Y-%m-%d %H:%M:%S')
-    volt_column = ['单体电压'+str(i) for i in range(1,param.CellVoltNums+1)]
-    columns=['time']+volt_column
-    df_bms=df_bms[(df_bms['SOC[%]']>10)]
-    # df_bms=df_bms[(df_bms['PackCrnt']<1)]
-    # df_chrg=df_bms[(df_bms['PackCrnt']<-1)]
-
-    #电压/SOC变化率计算
-    if celltype<50:
-        df_ram=pd.DataFrame(columns=['sn','time4','cellsoc'])
-        df_ori = df_bms[columns]
-        df = df_ori.drop_duplicates(subset=['time']) # 删除时间相同的数据
-        df= df.set_index('time')
-        df=df[(df[volt_column]>2000) & (df[volt_column]<4500)]
-        df[volt_column]=pd.DataFrame(df[volt_column],dtype=np.float)
-        df=df.resample('H').mean()  #取一个小时的平均值
-        df=df.dropna(how='any')
-        time_list1=df.index.tolist()
-    
-        fun=lambda x: np.interp(x/1000, param.LookTab_OCV, param.LookTab_SOC)
-        df_soc=df.applymap(fun)
-        if (not df_soh.empty) and len(df_soc)>1:
-            if (not df_last.empty) and (time_list1[0]-df_last.loc[0,'time4']).total_seconds()<12*3600:
-                df_delt_soc1=df_soc-df_last.loc[0,'cellsoc']
-                cellsoh=eval(df_soh.loc[0,'cellsoh'])
-                df_delt_soc2=df_delt_soc1*np.array(cellsoh)/100
-                df_delt_soc=df_delt_soc2-df_delt_soc1
-                df_soc=df_soc+df_delt_soc
-            else:
-                df_delt_soc1=df_soc-df_soc.iloc[0]
-                cellsoh=eval(df_soh.loc[0,'cellsoh'])
-                df_delt_soc2=df_delt_soc1*np.array(cellsoh)/100
-                df_delt_soc=df_delt_soc2-df_delt_soc1
-                df_soc=df_soc+df_delt_soc
-            df_ram.loc[0]=[sn,df_soc.index[-1],list(df_soc.iloc[-1])]
-        else:
-            df_ram=df_last
-
-        VolChng = cal_volt_change(df_soc,volt_column)
-    else:
-        # df_bms=df_bms[(df_bms['PackCrnt']>-0.1) & (df_bms['PackCrnt']<0.1)]
-        df_ori = df_bms[columns]
-        df = df_ori.drop_duplicates(subset=['time']) # 删除时间相同的数据
-        df= df.set_index('time')
-        df=df[(df[volt_column]>3200) & (df[volt_column]<3400)]
-        df[volt_column]=pd.DataFrame(df[volt_column],dtype=np.float)
-        df=df.resample('H').mean()  #取一个小时的平均值
-        df=df.dropna(how='any')
-        time_list1=df.index.tolist()
-        VolChng = cal_volt_change(df,volt_column)
-    
-
-    VolSigma = cal_volt_sigma(df,volt_column)
-
-    OutLineVol=DataFrame(columns=['time','sn','VolOl_Uni','VolChng_Uni'])
-
-    #电压变化率和离群度计算
-    if len(VolChng)>5 and len(VolSigma)>5:
-        VolChng['time'] = time_list1
-        VolChng= VolChng.set_index('time')
-        VolChng_Uni_result=VolChng.values.tolist()#改
-        
-        VolSigma['time'] = time_list1
-        VolSigma= VolSigma.set_index('time')
-        VolOl_Uni_result=VolSigma.values.tolist()#改
-       
-        for i in range(0,len(VolChng)):
-            if max(VolOl_Uni_result[i])>3 and min(VolOl_Uni_result[i])<-3:
-                pass
-            else:
-                OutLineVol.loc[i,'VolOl_Uni']=str(list(np.around(VolOl_Uni_result[i],decimals=2)))
-                OutLineVol.loc[i,'VolChng_Uni']=str(list(np.around(VolChng_Uni_result[i],decimals=2)))
-        OutLineVol=OutLineVol[~OutLineVol['VolOl_Uni'].str.contains('nan')]
-        OutLineVol=OutLineVol[~OutLineVol['VolChng_Uni'].str.contains('nan')]
-        OutLineVol=OutLineVol.applymap((lambda x:''.join(x.split()) if type(x) is str else x)) 
-        OutLineVol=OutLineVol.reset_index(drop=True) 
-        OutLineVol['time']= VolSigma.index
-        OutLineVol['sn']=sn
-
-    return(OutLineVol,df_ram)
-    # this_alarm = {}
-    # df_alarm = df_voltdiff_rolling_norm[abs(df_voltdiff_rolling_norm)>threshold].dropna(how='all')
-    # for index in df_alarm.index:
-    #     df_temp = df_alarm.loc[index, :].dropna(how='all', axis=0)
-    #     this_alarm.update({df_cell_volt.loc[index+1, 'date']:[str(df_temp.keys().tolist()), str([round(x, 2) for x in df_temp.values.tolist()])]})
-    # df_alarm1 = pd.DataFrame(this_alarm)
-
-
-    # return pd.DataFrame(df_alarm1.values.T, index=df_alarm1.columns, columns=df_alarm1.index), pd.DataFrame(df_alarm2.values.T, index=df_alarm2.columns, columns=df_alarm2.index)
-
-    # # 孤立森林算法
-    # def iso_froest(df):
-
-    #     #1. 生成训练数据
-    #     rng = np.random.RandomState(42)
-    #     X = 0.3 * rng.randn(100, 2) #生成100 行,2 列
-    #     X_train = np.r_[X + 2, X - 2]
-    #     print(X_train)
-    #     # 产生一些异常数据
-    #     X_outliers = rng.uniform(low=-4, high=4, size=(20, 2))
-    #     iForest= IsolationForest(contamination=0.1)
-    #     iForest = iForest.fit(X_train)
-    #     #预测
-    #     pred = iForest.predict(X_outliers)
-    #     print(pred)
-    #     # [-1 1 -1 -1 -1 -1 -1 1 -
-
-# # 计算相关系数
-# def cal_coff(df):
-#     cc_mean = np.mean(df, axis=0)  #axis=0,表示按列求均值 ——— 即第一维
-#     cc_std = np.std(df, axis=0)
-#     cc_zscore = (df-cc_mean)/cc_std   #标准化
-#     cc_zscore = cc_zscore.dropna(axis=0, how='any')
-
-#     cc_zscore_corr = cc_zscore.corr(method='spearman')
-    
-#     result = []
-#     for i in range(len(cc_zscore_corr)):
-#         v = abs(np.array((sorted(cc_zscore_corr.iloc[i]))[2:-1])).mean() # 去掉1 和两个最小值后求均值
-#         result.append(v)
-#     return cc_zscore_corr, result
-
-
-# def instorage(sn, df_voltdiff_result, df_volt_result):
-    
-#     df_all_result = pd.DataFrame(columns=['sn', 'time', 'cellnum', 'value', 'type'])
-    
-#     value_list = []
-#     cellnum_list = []
-#     time_list = []
-#     type_list = []
-#     df_result = df_voltdiff_result.copy().drop(columns='time')
-#     time_list_1 = df_voltdiff_result['time']
-#     df_result = df_result[(df_result>3) | (df_result<-3)].dropna(axis=0, how='all').dropna(axis=1, how='all')
-#     for column in df_result.columns:
-#         df = df_result[[column]].dropna(axis=0, how='all')
-#         value_list.extend(df[column].tolist())
-#         cellnum_list.extend([column]*len(df))
-#         time_list.extend([time_list_1[x] for x in df.index])
-#     length_1 = len(value_list)
-    
-
-
-#     df_result = df_volt_result.copy().drop(columns='time')
-#     time_list_2 = df_volt_result['time']
-#     df_result = df_result[(df_result>3) | (df_result<-3)].dropna(axis=0, how='all').dropna(axis=1, how='all')
-#     for column in df_result.columns:
-#         df = df_result[[column]].dropna(axis=0, how='all')
-#         value_list.extend(df[column].tolist())
-#         cellnum_list.extend([column]*len(df))
-#         time_list.extend([time_list_2[x] for x in df.index])
-
-#     length_2 = len(value_list) - length_1
-#     type_list.extend(['电压变化量离群'] * length_1)
-#     type_list.extend(['电压离群'] * length_2)
-#     df_all_result['sn'] = [sn] * len(value_list)
-#     df_all_result['cellnum'] = cellnum_list
-#     df_all_result['value'] = value_list
-#     df_all_result['time'] = time_list
-#     df_all_result['type'] = type_list
-#     return df_all_result
-
-# # 报警.如果在某个窗口内,有超过ratio个的点,偏离度超过threshold, 则报警
-# def alarm(dfin, volt_column, alarm_window=10, alarm_ratio=0.8, alarm_threshold=2.5):
-
-    
-#     time_list = dfin['time'].tolist()
-#     df_result = dfin[volt_column].copy()
-#     alarm_result = pd.DataFrame(columns=['type', 'num', 'alarm_time'])      
-#     df_result_1 = df_result.copy()
-#     df_result_1[df_result_1<alarm_threshold] = 0
-#     df_result_1[df_result_1>alarm_threshold] = 1    
-#     df_result_1 = df_result_1.rolling(alarm_window).sum()
-#     for column in volt_column:
-#         if len(df_result_1[df_result_1[column]>alarm_window * alarm_ratio])>0:
-#             alarm_result = alarm_result.append({'type':'1', 'num':column, 'alarm_time':time_list[df_result_1[df_result_1[column]>alarm_window * alarm_ratio].index[0]]}, ignore_index=True)
-
-#     # time_list = time_list[window-1::step] 
-
-#     df_result_2 = df_result.copy()
-#     df_result_2[df_result_2>-alarm_threshold] = 0
-#     df_result_2[df_result_2<-alarm_threshold] = 1
-#     df_result_2 = df_result_2.rolling(alarm_window).sum()
-#     for column in volt_column:
-#         if len(df_result_2[df_result_2[column]>alarm_window * alarm_ratio])>0:
-#             alarm_result = alarm_result.append({'type':'2', 'num':column, 'alarm_time':time_list[df_result_2[df_result_2[column]>alarm_window * alarm_ratio].index[0]]}, ignore_index=True)
-#     return alarm_result

+ 0 - 279
USER/SPF/01qixiang/07BatSafetyWarning copy/main.py

@@ -1,279 +0,0 @@
-import pandas as pd
-import pymysql
-from LIB.BACKEND import DBManager, Log
-from apscheduler.schedulers.blocking import BlockingScheduler
-import time, datetime
-from sqlalchemy import create_engine
-from urllib import parse
-from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload
-from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import log
-import CBMSBatInterShort
-import CBMSBatUniform
-import VoltStray
-import CBMSSafetyWarning
-
-#电池热安全预警核心算法函数......................................................................................................................
-def saftywarning_cal():
-    global SNnums
-    global df_warning_ram
-    global df_warning_ram1
-    global df_warning_ram2
-    global df_warning_ram3
-    global df_warning_ram4
-    global df_lfp_ram
-    global df_lfp_ram1
-    global now_time
-
-    pd.set_option('display.width', 300) # 设置字符显示宽度
-    pd.set_option('display.max_rows', None) # 设置显示最大行
-    pd.set_option('display.max_columns', None) # 设置显示最大列,None为显示所有列
-    
-    start=time.time()
-    # now_time=datetime.datetime.now()
-    # start_time=now_time-datetime.timedelta(hours=6)
-    # start_time1=now_time-datetime.timedelta(days=7)
-    # start_time2=now_time-datetime.timedelta(days=3)
-    # start_time3=now_time-datetime.timedelta(days=1)
-    # start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
-    # start_time1=start_time1.strftime('%Y-%m-%d %H:%M:%S')
-    # start_time2=start_time2.strftime('%Y-%m-%d %H:%M:%S')
-    # start_time3=start_time3.strftime('%Y-%m-%d %H:%M:%S')
-    # end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
-
-    now_time=now_time+datetime.timedelta(hours=6)
-    start_time=now_time-datetime.timedelta(hours=6)
-    start_time1=now_time-datetime.timedelta(days=7)
-    start_time2=now_time-datetime.timedelta(days=3)
-    start_time3=now_time-datetime.timedelta(days=1)
-    start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
-    start_time1=start_time1.strftime('%Y-%m-%d %H:%M:%S')
-    start_time2=start_time2.strftime('%Y-%m-%d %H:%M:%S')
-    start_time3=start_time3.strftime('%Y-%m-%d %H:%M:%S')
-    end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
-
-    #数据库配置
-    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
-    port=3306
-    user='qx_algo_rw'
-    password='qx@123456'
-
-    #读取故障结果库中code==110且end_time='0000-00-00 00:00:00'...............................
-    db='safety_platform'
-    mysql = pymysql.connect (host=host, user=user, password=password, port=port, database=db)
-    cursor = mysql.cursor()
-    param='start_time,end_time,product_id,code,level,info,advice'
-    tablename='all_fault_info_copy'
-    sql =  "select %s from %s where end_time='0000-00-00 00:00:00' and level=4" %(param,tablename)
-    cursor.execute(sql)
-    res = cursor.fetchall()
-    df_fault_ram= pd.DataFrame(res,columns=param.split(','))
-    
-    db_res_engine1 = create_engine(
-        "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
-            user, parse.quote_plus(password), host, port, db
-        ))
-    
-    db='qx_cas'
-    db_res_engine2 = create_engine(
-        "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
-            user, parse.quote_plus(password), host, port, db
-        ))
-
-    for sn in SNnums:
-        try:
-            if 'PK500' in sn:
-                celltype=1 #6040三元电芯
-            elif 'PK502' in sn:
-                celltype=2 #4840三元电芯
-            elif 'K504B' in sn:
-                celltype=99    #60ah林磷酸铁锂电芯
-            elif 'MGMLXN750' in sn:
-                celltype=3 #力信50ah三元电芯
-            elif ('MGMCLN750' in sn) or ('UD' in sn): 
-                celltype=4 #CATL 50ah三元电芯
-            elif 'TJMCL'in sn: 
-                celltype=100 #重卡换电
-            else:
-                print('SN:{},未找到对应电池类型!!!'.format(sn))
-                continue
-                # sys.exit()
-
-            #读取原始数据库数据........................................................................................................................................................
-            dbManager = DBManager.DBManager()
-            df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
-            df_bms = df_data['bms']
-            df_bms=df_bms.dropna(axis=0,subset=['总电流[A]','SOH[%]','SOC[%]']) #去除有空值的行
-            df_bms.reset_index(inplace=True,drop=True)     #重置索引
-            # print(df_bms)
-            # df_bms.to_csv(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\98Download\\'+sn+'_BMS_'+'.csv',encoding='GB18030')
-
-            #读取结果数据库数据........................................................................................................................................................
-            db='qx_cas'
-            mode=1
-            DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
-            with DBRead as DBRead:
-                df_soh=DBRead.getdata('time_st,sn,soh,cellsoh', tablename='cellstateestimation_soh', sn=sn, timename='time_sp', st=start_time, sp=end_time)
-                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)
-
-            if not df_bms.empty:
-                #ram处理...............................................................................................................
-                df_warning_ram_sn=df_warning_ram[df_warning_ram['sn']==sn]
-                df_warning_ram_sn1=df_warning_ram1[df_warning_ram1['sn']==sn]
-                df_warning_ram_sn2=df_warning_ram2[df_warning_ram2['sn']==sn]
-                df_warning_ram_sn3=df_warning_ram3[df_warning_ram3['sn']==sn]
-                df_warning_ram_sn4=df_warning_ram4[df_warning_ram4['sn']==sn]
-                df_warning_ram_sn.reset_index(inplace=True,drop=True)     #重置索引
-                df_warning_ram_sn1.reset_index(inplace=True,drop=True)     #重置索引
-                df_warning_ram_sn2.reset_index(inplace=True,drop=True)     #重置索引
-                df_warning_ram_sn3.reset_index(inplace=True,drop=True)     #重置索引
-                df_warning_ram_sn4.reset_index(inplace=True,drop=True)     #重置索引
-                if celltype>50 and (not df_lfp_ram.empty):
-                    df_lfp_ram_sn=df_lfp_ram[df_lfp_ram['sn']==sn]
-                    df_lfp_ram_sn.reset_index(inplace=True,drop=True)     #重置索引
-                else:
-                    df_lfp_ram_sn=pd.DataFrame()
-                    df_lfp_ram=pd.DataFrame(columns=df_bms.columns.tolist()+['sn'])
-                if celltype>50 and (not df_lfp_ram1.empty):
-                    df_lfp_ram_sn1=df_lfp_ram1[df_lfp_ram1['sn']==sn]
-                    df_lfp_ram_sn1.reset_index(inplace=True,drop=True)     #重置索引
-                else:
-                    df_lfp_ram_sn1=pd.DataFrame()
-                    df_lfp_ram1=pd.DataFrame(columns=df_bms.columns.tolist()+['sn'])
-
-                #内短路计算..................................................................................................................................................
-                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)
-                df_short_res, df_ram_res, df_ram_res1, df_ram_res2, df_ram_res3, df_ram_res5=BatShort.intershort() 
-                if not df_short_res.empty:
-                    df_short_res.to_sql("cellstateestimation_intershort",con=db_res_engine2, if_exists="append",index=False)
-                
-                #静置电压排名..................................................................................................................................................
-                BatUniform=CBMSBatUniform.BatUniform(sn,celltype,df_bms,df_uniform,df_ram_res3,df_lfp_ram_sn1)
-                df_rank_res, df_ram_res3, df_ram_res6=BatUniform.batuniform()
-                if not df_rank_res.empty:
-                    df_uniform=df_rank_res
-                    df_uniform.to_sql("cellstateestimation_uniform_socvoltdiff",con=db_res_engine2, if_exists="append",index=False)
-                
-                #电压离群.....................................................................................................................................................
-                df_voltsigma,df_ram_res4=VoltStray.main(sn,df_bms,df_soh,celltype,df_warning_ram_sn4)
-                if not df_voltsigma.empty:
-                    df_voltsigma.to_sql("outlier_voltchangeratio",con=db_res_engine2, if_exists="append",index=False)
-
-                #ram处理................................................................................................................
-                df_warning_ram=df_warning_ram.drop(df_warning_ram[df_warning_ram.sn==sn].index)
-                df_warning_ram1=df_warning_ram1.drop(df_warning_ram1[df_warning_ram1.sn==sn].index)
-                df_warning_ram2=df_warning_ram2.drop(df_warning_ram2[df_warning_ram2.sn==sn].index)
-                df_warning_ram3=df_warning_ram3.drop(df_warning_ram3[df_warning_ram3.sn==sn].index)
-                df_warning_ram4=df_warning_ram4.drop(df_warning_ram4[df_warning_ram4.sn==sn].index)
-
-                df_warning_ram=pd.concat([df_warning_ram,df_ram_res],ignore_index=True)
-                df_warning_ram1=pd.concat([df_warning_ram1,df_ram_res1],ignore_index=True)
-                df_warning_ram2=pd.concat([df_warning_ram2,df_ram_res2],ignore_index=True)
-                df_warning_ram3=pd.concat([df_warning_ram3,df_ram_res3],ignore_index=True)
-                df_warning_ram4=pd.concat([df_warning_ram4,df_ram_res4],ignore_index=True)
-                
-                if celltype>50:
-                    df_lfp_ram=df_lfp_ram.drop(df_lfp_ram[df_lfp_ram.sn==sn].index)
-                    df_lfp_ram=pd.concat([df_lfp_ram,df_ram_res5],ignore_index=True)
-                    df_lfp_ram1=df_lfp_ram1.drop(df_lfp_ram1[df_lfp_ram1.sn==sn].index)
-                    df_lfp_ram1=pd.concat([df_lfp_ram1,df_ram_res6],ignore_index=True)
-            
-            else:
-                df_voltsigma=pd.DataFrame()
-                
-
-            #电池热安全预警..............................................................................................................................................................
-            #读取内短路、析锂和一致性结果数据库数据
-            db='qx_cas'
-            mode=2
-            tablename1='cellstateestimation_intershort'
-            tablename3='cellstateestimation_uniform_socvoltdiff'
-            tablename4='outlier_voltchangeratio'   #电压离群表单
-            DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
-            with DBRead as DBRead:
-                df_short=DBRead.getdata('time_sp,sn,short_current', tablename=tablename1, sn=sn, timename='time_sp', st=start_time1, sp=end_time)
-                # df_liplated=DBRead.getdata('time,sn,liplated,liplated_amount', tablename=tablename2, sn=sn, timename='time', st=start_time2, sp=end_time)
-                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)
-                df_voltsigma=DBRead.getdata('time,sn,VolOl_Uni,VolChng_Uni', tablename=tablename4, sn=sn, timename='time', st=start_time3, sp=end_time)
-                df_uniform=df_uniform.dropna(axis=0,how='any')
-            
-            #获取sn的故障RAM
-            df_fault_ram_sn=df_fault_ram[df_fault_ram['product_id']==sn]
-            df_fault_ram_sn.reset_index(inplace=True,drop=True)  #重置索引
-            
-            #热安全预警
-            BatWarning=CBMSSafetyWarning.SafetyWarning(sn,celltype,df_short,df_uniform,df_voltsigma,df_soh,df_fault_ram_sn)
-            df_warning_res=BatWarning.diag()
-            
-            if not df_warning_res.empty:
-                df_warning_new = pd.concat([df_warning_res,df_fault_ram_sn,df_fault_ram_sn]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
-                df_warning_new.reset_index(inplace=True,drop=True)  #重置索引
-                df_warning_end=pd.concat([df_warning_res,df_warning_new,df_warning_new]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
-                df_warning_end=df_warning_end[df_warning_end['end_time'] != '0000-00-00 00:00:00']
-                df_warning_end.reset_index(inplace=True,drop=True)  #重置索引
-            
-                #新增热失控预警写入数据库
-                if not df_warning_new.empty:
-                    df_warning_new.to_sql("all_fault_info_copy",con=db_res_engine1, if_exists="append",index=False)
-                        
-                #结束热失控预警更新数据库
-                if not df_warning_end.empty:
-                    for j in range(len(df_warning_end)):
-                        cursor.execute('''
-                                    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='{}'
-                                    '''.format(datetime.datetime.now(), df_warning_end.loc[j,'end_time'], 1 ,sn, df_warning_end.loc[j,'code']))
-                        mysql.commit()
-        
-            end=time.time()
-            print(end-start)
-        except Exception as e:
-            print(repr(e))
-            mylog.logopt(sn+str(e))
-    
-    mysql.close()
-    cursor.close()
-
-#...............................................主函数起定时作用.......................................................................................................................
-if __name__ == "__main__":
-    
-    excelpath=r'D:\Develop\User\Songpengfei\data_analyze_platform\WORK\01qixiang\sn-20210903.xlsx'
-    SNdata_6060 = pd.read_excel(excelpath, sheet_name='科易6060')
-    SNdata_6040 = pd.read_excel(excelpath, sheet_name='科易6040')
-    SNdata_4840 = pd.read_excel(excelpath, sheet_name='科易4840')
-    SNdata_L7255 = pd.read_excel(excelpath, sheet_name='格林美-力信7255')
-    SNdata_C7255 = pd.read_excel(excelpath, sheet_name='格林美-CATL7255')
-    SNdata_U7255 = pd.read_excel(excelpath, sheet_name='优旦7255')
-    SNnums_6060=SNdata_6060['SN号'].tolist()
-    SNnums_6040=SNdata_6040['SN号'].tolist()
-    SNnums_4840=SNdata_4840['SN号'].tolist()
-    SNnums_L7255=SNdata_L7255['SN号'].tolist()
-    SNnums_C7255=SNdata_C7255['SN号'].tolist()
-    SNnums_U7255=SNdata_U7255['SN号'].tolist()
-    SNnums=SNnums_6060 + SNnums_6040 + SNnums_4840 + SNnums_L7255 + SNnums_C7255 + SNnums_U7255
-    SNnums=['MGMCLN750N215N044']
-    
-    mylog=log.Mylog('log_warning.txt','error')
-    mylog.logcfg()
-
-    #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取...................................
-    df_warning_ram=pd.DataFrame(columns=['sn','time','deltsoc','cellsoc'])
-    df_warning_ram1=pd.DataFrame(columns=['sn','time1','deltsoc1'])
-    df_warning_ram2=pd.DataFrame(columns=['sn','time2','deltAs2'])
-    df_warning_ram3=pd.DataFrame(columns=['sn','time3','standingtime','standingtime1','standingtime2'])
-    df_warning_ram4=pd.DataFrame(columns=['sn','time4','cellsoc'])
-    df_lfp_ram=pd.DataFrame()
-    df_lfp_ram1=pd.DataFrame()
-
-    now_time='2022-2-15 10:00:56'
-    now_time=datetime.datetime.strptime(now_time,'%Y-%m-%d %H:%M:%S')
-
-    #定时任务.......................................................................................................................................................................
-    # saftywarning_cal()
-    scheduler = BlockingScheduler()
-    scheduler.add_job(saftywarning_cal, 'interval', seconds=6)
-
-    try:  
-        scheduler.start()
-    except Exception as e:
-        scheduler.shutdown()
-        print(repr(e))
-        mylog.logopt(e)

BIN
USER/SPF/01qixiang/USER - 快捷方式.lnk