You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
137 lines
5.3 KiB
137 lines
5.3 KiB
6 years ago
|
from detectors.general_detector.supervised_algorithm import SupervisedAlgorithm
|
||
6 years ago
|
import utils
|
||
6 years ago
|
from grafana_data_provider import GrafanaDataProvider
|
||
7 years ago
|
from data_preprocessor import data_preprocessor
|
||
|
import pandas as pd
|
||
|
import logging
|
||
7 years ago
|
from urllib.parse import urlparse
|
||
7 years ago
|
import config
|
||
6 years ago
|
import os.path
|
||
|
import json
|
||
7 years ago
|
|
||
6 years ago
|
|
||
6 years ago
|
NANOSECONDS_IN_MS = 1000000
|
||
7 years ago
|
|
||
|
logger = logging.getLogger('analytic_toolset')
|
||
|
|
||
|
|
||
6 years ago
|
class GeneralDetector:
|
||
7 years ago
|
|
||
|
def __init__(self, anomaly_name):
|
||
|
self.anomaly_name = anomaly_name
|
||
|
self.load_anomaly_config()
|
||
|
|
||
7 years ago
|
parsedUrl = urlparse(self.anomaly_config['panelUrl'])
|
||
|
origin = parsedUrl.scheme + '://' + parsedUrl.netloc
|
||
|
|
||
|
datasource = self.anomaly_config['datasource']
|
||
|
datasource['origin'] = origin
|
||
7 years ago
|
metric_name = self.anomaly_config['metric']['targets'][0]
|
||
|
|
||
7 years ago
|
target_filename = os.path.join(config.METRICS_FOLDER, metric_name + ".json")
|
||
7 years ago
|
|
||
7 years ago
|
dataset_filename = os.path.join(config.DATASET_FOLDER, metric_name + ".csv")
|
||
|
augmented_path = os.path.join(config.DATASET_FOLDER, metric_name + "_augmented.csv")
|
||
7 years ago
|
|
||
|
with open(target_filename, 'r') as file:
|
||
|
target = json.load(file)
|
||
|
|
||
6 years ago
|
self.data_prov = GrafanaDataProvider(datasource, target, dataset_filename)
|
||
7 years ago
|
self.preprocessor = data_preprocessor(self.data_prov, augmented_path)
|
||
|
self.model = None
|
||
|
|
||
|
self.__load_model()
|
||
|
|
||
6 years ago
|
async def learn(self, segments):
|
||
7 years ago
|
logger.info("Start to learn for anomaly_name='%s'" % self.anomaly_name)
|
||
|
|
||
|
confidence = 0.02
|
||
|
dataframe = self.data_prov.get_dataframe()
|
||
|
start_index, stop_index = 0, len(dataframe)
|
||
6 years ago
|
if len(segments) > 0:
|
||
7 years ago
|
confidence = 0.0
|
||
6 years ago
|
min_time, max_time = utils.segments_box(segments)
|
||
7 years ago
|
dataframe = dataframe[dataframe['timestamp'] <= max_time]
|
||
|
dataframe = dataframe[dataframe['timestamp'] >= min_time]
|
||
7 years ago
|
|
||
|
train_augmented = self.preprocessor.get_augmented_data(
|
||
7 years ago
|
dataframe.index[0],
|
||
|
dataframe.index[-1],
|
||
6 years ago
|
segments
|
||
7 years ago
|
)
|
||
|
|
||
|
self.model = self.create_algorithm()
|
||
6 years ago
|
await self.model.fit(train_augmented, confidence)
|
||
6 years ago
|
if len(segments) > 0:
|
||
7 years ago
|
last_dataframe_time = dataframe.iloc[-1]['timestamp']
|
||
7 years ago
|
last_prediction_time = int(last_dataframe_time.timestamp() * 1000)
|
||
|
else:
|
||
|
last_prediction_time = 0
|
||
|
|
||
|
self.__save_model()
|
||
|
logger.info("Learning is finished for anomaly_name='%s'" % self.anomaly_name)
|
||
|
return last_prediction_time
|
||
|
|
||
6 years ago
|
async def predict(self, last_prediction_time):
|
||
7 years ago
|
logger.info("Start to predict for anomaly type='%s'" % self.anomaly_name)
|
||
|
last_prediction_time = pd.to_datetime(last_prediction_time, unit='ms')
|
||
|
|
||
|
start_index = self.data_prov.get_upper_bound(last_prediction_time)
|
||
|
stop_index = self.data_prov.size()
|
||
6 years ago
|
last_prediction_time = int(last_prediction_time.value / NANOSECONDS_IN_MS)
|
||
7 years ago
|
|
||
|
predicted_anomalies = []
|
||
|
if start_index < stop_index:
|
||
|
max_chunk_size = 50000
|
||
|
predicted = pd.Series()
|
||
|
for index in range(start_index, stop_index, max_chunk_size):
|
||
|
chunk_start = index
|
||
|
chunk_finish = min(index + max_chunk_size, stop_index)
|
||
|
predict_augmented = self.preprocessor.get_augmented_data(chunk_start, chunk_finish)
|
||
|
|
||
|
assert(len(predict_augmented) == chunk_finish - chunk_start)
|
||
|
|
||
6 years ago
|
predicted_current = await self.model.predict(predict_augmented)
|
||
7 years ago
|
predicted = pd.concat([predicted, predicted_current])
|
||
|
predicted_anomalies = self.preprocessor.inverse_transform_anomalies(predicted)
|
||
|
|
||
|
last_row = self.data_prov.get_data_range(stop_index - 1, stop_index)
|
||
|
|
||
|
last_dataframe_time = last_row.iloc[0]['timestamp']
|
||
6 years ago
|
predicted_anomalies = utils.anomalies_to_timestamp(predicted_anomalies)
|
||
7 years ago
|
last_prediction_time = int(last_dataframe_time.timestamp() * 1000)
|
||
|
|
||
|
logger.info("Predicting is finished for anomaly type='%s'" % self.anomaly_name)
|
||
|
return predicted_anomalies, last_prediction_time
|
||
|
|
||
|
def synchronize_data(self):
|
||
|
self.data_prov.synchronize()
|
||
|
self.preprocessor.set_data_provider(self.data_prov)
|
||
|
self.preprocessor.synchronize()
|
||
|
|
||
|
def load_anomaly_config(self):
|
||
6 years ago
|
with open(os.path.join(config.ANALYTIC_UNITS_FOLDER, self.anomaly_name + ".json"), 'r') as config_file:
|
||
7 years ago
|
self.anomaly_config = json.load(config_file)
|
||
|
|
||
|
def get_anomalies(self):
|
||
6 years ago
|
labeled_anomalies_file = os.path.join(config.ANALYTIC_UNITS_FOLDER, self.anomaly_name + "_labeled.json")
|
||
7 years ago
|
if not os.path.exists(labeled_anomalies_file):
|
||
|
return []
|
||
|
with open(labeled_anomalies_file) as file:
|
||
|
return json.load(file)
|
||
|
|
||
|
def create_algorithm(self):
|
||
6 years ago
|
return SupervisedAlgorithm()
|
||
7 years ago
|
|
||
|
def __save_model(self):
|
||
|
logger.info("Save model '%s'" % self.anomaly_name)
|
||
7 years ago
|
model_filename = os.path.join(config.MODELS_FOLDER, self.anomaly_name + ".m")
|
||
7 years ago
|
self.model.save(model_filename)
|
||
|
|
||
|
def __load_model(self):
|
||
|
logger.info("Load model '%s'" % self.anomaly_name)
|
||
7 years ago
|
model_filename = os.path.join(config.MODELS_FOLDER, self.anomaly_name + ".m")
|
||
7 years ago
|
if os.path.exists(model_filename):
|
||
|
self.model = self.create_algorithm()
|
||
|
self.model.load(model_filename)
|