[RICAPP-181] Update Prediction message (from QP to TS) with serving cell prediciton
[ric-app/qp.git] / qp / insert.py
1 # ==================================================================================
2 #       Copyright (c) 2020 AT&T Intellectual Property.
3 #       Copyright (c) 2020 HCL Technologies Limited.
4 #
5 #   Licensed under the Apache License, Version 2.0 (the "License");
6 #   you may not use this file except in compliance with the License.
7 #   You may obtain a copy of the License at
8 #
9 #          http://www.apache.org/licenses/LICENSE-2.0
10 #
11 #   Unless required by applicable law or agreed to in writing, software
12 #   distributed under the License is distributed on an "AS IS" BASIS,
13 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 #   See the License for the specific language governing permissions and
15 #   limitations under the License.
16 # ==================================================================================
17 """
18
19 This module is temporary which aims to populate cell data into influxDB. This will be depreciated once KPIMON push cell info. into influxDB.
20
21 """
22 import pandas as pd
23 from influxdb import DataFrameClient
24 import datetime
25
26
27 class INSERTDATA:
28
29     def __init__(self):
30         host = 'r4-influxdb.ricplt'
31         self.client = DataFrameClient(host, '8086', 'root', 'root')
32         self.switchdb('UEData')
33         self.dropmeas('QP')
34
35     def switchdb(self, dbname):
36         print("Switch database: " + dbname)
37         self.client.switch_database(dbname)
38
39     def dropmeas(self, measname):
40         print("DROP MEASUREMENT: " + measname)
41         self.client.query('DROP MEASUREMENT '+measname)
42
43
44 def explode(df):
45     for col in df.columns:
46         if isinstance(df.iloc[0][col], list):
47             df = df.explode(col)
48         d = df[col].apply(pd.Series)
49         df[d.columns] = d
50         df = df.drop(col, axis=1)
51     return df
52
53
54 def jsonToTable(df):
55     df.index = range(len(df))
56     cols = [col for col in df.columns if isinstance(df.iloc[0][col], dict) or isinstance(df.iloc[0][col], list)]
57     if len(cols) == 0:
58         return df
59     for col in cols:
60         d = explode(pd.DataFrame(df[col], columns=[col]))
61         d = d.dropna(axis=1, how='all')
62         df = pd.concat([df, d], axis=1)
63         df = df.drop(col, axis=1).dropna()
64     return jsonToTable(df)
65
66
67 def time(df):
68     df.index = pd.date_range(start=datetime.datetime.now(), freq='10ms', periods=len(df))
69     df['measTimeStampRf'] = df['measTimeStampRf'].apply(lambda x: str(x))
70     return df
71
72
73 def populatedb():
74     df = pd.read_json('qp/cell.json.gz', lines=True)
75     df = df[['cellMeasReport']].dropna()
76     df = jsonToTable(df)
77     df = time(df)
78     db = INSERTDATA()
79     db.client.write_points(df, 'liveCell', batch_size=500, protocol='line')