68dcb35912ef4608d4d31da6c366cd5260988e20
[ric-app/qp.git] / qp / qptrain.py
1 # ==================================================================================
2 #  Copyright (c) 2020 HCL Technologies Limited.
3 #
4 #  Licensed under the Apache License, Version 2.0 (the "License");
5 #  you may not use this file except in compliance with the License.
6 #  You may obtain a copy of the License at
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #  Unless required by applicable law or agreed to in writing, software
11 #  distributed under the License is distributed on an "AS IS" BASIS,
12 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 #  See the License for the specific language governing permissions and
14 #  limitations under the License.
15 # ==================================================================================
16
17 from statsmodels.tsa.api import VAR
18 from statsmodels.tsa.stattools import adfuller
19 import joblib
20
21
22 class PROCESS(object):
23
24     def __init__(self, data):
25         self.diff = 0
26         self.data = data
27
28     def adfuller_test(self, series, thresh=0.05, verbose=False):
29         """ADFuller test for Stationarity of given series and return True or False"""
30         r = adfuller(series, autolag='AIC')
31         output = {'test_statistic': round(r[0], 4), 'pvalue': round(r[1], 4), 'n_lags': round(r[2], 4), 'n_obs': r[3]}
32         p_value = output['pvalue']
33         if p_value <= thresh:
34             return True
35         else:
36             return False
37
38     def make_stationary(self):
39         """ call adfuller_test() to check for stationary
40             If the column is stationary, perform 1st differencing and return data"""
41         df = self.data.copy()
42         res_adf = []
43         for name, column in df.iteritems():
44             res_adf.append(self.adfuller_test(column))  # Perform ADF test
45         if not all(res_adf):
46             self.data = df.diff().dropna()
47             self.diff += 1
48
49     def invert_transformation(self, inp, forecast):
50         """Revert back the differencing to get the forecast to original scale."""
51         if self.diff == 0:
52             return forecast
53         df = forecast.copy()
54         columns = inp.columns
55         for col in columns:
56             df[col] = inp[col].iloc[-1] + df[col].cumsum()
57         self.diff = 0
58         return df
59
60     def process(self):
61         """ Filter throughput parameters, call make_stationary() to check for Stationarity time series
62         """
63         df = self.data.copy()
64         df = df[['pdcpBytesDl', 'pdcpBytesUl']]
65         self.data = df.loc[:, (df != 0).any(axis=0)]
66         self.make_stationary()  # check for Stationarity and make the Time Series Stationary
67
68     def valid(self):
69         df = self.data.copy()
70         df = df.loc[:, (df != 0).any(axis=0)]
71         if len(df) != 0 and df.shape[1] == 2:
72             return True
73         else:
74             return False
75
76
77 def train(db, cid):
78     """
79      Read the input file(based on cell id received from the main program)
80      call process() to forecast the downlink and uplink of the input cell id
81      Make a VAR model, call the fit method with the desired lag order.
82     """
83     db.read_data(meas='liveCell', cellid=cid)
84     md = PROCESS(db.data)
85     md.process()
86     if md.valid():
87         model = VAR(md.data)          # Make a VAR model
88         model_fit = model.fit(10)            # call fit method with lag order
89         file_name = 'qp/'+cid.replace('/', '')
90         with open(file_name, 'wb') as f:
91             joblib.dump(model_fit, f)     # Save the model with the cell id name