#热失控预警：PCA异常指数
#训练模型

from LIB.BACKEND import DBManager
dbManager = DBManager.DBManager()
from LIB.MIDDLE.CellStateEstimation.Common import log
import pandas as pd
from anomalyPCA import *
import joblib
import datetime

dataSOH = pd.read_excel('sn-20210903.xlsx',sheet_name='sn-20210903')
fileNames = dataSOH['sn']
fileNames = list(fileNames)
l = len(fileNames)

now_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')   #type: str
now_time=datetime.datetime.strptime(now_time,'%Y-%m-%d %H:%M:%S')     #type: datetime
start_time=now_time-datetime.timedelta(days=365)
end_time=str(now_time)
start_time=str(start_time)

mylog=log.Mylog('log.txt','error')
mylog.logcfg()

for k in range(l): 
    try: 
        sn = fileNames[k]
        df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
        data_train = df_data['bms']
        
        if len(data_train)>0:
            pca1,pca2,res1,res2=train_model(data_train) 
            joblib.dump(pca1,'pca1_'+sn+'.m')  
            joblib.dump(pca2,'pca2_'+sn+'.m')  
            res1.to_csv('res1_'+sn+'.csv',encoding='gbk')
            res2.to_csv('res2_'+sn+'.csv',encoding='gbk')
    
    except Exception as e:
        print(repr(e))
        mylog.logopt(sn,e)
        pass