|
| 1 | +"""Module for Generic Algorithm class""" |
| 2 | + |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from itertools import groupby |
| 5 | +import json |
| 6 | +from typing import Any, Dict, List, Tuple, Union |
| 7 | +import pandas as pd |
| 8 | +from fmatch.matcher import Matcher |
| 9 | +from hunter.report import Report, ReportType |
| 10 | +from hunter.series import Series, Metric, ChangePoint, ChangePointGroup |
| 11 | +import pkg.constants as cnsts |
| 12 | + |
| 13 | + |
| 14 | +from pkg.utils import json_to_junit |
| 15 | + |
| 16 | + |
| 17 | +class Algorithm(ABC): |
| 18 | + """Generic Algorithm class for algorithm factory""" |
| 19 | + |
| 20 | + def __init__( # pylint: disable = too-many-arguments |
| 21 | + self, |
| 22 | + matcher: Matcher, |
| 23 | + dataframe: pd.DataFrame, |
| 24 | + test: dict, |
| 25 | + options: dict, |
| 26 | + metrics_config: dict[str, dict], |
| 27 | + ) -> None: |
| 28 | + self.matcher = matcher |
| 29 | + self.dataframe = dataframe |
| 30 | + self.test = test |
| 31 | + self.options = options |
| 32 | + self.metrics_config = metrics_config |
| 33 | + |
| 34 | + def output_json(self) -> Tuple[str, str]: |
| 35 | + """Method to output json output |
| 36 | +
|
| 37 | + Returns: |
| 38 | + Tuple[str, str]: returns test_name and json output |
| 39 | + """ |
| 40 | + _, change_points_by_metric = self._analyze() |
| 41 | + dataframe_json = self.dataframe.to_json(orient="records") |
| 42 | + dataframe_json = json.loads(dataframe_json) |
| 43 | + |
| 44 | + for index, entry in enumerate(dataframe_json): |
| 45 | + entry["metrics"] = { |
| 46 | + key: {"value": entry.pop(key), "percentage_change": 0} |
| 47 | + for key in self.metrics_config |
| 48 | + } |
| 49 | + entry["is_changepoint"] = False |
| 50 | + |
| 51 | + for key, value in change_points_by_metric.items(): |
| 52 | + for change_point in value: |
| 53 | + index = change_point.index |
| 54 | + percentage_change = ( |
| 55 | + (change_point.stats.mean_2 - change_point.stats.mean_1) |
| 56 | + / change_point.stats.mean_1 |
| 57 | + ) * 100 |
| 58 | + if ( |
| 59 | + percentage_change * self.metrics_config[key]["direction"] > 0 |
| 60 | + or self.metrics_config[key]["direction"] == 0 |
| 61 | + ): |
| 62 | + dataframe_json[index]["metrics"][key][ |
| 63 | + "percentage_change" |
| 64 | + ] = percentage_change |
| 65 | + dataframe_json[index]["is_changepoint"] = True |
| 66 | + |
| 67 | + return self.test["name"], json.dumps(dataframe_json, indent=2) |
| 68 | + |
| 69 | + def output_text(self) -> Tuple[str,str]: |
| 70 | + """Outputs the data in text/tabular format""" |
| 71 | + series, change_points_by_metric = self._analyze() |
| 72 | + change_points_by_time = self.group_change_points_by_time( |
| 73 | + series, change_points_by_metric |
| 74 | + ) |
| 75 | + report = Report(series, change_points_by_time) |
| 76 | + output_table = report.produce_report( |
| 77 | + test_name=self.test["name"], report_type=ReportType.LOG |
| 78 | + ) |
| 79 | + return self.test["name"], output_table |
| 80 | + |
| 81 | + def output_junit(self) -> Tuple[str,str]: |
| 82 | + """Output junit format |
| 83 | +
|
| 84 | + Returns: |
| 85 | + _type_: return |
| 86 | + """ |
| 87 | + test_name, data_json = self.output_json() |
| 88 | + data_json = json.loads(data_json) |
| 89 | + data_junit = json_to_junit( |
| 90 | + test_name=test_name, |
| 91 | + data_json=data_json, |
| 92 | + metrics_config=self.metrics_config, |
| 93 | + options=self.options, |
| 94 | + ) |
| 95 | + return test_name, data_junit |
| 96 | + |
| 97 | + @abstractmethod |
| 98 | + def _analyze(self): |
| 99 | + """Analyze algorithm""" |
| 100 | + |
| 101 | + def group_change_points_by_time( |
| 102 | + self, series: Series, change_points: Dict[str, List[ChangePoint]] |
| 103 | + ) -> List[ChangePointGroup]: |
| 104 | + """Return changepoint by time |
| 105 | +
|
| 106 | + Args: |
| 107 | + series (Series): Series of data |
| 108 | + change_points (Dict[str, List[ChangePoint]]): Group of changepoints wrt time |
| 109 | +
|
| 110 | + Returns: |
| 111 | + List[ChangePointGroup]: _description_ |
| 112 | + """ |
| 113 | + changes: List[ChangePoint] = [] |
| 114 | + for metric in change_points.keys(): |
| 115 | + changes += change_points[metric] |
| 116 | + |
| 117 | + changes.sort(key=lambda c: c.index) |
| 118 | + points = [] |
| 119 | + for k, g in groupby(changes, key=lambda c: c.index): |
| 120 | + cp = ChangePointGroup( |
| 121 | + index=k, |
| 122 | + time=series.time[k], |
| 123 | + prev_time=series.time[k - 1], |
| 124 | + attributes=series.attributes_at(k), |
| 125 | + prev_attributes=series.attributes_at(k - 1), |
| 126 | + changes=list(g), |
| 127 | + ) |
| 128 | + points.append(cp) |
| 129 | + |
| 130 | + return points |
| 131 | + |
| 132 | + def setup_series(self) -> Series: |
| 133 | + """ |
| 134 | + Returns series |
| 135 | + Returns: |
| 136 | + _type_: _description_ |
| 137 | + """ |
| 138 | + metrics = { |
| 139 | + column: Metric(value.get("direction", 1), 1.0) |
| 140 | + for column, value in self.metrics_config.items() |
| 141 | + } |
| 142 | + data = {column: self.dataframe[column] for column in self.metrics_config} |
| 143 | + attributes = { |
| 144 | + column: self.dataframe[column] |
| 145 | + for column in self.dataframe.columns |
| 146 | + if column in ["uuid", "buildUrl"] |
| 147 | + } |
| 148 | + series = Series( |
| 149 | + test_name=self.test["name"], |
| 150 | + branch=None, |
| 151 | + time=list(self.dataframe["timestamp"]), |
| 152 | + metrics=metrics, |
| 153 | + data=data, |
| 154 | + attributes=attributes, |
| 155 | + ) |
| 156 | + |
| 157 | + return series |
| 158 | + |
| 159 | + def output(self, output_format) -> Union[Any,None]: |
| 160 | + """Method to select output method |
| 161 | +
|
| 162 | + Args: |
| 163 | + output_format (str): format of the output |
| 164 | +
|
| 165 | + Raises: |
| 166 | + ValueError: In case of unmatched output |
| 167 | +
|
| 168 | + Returns: |
| 169 | + method: return method to be used |
| 170 | + """ |
| 171 | + if output_format == cnsts.JSON: |
| 172 | + return self.output_json() |
| 173 | + if output_format == cnsts.TEXT: |
| 174 | + return self.output_text() |
| 175 | + if output_format == cnsts.JUNIT: |
| 176 | + return self.output_junit() |
| 177 | + raise ValueError("Unsupported output format {output_format} selected") |
0 commit comments