Release 0.0.2
[ric-app/ad.git] / ad / ad_model / ad_model.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 import joblib
18
19
20 class modelling(object):
21     r""" Filter dataframe based on paramters that were used to train model
22     use transormer to transform the data
23     load model and predict the label(normal/anomalous)
24
25     Parameters:
26     data:DataFrame
27     """
28
29     def __init__(self, data):
30
31         with open('params', 'rb') as f:
32             cols = joblib.load(f)
33         if all(cols.isin(data.columns)):
34             self.data = data[cols]
35         else:
36             print(data.columns, cols)
37
38         self.transformation()
39
40     def transformation(self):
41         """ load transformer to transform data """
42
43         sc = joblib.load('scale')
44         self.data = sc.transform(self.data)
45
46     def predict(self, name):
47         """ Load the saved model and return predicted result.
48         Parameters
49         .........
50         name:str
51             name of model
52
53         Return
54         ......
55         pred:int
56             predict label on a given sample
57
58         """
59
60         model = joblib.load(name)
61         pred = model.predict(self.data)
62         pred = [1 if p == -1 else 0 for p in pred]
63         return pred
64
65
66 class CAUSE(object):
67     r""""Rule basd method to find degradation type of anomalous sample
68
69     Attributes:
70     normal:DataFrame
71         Dataframe that contains only normal sample
72     """
73
74     def __init__(self, db):
75         db.read_data('train')
76         self.normal = db.data[['rsrp', 'rsrq', 'rssinr', 'throughput', 'prb_usage', 'ue-id']]
77
78     def cause(self, sample):
79         """ Filter normal data for a particular ue-id to compare with a given sample
80             Compare with normal data to find and return degradaton type
81         """
82         normal = self.normal[self.normal['ue-id'] == sample.iloc[0]['ue-id']].drop('ue-id', axis=1)
83         param = self.find(sample, normal.max())
84         return param
85
86     def find(self, sample, Range):
87         """ store if a particular parameter is below threshold and return """
88
89         deg = []
90         if sample.iloc[0]['throughput'] < Range['throughput']*0.5:
91             deg.append('Throughput')
92         if sample.iloc[0]['rsrp'] <= Range['rsrp']-20:
93             deg.append('RSRP')
94         if sample.iloc[0]['rsrq'] <= Range['rsrq']-20:
95             deg.append('RSRQ')
96         if sample.iloc[0]['rssinr'] <= Range['rssinr']-25:
97             deg.append('RSSINR')
98         if sample.iloc[0]['prb_usage'] <= Range['prb_usage']*0.5:
99             deg.append('prb_usage')
100         if len(deg) == 0:
101             deg = False
102         else:
103             deg = ' '.join(deg)
104         return deg
105
106
107 def ad_predict(df):
108     """
109         Call Predict method to predict whether a given sample is normal or anomalous
110     """
111
112     db = modelling(df)
113     db_df = db.predict('model')  # Calls predict module and store the result into db_df
114     del db
115     return db_df