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

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

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='2021-06-01 00:00:00', end_time='2021-10-01 00:00:00', data_groups=['bms'])
        data_train = df_data['bms']
        df_data = dbManager.get_data(sn=sn, start_time='2021-10-01 00:00:00', end_time='2021-11-01 00:00:00', data_groups=['bms'])
        data_test = df_data['bms']
        if len(data_train)>0:
            x_train=anomalyPCA.makedataset(data_train)  
            x_train_pro=anomalyPCA.process(x_train) 
            pca=anomalyPCA.anomalyPCA(x_train_pro) 
            res=anomalyPCA.transform(x_train_pro,pca,x_train)
            res.to_csv('res'+sn+'.csv',encoding='gbk')
        if len(data_test)>0: 
            x_test=anomalyPCA.makedataset(data_test)  
            x_test_pro=anomalyPCA.process(x_test) 
            pred=anomalyPCA.transform(x_test_pro,pca,x_test) 
            pred.to_csv('pred'+sn+'.csv',encoding='gbk')
            outliers=anomalyPCA.detect_outliers(pred,threshold=0.95)
            outliers2=anomalyPCA.detect_outliers2(res,pred,threshold=36)
            outliers.to_csv('outliers'+sn+'.csv',encoding='gbk')
            outliers2.to_csv('outliers2'+sn+'.csv',encoding='gbk')
    except Exception as e:
        print(repr(e))
        mylog.logopt(sn,e)
        pass 