### Install Anomeda Package Source: https://anomeda.readthedocs.io/en/latest Install the Anomeda package from PyPI using pip. Ensure you have Python and pip installed. ```bash pip install anomeda ``` -------------------------------- ### Install Development Requirements Source: https://anomeda.readthedocs.io/en/latest Install the necessary development requirements for contributing to the Anomeda project. This command should be run within your cloned repository and an activated virtual environment. ```bash pip install -r dev-requirements.txt ``` -------------------------------- ### Get Metric Name Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Returns the name of the metric column. ```python get_metric_name() ``` -------------------------------- ### Plot Specified Clusters by Condition Source: https://anomeda.readthedocs.io/en/latest/anomeda_api This example demonstrates how to plot specific clusters defined by conditional statements. The 'data' parameter must be an anomeda.DataFrame. ```python anomeda.plot_clusters( data, # anomeda.DataFrame breakdowns=['measure_a==1', 'measure_a == 1 and measure_b == 2'] # plot two specified clusters ) ``` -------------------------------- ### Get Measures Names Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Returns a list of column names that are considered measures. ```python get_measures_names() ``` -------------------------------- ### Get Discretization Mapping Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Returns a dictionary mapping discrete values to continuous measure ranges. Note that multiple intervals may map to the same discrete value. ```python get_discretization_mapping() ``` ```python >>> anmd_df.get_discretization_mapping() { 'dummy_numeric_measure': { 0: [[0.08506988648110014, 0.982366623262143]], # [[inc, exl)] 1: [[0.9855150328648835, 2.458970726947438]] # [[inc, exl)] } } ``` -------------------------------- ### Get Measures Types Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Retrieves the dictionary that defines the types of the measures. ```python get_measures_types() ``` -------------------------------- ### Get Aggregation Function Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Retrieves the function used for aggregating metrics by measures. ```python get_agg_func() ``` -------------------------------- ### Get Index Name Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Retrieves the name of the index column in the DataFrame. ```python get_index_name() ``` -------------------------------- ### Get Discretized Measures Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Returns discretized versions of continuous measures within the DataFrame. ```python get_discretized_measures() ``` -------------------------------- ### Initialize DataFrame with pandas DataFrame and metric name Source: https://anomeda.readthedocs.io/en/latest/usage_guide Use this when you have an existing pandas DataFrame and only need to specify the metric name for anomeda.DataFrame. ```python anomeda.DataFrame(pandas_df, metric_name='my_metric') ``` -------------------------------- ### Fit Trends and Find Anomalies Source: https://anomeda.readthedocs.io/en/latest/usage_guide This snippet demonstrates the basic workflow for anomaly detection: first fitting the trends to the data, then finding the anomalies. Ensure your data is prepared before calling these methods. ```python >>> anomeda.fit_trends(data) >>> anomeda.find_anomalies(data) ``` -------------------------------- ### Initialize DataFrame with measures Source: https://anomeda.readthedocs.io/en/latest/usage_guide Initialize an anomeda.DataFrame by specifying the columns that represent measures, along with the metric name. ```python anomeda.DataFrame(pandas_df, measures_names=['A', 'B', 'C'], metric_name='my_metric') ``` -------------------------------- ### Initialize DataFrame in pandas style Source: https://anomeda.readthedocs.io/en/latest/usage_guide Initialize an anomeda.DataFrame using a dictionary, similar to how you would initialize a pandas DataFrame, while also specifying measures and metric name. ```python anomeda.DataFrame( { 'A': [0, 1, 2], 'B': [3, 4, 5], 'C': [6, 7, 8], 'my_metric': [10, 20, 30] }, measures_names=['A', 'B', 'C'], metric_name='my_metric' ) ``` -------------------------------- ### Initialize Anomeda DataFrame Source: https://anomeda.readthedocs.io/en/latest Define an Anomeda DataFrame by specifying measures, their types, index, metric name, and aggregation function. This is the first step to using Anomeda for data analysis. ```python import anomeda anomeda_df = anomeda.DataFrame( df, # pandas.DataFrame measures_names=['country', 'system', 'url', 'duration'], # columns represending measures or characteristics of your events measures_types={ 'categorical': [;'country', 'system', 'url'], 'continuous': ['duration'] # measures can also be continuous - anomeda will take care of clustering them properly }, index_name='date', metric_name='visit', # dummy metric, always 1 agg_func='sum' # function that is used to aggregate metric ) ``` -------------------------------- ### Create a New Branch Source: https://anomeda.readthedocs.io/en/latest Create a new branch for your development work. This is a standard Git command used before making changes. ```bash git checkout -b my_branch ``` -------------------------------- ### Fit Trends with Custom Configuration Source: https://anomeda.readthedocs.io/en/latest/usage_guide Use this snippet to fit trends in time-series data with specific configurations for the number of trends, breakdowns, metric propagation, and cluster size. It also enables plotting and returns a DataFrame of the fitted trends. ```python fitted_trends = anomeda.fit_trends( data, trend_fitting_conf={'max_trends': 3}, breakdowns='all', metric_propagate='zeros', min_cluster_size=3, plot=True, df=True ) ``` -------------------------------- ### Initialize DataFrame with discretization mapping Source: https://anomeda.readthedocs.io/en/latest/usage_guide Initialize an anomeda.DataFrame and provide a custom mapping to discretize measure values. This is useful for defining custom ranges for discrete values. ```python anomeda.DataFrame( pandas_df, measures_names=['A', 'B', 'C'], metric_name='my_metric', discretized_measures_mapping={ 'A': { 0: [[20, 80]], # map values from 20 to 80 to 0 - "normal values" 1: [[0, 20], [80, 100]], # map values from 0 and 20 or between 80 and 100 to 1 - "abnormal values" } } ) ``` -------------------------------- ### DataFrame Constructor Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Initializes an Anomeda DataFrame object. It accepts arguments for a pandas.DataFrame and specific Anomeda parameters for measures, types, discretization, index, metric, and aggregation. ```APIDOC ## DataFrame Constructor ### Description Initializes an Anomeda DataFrame object. It accepts arguments for a pandas.DataFrame and specific Anomeda parameters for measures, types, discretization, index, metric, and aggregation. ### Parameters #### Initialization Parameters - **`*args`** – Parameters for initializing a pandas.DataFrame object. - **`**kwargs`** – Parameters for initializing a pandas.DataFrame object. #### Anomeda Specific Parameters - **`measures_names`** (list | tuple, optional) – A list containing columns considered as measures. Defaults to []. - **`measures_types`** (dict, optional) – A dictionary containing 'categorical' and/or 'continuous' keys with lists of measures as values. Defaults to {}. - **`discretized_measures_mapping`** (dict, optional) – Custom dictionary with a mapping between a discrete value of the measure and corresponding continuous ranges. Defaults to {}. - **`discretized_measures`** (dict, optional) – A dictionary containing names of the measures as keys and array-like objects containing customly discretized values of the measure. Defaults to {}. - **`index_name`** (str | list | None, optional) – An index column containing Integer or pandas.DatetimeIndex. Defaults to None. - **`metric_name`** (str) – A metric column. - **`agg_func`** – Way of aggregating metric_name by measures. Can be 'sum', 'avg', 'count' or a callable compatible with pandas.DataFrame.groupby. ### Request Example ```python anmd_df = anomeda.DataFrame( df, measures_names=['dummy_measure_col', 'dummy_numeric_measure_col'], measures_types={ 'categorical': ['dummy_measure_col'], 'continuous': ['dummy_numeric_measure_col'] }, index_name='dt', metric_name='metric_col', agg_func='sum' ) ``` ``` -------------------------------- ### Commit Changes Source: https://anomeda.readthedocs.io/en/latest Commit your code changes with a descriptive message. This is a standard Git command. ```bash git commit -m "Foo the bars" ``` -------------------------------- ### Fit Trends and Plot Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Fit time series trends using `anomeda.fit_trends` and then visualize these trends with `anomeda.plot_trends`. Ensure the data is prepared before fitting. ```python >>> anomeda.fit_trends(data) >>> anomeda.plot_trends(data) ``` -------------------------------- ### Fit Time Series Trends Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Use this snippet to fit trends for time series data. It allows configuration of trend fitting parameters, breakdowns, metric propagation, cluster sizes, plotting, and return format. The trends are stored in the `_trends` attribute if `save_trends` is True. ```python >>> fitted_trends = anomeda.fit_trends( data, trend_fitting_conf={'max_trends': 3}, breakdowns='all', metric_propagate='zeros', min_cluster_size=3, plot=True, df=True ) ``` -------------------------------- ### Push Changes to Fork Source: https://anomeda.readthedocs.io/en/latest Push your committed changes to your fork on GitHub. This makes your branch available for creating a pull request. ```bash git push origin HEAD ``` -------------------------------- ### get_discretization_mapping Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Provides a dictionary mapping discrete values to the actual ranges of continuous measures. This is helpful for understanding how continuous data is categorized. ```APIDOC ## get_discretization_mapping ### Description Returns a dict with a mapping between discrete values and actual ranges of continuous measures. ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ### Parameters None ### Response - **dict**: A dictionary where keys are discrete values and values are lists of intervals representing continuous ranges. Example: ```json { "dummy_numeric_measure": { 0: [[0.08506988648110014, 0.982366623262143]], # [[inc, exl)] 1: [[0.9855150328648835, 2.458970726947438]] # [[inc, exl)] } } ``` ``` -------------------------------- ### Compare Clusters Between Time Periods Source: https://anomeda.readthedocs.io/en/latest Compare the characteristics of clusters between two defined time periods. This is useful for identifying changes or anomalies in specific segments of your data over time. ```python anomeda.compare_clusters( anomeda_df, period1='date < "2024-01-30"', period2='date >= "2024-01-30"' ) ``` -------------------------------- ### compare_clusters Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Compares metric values for two specified periods, identifying clusters that may explain differences in overall metric behavior. Returns a pandas DataFrame with cluster descriptions for each period. ```APIDOC ## compare_clusters ### Description Compares metric values for two specified periods, identifying clusters that may explain differences in overall metric behavior. Returns a pandas DataFrame with cluster descriptions for each period. ### Method `compare_clusters(data: anomeda.DataFrame, period1: str, period2: str, breakdowns: 'no' | 'all' | list[str] | list[list[str]] = 'no')` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **`data`** (`DataFrame`) – Object containing data to be analyzed * **`period1`** (`str`) – Query to filter the first period. For example, 'dt < 10'. * **`period2`** (`str`) – Query to filter the second period. For example, 'dt >= 10'. * **`breakdowns`** (`no | all | list[str] | list[list[str]]`, default: `'no'`) – If 'no', the metric is grouped by date points only. If 'all', all combinations of measures are used to extract and plot clusters. If list[str], then only specific clusters specified in the list are plotted. If list[list[str]] then each internal list is a list of measures used to extract clusters. ### Returns * **`output`** (`DataFrame`) – Object describing the clusters and the changes in the metric behavior between them. ### Request Example ```python anomeda.compare_clusters( data, period1='dt < 10', period2='dt >= 10', breakdowns='no' ) ``` ``` -------------------------------- ### Set Discretized Measures Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Applies custom discretization to continuous measures by providing a dictionary of discrete values. The array of values for each measure must match the original measure's shape. ```python set_discretized_measures(discretized_measures: dict) ``` -------------------------------- ### Compare Clusters using Anomeda Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Use this function to compare metric values between two distinct periods. It helps identify clusters responsible for metric differences. Ensure your data is in an Anomeda DataFrame format. ```python anomeda.compare_clusters( data, period1='dt < 10', period2='dt >= 10', breakdowns='no' ) ``` -------------------------------- ### Copy Anomeda DataFrame Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Returns a copy of the current anomeda.DataFrame object. ```python copy_anomeda_df() ``` -------------------------------- ### Set Discretization Mapping Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Defines custom thresholds for discretizing measures. The mapping specifies ranges of continuous values that correspond to discrete values. Lower bounds are inclusive, and upper bounds are exclusive. ```python set_discretization_mapping(discretized_measures_mapping, recalculate_measures=True) ``` ```python anmd_df.set_discretization_mapping({ 'dummy_numeric_measure': { 0: [[0.00, 0.05001], [0.95, 1.001]], # may correspond to "extreme" values; 0.05 are 1. are excluding bounds 1: [[0.5, 0.94999]] # may correspond to "normal" values; 94999 is an excluding bound } }) ``` -------------------------------- ### Plot Clusters with Specific Criteria Source: https://anomeda.readthedocs.io/en/latest/usage_guide This snippet demonstrates how to plot clusters based on specific criteria, such as filtering for a particular country. Ensure an Anomeda DataFrame is available. ```python anomeda.plot_clusters(anomeda_df, clusters=['`country`=="Germany"']) ``` -------------------------------- ### Plot Trends for a Specific Cluster Source: https://anomeda.readthedocs.io/en/latest Visualize the fitted trends for a specific cluster using the plot_trends method. This helps in understanding the patterns identified by Anomeda. ```python anomeda.plot_trends(anomeda_df, clusters=['`country`=="Germany"']) ``` -------------------------------- ### Fit Trends to Data Source: https://anomeda.readthedocs.io/en/latest Fit trends to the Anomeda DataFrame to extract important patterns. Configure trend fitting with options like maximum trends, minimum variance reduction, breakdown scope, metric propagation, and minimum cluster size. ```python trends = anomeda.fit_trends( anomeda_df, trend_fitting_conf={'max_trends': 'auto', 'min_var_reduction': 0.75}, # set the number of trends automatically, # try to reduce error variance compared to error of estimating values by 1-line trend by 75% breakdown='all-clusters', # fit trends for clusters extracted from all possible sets of measures metric_propagate='zeros', # if some index values are missed after aggregation for a cluster, fill them with zeros min_cluster_size=3 # skip small clusters, they all will be combined into 'skipped' cluster ) ``` -------------------------------- ### Find Point Anomalies Source: https://anomeda.readthedocs.io/en/latest Detect point anomalies within the data using specified anomaly detection configurations. This helps in identifying unusual individual data points that deviate from the expected patterns. ```python anomeda.find_anomalies( anomeda_df, anomalies_conf: {'p_large': 1, 'p_low': 1, 'n_neighbors': 3} ) ``` -------------------------------- ### Plot Clusters Directly Source: https://anomeda.readthedocs.io/en/latest Quickly plot clusters without fitting trends, useful for a brief look at data segmentation. This method is simpler than fitting trends when detailed pattern analysis is not immediately required. ```python anomeda.plot_clusters(anomeda_df, clusters=['`country`=="Germany"']) ``` -------------------------------- ### copy_anomeda_df Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Returns a copy of an anomeda.DataFrame object. This is useful for creating independent copies of your data to perform operations without affecting the original DataFrame. ```APIDOC ## copy_anomeda_df ### Description Returns a copy of an anomeda.DataFrame object. ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ### Parameters None ### Response - **anomeda.DataFrame**: A new DataFrame object that is a copy of the original. ``` -------------------------------- ### Plot Clusters with Specific Breakdowns Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Use this snippet to plot clusters extracted using specific measures or combinations of measures. Ensure the 'data' object is an anomeda.DataFrame instance. ```python anomeda.plot_clusters( data, # anomeda.DataFrame breakdowns=[['measure_a'], ['measure_a', 'measure_b']] # plot clusters extracted using measure_a and a combination of measure_a and measure_b ) ``` -------------------------------- ### replace_df Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Replaces the content of the underlying pandas.DataFrame within the anomeda.DataFrame. Allows for in-place replacement or creation of a new DataFrame. ```APIDOC ## replace_df ### Description Replace the pandas.DataFrame content, underlying the anomeda.DataFrame, with a new one. ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (DataFrame) - Required - A new data object. - **inplace** (bool) - Optional - If True, then no new object will be returned. Defaults to False. - **keep_clusters** (bool) - Optional - Defaults to False. - **keep_trends** (bool) - Optional - Defaults to False. - **keep_discretization** (bool) - Optional - Defaults to False. ### Response - **anomeda.DataFrame**: A new anomeda.DataFrame object if `inplace` is False, otherwise None. ``` -------------------------------- ### set_discretization_mapping Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Sets custom thresholds for discretizing measures. It allows defining specific continuous value ranges that map to discrete values. ```APIDOC ## set_discretization_mapping ### Description Sets custom thresholds for discretization of measures. Allows mapping specific continuous value ranges to discrete values. ### Method ``` set_discretization_mapping(discretized_measures_mapping, recalculate_measures=True) ``` ### Parameters #### Path Parameters None #### Query Parameters * **`recalculate_measures`** (boolean) - Optional - Whether to recalculate measures after setting the mapping. #### Request Body * **`discretized_measures_mapping`** (dict) - Required - A dictionary mapping measure names to their discrete value mappings. The format is {'measure_name': {discrete_value: [[continuous_threshold_min_inc, continuous_threshold_max_excl], ...], ...}}. ### Request Example ```json { "example": "anmd_df.set_discretization_mapping({\"dummy_numeric_measure\": {0: [[0.00, 0.05001], [0.95, 1.001]], 1: [[0.5, 0.94999]]}})" } ``` ### Response #### Success Response (200) None explicitly documented. #### Response Example None explicitly documented. ``` -------------------------------- ### Set Measure Names in Anomeda DataFrame Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Inform the Anomeda DataFrame which columns should be treated as measures. These columns must exist in the underlying pandas DataFrame. ```python set_measures_names(measures_names) ``` -------------------------------- ### Set Aggregation Function Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Sets the aggregation function for metrics. Accepts 'sum', 'avg', 'count', or a pandas.DataFrame.groupby compatible callable. ```python set_agg_func(agg_func) ``` -------------------------------- ### find_anomalies Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Finds metric anomalies by identifying extreme changes in metric values compared to fitted trends. This method can analyze data directly or use pre-fitted trends. ```APIDOC ## find_anomalies ### Description Finds metric anomalies by looking for the most extreme metric changes. The method finds differences between real metric and a fitted trends, find points with extreme differences and marks them as anomalies. You can find anomalies for automatically extracted clusters only if passing an anomeda.DataFrame. ### Method `find_anomalies` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **`data`**(`DataFrame | (ndarray[int], ndarray[float])`) – Object containing metric values to be analyzed. Trends must be fitted for the object with anomeda.fit_trends() method if anomeda.DataFrame is passed. * **`breakdowns`**(`no | all | list[str] | list[list[str]]` , default: `'no'` ) – If 'no', the metric is grouped by date points only. If 'all', all combinations of measures are used to extract and plot clusters. If list[str], then only specific clusters specified in the list are plotted. If list[list[str]] then each internal list is a list of measures used to extract clusters. * **`anomalies_conf`**(`dict` , default: `{'p_large': 1., 'p_low': 1., 'n_neighbors': 3}` ) – Dict containing 'p_large' and 'p_low' values. Both are float values between 0 and 1 corresponding to the % of the anomalies with largest and lowest metric values to be returned. For example, if you set 'p_low' to 0, no points with abnormally low metric values will be returned; if 0.5, then 50% of points with abnormally values will be returned, etc. If some of the keys is not present or None, 1 is assumed. 'n_neighbors' means number of neighbors parameter for sklearn.neighbors.LocalOutlierFactor class. The class is used to find points with abnormally large MAE. The more the parameter, typically, the less sensitive the model to anomalies. * **`return_all_points`**(`bool` , default: `False` ) – If False, only anomaly points are returned. If True, all points with anomalies marks are returned. Default False. * **`trend_fitting_conf`**(`dict` , default: `None` ) – Used only if data is not anomeda.DataFrame, but numpy arrays, to run anomeda.fit_trends method for them. Parameters are similar to those you would pass to the argument anomeda.fit_trends(..., trend_fitting_conf=...). ### Returns * **`res`**(`DataFrame` ) – A DataFrame containing fields 'cluster', 'index', 'metric_value', 'fitted_trend_value', 'anomaly'. ### Examples: ```python >>> anomeda.fit_trends(data) >>> anomeda.find_anomalies(data) ``` ``` -------------------------------- ### anomeda.fit_trends Source: https://anomeda.readthedocs.io/en/latest/usage_guide Fits trends in time-series data, allowing for automatic identification of trend changes and plotting of these trends. The fitted trends are stored in the `anomeda.DataFrame._trends` attribute. ```APIDOC ## anomeda.fit_trends ### Description Fits trends in time-series data, allowing for automatic identification of trend changes and plotting of these trends. The fitted trends are stored in the `anomeda.DataFrame._trends` attribute. ### Method `anomeda.fit_trends` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **`data`** (`DataFrame | (ndarray[int], ndarray[float]) | (DatetimeIndex, ndarray[float])`) – Object containing metric values. If numpy.ndarray, a tuple of arrays corresponding to x (data points) and y (metric values) respectively. * **`trend_fitting_conf`** (`dict`, default: `{'max_trends': 'auto', 'min_var_reduction': 0.75}`) – Parameters for calling `anomeda.extract_trends()` function. It consists of 'max_trends' parameter, which is responsible for the maximum number of trends that you want to identify, and 'min_var_reduction' parameter, which describes what part of variance must be reduced by estimating trends. Values close to 1 will produce more trends since more trends reduce variance more signigicantly. Default is `{'max_trends': 'auto', 'min_var_reduction': 0.75}`. * **`save_trends`** (`bool`, default: `True`) – If False, return pandas.DataFrame with trends description without assigning it to the `anomeda.DataFrame._trends`. * **`breakdowns`** (`'no' | 'all' | list[str]`, default: `'no'`) – If 'no', the metric is grouped by date points only. If 'all', all combinations of measures are used to extract and plot clusters. If list[str], then only specific clusters specified in the list are plotted. If list[list[str]] then each internal list is a list of measures used to extract clusters. * **`metric_propagate`** (`'"zeros" | "ffil" | None'`, default: `None`) – How to propogate aggregated time-series for missing index values. - zeros: Let metric for missing index be equal 0. For example, aggregated metric values '2024-01-01': 1 '2024-01-03': 2 Will be propagated as '2024-01-01': 1 '2024-01-02': 0 '2024-01-03': 2 - ffil: Let metric for missing index be equal the last observed value. For example, aggregated metric values '2024-01-01': 1 '2024-01-03': 2 Will be propagated as '2024-01-01': 1 '2024-01-02': 1 '2024-01-03': 2 - None: Use only present metric and index values. * **`min_cluster_size`** (`int`, default: `None`) – Skip clusters whose total size among all date points is less than the value. * **`max_cluster_size`** (`int`, default: `None`) – Skip clusters whose total size among all date points is more than the value. * **`plot`** (`bool`, default: `False`) – Indicator if to plot fitted trends. `anomeda.plot_trends` is responsibe for plotting if the flag is True. * **`df`** (`bool`, default: `True`) – Indicator if to return a pandas.DataFrame containing fitted trends. * **`verbose`** (`bool`, default: `False`) – Indicator if to print additional output. ### Request Example ```python fitted_trends = anomeda.fit_trends( data, trend_fitting_conf={'max_trends': 3}, breakdowns='all', metric_propagate='zeros', min_cluster_size=3, plot=True, df=True ) ``` ### Response #### Success Response (200) * **`resp`** (`DataFrame`) – An object containing information about trends #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### plot_trends Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Plots fitted trends using data from an Anomeda DataFrame or the output of anomeda.fit_trends(). Allows for various breakdown configurations and customization of metric display and plot axes. ```APIDOC ## plot_trends ### Description Plots fitted trends using data from an Anomeda DataFrame or the output of anomeda.fit_trends(). Allows for various breakdown configurations and customization of metric display and plot axes. ### Method `plot_trends` ### Parameters * **`data`** (`anomeda.DataFrame | pandas.DataFrame returned from anomeda.fit_trends()`): Object containing trends to be plotted. * **`breakdowns`** (`'no' | 'all' | list[str] | list[list[str]]`, default: `'no'`): Controls how trends are grouped and plotted. If 'no', only date points are used. If 'all', all combinations of measures are used. If a list of strings, only specified clusters are plotted. If a list of lists of strings, each inner list defines measures for cluster extraction. * **`show_metric`** (`bool`, default: `True`): Indicator if to show the actual metric on plots. * **`colors`** (`dict`, default: `None`): A dictionary to specify custom colors for the plot. * **`ax`** (`matplotlib.axes.Axes`, default: `None`): The Axes object to use for plotting. If None, a new Axes is created. ### Returns * `None` ### Examples: ```python >>> anomeda.fit_trends(data) >>> anomeda.plot_trends(data) ``` ``` -------------------------------- ### Plot Clusters Grouped by Index Only Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Use this snippet to plot a metric grouped solely by index values. The 'data' parameter should be an anomeda.DataFrame. ```python anomeda.plot_clusters( data, # anomeda.DataFrame breakdowns='no' # plot a metric grouped by index values only ) ``` -------------------------------- ### extract_trends Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Fits and returns automatically determined linear trends for given time-series data (X and Y). This method can identify multiple trends if the metric's behavior changes significantly, controlled by `max_trends` and `min_var_reduction` parameters. ```APIDOC ## extract_trends ### Description Fits and returns automatically determined linear trends for given time-series data (X and Y). This method can identify multiple trends if the metric's behavior changes significantly, controlled by `max_trends` and `min_var_reduction` parameters. ### Method `extract_trends(x: numpy.ndarray[int] | pandas.DatetimeIndex, y: numpy.ndarray[float], freq: 'frequency unit for pandas.DatetimeIndex' = None, propagation_strategy: 'zeros' | 'ffil' | None = None, max_trends: int | 'auto' = 'auto', min_var_reduction: float[0, 1] | None = 0.5, verbose: bool = False)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **`x`** (`ndarray[int] | DatetimeIndex`) – Indices corresponding to time points. Must be an increasing array of integers. Some of the values may be omitted, e.g such x is OK: [0, 1, 5, 10]. * **`y`** (`ndarray[float]`) – Metric values corresponding to time points. * **`freq`** (`'frequency unit for pandas.DatetimeIndex'`, optional) – Frequency unit for pandas.DatetimeIndex. * **`propagation_strategy`** (`'"zeros" | "ffil" | None'`, optional, default: `None`) – How to propagate aggregated time-series for missing index values. - `zeros`: Let metric for missing index be equal 0. - `ffil`: Let metric for missing index be equal the last observed value. - `None`: Use only present metric and index values. * **`max_trends`** (`int | auto`, optional, default: `'auto'`) – Number of trends to extract. If int, the method extracts defined amount of trends or less. Less trends may be extracted if no more trends were found or if the `min_var_reduction` is reached. If `'auto'`, the method defines the number of trends automatically using `min_var_reduction` parameter. * **`min_var_reduction`** (`float[0, 1] | None`, optional, default: `0.5`) – % of the variance of approximation error that must be reduced by adding trends comparing to the variance of the initial approximation with one trend. Values closer to 1 will cause extracting more trends. Values closer to 0 will cause producing less trends. If `max_trends` is set and reached, the extraction finishes regardless the value of the variance. If `None`, then not used. * **`verbose`** (`bool`, optional, default: `False`) – If to produce more logs. ### Returns * **`trends`** (`dict`) – Dict contains the extracted trends in the format `{ trend_id: (xmin_inc, xmax_exc, (trend_slope, trend_intersept), (n_samples, metric_mean, mae, metric_sum)), ... }` ### Request Example ```python >>> import numpy as np >>> x = np.array([0, 1, 4, 5]) >>> y = np.array([11.2, 10.4, 3.4, 3.1]) >>> anomeda.extract_trends(x, y, max_trends=2) { 0: (0, 4, (-0.7999999999999989, 11.2), (2, 10.8, 0.0, 21.6)), # trend 1, for date points from 0 (inc) to 4 (excl) # with slope -0.79 and intercept 11.2 # consisting of 2 samples, # metric mean over date points is 10.8, # mae for fitting trend over date points is 0.0 # sum for all metric values is 21.6 1: (4, 6, (-0.2999999999999998, 4.6), (2, 3.25, 0.0, 6.5)) } ``` ``` -------------------------------- ### Set Metric Name in Anomeda DataFrame Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Specify the primary metric column for analysis. This column must be present in the underlying pandas DataFrame. If the intended metric is currently listed as a measure, it must be removed from the measures list first. ```python set_metric_name(metric_name) ``` -------------------------------- ### fit_trends Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Fits trends for a given time series dataset. This function can process data from an Anomeda DataFrame or NumPy arrays and allows for various configurations related to trend identification, breakdown analysis, and data propagation. ```APIDOC ## fit_trends ### Description Fit trends for a time series using the data from an anomeda.DataFrame or a numpy.ndarray with metric values. Trends can be fitted for automatically extracted clusters when passing an anomeda.DataFrame. If an anomeda.DataFrame is passed and `save_trends` is True, the trends are stored in the `anomeda.DataFrame._trends` attribute. ### Method fit_trends ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **`data`** (`DataFrame | (ndarray[int], ndarray[float]) | (DatetimeIndex, ndarray[float])`) – Object containing metric values. If numpy.ndarray, a tuple of arrays corresponding to x (data points) and y (metric values) respectively. * **`trend_fitting_conf`** (`dict` , default: `{'max_trends': 'auto', 'min_var_reduction': 0.75}` ) – Parameters for calling `anomeda.extract_trends()` function. It consists of 'max_trends' parameter, which is responsible for the maximum number of trends that you want to identify, and 'min_var_reduction' parameter, which describes what part of variance must be reduced by estimating trends. Values close to 1 will produce more trends since more trends reduce variance more signigicantly. * **`save_trends`** (`bool` , default: `True` ) – If False, return pandas.DataFrame with trends description without assigning it to the `anomeda.DataFrame._trends`. * **`breakdowns`** (`'no' | 'all' | list[str] | list[list[str]]` , default: `'no'` ) – If 'no', the metric is grouped by date points only. If 'all', all combinations of measures are used to extract and plot clusters. If list[str], then only specific clusters specified in the list are plotted. If list[list[str]] then each internal list is a list of measures used to extract clusters. * **`metric_propagate`** (`'zeros' | 'ffil' | None` , default: `None` ) – How to propogate aggregated time-series for missing index values. - zeros: Let metric for missing index be equal 0. - ffil: Let metric for missing index be equal the last observed value. - None: Use only present metric and index values. * **`min_cluster_size`** (`int` , default: `None` ) – Skip clusters whose total size among all date points is less than the value. * **`max_cluster_size`** (`int` , default: `None` ) – Skip clusters whose total size among all date points is more than the value. * **`plot`** (`bool` , default: `False` ) – Indicator if to plot fitted trends. `anomeda.plot_trends` is responsibe for plotting if the flag is True. * **`df`** (`bool` , default: `True` ) – Indicator if to return a pandas.DataFrame containing fitted trends. * **`verbose`** (`bool` , default: `False` ) – Indicator if to print additional output. ### Request Example ```python fitted_trends = anomeda.fit_trends( data, trend_fitting_conf={'max_trends': 3}, breakdowns='all', metric_propagate='zeros', min_cluster_size=3, plot=True, df=True ) ``` ### Response #### Success Response (200) * **`resp`** (`DataFrame`) – An object containing information about trends #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Extracting Linear Trends Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Use `extract_trends` to fit and return automatically determined linear trends for given time-series data. This function is useful for identifying significant changes in metric behavior over time. Ensure you have numpy and pandas imported for array and DatetimeIndex handling. ```python import numpy as np import pandas as pd def extract_trends(x: numpy.ndarray[int] | pandas.DatetimeIndex, y: numpy.ndarray[float], freq: 'frequency unit for pandas.DatetimeIndex' = None, propagation_strategy: 'zeros' | 'ffil' | None = None, max_trends: int | 'auto' = 'auto', min_var_reduction: float[0, 1] | None = 0.5, verbose: bool = False) ``` ``` ```python >>> x = np.array([0, 1, 4, 5]) >>> y = np.array([11.2, 10.4, 3.4, 3.1]) >>> anomeda.extract_trends(x, y, max_trends=2) { 0: (0, 4, (-0.7999999999999989, 11.2), (2, 10.8, 0.0, 21.6)), # trend 1, for date points from 0 (inc) to 4 (excl) # with slope -0.79 and intercept 11.2 # consisting of 2 samples, # metric mean over date points is 10.8, # mae for fitting trend over date points is 0.0 # sum for all metric values is 21.6 1: (4, 6, (-0.2999999999999998, 4.6), (2, 3.25, 0.0, 6.5)) } ``` -------------------------------- ### plot_clusters Source: https://anomeda.readthedocs.io/en/latest/anomeda_api Plots metric data grouped into clusters. This function allows for flexible visualization of time-series data based on various clustering and breakdown configurations. ```APIDOC ## plot_clusters ### Description Plots metric extracted from clusters from anomeda.DataFrame instance. ### Method `plot_clusters` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **`data`** (`DataFrame`) – Required - Object containing clusters to be plotted. - **`breakdowns`** (`'no' | 'all' | list[str] | list[list[str]]`) – Optional - If 'no', the metric is grouped by date points only. If 'all', all combinations of measures are used to extract and plot clusters. If list[str], then only specific clusters specified in the list are plotted. If list[list[str]] then each internal list is a list of measures used to extract clusters. Defaults to 'no'. - **`metric_propagate`** (`'zeros' | 'ffil' | None`) – Optional - How to propagate aggregated time-series for missing index values. Defaults to None. - **`min_cluster_size`** (`int`) – Optional - Skip clusters whose total size among all date points is less than the value. - **`max_cluster_size`** (`int`) – Optional - Skip clusters whose total size among all date points is more than the value. - **`colors`** (`dict`) – Optional - Dictionary with a mapping between clusters and colors used in matplotlib. - **`ax`** (`Axes`) – Optional - Axes to use for plotting. If None, a new object is created. ### Request Example ```python anomeda.plot_clusters( data, # anomeda.DataFrame breakdowns=[['measure_a'], ['measure_a', 'measure_b']] # plot clusters extracted using measure_a and a combination of measure_a and measure_b ) ``` ```python anomeda.plot_clusters( data, # anomeda.DataFrame breakdowns=['measure_a==1', 'measure_a == 1 and measure_b == 2'] # plot two specified clusters ) ``` ```python anomeda.plot_clusters( data, # anomeda.DataFrame breakdowns='no' # plot a metric grouped by index values only ) ``` ### Response #### Success Response (None) Returns None. #### Response Example None ``` -------------------------------- ### Replace DataFrame Content Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Replaces the underlying pandas.DataFrame of an anomeda.DataFrame. Use `inplace=True` to modify the object directly without returning a new one. ```python replace_df(data: pandas.DataFrame, inplace=False, keep_clusters: bool = False, keep_trends: bool = False, keep_discretization: bool = False) ``` -------------------------------- ### Set Measure Types in Anomeda DataFrame Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Define whether measures are 'categorical' or 'continuous'. This is essential for proper data clustering and analysis. The input is a dictionary mapping type to a list of measure names. ```python anmd_df.set_measures_types({ 'continous': ['numeric_measure_1'], 'categorical': ['measure_1'] }) ``` -------------------------------- ### set_metric_name Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Sets the name of the metric to be analyzed. The specified metric name must be present in the underlying pandas.DataFrame columns. ```APIDOC ## set_metric_name ### Description Sets the name of the metric to be analyzed. The specified metric name must be present in the underlying pandas.DataFrame columns. If the metric column is currently set as a measure, you need to change the list of measures first. ### Method ``` set_metric_name(metric_name) ``` ### Parameters #### Path Parameters - **metric_name** (str) - Required - Must be present among columns of an underlying pandas.DataFrame. ``` -------------------------------- ### set_agg_func Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Sets the aggregation function to be used for metrics. This function can be a predefined string like 'sum', 'avg', or 'count', or a custom callable compatible with pandas.DataFrame.groupby. ```APIDOC ## set_agg_func ### Description Sets a function to aggregate the metric by measures. This can be a string ('sum', 'avg', 'count') or a pandas-compatible callable. ### Method ``` set_agg_func(agg_func) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **`agg_func`** (string or callable) - The aggregation function to use. ``` -------------------------------- ### anomeda.plot_clusters Source: https://anomeda.readthedocs.io/en/latest/usage_guide Plots clusters from an Anomeda DataFrame, allowing for filtering by specific cluster conditions. ```APIDOC ## anomeda.plot_clusters ### Description Plots clusters from an Anomeda DataFrame, allowing for filtering by specific cluster conditions. ### Method `anomeda.plot_clusters` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **`anomeda_df`** (DataFrame) – The Anomeda DataFrame containing the data. * **`clusters`** (list[str]) – A list of strings specifying the clusters to plot. For example: `['`country`=="Germany"']`. ### Request Example ```python anomeda.plot_clusters(anomeda_df, clusters=['`country`=="Germany"']) ``` ### Response This method does not return a value, but displays a plot. #### Success Response (200) None #### Response Example None ``` -------------------------------- ### get_measures_types Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Retrieves the dictionary that defines the types of the measures. This provides insight into the data types and characteristics of measure columns. ```APIDOC ## get_measures_types ### Description Returns the measures_types dict. ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ### Parameters None ### Response - **dict**: A dictionary containing the types of the measures. ``` -------------------------------- ### get_measures_names Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Returns a list of column names that are considered measures within the DataFrame. This helps in identifying which columns hold quantitative data. ```APIDOC ## get_measures_names ### Description Returns a list of columns considered as measures. ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ### Parameters None ### Response - **list**: A list of strings, where each string is the name of a measure column. ``` -------------------------------- ### set_measures_names Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Informs the anomeda.DataFrame object about which columns represent measures. These columns must exist in the underlying pandas.DataFrame. ```APIDOC ## set_measures_names ### Description Informs the anomeda.DataFrame object about which columns represent measures. These columns must exist in the underlying pandas.DataFrame. ### Method ``` set_measures_names(measures_names) ``` ### Parameters #### Path Parameters - **measures_names** (list of str) - Required - List containing columns which will be considered as measures ``` -------------------------------- ### get_discretized_measures Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Returns discretized versions of continuous measures. This method transforms continuous data into discrete categories. ```APIDOC ## get_discretized_measures ### Description Returns discretized versions of continuous measures. ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ### Parameters None ### Response - **DataFrame**: A DataFrame containing the discretized measures. ``` -------------------------------- ### get_agg_func Source: https://anomeda.readthedocs.io/en/latest/dataframe_api Retrieves the aggregation function used for metrics by measures. This function is crucial for understanding how data is aggregated within the Anomeda DataFrame. ```APIDOC ## get_agg_func ### Description Returns the function used to aggregate the metric by measures. ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ### Parameters None ### Response - **function**: The aggregation function used for metrics. ```