├── common ├── __init__.py ├── logger.py ├── constants.py ├── classes.py ├── request_builder.py └── utils.py ├── test ├── __init__.py ├── test_up_cs.py ├── test_down_stable_dd.py ├── test_up_periodic_dd.py ├── test_down_periodic_dd.py ├── test_up_stable_dd.py ├── test_down_cs_noise.py ├── test_up_cs_noise.py ├── test_down_cs.py ├── test_up_stable_dd_noise.py ├── assert_test_cases.py └── test_data_creator.py ├── algorithm ├── __init__.py ├── cold_start │ ├── __init__.py │ ├── similarity_filter.py │ ├── rule_checker.py │ └── diff_outlier_detector.py ├── dyn_thresh │ ├── __init__.py │ ├── dyn_thresh_algo │ │ ├── __init__.py │ │ ├── features.py │ │ ├── node.py │ │ ├── threshold.py │ │ └── events.py │ ├── rule_checker.py │ └── dyn_thresh_detector.py ├── sensitivity.py ├── module.py ├── pipeline.py ├── dt_module.py └── cs_module.py ├── handlers ├── __init__.py ├── run_main.py └── detect_handlers.py ├── requirements.txt ├── Dockerfile ├── serving.py ├── README-CN.md ├── README.md ├── .gitignore └── LICENSE /common/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithm/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /handlers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithm/cold_start/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithm/dyn_thresh/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /algorithm/dyn_thresh/dyn_thresh_algo/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==2.2.3 2 | matplotlib==3.5.3 3 | numpy==1.19.5 4 | pandas==1.3.5 5 | -------------------------------------------------------------------------------- /algorithm/sensitivity.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'sensitivity_mapper' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/18 15:17' 6 | __info__ = 7 | """ 8 | # todo 9 | 10 | if __name__ == "__main__": 11 | pass 12 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax=docker/dockerfile:1 2 | FROM python:3.7 3 | 4 | RUN ln -snf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 5 | 6 | WORKDIR /home/admin 7 | COPY requirements.txt requirements.txt 8 | RUN pip3 install -r requirements.txt 9 | COPY . . 10 | CMD [ "python3", "-m" , "serving", "run", "--host=0.0.0.0"] 11 | EXPOSE 5000 -------------------------------------------------------------------------------- /common/logger.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project_ = 'holoinsight-ai' 3 | __file_name__ = 'common_logger' 4 | __author__ = 'luyuan' 5 | __time__ = '2021-12-15 22:24' 6 | __product_name = PyCharm 7 | __info__: 8 | """ 9 | import logging 10 | 11 | 12 | class Logger(object): 13 | def __init__(self): 14 | super() 15 | 16 | @staticmethod 17 | def get_logger(): 18 | logging.basicConfig(level=logging.INFO) 19 | return logging 20 | 21 | 22 | if __name__ == "__main__": 23 | pass 24 | -------------------------------------------------------------------------------- /serving.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'serving' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/7 15:44' 6 | __info__ = 7 | """ 8 | from flask import Flask, request 9 | 10 | from handlers.run_main import run_main 11 | 12 | app = Flask(__name__) 13 | 14 | 15 | @app.route('/anomaly_detect', methods=['POST']) 16 | def anomaly_detect(): 17 | body = request.json 18 | result = run_main(body) 19 | trace_id = body.get("traceId") 20 | detect_time = body.get("detectTime") 21 | result["traceId"] = trace_id 22 | result["detectTime"] = detect_time 23 | result["errorCode"] = {} 24 | return result 25 | 26 | 27 | if __name__ == '__main__': 28 | app.run(host='0.0.0.0', port=8000, debug=True) 29 | pass 30 | -------------------------------------------------------------------------------- /common/constants.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project_ = 'holoinsight-ai' 3 | __file_name__ = 'contants' 4 | __author__ = 'luyuan' 5 | __time__ = '2021-08-09 16:30' 6 | __product_name = PyCharm 7 | __info__: 8 | """ 9 | from enum import Enum 10 | from math import inf 11 | 12 | 13 | class Constants(Enum): 14 | """ 15 | A class containing various constants used in the AD system. 16 | """ 17 | WINDOW_LIST = [1, 3, 5, 7, 9] # A list of window sizes used in the AD system. 18 | MIN_DURATION_DEFAULT = 1 # The default minimum duration used in the AD system. 19 | CUSTOM_UP_THRESHOLD = float(inf) # The default upper threshold used in the AD system. 20 | CUSTOM_DOWN_THRESHOLD = -float(inf) # The default lower threshold used in the AD system. 21 | CUSTOM_CHANGE_RATE_DEFAULT = 0.05 # The default change rate used in the AD system. 22 | ALGORITHM_TYPE_UP = "up" # the algorithm_type up 23 | ALGORITHM_TYPE_DOWN = "down" # the algorithm_type down 24 | 25 | 26 | if __name__ == "__main__": 27 | pass 28 | -------------------------------------------------------------------------------- /README-CN.md: -------------------------------------------------------------------------------- 1 | # Holoinsight AI 2 | ![License](https://img.shields.io/badge/license-Apache--2.0-green.svg) 3 | [![Github stars](https://img.shields.io/github/stars/traas-stack/holoinsight-ai?style=flat-square])](https://github.com/traas-stack/holoinsight-ai) 4 | [![OpenIssue](https://img.shields.io/github/issues/traas-stack/holoinsight-ai)](https://github.com/traas-stack/holoinsight-ai/issues) 5 | 6 | [English](./README.md) 7 | 8 | Holoinsight AI为[Holoinsight](https://github.com/traas-stack/holoinsight) 提供时序数据实时异常检测功能 9 | 10 | #概述 11 | 本项目提供了一种针对时间序列的异常检测服务,适用于互联网企业海量KPI指标的实时异常检测。 12 | 采用特有的动态阈值生成技术,能够自适应地提取时间序列周期信息,并给出准确的告警阈值,在保证故障召回率的前提下能够有效抑制告警风暴的产生。 13 | 14 | # 文档 15 | * [HoloInsight AI 文档](https://traas-stack.github.io/holoinsight-docs/dev-guide/internals/anomaly-detection-algorithm.html) 16 | 17 | # 构建 18 | ```bash 19 | docker build -t holoinsight-ai:{version} . 20 | ``` 21 | 22 | # 安装 23 | ### Docker 镜像 24 | [holoinsight/ai](https://hub.docker.com/r/holoinsight/ai) 25 | 26 | # 开源许可 27 | Holoinsight AI 基于 [Apache License 2.0](https://github.com/traas-stack/holoinsight/blob/main/LICENSE) 协议。 28 | -------------------------------------------------------------------------------- /test/test_up_cs.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test_up' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 14:33' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from handlers.run_main import run_main 11 | from test.test_data_creator import TestDataCreator 12 | 13 | 14 | def run_4(): 15 | """ 16 | Generates data for a cold-start scenario, 17 | tests the cold_start's ability to detect anomalies. 18 | 19 | :return: 20 | """ 21 | detect_time = 1681711200000 22 | ts = TestDataCreator.create_stable_ts(detect_time, 1 * 1440, 60000, 500, 600) 23 | ts[str(detect_time)] = 1000 24 | body = {"inputTimeSeries": ts, "intervalTime": 60000, 25 | "detectTime": detect_time, 26 | "algorithmConfig": {"algorithmType": "up", "sensitivity": "mid"}, 27 | "ruleConfig": {"defaultDuration": 1, 28 | "customChangeRate": 0.1}} 29 | result = run_main(body) 30 | return result 31 | 32 | 33 | # class TestFunction(unittest.TestCase): 34 | # 35 | # def test(self): 36 | # self.assertEqual(run_4().get("isException"), True) 37 | # pass 38 | 39 | 40 | if __name__ == "__main__": 41 | run_4() 42 | pass 43 | -------------------------------------------------------------------------------- /test/test_down_stable_dd.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test_up' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 14:33' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from handlers.run_main import run_main 11 | from test.test_data_creator import TestDataCreator 12 | 13 | 14 | def run_3(): 15 | """ 16 | Generates stable data for a normal scenario, 17 | tests the data-driven detector's ability to detect anomalies. 18 | 19 | :return: 20 | """ 21 | detect_time = 1681711200000 22 | ts = TestDataCreator.create_stable_ts(end_time=detect_time, ts_length=5 * 1440, period=60000, down=500, up=600) 23 | ts[str(detect_time)] = 0 24 | body = {"inputTimeSeries": ts, "intervalTime": 60000, 25 | "detectTime": detect_time, 26 | "algorithmConfig": {"algorithmType": "down", "sensitivity": "mid"}, 27 | "ruleConfig": {"defaultDuration": 1, 28 | "customChangeRate": 0.1}} 29 | result = run_main(body) 30 | return result 31 | 32 | 33 | class TestFunction(unittest.TestCase): 34 | 35 | def test(self): 36 | self.assertEqual(run_3().get("isException"), True) 37 | pass 38 | 39 | 40 | if __name__ == "__main__": 41 | pass 42 | -------------------------------------------------------------------------------- /test/test_up_periodic_dd.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test_up' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 14:33' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from handlers.run_main import run_main 11 | from test.test_data_creator import TestDataCreator 12 | 13 | 14 | def run_5(): 15 | """ 16 | Generates periodic data for a normal scenario, 17 | tests the data-driven detector's ability to detect anomalies. 18 | 19 | :return: 20 | """ 21 | detect_time = 1681711200000 22 | ts = TestDataCreator.create_periodic_ts(end_time=detect_time, ts_length=5 * 1440, period=60000, median_value=1000) 23 | ts[str(detect_time)] = 1100 24 | body = {"inputTimeSeries": ts, "intervalTime": 60000, 25 | "detectTime": detect_time, 26 | "algorithmConfig": {"algorithmType": "up", "sensitivity": "mid"}, 27 | "ruleConfig": {"defaultDuration": 1, 28 | "customChangeRate": 0.05}} 29 | result = run_main(body) 30 | return result 31 | 32 | 33 | class TestFunction(unittest.TestCase): 34 | 35 | def test(self): 36 | self.assertEqual(run_5().get("isException"), True) 37 | pass 38 | 39 | 40 | if __name__ == "__main__": 41 | pass 42 | -------------------------------------------------------------------------------- /test/test_down_periodic_dd.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test_up' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 14:33' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from handlers.run_main import run_main 11 | from test.test_data_creator import TestDataCreator 12 | 13 | 14 | def run_2(): 15 | """ 16 | Generates periodic data for a normal scenario, 17 | tests the data-driven detector's ability to detect anomalies. 18 | 19 | :return: 20 | """ 21 | detect_time = 1681711200000 22 | ts = TestDataCreator.create_periodic_ts(end_time=detect_time, ts_length=5 * 1440, period=60000, median_value=1000) 23 | ts[str(detect_time)] = 500 24 | body = {"inputTimeSeries": ts, "intervalTime": 60000, 25 | "detectTime": detect_time, 26 | "algorithmConfig": {"algorithmType": "down", "sensitivity": "mid"}, 27 | "ruleConfig": {"defaultDuration": 1, 28 | "customChangeRate": 0.05}} 29 | result = run_main(body) 30 | return result 31 | 32 | 33 | class TestFunction(unittest.TestCase): 34 | 35 | def test(self): 36 | self.assertEqual(run_2().get("isException"), True) 37 | pass 38 | 39 | 40 | if __name__ == "__main__": 41 | pass 42 | -------------------------------------------------------------------------------- /test/test_up_stable_dd.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test_up' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 14:33' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from handlers.run_main import run_main 11 | from test.test_data_creator import TestDataCreator 12 | 13 | 14 | def run_6(): 15 | """ 16 | Generates stable data for a normal scenario, 17 | tests the data-driven detector's ability to detect anomalies. 18 | 19 | :return: 20 | """ 21 | detect_time = 1681711200000 22 | ts = TestDataCreator.create_stable_ts(end_time=detect_time, ts_length=5 * 1440, period=60000, down=500, up=600) 23 | ts[str(detect_time)] = 1000 24 | body = {"inputTimeSeries": ts, "intervalTime": 60000, 25 | "detectTime": detect_time, 26 | "algorithmConfig": {"algorithmType": "up", "sensitivity": "mid"}, 27 | "ruleConfig": {"defaultDuration": 1, 28 | "customChangeRate": 0.1} 29 | } 30 | result = run_main(body) 31 | return result 32 | 33 | 34 | class TestFunction(unittest.TestCase): 35 | 36 | def test(self): 37 | self.assertEqual(run_6().get("isException"), True) 38 | pass 39 | 40 | 41 | if __name__ == "__main__": 42 | pass 43 | -------------------------------------------------------------------------------- /test/test_down_cs_noise.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test_up' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 14:33' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from handlers.run_main import run_main 11 | from test.test_data_creator import TestDataCreator 12 | 13 | 14 | def run_8(): 15 | """ 16 | Generates data for a cold-start scenario, 17 | tests the similarity filter's ability to filter the noise. 18 | 19 | :return: 20 | """ 21 | detect_time = 1681711200000 22 | ts = TestDataCreator.create_stable_ts(detect_time, 1 * 1440, 60000, 500, 600) 23 | # Add anomaly value at the detection time and a value 500 intervals before the detection time 24 | ts[str(detect_time)] = 0 25 | ts[str(detect_time - 500 * 60000)] = 0 26 | body = {"inputTimeSeries": ts, "intervalTime": 60000, 27 | "detectTime": detect_time, 28 | "algorithmConfig": {"algorithmType": "down", "sensitivity": "mid"}, 29 | "ruleConfig": {"defaultDuration": 1, "customChangeRate": 0.1}} 30 | result = run_main(body) 31 | return result 32 | 33 | 34 | class TestFunction(unittest.TestCase): 35 | 36 | def test(self): 37 | self.assertEqual(run_8().get("isException"), False) 38 | pass 39 | 40 | 41 | if __name__ == "__main__": 42 | pass 43 | -------------------------------------------------------------------------------- /test/test_up_cs_noise.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test_up' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 14:33' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from handlers.run_main import run_main 11 | from test.test_data_creator import TestDataCreator 12 | 13 | 14 | def run_9(): 15 | """ 16 | Generates data for a cold-start scenario, 17 | tests the rule filter's ability to filter noise. 18 | 19 | :return: 20 | """ 21 | detect_time = 1681711200000 22 | ts = TestDataCreator.create_stable_ts(detect_time, 1 * 1440, 60000, 500, 600) 23 | ts[str(detect_time)] = 1000 24 | body = {"inputTimeSeries": ts, "intervalTime": 60000, 25 | "detectTime": detect_time, 26 | "algorithmConfig": {"algorithmType": "up", "sensitivity": "mid"}, 27 | "ruleConfig": {"defaultDuration": 1, 28 | # "customUpThreshold": 0, 29 | "customDownThreshold": 1001, # rule filer 30 | "customChangeRate": 0.1}} 31 | result = run_main(body) 32 | # TestDataCreator.plot(ts, detect_time, 60000) 33 | return result 34 | 35 | 36 | class TestFunction(unittest.TestCase): 37 | 38 | def test(self): 39 | self.assertEqual(run_9().get("isException"), False) 40 | pass 41 | 42 | 43 | if __name__ == "__main__": 44 | pass 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Holoinsight AI 2 | ![License](https://img.shields.io/badge/license-Apache--2.0-green.svg) 3 | [![Github stars](https://img.shields.io/github/stars/traas-stack/holoinsight-ai?style=flat-square])](https://github.com/traas-stack/holoinsight-ai) 4 | [![OpenIssue](https://img.shields.io/github/issues/traas-stack/holoinsight-ai)](https://github.com/traas-stack/holoinsight-ai/issues) 5 | 6 | [中文](./README-CN.md) 7 | 8 | Holoinsight AI provides real-time anomaly detection capabilities for time series data for [Holoinsight](https://github.com/traas-stack/holoinsight). 9 | 10 | # Overview 11 | The service utilizes a proprietary dynamic threshold generation model for anomaly detection, which is suitable for real-time anomaly detection of massive KPI data in Internet enterprises. 12 | The algorithm can adaptively extract time series cycle information and provide appropriate anomaly detection thresholds, effectively suppressing the occurrence of alarm storms while ensuring alarm recall. 13 | 14 | # Documentation 15 | * [HoloInsight AI Documentation](https://traas-stack.github.io/holoinsight-docs/dev-guide/internals/anomaly-detection-algorithm.html) 16 | 17 | # Build 18 | ```bash 19 | docker build -t holoinsight-ai:{version} . 20 | ``` 21 | 22 | # Install 23 | ### Docker Image 24 | See [holoinsight/ai](https://hub.docker.com/r/holoinsight/ai) 25 | 26 | # Licensing 27 | Holoinsight AI is under [Apache License 2.0](https://github.com/traas-stack/holoinsight-ai/blob/main/LICENSE). -------------------------------------------------------------------------------- /algorithm/module.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'abnormal_detect' 4 | __author__ = 'LuYuan' 5 | __time__ = '2021-08-09 11:52' 6 | __product_name = PyCharm 7 | __info__: algo module 8 | """ 9 | from abc import ABC 10 | 11 | from common.classes import Response4AD, Request4AD, StatusInOut 12 | from common.logger import Logger 13 | 14 | 15 | class BaseModule(ABC): 16 | def __init__(self, req: Request4AD): 17 | """ 18 | Initializes the BaseModule object with a given request object, response object, logger object, and run success flag. 19 | 20 | :param req: The initial request object for the module 21 | """ 22 | self.run_success = True 23 | self.req = req 24 | self.resp = Response4AD() 25 | self.logger = Logger.get_logger() 26 | 27 | @staticmethod 28 | def pipeline(): 29 | """The core processing pipeline for the module""" 30 | 31 | @staticmethod 32 | def filter(status: StatusInOut) -> StatusInOut: 33 | """Noise filter""" 34 | 35 | @staticmethod 36 | def detector(status: StatusInOut) -> StatusInOut: 37 | """Abnormal detector""" 38 | 39 | @staticmethod 40 | def msg_builder(status: StatusInOut) -> StatusInOut: 41 | """Alarm information builder""" 42 | 43 | @staticmethod 44 | def to_resp(status: StatusInOut) -> StatusInOut: 45 | """Output the result""" 46 | 47 | 48 | if __name__ == "__main__": 49 | pass 50 | -------------------------------------------------------------------------------- /test/test_down_cs.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test_up' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 14:33' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from handlers.run_main import run_main 11 | from test.test_data_creator import TestDataCreator 12 | 13 | 14 | def run_1(): 15 | """ 16 | Generates data for a cold-start scenario, 17 | tests the cold_start's ability to detect anomalies. 18 | 19 | :return: 20 | """ 21 | # Set the detection time 22 | detect_time = 1681711200000 23 | # Create a stable time series with specified parameters 24 | ts = TestDataCreator.create_stable_ts(detect_time, 1 * 1440, 60000, 500, 600) 25 | # Add anomaly value at the detection time 26 | ts[str(detect_time)] = 0 27 | # Create the request body with input time series, detection time, and algorithm and rule configurations 28 | body = {"inputTimeSeries": ts, "intervalTime": 60000, 29 | "detectTime": detect_time, 30 | "algorithmConfig": {"algorithmType": "down", "sensitivity": "mid"}, 31 | "ruleConfig": {"defaultDuration": 1, "customChangeRate": 0.1}} 32 | # Run the main function with the request body and return the result 33 | result = run_main(body) 34 | return result 35 | 36 | 37 | class TestFunction(unittest.TestCase): 38 | 39 | def test(self): 40 | self.assertEqual(run_1().get("isException"), True) 41 | pass 42 | 43 | 44 | if __name__ == "__main__": 45 | pass 46 | -------------------------------------------------------------------------------- /algorithm/pipeline.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'pipeline' 4 | __author__ = 'LuYuan' 5 | __time__ = '2022/11/7 17:44' 6 | __info__ = pipeLine 7 | """ 8 | import collections 9 | 10 | from common.classes import StatusInOut 11 | 12 | 13 | class DetectPipeLine: 14 | def __init__(self, status: StatusInOut): 15 | """ 16 | Initializes the DetectPipeLine object with a given status. 17 | 18 | :param status: The initial status for the pipeline 19 | """ 20 | self.q = None 21 | self.status = status 22 | 23 | def start(self, func): 24 | """ 25 | Initializes the pipeline queue with the given function. 26 | 27 | :param func: The function to be added to the queue 28 | :return: None 29 | """ 30 | self.q = collections.deque() 31 | self.q.append(func) 32 | 33 | def add(self, func): 34 | """ 35 | Adds a function to the end of the pipeline queue. 36 | 37 | :param func: The function to be added to the queue 38 | :return: None 39 | """ 40 | self.q.append(func) 41 | 42 | def handler(self): 43 | """ 44 | Iterates through the pipeline queue, passing the status object to each function and updating the status object. 45 | 46 | :return: None 47 | """ 48 | while self.q: 49 | self.status = self.q[0](self.status) 50 | self.q.popleft() 51 | 52 | 53 | if __name__ == "__main__": 54 | pass 55 | -------------------------------------------------------------------------------- /handlers/run_main.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'run_detector' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/2/1 16:25' 6 | __info__ = 7 | """ 8 | from common.classes import Request4AD 9 | from common.request_builder import RequestBuilder 10 | from handlers.detect_handlers import ColdStartDetectHandler, DynamicThresholdDetectHandler 11 | 12 | 13 | def run_main(body): 14 | """ 15 | Runs the detection pipeline on the input request body. 16 | 17 | :param body: A dictionary containing data to be processed 18 | :return: A string message containing the results of the detection pipeline 19 | """ 20 | # Builds a request object from the input body 21 | req = RequestBuilder(body).build_req() 22 | # Maps the request to the appropriate handler based on the data by day 23 | target_handler = handler_mapper(req=req) 24 | # Runs the detection pipeline using the target handler 25 | resp = target_handler(req).run() 26 | # Returns the result message from the response 27 | return resp.get_msg() 28 | 29 | 30 | def handler_mapper(req: Request4AD): 31 | """ 32 | Maps the request to the appropriate handler based on the data by day 33 | """ 34 | if len(req.data_by_day) == 1: 35 | # Use ColdStartDetectHandler for single-day data 36 | return ColdStartDetectHandler 37 | elif len(req.data_by_day) > 1: 38 | # Use DynamicThresholdDetectHandler for multi-day data 39 | return DynamicThresholdDetectHandler 40 | 41 | 42 | if __name__ == "__main__": 43 | pass 44 | -------------------------------------------------------------------------------- /test/test_up_stable_dd_noise.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test_up' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 14:33' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from handlers.run_main import run_main 11 | from test.test_data_creator import TestDataCreator 12 | 13 | 14 | def run_7(): 15 | """ 16 | Generates stable data for a normal scenario, 17 | tests the data-driven detector's ability to filter the noise. 18 | 19 | :return: 20 | """ 21 | detect_time = 1681711200000 22 | ts = TestDataCreator.create_stable_ts(end_time=detect_time, ts_length=5 * 1440, period=60000, down=500, up=600) 23 | # Add values at specific times to create a periodic noise 24 | ts[str(detect_time)] = 1000 25 | ts[str(detect_time - 1440 * 60000)] = 1000 26 | ts[str(detect_time - 2 * 1440 * 60000)] = 1000 27 | ts[str(detect_time - 3 * 1440 * 60000)] = 1000 28 | ts[str(detect_time - 4 * 1440 * 60000)] = 1000 29 | body = {"inputTimeSeries": ts, "intervalTime": 60000, 30 | "detectTime": detect_time, 31 | "algorithmConfig": {"algorithmType": "up", "sensitivity": "mid"}, 32 | "ruleConfig": {"defaultDuration": 1, 33 | "customChangeRate": 0.1} 34 | } 35 | result = run_main(body) 36 | return result 37 | 38 | 39 | class TestFunction(unittest.TestCase): 40 | 41 | def test(self): 42 | self.assertEqual(run_7().get("isException"), False) 43 | pass 44 | 45 | 46 | if __name__ == "__main__": 47 | pass 48 | -------------------------------------------------------------------------------- /algorithm/cold_start/similarity_filter.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'outlier_detector' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/13 15:43' 6 | __info__ = 7 | """ 8 | from typing import List 9 | 10 | from common.constants import Constants 11 | from common.utils import Utils 12 | 13 | RATE = 2 14 | 15 | 16 | class SimilarityFilter: 17 | def __init__(self, detect_data: List[float], algorithm_type: str, anomaly_duration: int): 18 | self.algorithm_type = algorithm_type 19 | self.detect_data = self.minus_data(detect_data) 20 | self.anomaly_duration = anomaly_duration 21 | 22 | def run(self): 23 | """ 24 | Check if the current data is similar to the historical data. 25 | 26 | :return: True if the current data is similar to the historical data. 27 | """ 28 | agg_list = Utils.agg_diff_fe_calc(self.detect_data, self.anomaly_duration) 29 | if agg_list[-1] < RATE * min(agg_list[:-self.anomaly_duration]): 30 | return False 31 | return True 32 | 33 | def minus_data(self, input_data: List[float]) -> List[float]: 34 | """ 35 | If the algorithm is "up", invert the input data. 36 | 37 | :param input_data: List of input data. 38 | :return: List of input data with inverted values if the algorithm is "up". 39 | """ 40 | if self.algorithm_type == Constants.ALGORITHM_TYPE_UP.value: 41 | return [-value for value in input_data] 42 | return input_data 43 | 44 | 45 | if __name__ == "__main__": 46 | pass 47 | -------------------------------------------------------------------------------- /test/assert_test_cases.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'test' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/18 11:56' 6 | __info__ = 7 | """ 8 | import unittest 9 | 10 | from test.test_down_cs import run_1 11 | from test.test_down_cs_noise import run_8 12 | from test.test_down_periodic_dd import run_2 13 | from test.test_down_stable_dd import run_3 14 | from test.test_up_cs import run_4 15 | from test.test_up_cs_noise import run_9 16 | from test.test_up_periodic_dd import run_5 17 | from test.test_up_stable_dd import run_6 18 | from test.test_up_stable_dd_noise import run_7 19 | 20 | 21 | class TestFunction(unittest.TestCase): 22 | """ 23 | All test cases. 24 | """ 25 | 26 | def test1(self): 27 | self.assertEqual(run_1().get("isException"), True) 28 | pass 29 | 30 | def test2(self): 31 | self.assertEqual(run_2().get("isException"), True) 32 | pass 33 | 34 | def test3(self): 35 | self.assertEqual(run_3().get("isException"), True) 36 | pass 37 | 38 | def test4(self): 39 | self.assertEqual(run_4().get("isException"), True) 40 | pass 41 | 42 | def test5(self): 43 | self.assertEqual(run_5().get("isException"), True) 44 | pass 45 | 46 | def test6(self): 47 | self.assertEqual(run_6().get("isException"), True) 48 | pass 49 | 50 | def test7(self): 51 | self.assertEqual(run_7().get("isException"), False) 52 | pass 53 | 54 | def test8(self): 55 | self.assertEqual(run_8().get("isException"), False) 56 | pass 57 | 58 | def test9(self): 59 | self.assertEqual(run_9().get("isException"), False) 60 | pass 61 | 62 | 63 | if __name__ == "__main__": 64 | pass 65 | -------------------------------------------------------------------------------- /handlers/detect_handlers.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project_ = 'holoinsight-ai' 3 | __file_name__ = 'handler base' 4 | __author__ = 'LuYuan' 5 | __time__ = '2021-08-09 14:02' 6 | __product_name = PyCharm 7 | __info__: handler 8 | """ 9 | from abc import ABC 10 | 11 | from algorithm.cs_module import ColdStartModule 12 | from algorithm.dt_module import DynamicThresholdModule 13 | from common.classes import Request4AD, Response4AD 14 | 15 | 16 | class BaseHandler(ABC): 17 | def __init__(self, req: Request4AD): 18 | """ 19 | Initializes the BaseHandler with a request object and sets the run_success attribute to True. 20 | 21 | :param req: A Request4AD object containing data to be processed. 22 | """ 23 | self.req = req 24 | self.run_success = True 25 | 26 | @staticmethod 27 | def run(self): 28 | """ 29 | Runs the detection pipeline. 30 | This method is abstract and must be implemented by child classes. 31 | """ 32 | 33 | 34 | class ColdStartDetectHandler(BaseHandler): 35 | """ 36 | Handles detection of a single dimension value increase. 37 | """ 38 | def run(self) -> Response4AD: 39 | """ 40 | Runs the ColdStartModule pipeline and returns the result. 41 | 42 | :return: A Response4AD object containing the result of the pipeline. 43 | """ 44 | cs = ColdStartModule(self.req) 45 | cs.pipeline() 46 | return cs.resp 47 | 48 | 49 | class DynamicThresholdDetectHandler(BaseHandler): 50 | """ 51 | Handles detection of a single dimension value decrease. 52 | """ 53 | def run(self) -> Response4AD: 54 | """ 55 | Runs the DataDrivenModule pipeline and returns the result. 56 | 57 | :return: A Response4AD object containing the result of the pipeline. 58 | """ 59 | dd = DynamicThresholdModule(self.req) 60 | dd.pipeline() 61 | return dd.resp 62 | 63 | 64 | if __name__ == "__main__": 65 | pass 66 | -------------------------------------------------------------------------------- /algorithm/dyn_thresh/rule_checker.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'rule_filter' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/14 10:14' 6 | __info__ = 7 | """ 8 | import numpy as np 9 | 10 | from typing import List 11 | from common.classes import Request4AD 12 | from common.constants import Constants 13 | 14 | 15 | class RuleChecker: 16 | def __init__(self, detect_data: List[float], req: Request4AD): 17 | self.req = req 18 | self.detect_data = detect_data 19 | self.up = self.req.rule_info.up_threshold 20 | self.down = self.req.rule_info.down_threshold 21 | self.algorithm_type = self.req.detect_info.algorithm_type 22 | 23 | def detector(self): 24 | """ 25 | Excessive alarm detection 26 | 27 | :return: Boolean indicating if the data exceeds the threshold 28 | """ 29 | if self.algorithm_type == Constants.ALGORITHM_TYPE_UP.value: 30 | if self.detect_data[-1] > self.up: 31 | return True 32 | elif self.algorithm_type == Constants.ALGORITHM_TYPE_DOWN.value: 33 | if self.detect_data[-1] < self.down: 34 | return True 35 | return False 36 | 37 | def filter(self): 38 | """ 39 | Rule filtering 40 | 41 | :return: Boolean indicating if the data violates the rules 42 | """ 43 | if self.algorithm_type == Constants.ALGORITHM_TYPE_UP.value and self.detect_data[-1] < self.down: 44 | return True 45 | elif self.algorithm_type == Constants.ALGORITHM_TYPE_DOWN.value and self.detect_data[-1] > self.up: 46 | return True 47 | 48 | custom_change_rate = self.req.rule_info.change_rate 49 | train_data = {k: v for k, v in self.req.data_by_day.items() if k != "0"} 50 | compare_values = [] 51 | for k, v in train_data.items(): 52 | compare_values.append(v[-1]) 53 | baseline = np.max(compare_values) 54 | if baseline == 0: 55 | return True 56 | if self.algorithm_type == "down": 57 | if custom_change_rate > -(self.detect_data[-1] - baseline) / baseline: 58 | return True 59 | else: 60 | if custom_change_rate > (self.detect_data[-1] - baseline) / baseline: 61 | return True 62 | return False 63 | 64 | 65 | if __name__ == "__main__": 66 | pass 67 | -------------------------------------------------------------------------------- /test/test_data_creator.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | __project__ = 'holoinsight-ai' 5 | __file_name__ = 'data_process' 6 | __author__ = 'LuYuan' 7 | __time__ = '2023/4/12 10:50' 8 | __info__ = 9 | """ 10 | import random 11 | import numpy as np 12 | import matplotlib.pyplot as plt 13 | 14 | from typing import Dict 15 | 16 | from common.utils import Utils 17 | 18 | 19 | class TestDataCreator: 20 | 21 | @staticmethod 22 | def create_stable_ts(end_time: int, ts_length: int, period: int, down: int, up: int) -> Dict[str, float]: 23 | """ 24 | 25 | :param up: 26 | :param down: 27 | :param end_time: 28 | :param ts_length: 29 | :param period: 粒度,此处默认为60000 30 | :return: 31 | """ 32 | ts = {} 33 | start_time = end_time - ts_length * period 34 | random.seed(0) 35 | for i in range(start_time, end_time + period, period): # 确保能够取到detect time 36 | ts[str(i)] = random.randint(down, up) 37 | return ts 38 | 39 | @staticmethod 40 | def create_periodic_ts(end_time: int, ts_length: int, period: int, median_value: int) -> Dict[str, float]: 41 | """ 42 | 43 | :param median_value: 44 | :param end_time: 45 | :param ts_length: 46 | :param period: 粒度,此处默认为60000 47 | :return: 48 | """ 49 | days = int(np.ceil(ts_length / 1440)) 50 | start_time = end_time - ts_length * period 51 | all_ts = [] 52 | for i in range(days): 53 | time_points = [i * (2 * np.pi / 1440) for i in range(1440)] 54 | all_ts += [median_value + -int(100 * np.sin(t) + int(100 * random.uniform(-0.1, 0.1))) for t in time_points] 55 | time_stamps = list(range(start_time + period, end_time + period, period)) 56 | ts = {} 57 | for i, v in enumerate(time_stamps): 58 | ts[str(v)] = all_ts[i] 59 | return ts 60 | 61 | @staticmethod 62 | def plot(ts, detect_time, period): 63 | start = min([int(key) for key in ts.keys()]) 64 | ts = Utils().time_series_min_str(ts, start, detect_time + 60000, period) 65 | plt.plot(ts) 66 | plt.show() 67 | 68 | 69 | if __name__ == "__main__": 70 | ts = TestDataCreator.create_periodic_ts(1681711200000, 3 * 1440 + 1, 60000, 1000) 71 | TestDataCreator.plot(ts, 1681711200000, 60000) 72 | pass 73 | -------------------------------------------------------------------------------- /algorithm/dyn_thresh/dyn_thresh_algo/features.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'features' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/16 20:52' 6 | __info__ = 7 | """ 8 | from typing import Dict, List 9 | 10 | import numpy as np 11 | 12 | from common.utils import Utils 13 | from common.constants import Constants 14 | 15 | 16 | class Features: 17 | def __init__(self, data_by_day: Dict[str, List[float]], algorithm_type: str): 18 | self.data_by_day = data_by_day 19 | self.smoothness = True # A flag indicating whether the waveform is smooth or not 20 | self.algorithm_type = algorithm_type 21 | 22 | def run(self): 23 | self.smoothness = self.waveform_smoothness_checker() 24 | if self.smoothness: 25 | features = self.one_diff() 26 | else: 27 | features = self.zero_diff() 28 | return features 29 | 30 | def one_diff(self): 31 | features_by_duration = {} 32 | for duration in Constants.WINDOW_LIST.value: 33 | features_by_duration[str(duration)] = self.do_cutoff(data_by_day=self.data_by_day, duration=duration) 34 | return features_by_duration 35 | 36 | def zero_diff(self): 37 | return self.data_by_day # If the waveform is not smooth, return the raw data 38 | 39 | def do_cutoff(self, data_by_day: Dict[str, List[float]], duration: int) -> Dict[str, List[float]]: 40 | """ 41 | Use a layering algorithm to determine whether the data should be sliced. 42 | 43 | @param duration: The length of the fixed window to use for slicing. 44 | @param data_by_day: The data to be analyzed, grouped by day. 45 | @return: A dictionary of features, grouped by day. 46 | """ 47 | features = {} 48 | is_down = True if self.algorithm_type == "down" else False 49 | for k, v in data_by_day.items(): 50 | features[k] = Utils.diff_percentile_func(v, duration, is_down) 51 | return features 52 | 53 | def waveform_smoothness_checker(self): 54 | """ 55 | Evaluate the smoothness of a time series. 56 | 57 | @return: A flag indicating whether the waveform is smooth or not. 58 | """ 59 | diff_values = [] 60 | for k, v in self.data_by_day.items(): 61 | diff_values += Utils.diff_percentile_func(v, 1) 62 | diff_values = [abs(value) for value in diff_values] 63 | if np.percentile(diff_values, 60) < 10: # todo test 为小流量最好准备! 64 | return True 65 | else: 66 | return False 67 | 68 | 69 | if __name__ == "__main__": 70 | pass 71 | -------------------------------------------------------------------------------- /algorithm/dyn_thresh/dyn_thresh_detector.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'anomaly_detector' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/17 13:35' 6 | __info__ = 7 | """ 8 | from typing import List, Dict 9 | 10 | from algorithm.dyn_thresh.dyn_thresh_algo.features import Features 11 | from algorithm.dyn_thresh.dyn_thresh_algo.threshold import ThresholdCalc 12 | from common.constants import Constants 13 | from common.utils import Utils 14 | 15 | 16 | class DynamicThresholdDetector: 17 | def __init__(self, detect_data: List[float], train_data: Dict[str, List[float]], algorithm_type: str): 18 | self.algorithm_type = algorithm_type 19 | self.detect_data = detect_data 20 | self.train_data = train_data 21 | self.minus_data() 22 | self.smoothness = True 23 | self.alarm_info = "" 24 | 25 | def run(self): 26 | """ 27 | Detect an anomaly using the dynamic threshold algo. 28 | 29 | :return: True if an anomaly is detected. 30 | """ 31 | fe = Features(self.train_data, self.algorithm_type) 32 | features = fe.run() 33 | self.smoothness = fe.smoothness 34 | is_down = True if self.algorithm_type == "down" else False 35 | if self.smoothness: 36 | for k, v in features.items(): 37 | cur_fe = Utils.diff_percentile_func(self.detect_data, int(k), is_down)[-1] 38 | target_th = ThresholdCalc(v).run() 39 | if cur_fe < target_th: 40 | self.alarm_info = f"The current feature {round(abs(cur_fe),2)} " \ 41 | f"exceeds the alert baseline {round(abs(target_th),2)}" 42 | return True 43 | else: 44 | target_th = ThresholdCalc(features).run() 45 | if self.detect_data[-1] < target_th: 46 | self.alarm_info = f"The current value {round(abs(self.detect_data[-1]),2)} " \ 47 | f"exceeds the alert baseline {round(abs(target_th),2)}" 48 | return True 49 | return False 50 | 51 | def minus_data(self): 52 | """ 53 | Invert the input data if the algorithm is "up". 54 | 55 | :return: None 56 | """ 57 | if self.algorithm_type == Constants.ALGORITHM_TYPE_UP.value: 58 | self.detect_data = [-value for value in self.detect_data] 59 | new_train_data = {} 60 | for k, v in self.train_data.items(): 61 | new_train_data[k] = [-value for value in v] 62 | self.train_data = new_train_data 63 | 64 | 65 | if __name__ == "__main__": 66 | pass 67 | -------------------------------------------------------------------------------- /common/classes.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'base' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/12 20:45' 6 | __info__ = 7 | """ 8 | from dataclasses import dataclass, field 9 | from typing import List 10 | 11 | 12 | @dataclass 13 | class DetectInfo: 14 | """ 15 | Information about the sensitive data and algorithm type used for anomaly detection. 16 | """ 17 | sensitive: str 18 | algorithm_type: str # "up"/"down" 19 | 20 | 21 | @dataclass 22 | class RuleInfo: 23 | """ 24 | Information about the anomaly detection rules, including minimum duration, thresholds, and change rate. 25 | """ 26 | min_duration: int 27 | up_threshold: float 28 | down_threshold: float 29 | change_rate: float 30 | 31 | 32 | @dataclass 33 | class ErrorInfo: 34 | """ 35 | Information about any errors encountered during the anomaly detection process. 36 | """ 37 | errorOrNot: bool = False 38 | msg: str = '' 39 | 40 | 41 | @dataclass 42 | class Request4AD: 43 | """ 44 | Request information for time series anomaly detection, including trace ID, data by day, detection info, 45 | and rule info. 46 | """ 47 | trace_id: str 48 | data_by_day: dict 49 | detect_info: DetectInfo 50 | rule_info: RuleInfo 51 | 52 | 53 | @dataclass 54 | class StatusInOut: 55 | """ 56 | Pipeline status information for anomaly detection. 57 | """ 58 | alarmOrNot: bool = False # True indicates current alarm, default is False 59 | needNext: bool = False # True indicates no need for next step, default is False 60 | duration: int = 0 # Default is 0 61 | passReason: str = '' # Default is '' 62 | alarmReason: str = '' # Default is '' 63 | 64 | 65 | @dataclass 66 | class Response4AD: 67 | """ 68 | Results of time series anomaly detection, including whether an anomaly was detected, success status, duration, 69 | and various metrics. 70 | """ 71 | isException: bool = False 72 | success: bool = True # Whether the detection ran successfully 73 | duration: int = 0 74 | alarmCategory: str = "" 75 | filterReason: str = "" 76 | alarmMsg: str = "" 77 | currentValue: float = 0.0 78 | changeRate: float = 0.0 # # Not percentage format 79 | extremeValue: float = 0.0 80 | baseLineValue: float = 0.0 81 | anomalyData: List[float] = field(default_factory=lambda: []) 82 | 83 | def get_msg(self): 84 | """ 85 | Returns a dictionary containing the isException and success attributes of the Response4AD object. 86 | """ 87 | return {"isException": self.isException, "isSuccessful": self.success, "alarmMsg": self.alarmMsg} 88 | 89 | 90 | if __name__ == "__main__": 91 | pass 92 | -------------------------------------------------------------------------------- /algorithm/cold_start/rule_checker.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'rule_filter' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/14 10:14' 6 | __info__ = 7 | """ 8 | import numpy as np 9 | 10 | from typing import List 11 | from common.classes import Request4AD 12 | from common.constants import Constants 13 | 14 | 15 | class RuleChecker: 16 | def __init__(self, detect_data: List[float], req: Request4AD): 17 | self.req = req 18 | self.detect_data = detect_data 19 | self.up = self.req.rule_info.up_threshold 20 | self.down = self.req.rule_info.down_threshold 21 | self.algorithm_type = self.req.detect_info.algorithm_type 22 | ## 23 | self.alarm_info = '' 24 | 25 | def detector(self): 26 | """ 27 | Excessive alarm detection 28 | 29 | :return: Boolean indicating if the data exceeds the threshold 30 | """ 31 | if self.algorithm_type == Constants.ALGORITHM_TYPE_UP.value: 32 | if self.detect_data[-1] > self.up: 33 | self.alarm_info = f"The current value {round(abs(self.detect_data[-1]), 2)} " \ 34 | f"exceeds the alert baseline {round(abs(self.up), 2)}" 35 | return True 36 | elif self.algorithm_type == Constants.ALGORITHM_TYPE_DOWN.value: 37 | if self.detect_data[-1] < self.down: 38 | self.alarm_info = f"The current value {round(abs(self.detect_data[-1]), 2)} " \ 39 | f"exceeds the alert baseline {round(abs(self.down), 2)}" 40 | return True 41 | return False 42 | 43 | def filter(self, duration): 44 | """ 45 | Rule filtering 46 | 47 | :return: Boolean indicating if the data violates the rules 48 | """ 49 | custom_change_rate = self.req.rule_info.change_rate 50 | post = self.detect_data[-duration:] 51 | pre = self.detect_data[-2 * duration: - duration] 52 | if self.algorithm_type == "down": 53 | real_change_rate = 1.0 if max(pre) == 0 else -(min(post) - max(pre)) / max(pre) 54 | else: 55 | real_change_rate = 1.0 if np.percentile(pre, 90) == 0 else (max(post) - np.percentile(pre, 90)) \ 56 | / np.percentile(pre, 90) 57 | if custom_change_rate > real_change_rate: 58 | return True 59 | if self.algorithm_type == Constants.ALGORITHM_TYPE_UP.value and self.detect_data[-1] < self.down: 60 | return True 61 | elif self.algorithm_type == Constants.ALGORITHM_TYPE_DOWN.value and self.detect_data[-1] > self.up: 62 | return True 63 | return False 64 | 65 | 66 | if __name__ == "__main__": 67 | pass 68 | -------------------------------------------------------------------------------- /algorithm/dt_module.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'outlier_detector' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/13 15:43' 6 | __info__ = 7 | """ 8 | from algorithm.module import BaseModule 9 | from algorithm.pipeline import DetectPipeLine 10 | from algorithm.dyn_thresh.dyn_thresh_detector import DynamicThresholdDetector 11 | from algorithm.dyn_thresh.rule_checker import RuleChecker 12 | from common.classes import StatusInOut 13 | 14 | 15 | class DynamicThresholdModule(BaseModule): 16 | 17 | def pipeline(self): 18 | """ 19 | The core processing pipeline for the DynamicThresholdModule 20 | 21 | @return: 22 | """ 23 | status = StatusInOut() 24 | try: 25 | dpp = DetectPipeLine(status) 26 | dpp.start(self.detector) 27 | dpp.add(self.filter) 28 | dpp.add(self.msg_builder) 29 | dpp.add(self.to_resp) 30 | dpp.handler() 31 | except Exception as e: 32 | self.run_success = False 33 | self.logger.info(f"traceId: {self.req.trace_id}, runSuccess: {self.run_success}, errorInfo: {e}") 34 | finally: 35 | self.logger.info(f"traceId: {self.req.trace_id}, runSuccess: {self.run_success}") 36 | 37 | def detector(self, status: StatusInOut) -> StatusInOut: 38 | """ 39 | Detects anomalies in the input data and sets the alarmOrNot flag in the status object 40 | 41 | :param status: The current status object 42 | :return: The updated status object 43 | """ 44 | detect_data = self.req.data_by_day.get("0") 45 | train_data = {k: v for k, v in self.req.data_by_day.items() if k != "0"} 46 | rule_result = RuleChecker(detect_data, self.req).detector() 47 | if rule_result: 48 | status.alarmOrNot = rule_result 49 | return status 50 | dtd = DynamicThresholdDetector(detect_data, train_data, self.req.detect_info.algorithm_type) 51 | dt = dtd.run() 52 | if dt: 53 | status.alarmOrNot = dt 54 | status.needNext = True 55 | status.alarmReason = dtd.alarm_info 56 | return status 57 | 58 | def filter(self, status: StatusInOut) -> StatusInOut: 59 | """ 60 | Filters out false positives in the input data 61 | 62 | :param status: The current status object 63 | :return: The updated status object 64 | """ 65 | if status.needNext is False: 66 | return status 67 | 68 | detect_data = self.req.data_by_day.get("0") 69 | rre = RuleChecker(detect_data, self.req).filter() 70 | if rre: 71 | status.alarmOrNot = False 72 | status.needNext = False 73 | return status 74 | 75 | def msg_builder(self, status: StatusInOut) -> StatusInOut: 76 | """ 77 | Builds the alarm message for the input data 78 | 79 | :param status: The current status object 80 | :return: The updated status object 81 | """ 82 | return status 83 | 84 | def to_resp(self, status): 85 | """ 86 | Returns the final response object based on the input data and the status object 87 | 88 | :param status: The current status object 89 | :return: The updated status object 90 | """ 91 | if status.alarmOrNot: 92 | self.resp.isException = True 93 | self.resp.alarmMsg = status.alarmReason 94 | return status 95 | 96 | 97 | if __name__ == "__main__": 98 | pass 99 | -------------------------------------------------------------------------------- /algorithm/cold_start/diff_outlier_detector.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'outlier_detector' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/13 15:43' 6 | __info__ = 7 | """ 8 | import numpy as np 9 | 10 | from typing import List 11 | 12 | from common.constants import Constants 13 | from common.utils import Utils 14 | 15 | 16 | class DiffOutlierDetector: 17 | def __init__(self, detect_data: List[float], algorithm_type: str): 18 | self.algorithm_type = algorithm_type 19 | self.detect_data = self.minus_data(detect_data) 20 | self.default_point = 4 21 | self.alarm_last_time = 15 22 | self.tk_delta = 2.0 23 | self.default_duration = 1 24 | # output 25 | self.real_duration = 0 26 | self.alarm_info = '' 27 | 28 | def run(self): 29 | """ 30 | Detect an anomaly using the previous difference. 31 | 32 | :return: True if an anomaly is detected. 33 | """ 34 | potential_indexes, down_threshold = self.prev_diff_outlier(self.detect_data) 35 | if len(potential_indexes) == 0 or potential_indexes is None: 36 | return False 37 | for cur_index in potential_indexes: 38 | self.real_duration = len(self.detect_data) - cur_index 39 | pre = self.detect_data[cur_index - self.real_duration: cur_index] 40 | post = self.detect_data[-self.real_duration:] 41 | real_threshold = max(np.median(pre) + down_threshold, self.detect_data[-self.real_duration - 1]) 42 | if max(post) < real_threshold: 43 | if self.real_duration >= self.default_duration: 44 | self.alarm_info = f"The current value {round(abs(post[-1]),2)} " \ 45 | f"exceeds the alert baseline {round(abs(real_threshold),2)}" 46 | return True 47 | return False 48 | 49 | def prev_diff_outlier(self, detect_data: List[float]): 50 | """ 51 | Calculate the potential indexes of anomalies and the down threshold for the previous difference. 52 | 53 | :param detect_data: List of data to detect anomalies from. 54 | :return: A tuple of the potential indexes of anomalies and the down threshold for the previous difference. 55 | """ 56 | detect_data_diff = Utils().diff_feature_calc(detect_data, self.default_point) 57 | down_threshold = Utils.turkey_box_plot(detect_data_diff, self.tk_delta)[3] 58 | cp_indexes = [] 59 | for index, value in enumerate(detect_data_diff): 60 | if value < down_threshold: 61 | cp_indexes.append(index) 62 | cp_indexes = [c_i for c_i in cp_indexes if c_i > len(detect_data) - self.alarm_last_time] 63 | return cp_indexes, down_threshold 64 | 65 | def minus_data(self, input_data: List[float]) -> List[float]: 66 | """ 67 | Invert the input data if the algorithm is "up". 68 | 69 | :param input_data: List of input data. 70 | :return: List of input data with inverted values if the algorithm is "up". 71 | """ 72 | if self.algorithm_type == Constants.ALGORITHM_TYPE_UP.value: 73 | return [-value for value in input_data] 74 | return input_data 75 | 76 | def set_default_duration(self, input_duration): 77 | """ 78 | Set the default duration for an anomaly. 79 | 80 | :param input_duration: The duration to set as default. 81 | """ 82 | self.default_duration = input_duration 83 | 84 | 85 | if __name__ == "__main__": 86 | pass 87 | -------------------------------------------------------------------------------- /algorithm/cs_module.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'cold_start_algo' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/13 10:19' 6 | __info__ = 7 | """ 8 | from algorithm.module import BaseModule 9 | from algorithm.cold_start.diff_outlier_detector import DiffOutlierDetector 10 | from algorithm.cold_start.rule_checker import RuleChecker 11 | from algorithm.cold_start.similarity_filter import SimilarityFilter 12 | from algorithm.pipeline import DetectPipeLine 13 | from common.classes import StatusInOut 14 | 15 | 16 | class ColdStartModule(BaseModule): 17 | 18 | def pipeline(self): 19 | """ 20 | The core processing pipeline for the ColdStartModule 21 | 22 | @return: 23 | """ 24 | status = StatusInOut() 25 | try: 26 | dpp = DetectPipeLine(status) 27 | dpp.start(self.detector) 28 | dpp.add(self.filter) 29 | dpp.add(self.msg_builder) 30 | dpp.add(self.to_resp) 31 | dpp.handler() 32 | except Exception as e: 33 | self.run_success = False 34 | self.logger.info(f"traceId: {self.req.trace_id}, runSuccess: {self.run_success}, errorInfo: {e}") 35 | finally: 36 | self.logger.info(f"traceId: {self.req.trace_id}, runSuccess: {self.run_success}") 37 | 38 | def detector(self, status: StatusInOut) -> StatusInOut: 39 | """ 40 | Detects anomalies in the input data and sets the alarmOrNot flag in the status object 41 | 42 | :param status: The current status object 43 | :return: The updated status object 44 | """ 45 | detect_data = self.req.data_by_day.get("0") 46 | rc = RuleChecker(detect_data, self.req) 47 | rule_result = rc.detector() 48 | if rule_result: 49 | status.alarmOrNot = rule_result 50 | status.alarmReason = rc.alarm_info 51 | return status 52 | p_d_a_d = DiffOutlierDetector(detect_data, self.req.detect_info.algorithm_type) 53 | re = p_d_a_d.run() 54 | if re: 55 | status.alarmOrNot = re 56 | status.needNext = True 57 | status.alarmReason = p_d_a_d.alarm_info 58 | status.duration = p_d_a_d.real_duration 59 | return status 60 | 61 | def filter(self, status: StatusInOut) -> StatusInOut: 62 | """ 63 | Filters out false positives in the input data 64 | 65 | :param status: The current status object 66 | :return: The updated status object 67 | """ 68 | if status.needNext is False: 69 | return status 70 | 71 | detect_data = self.req.data_by_day.get("0") 72 | sre = SimilarityFilter(detect_data, self.req.detect_info.algorithm_type, status.duration).run() 73 | rre = RuleChecker(detect_data, self.req).filter(status.duration) 74 | if sre or rre: 75 | status.alarmOrNot = False 76 | status.needNext = False 77 | return status 78 | 79 | def msg_builder(self, status: StatusInOut) -> StatusInOut: 80 | """ 81 | Builds the alarm message for the input data 82 | 83 | :param status: The current status object 84 | :return: The updated status object 85 | """ 86 | return status 87 | 88 | def to_resp(self, status): 89 | """ 90 | Returns the final response object based on the input data and the status object 91 | 92 | :param status: The current status object 93 | :return: The updated status object 94 | """ 95 | if status.alarmOrNot: 96 | self.resp.isException = True 97 | self.resp.alarmMsg = status.alarmReason 98 | return status 99 | 100 | 101 | if __name__ == "__main__": 102 | pass 103 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /algorithm/dyn_thresh/dyn_thresh_algo/node.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'node.py' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/11 17:36' 6 | __info__ = 'Define the core class Node and implement functions for parent-child relationships, drilling down, copying, 7 | and matching nodes in an interval tree.' 8 | """ 9 | 10 | 11 | class Node: 12 | """ 13 | Core class representing a node in an interval tree. 14 | """ 15 | 16 | def __init__(self, level, left, right, parents=None): 17 | """ 18 | Initialize a new Node with the given level, left endpoint, right endpoint, and parent nodes. 19 | 20 | :param level: The current level of the node. 21 | :param left: The left endpoint of the interval (closed interval). 22 | :param right: The right endpoint of the interval (closed interval). 23 | :param parents: A list of parent nodes, with the left parent at index 0 and the right parent at index -1. 24 | Defaults to an empty list. 25 | """ 26 | if parents is None: 27 | parents = [] 28 | self.level = level 29 | self.left = left 30 | self.right = right 31 | self.parents = parents 32 | 33 | def add_parent(self, parent_node): 34 | """ 35 | Add a parent node to the node's list of parent nodes if the parent node fully contains the current node. 36 | 37 | :param parent_node: The parent node to add. 38 | :return: None. 39 | """ 40 | if self.left <= parent_node.left and self.right >= parent_node.right: 41 | self.parents.append(parent_node) 42 | 43 | def drill_down_to_node(self, direction): 44 | """ 45 | Drill down from the current node to the node in the specified direction. 46 | 47 | :param direction: The direction to drill down, with direction=0 indicating the left direction and direction=-1 48 | indicating the right direction. 49 | :return: The node in the specified direction. 50 | """ 51 | current_node = self 52 | while current_node.parents: 53 | current_node = current_node.parents[direction] 54 | return current_node 55 | 56 | def drill_down_to_level(self, direction): 57 | """ 58 | Drill down from the current node to the level in the specified direction. 59 | 60 | :param direction: The direction to drill down, with direction=0 indicating the left direction and direction=-1 61 | indicating the right direction. 62 | :return: The level in the specified direction. 63 | """ 64 | 65 | def get_endpoint(node, direction): 66 | if direction == 0: 67 | return node.left 68 | else: 69 | return node.right 70 | 71 | ts = [] 72 | current_node = self 73 | ts.append(get_endpoint(current_node, direction)) 74 | while current_node.parents: 75 | current_node = current_node.parents[direction] 76 | ts.append(get_endpoint(current_node, direction)) 77 | return ts 78 | 79 | def copy_node(self): 80 | """ 81 | Create a copy of the current node. 82 | 83 | :return: A new Node object with the same level, left endpoint, and right endpoint as the original node. 84 | """ 85 | new_node = Node(self.level, self.left, self.right) 86 | return new_node 87 | 88 | def matches_interval(self, ll, rr): 89 | """ 90 | Check if the current node matches the given interval. 91 | 92 | :param ll: The left endpoint of the interval. 93 | :param rr: The right endpoint of the interval. 94 | :return: True if the current node's interval matches the given interval, False otherwise. 95 | """ 96 | if self.left == ll and self.right == rr: 97 | return True 98 | return False 99 | 100 | 101 | if __name__ == "__main__": 102 | pass 103 | -------------------------------------------------------------------------------- /common/request_builder.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'context_builder' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/12 20:35' 6 | __info__ = build the request 7 | """ 8 | from typing import Dict 9 | 10 | from common.classes import DetectInfo, RuleInfo, Request4AD 11 | from common.constants import Constants 12 | from common.utils import Utils 13 | 14 | 15 | class RequestBuilder: 16 | def __init__(self, input_body: dict): 17 | self.body = input_body 18 | self.req = None 19 | 20 | def build_req(self): 21 | """ 22 | Builds and returns an AD request object based on the input body. 23 | 24 | @return: The built AD request object. 25 | """ 26 | # Data processing 27 | ts = self.body.get("inputTimeSeries") 28 | detect_time = self.body.get("detectTime") 29 | period = self.body.get("intervalTime") 30 | data_by_data = self.data_process(ts, detect_time, period, detect_length=self.period_mapper(period)) 31 | 32 | # Detect information 33 | algorithm_type = self.body.get("algorithmConfig").get("algorithmType") 34 | detect_info = DetectInfo(sensitive=self.body.get("algorithmConfig").get("sensitivity", "mid"), 35 | algorithm_type=algorithm_type 36 | ) 37 | 38 | # Rule information 39 | if self.body.get("ruleConfig") is None: 40 | self.body["ruleConfig"] = {} 41 | up_threshold = Constants.CUSTOM_UP_THRESHOLD.value 42 | down_threshold = Constants.CUSTOM_DOWN_THRESHOLD.value 43 | rule_info = RuleInfo( 44 | min_duration=self.body.get("ruleConfig").get("defaultDuration", Constants.MIN_DURATION_DEFAULT.value), 45 | up_threshold=self.body.get("ruleConfig").get("customUpThreshold", up_threshold), 46 | down_threshold=self.body.get("ruleConfig").get("customDownThreshold", down_threshold), 47 | change_rate=self.body.get("ruleConfig").get("customChangeRate", Constants.CUSTOM_CHANGE_RATE_DEFAULT.value), 48 | ) 49 | 50 | # Build and return the AD request object 51 | self.req = Request4AD(trace_id=self.body.get("traceId"), 52 | data_by_day=data_by_data, 53 | detect_info=detect_info, 54 | rule_info=rule_info 55 | ) 56 | return self.req 57 | 58 | @staticmethod 59 | def data_process(time_series: Dict[str, float], detect_time: int, period: int, detect_length) -> dict: 60 | """ 61 | Transforms input test data into a list of tuples representing the time periods that need to be analyzed. 62 | 63 | @param time_series: A dictionary containing the input time series data. 64 | @param detect_time: The detection time. 65 | @param period: The period of the input data. 66 | @param detect_length: The detection length. 67 | @return: A dictionary containing the processed data grouped by day. 68 | """ 69 | detect_time += period # make sure to get the running time 70 | detect_left_time = detect_time - detect_length * period 71 | earliest_time = min([int(key) for key in list(time_series.keys())]) 72 | day_num = int((detect_left_time - earliest_time) / (1440 * 60000)) 73 | data_groups = [] 74 | while len(data_groups) < day_num: 75 | if len(data_groups) == 0: 76 | data_groups.append((detect_time - detect_length * period, detect_time)) 77 | else: 78 | cur_start, cur_end = data_groups[-1][0], data_groups[-1][1] 79 | data_groups.append((cur_start - 1440 * 60000, cur_end - 1440 * 60000)) 80 | data_by_day = {} 81 | for i, (left, right) in enumerate(data_groups): 82 | data_by_day[str(i)] = Utils().time_series_min_str(time_series, left, right, period) 83 | if len(data_groups) == 0: 84 | data_by_day = {str(0): Utils().time_series_min_str(time_series, earliest_time, detect_time, period)} 85 | return data_by_day 86 | 87 | @staticmethod 88 | def period_mapper(period) -> int: 89 | """ 90 | Maps the period of the input data to the corresponding analysis length. 91 | 92 | @param period: The period of the input data. 93 | @return: The corresponding analysis length. 94 | """ 95 | if period == 60000: 96 | return 24 * 60 97 | else: 98 | return 24 * 60 99 | 100 | 101 | if __name__ == "__main__": 102 | pass 103 | -------------------------------------------------------------------------------- /algorithm/dyn_thresh/dyn_thresh_algo/threshold.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'threshold' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/16 19:27' 6 | __info__ = 7 | """ 8 | from typing import List, Dict 9 | 10 | import pandas as pd 11 | import numpy as np 12 | 13 | from algorithm.dyn_thresh.dyn_thresh_algo.events import PeriodicEventDetector 14 | from algorithm.dyn_thresh.dyn_thresh_algo.node import Node 15 | from common.utils import Utils 16 | 17 | 18 | class ThresholdCalc: 19 | def __init__(self, data_by_day: Dict[str, List[float]], boundary=1440): 20 | self.data_by_day = data_by_day 21 | # Initialization 22 | self.boundary = boundary # Maximum number of data points in a day 23 | self.steps = 50 # Number of steps to use when calculating threshold values 24 | self.init_per = 90 # Initial percentile to use when calculating threshold values 25 | self.similar_index = 1 # Controls the similarity of the threshold values at different levels of the tree 26 | self.cont_len = 120 # Length of continuous time intervals to break when doing threshold searching 27 | 28 | def run(self): 29 | df = pd.DataFrame.from_dict(self.data_by_day, orient="index") 30 | period = self.pp_detect(list(df.min())) # Detect the periodicity of the data 31 | if period != -1: 32 | self.cont_len = int(self.boundary / period / 2) 33 | dt = PeriodicEventDetector(data_by_day=self.data_by_day, 34 | steps=self.steps, 35 | init_per=self.init_per, 36 | similar_index=self.similar_index, 37 | cont_len=self.cont_len 38 | ) 39 | node_events = dt.run() # Detect periodic events in the data 40 | intervals_with_th = self.slice_th_creator(node_events, dt.th_list) 41 | return self.regression(df, intervals_with_th[-1]) 42 | 43 | def slice_th_creator(self, node_events: List[Node], th_list: List[float]): 44 | """ 45 | Create intervals and their corresponding threshold values. 46 | 47 | @param node_events: A list of periodic event nodes. 48 | @param th_list: A list of threshold values. 49 | @return: A list of tuples containing each interval and its corresponding threshold value. 50 | """ 51 | index_stack = [] 52 | start = 0 53 | max_level = 0 54 | for n in node_events: 55 | max_level = max(n.level, max_level) 56 | if n.left > start: 57 | index_stack.append((start, n.left - 1)) 58 | index_stack.append((n.left, n.right)) 59 | start = n.right + 1 60 | if start < self.boundary: 61 | index_stack.append((start, self.boundary - 1)) 62 | out_put = [] 63 | if len(th_list) == 1: # Handle extreme cases 64 | out_put.append((index_stack[0][0], index_stack[-1][-1], th_list[-1], None)) 65 | return out_put 66 | for ll, rr in index_stack: 67 | cur_th = th_list[max_level] 68 | node = None 69 | for nn in node_events: 70 | if nn.matches_interval(ll, rr): 71 | node = nn 72 | cur_th = min(th_list[nn.drill_down_to_node(0).level], th_list[nn.drill_down_to_node(-1).level]) 73 | continue 74 | out_put.append((ll, rr, cur_th, node)) 75 | return out_put 76 | 77 | @staticmethod 78 | def regression(df, interval_with_th): 79 | """ 80 | Calculate the target threshold using regression. 81 | 82 | @param df: A pandas dataframe. 83 | @param interval_with_th: A tuple containing an interval and its corresponding threshold value. 84 | @return: The target threshold value. 85 | """ 86 | ll, rr = interval_with_th[0], interval_with_th[1] 87 | target_th = df.iloc[:, ll:rr + 1].min().min() 88 | return target_th 89 | 90 | @staticmethod 91 | def pp_detect(envelope, min_win=140, min_period_interval=15): 92 | """ 93 | Detect whether the data has a periodic pattern using FFT. 94 | 95 | @param envelope: A list of data points. 96 | @param min_win: The minimum window size to use when calculating FFT. 97 | @param min_period_interval: The minimum interval between periodic patterns. 98 | @return: The number of data points per period, or -1 if no periodic pattern is detected. 99 | """ 100 | fft_values = np.fft.fft(envelope) 101 | freq = [abs(v) for v in fft_values[:len(envelope) // 2]] 102 | search_range = range(int(len(envelope) / min_win), int(len(envelope) / min_period_interval)) 103 | up_threshold = Utils.turkey_box_plot([freq[k] for k in search_range])[4] 104 | up_threshold = max(1 / 3 * max([freq[k] for k in search_range]), up_threshold) 105 | index_in = [] 106 | for i, v in enumerate(freq): 107 | if v > up_threshold and i in search_range: 108 | index_in.append(i) 109 | potential_index = [] 110 | for v in index_in: 111 | if v != max(index_in) and max(index_in) % v == 0: 112 | potential_index.append(v) 113 | if len(potential_index) > 0: 114 | return min(potential_index) 115 | return -1 116 | 117 | 118 | if __name__ == "__main__": 119 | pass 120 | -------------------------------------------------------------------------------- /common/utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'utils' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/11 17:38' 6 | __info__ = the utils 7 | """ 8 | import math 9 | import numpy as np 10 | 11 | from numpy import nan 12 | from typing import List, Dict, Callable, Any 13 | 14 | 15 | class Utils: 16 | 17 | def diff_feature_calc(self, input_data: List[float], search_length: int) -> list: 18 | """ 19 | Calculates the difference feature for a given input list. 20 | 21 | :param input_data: A list of floats with length greater than search_length. 22 | :param search_length: The maximum range for which to calculate the difference feature. 23 | :return: A list of floats representing the difference feature. 24 | """ 25 | diff = [] 26 | for i in range(len(input_data) - 1, search_length - 1, -1): 27 | if input_data[i] - input_data[i - 1] < 0: 28 | search_list = input_data[i - search_length: i + 1] 29 | duration = self.monotonic_duration(search_list, True) 30 | diff.append(input_data[i] - input_data[i - duration + 1]) 31 | else: 32 | search_list = input_data[i - search_length: i + 1] 33 | duration = self.monotonic_duration(search_list) 34 | diff.append(input_data[i] - input_data[i - duration + 1]) 35 | diff.reverse() 36 | out_put_diffs = search_length * [0] + diff 37 | return out_put_diffs 38 | 39 | @staticmethod 40 | def monotonic_duration(lst: List[float], reverse=False): 41 | """ 42 | Calculates the duration of a monotonic sequence in a given list. 43 | 44 | :param lst: A list of floats. 45 | :param reverse: If True, treats the list as reversed for calculation. 46 | :return: An integer representing the duration of the monotonic sequence. 47 | """ 48 | if reverse: 49 | lst = [-v for v in lst] 50 | if len(lst) == 0: 51 | return 0 52 | if len(lst) == 1: 53 | return 1 54 | count = 1 55 | for i in range(len(lst) - 1, 0, -1): 56 | if lst[i] > lst[i - 1]: 57 | count += 1 58 | else: 59 | break 60 | return count 61 | 62 | @staticmethod 63 | def turkey_box_plot(input_data: List[float], delta=1.5) -> list: 64 | """ 65 | Calculates the Tukey box plot for a given input list. 66 | 67 | :param input_data: A list of floats. 68 | :param delta: The delta value to use for the box plot calculation. 69 | :return: A list of floats representing the Tukey box plot. 70 | """ 71 | q1 = np.percentile(input_data, 25) 72 | q3 = np.percentile(input_data, 75) 73 | q2 = np.percentile(input_data, 50) 74 | iqr = q3 - q1 75 | return [q1, q2, q3, q1 - delta * iqr, q3 + delta * iqr] 76 | 77 | def time_series_min_str(self, p_data: Dict[str, float], start: int, end: int, period: int) -> list: 78 | """ 79 | Generates a complete minute-level time series. 80 | 81 | @param p_data: A dictionary with index as key and amplitude as value. 82 | @param start: The start time of the time series in milliseconds. 83 | @param end: The end time of the time series in milliseconds. 84 | @param period: The period of each time step in milliseconds. 85 | @return: A list representing the complete time series. 86 | """ 87 | out_time_series = [] 88 | for i_time in range(start, end, period): 89 | if str(i_time) in p_data.keys(): 90 | out_time_series.append(p_data[str(i_time)]) 91 | else: 92 | out_time_series.append(None) 93 | out_time_series = self.time_series_imputation(out_time_series) 94 | return out_time_series 95 | 96 | @staticmethod 97 | def time_series_imputation(input_data: List[float]) -> list: 98 | """ 99 | Imputes missing values in a time series. 100 | 101 | @param input_data: A list of floats representing the time series. 102 | @return: A list of floats with imputed missing values. 103 | """ 104 | if None in input_data: 105 | if input_data.count(None) == len(input_data): 106 | return [] 107 | if input_data[0] is None: 108 | input_data[0] = next(item for item in input_data if item is not None) 109 | for i in range(1, len(input_data)): 110 | if input_data[i] is None or math.isnan(input_data[i]): 111 | input_data[i] = input_data[i - 1] 112 | return input_data 113 | 114 | @staticmethod 115 | def agg_diff_fe_calc(input_data: List[float], agg_length: int) -> list: 116 | """ 117 | Calculates aggregated difference features for a given input list. 118 | 119 | @param input_data: A list of floats representing the input data. 120 | @param agg_length: The length of the aggregation window. 121 | @return: A list of floats representing the aggregated difference features. 122 | """ 123 | diff_func: Callable[[Any, Any], None] = lambda a, b: np.sum(a) - np.sum(b) 124 | diff = [] 125 | for i in range(len(input_data) - 2 * agg_length + 1): 126 | post = input_data[i + agg_length:i + 2 * agg_length] 127 | pre = input_data[i:i + agg_length] 128 | diff.append(diff_func(post, pre)) 129 | return diff 130 | 131 | @staticmethod 132 | def longest_continuous(lst, target) -> int: 133 | """ 134 | Finds the length of the longest continuous sequence in a list that meets a given target condition. 135 | 136 | @param lst: A list of values to search. 137 | @param target: The target value to search for. 138 | @return: The length of the longest continuous sequence that meets the target condition. 139 | """ 140 | count = 0 141 | max_count = 0 142 | for num in lst: 143 | if num <= target: 144 | count += 1 145 | max_count = max(max_count, count) 146 | else: 147 | count = 0 148 | return max_count 149 | 150 | @staticmethod 151 | def diff_percentile_func(data: list, step: int, is_down=True) -> list: 152 | """ 153 | Calculates the percentile difference for a given data list and step size. 154 | 155 | @param data: A list of data values. 156 | @param step: The step size for calculating the percentile difference. 157 | @param is_down: A boolean indicating whether the percentile difference should be negative. 158 | @return: A list of percentile differences. 159 | """ 160 | diff_list = [] 161 | for i in range(2 * step, len(data)): 162 | if step == 1: 163 | if data[i - step] != 0: 164 | v = 100 * (data[i] - data[i - step]) / data[i - step] 165 | if is_down: 166 | diff_list.append(v if v < 0 else 0) 167 | else: 168 | diff_list.append(-v if v > 0 else 0) 169 | else: 170 | diff_list.append(nan) 171 | else: 172 | j = i + 1 173 | if np.mean(data[j - 2 * step: j - step]) != 0: 174 | v = 100 * (np.mean(data[j - step:j]) - np.mean(data[j - 2 * step: j - step])) / np.mean( 175 | data[j - 2 * step: j - step]) 176 | if is_down: 177 | diff_list.append(v if v < 0 else 0) 178 | else: 179 | diff_list.append(-v if v > 0 else 0) 180 | else: 181 | diff_list.append(nan) 182 | diff_array = np.array(diff_list) 183 | if diff_array.size - np.isnan(diff_array).sum() == 0: 184 | fill_value = -100 185 | else: 186 | fill_value = np.nanmean(diff_array) 187 | np.nan_to_num(diff_array, nan=fill_value, copy=False) 188 | diff_list = diff_array.tolist() 189 | return (2 * step) * [diff_list[0]] + diff_list 190 | 191 | 192 | if __name__ == "__main__": 193 | pass 194 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /algorithm/dyn_thresh/dyn_thresh_algo/events.py: -------------------------------------------------------------------------------- 1 | """ 2 | __project__ = 'holoinsight-ai' 3 | __file_name__ = 'DynamicThreshold' 4 | __author__ = 'LuYuan' 5 | __time__ = '2023/4/11 17:37' 6 | __info__ = 7 | """ 8 | import numpy as np 9 | import pandas as pd 10 | 11 | from typing import Dict, List 12 | from pandas import DataFrame 13 | 14 | from algorithm.dyn_thresh.dyn_thresh_algo.node import Node 15 | from common.utils import Utils 16 | 17 | NEIGHBOR = 30 18 | THRESHOLD_LEVEL_RATE = 0.2 19 | 20 | 21 | class PeriodicEventDetector: 22 | def __init__(self, data_by_day: Dict[str, List[float]], steps: int, init_per: float, similar_index: int, 23 | cont_len: int): 24 | self.dod_data = data_by_day 25 | self.history_keys = list(self.dod_data.keys()) 26 | self.data_len = None 27 | self.steps = steps 28 | self.init_per = init_per 29 | self.similar_index = similar_index 30 | self.cont_len = cont_len 31 | # 32 | self.neighbor = NEIGHBOR 33 | self.threshold_level_rate = THRESHOLD_LEVEL_RATE 34 | # out_put 35 | self.th_list = [] 36 | 37 | def run(self): 38 | df = pd.DataFrame.from_dict(self.dod_data, orient="index") 39 | self.data_len = df.shape[1] 40 | min_value, max_value = np.percentile(df.values, 0), np.percentile(df.values, self.init_per) 41 | if min_value == max_value: 42 | self.th_list = [min_value] 43 | return [Node(level=-1, left=0, right=self.data_len - 1)] 44 | th_list = [min_value - i * (min_value - max_value) / self.steps for i in range(self.steps)] 45 | self.th_list = th_list 46 | events = self.find_periodic_events(df, th_list) 47 | return events 48 | 49 | def find_periodic_events(self, df: DataFrame, th_list: List[float]) -> List[float]: 50 | """ 51 | Identify periodic events. 52 | 53 | @param df: The raw data. 54 | @param th_list: A list of threshold values to use for slicing the data. 55 | @return: A list of periodic events. 56 | """ 57 | pre_level_nodes = [] 58 | for i, cur_th in enumerate(th_list): 59 | raw_nodes = self.raw_nodes_search(df, cur_th, i) 60 | if len(raw_nodes) == 0: 61 | continue 62 | raw_nodes_with_parents = self.node_parents_update(raw_nodes, pre_level_nodes) 63 | cur_level_nodes = [] 64 | for r_node in raw_nodes_with_parents: 65 | if not r_node.parents: 66 | cur_level_nodes.append(r_node) 67 | elif len(r_node.parents) == 1: 68 | mid_left_nodes = self.modify_node_boundary(r_node, 0) 69 | mid_right_nodes = self.modify_node_boundary(mid_left_nodes[-1], -1) 70 | if len(mid_left_nodes) == 1: 71 | nodes_with_processed = mid_right_nodes 72 | else: 73 | nodes_with_processed = [mid_left_nodes[0]] + mid_right_nodes 74 | cur_level_nodes += nodes_with_processed 75 | elif len(r_node.parents) > 1: 76 | processed_node_cluster = self.nodes_process(r_node, self.node_cluster(r_node.parents)) 77 | cur_level_nodes += processed_node_cluster 78 | pre_level_nodes = cur_level_nodes 79 | return pre_level_nodes 80 | 81 | def raw_nodes_search(self, df: DataFrame, cur_th: float, level: int) -> List[Node]: 82 | """ 83 | Obtain raw nodes by dividing the data according to the specified threshold. 84 | 85 | @param df: The raw data. 86 | @param cur_th: The current threshold. 87 | @param level: The current level of the tree. 88 | @return: A list of raw nodes. 89 | """ 90 | outlier_list = (df < cur_th).sum(axis=0) 91 | duration = Utils.longest_continuous(outlier_list.tolist(), 0) 92 | if duration < self.cont_len: 93 | return [] 94 | raw_nodes = self.get_raw_nodes(outlier_list=outlier_list.tolist(), 95 | count=max(1, int(len(self.history_keys) / self.similar_index)), 96 | level=level, 97 | neighbor=self.neighbor) 98 | return raw_nodes 99 | 100 | def nodes_process(self, completed_node: Node, node_clu_list: List[List[Node]]) -> List[Node]: 101 | """ 102 | Split/merge nodes with multiple parents; split the two sides of the overall node! 103 | Splitting scenario: for example, when two parents are very large in size. 104 | 105 | @param completed_node: The entire Node after a split. 106 | @param node_clu_list: Clustering of parents corresponding to the overall node according to certain rules. 107 | @return: A list of processed nodes. 108 | """ 109 | processed_node_cluster = [] 110 | for n_list in node_clu_list: 111 | processed_node_cluster += self.node_process_within_group(n_list) 112 | processed_node_cluster = self.node_process_between_group(processed_node_cluster) 113 | if completed_node.left != processed_node_cluster[0].left: 114 | new_nodes = self.modify_node_boundary( 115 | Node(level=completed_node.level, left=completed_node.left, right=processed_node_cluster[0].right, 116 | parents=[processed_node_cluster[0]]), 0) 117 | processed_node_cluster = new_nodes + processed_node_cluster[1:] 118 | else: 119 | copy_node = processed_node_cluster[0].copy_node() 120 | copy_node.parents = [processed_node_cluster[0]] 121 | processed_node_cluster[0] = copy_node 122 | if completed_node.right != processed_node_cluster[-1].right: 123 | new_nodes = self.modify_node_boundary( 124 | Node(level=completed_node.level, left=processed_node_cluster[-1].left, right=completed_node.right, 125 | parents=[processed_node_cluster[-1]]), -1) 126 | processed_node_cluster = processed_node_cluster[:-1] + new_nodes 127 | else: 128 | copy_node = processed_node_cluster[-1].copy_node() 129 | copy_node.parents = [processed_node_cluster[-1]] 130 | processed_node_cluster[-1] = copy_node 131 | for p_n in processed_node_cluster: 132 | p_n.level = completed_node.level 133 | return processed_node_cluster 134 | 135 | def node_process_within_group(self, node_list: List[Node]) -> List[Node]: 136 | """ 137 | The input is a clustered list of nodes with levels within a certain range, 138 | arranged from left to right by default. 139 | 140 | @param node_list: A list of nodes with the same parent. 141 | @return: A list of processed nodes. 142 | """ 143 | new_node_list = [node_list[0]] # todo 144 | for node in node_list[1:]: 145 | l1, l2 = new_node_list[-1].drill_down_to_node(-1).level, node.drill_down_to_node(0).level 146 | pre_r_index, post_l_index = new_node_list[-1].right, node.left 147 | if post_l_index - pre_r_index > 1: 148 | if node.level - max(l1, l2) < int(self.threshold_level_rate * self.steps): 149 | new_node_list[-1] = self.node_merge(new_node_list[-1], node) 150 | else: 151 | mid_node = Node(level=node.level, left=pre_r_index + 1, right=post_l_index - 1) 152 | if l1 > l2: 153 | new_node_list[-1] = self.node_merge(new_node_list[-1], mid_node) 154 | new_node_list.append(node) 155 | else: 156 | new_node_list.append(self.node_merge(mid_node, node)) 157 | else: 158 | new_node_list[-1] = self.node_merge(new_node_list[-1], node) 159 | return new_node_list 160 | 161 | @staticmethod 162 | def node_process_between_group(node_list: List[Node]) -> List[Node]: 163 | """ 164 | The input is a list of processed nodes between clustered groups, 165 | arranged from left to right by default. 166 | 167 | @param node_list: A list of nodes with the same parent. 168 | @return: A list of processed nodes. 169 | """ 170 | new_node_list = [node_list[0]] 171 | for node in node_list[1:]: 172 | pre_r_index, post_l_index = new_node_list[-1].right, node.left 173 | if post_l_index - pre_r_index > 1: 174 | mid_node = Node(level=node.level, left=pre_r_index + 1, right=post_l_index - 1) 175 | new_node_list.append(mid_node) 176 | new_node_list.append(node) 177 | else: 178 | new_node_list.append(node) 179 | return new_node_list 180 | 181 | def modify_node_boundary(self, node: Node, pos: int) -> List[Node]: 182 | """ 183 | Boundary processing. 184 | 185 | @param node: The node to be modified. 186 | @param pos: If pos=0, modify the left boundary; if pos=-1, modify the right boundary. 187 | @return: A list of modified nodes. 188 | """ 189 | if not node.parents: 190 | return [node] 191 | if node.level - node.drill_down_to_node(pos).level < int(self.threshold_level_rate * self.steps): 192 | return [node] 193 | 194 | if pos == 0: 195 | if node.left == node.parents[0].left: 196 | return [node] 197 | else: 198 | ts = node.drill_down_to_level(pos) 199 | ts.reverse() 200 | if self.change_point_detect(ts, pos): 201 | new_node_list = [ 202 | Node(level=node.level, left=node.left, right=node.parents[0].left - 1)] 203 | node.left = node.parents[0].left 204 | new_node_list.append(node) 205 | return new_node_list 206 | elif pos == -1: 207 | if node.right == node.parents[-1].right: 208 | return [node] 209 | else: 210 | ts = node.drill_down_to_level(pos) 211 | ts.reverse() 212 | if self.change_point_detect(ts, pos): 213 | new_node_list = [ 214 | Node(level=node.level, left=node.left, right=node.parents[-1].right, 215 | parents=node.parents), 216 | Node(level=node.level, left=node.parents[-1].right + 1, right=node.right)] 217 | return new_node_list 218 | return [node] 219 | 220 | def get_raw_nodes(self, level: int, outlier_list: List[int], count: int, neighbor: int) -> List[Node]: 221 | """ 222 | Select potential event nodes based on specific conditions. 223 | 224 | @param level: The current level. 225 | @param outlier_list: The list of outlier points. 226 | @param count: Condition 1. 227 | @param neighbor: Condition 2. 228 | @return: A list of potential event nodes. 229 | """ 230 | event_clusters = self.event_cluster(outlier_list, count, neighbor) 231 | if len(event_clusters) == 0: 232 | return [] 233 | node_list = [] 234 | for clu in event_clusters: 235 | node_list.append(Node(level=level, left=clu[0][0], right=clu[-1][0])) # 初始parents为空 236 | return node_list 237 | 238 | @staticmethod 239 | def node_parents_update(raw_nodes: List[Node], pre_level_nodes: List[Node]) -> List[Node]: 240 | """ 241 | Find the parents of each raw_node. 242 | 243 | @param raw_nodes: A list of raw nodes. 244 | @param pre_level_nodes: A list of nodes from the previous level. 245 | @return: A list of nodes with updated parent information. 246 | """ 247 | for en in raw_nodes: 248 | for f_en in pre_level_nodes: 249 | en.add_parent(f_en) 250 | return raw_nodes 251 | 252 | @staticmethod 253 | def node_merge(pre_node: Node, post_node: Node) -> Node: 254 | """ 255 | Merge two nodes in order. 256 | 257 | @param pre_node: The previous node. 258 | @param post_node: The next node. 259 | @return: The merged node. 260 | """ 261 | node = Node(level=None, left=pre_node.left, right=post_node.right, 262 | parents=[pre_node, post_node]) 263 | return node 264 | 265 | @staticmethod 266 | def node_cluster(lst: List[Node]) -> List[List[Node]]: 267 | """ 268 | Cluster the nodes, preserving the original level. 269 | 270 | @param lst: A list of nodes. 271 | @return: A list of clustered nodes. 272 | """ 273 | if not lst: 274 | return [] 275 | result = [] 276 | i = 0 277 | while i < len(lst): 278 | j = i 279 | while j < len(lst) - 1 and abs( 280 | lst[i].drill_down_to_node(-1).level - lst[j + 1].drill_down_to_node(0).level) < 10: 281 | j += 1 282 | result.append(lst[i:j + 1]) # todo 父节点 283 | i = j + 1 284 | return result 285 | 286 | @staticmethod 287 | def change_point_detect(ts, pos) -> bool: 288 | """ 289 | Find the change point! 290 | 291 | @param pos: The position to check for a change point. 292 | @param ts: The time series data. 293 | @return: True if there is a change point at the specified position, False otherwise. 294 | """ 295 | for i in range(1, 3, 1): 296 | diffs = Utils().diff_feature_calc(ts, i) 297 | if pos == 0: 298 | down_threshold = Utils.turkey_box_plot(diffs[:-1], 2)[3] 299 | if diffs[-1] < down_threshold and diffs[-1] < min(diffs[:-1]): 300 | return True 301 | elif pos == -1: 302 | up_threshold = Utils.turkey_box_plot(diffs[:-1], 2)[4] 303 | if diffs[-1] > up_threshold and diffs[-1] > max(diffs[:-1]): 304 | return True 305 | return False 306 | 307 | @staticmethod 308 | def event_cluster(lst, count: int, interval): 309 | """ 310 | Cluster events! 311 | 312 | @param lst: The list of events to cluster. 313 | @param count: The maximum number of clusters to create. 314 | @param interval: The time interval to use for clustering. 315 | @return: The clustered events as a list of lists. 316 | """ 317 | clu = [] 318 | current_cluster = [] 319 | i = 0 320 | while i < len(lst): 321 | if len(current_cluster) == 0: 322 | if lst[i] >= count: # fixme 323 | current_cluster.append((i, lst[i])) 324 | else: 325 | start_loc = current_cluster[-1][0] + 1 326 | end_loc = min(start_loc + interval, len(lst)) 327 | slice_lst = lst[start_loc:end_loc] 328 | slice_idx = [start_loc + j for j in range(len(slice_lst)) if slice_lst[j] >= count] 329 | if slice_idx: 330 | current_cluster += [(k, lst[k]) for k in slice_idx] 331 | else: 332 | clu.append(current_cluster) 333 | current_cluster = [] 334 | i = end_loc - 1 335 | i += 1 336 | if current_cluster: 337 | clu.append(current_cluster) 338 | return clu 339 | 340 | def set_neighbor_len(self, neighbor): 341 | """ 342 | Set the length of the neighbor list. 343 | 344 | @param neighbor: The length of the neighbor list. 345 | @return: None 346 | """ 347 | self.neighbor = neighbor 348 | 349 | def set_threshold_level_rate(self, threshold_level_rate): 350 | """ 351 | Set the threshold level rate. 352 | 353 | @param threshold_level_rate: The threshold level rate. 354 | @return: None 355 | """ 356 | self.threshold_level_rate = threshold_level_rate 357 | 358 | 359 | if __name__ == "__main__": 360 | pass 361 | --------------------------------------------------------------------------------