# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Analysis Classes - a Unified Interface to Analysis Results
#
# MVG comes with a set of analysis classes which provide a unified interface to analysis results *irrespective of the specific feature*. Note that the analysis classes are helper classes, as such the mvg class does *not* depend on them.
#
# Except for step (1) requesting the specific feature analysis, the following generic workflow holds:
#
# 1. Request a specific analysis
# 2. Retrieve results and parse them into an analysis_class object
# 3. Use generic methods like plot(), summary() or to_df()
#
# One application is to use the analysis classes interactively from a Python REPL session.
#
# #### Or in (pseudo) code
# ```python
# result = parse_results(session.get_analysis_results(request_id))  # call API to get results
# result.plot() # plot results
# result.summary() # print summary table
# df = result.to_df() # convert to DataFrame
# result.save_pkl() # save to pickle file
# ```
#
# ### Prerequisites
# For running the examples in this notebook:
#
# 1. Installed mvg package
# 2. A token for API access from Viking Analytics
# 3. The database needs to be populated with our example assets. This can be achieved by running the ["Sources and Measurement"](2-sources_and_measurements.ipynb) example.

# ## Example flow
#
# ### Importing the required packages, classes and functions

# +
import os

from mvg import MVG, analysis_classes  # mvg library with python bindings to mvg-API
from mvg.analysis_classes import parse_results  # analysis classes
# -

# ### Create a Session and test API access
#
# Note that the `TOKEN` is used both for authorization and authentication. Thus, each unique token represents a unique user and each user has their own unique database on the Viking Analytics MultiViz Vibration service.
#
# **You need to insert your token received from Viking Analytics here:**

# + tags=["parameters"]
# Replace by your own Token
TOKEN = os.environ["TEST_TOKEN"] # use our own token
ENDPOINT = "https://api.beta.multiviz.com"
# -

session = MVG(ENDPOINT, TOKEN)
session.check_version() # Check if API is accessible

# + [markdown] pycharm={"name": "#%% md\n"}
# ###  Running the Analyses
#
# Once the API session is live, we start by checking if the source u0001 we will use is available in the database:

# + pycharm={"name": "#%%\n"}
SOURCE_ID = "u0001"
session.get_source(SOURCE_ID)

# + [markdown] pycharm={"name": "#%% md\n"}
# ### Requsting the Analysis
#
# We will now request an analysis (first two lines, uncomment one of them) and wait for the results to become available. 
#
# The results as returned will be stored in a dictionary named `raw_result`. The raw results are shown in the results cell, mainly to show that they are not optimized for readability or interpretation.

# + pycharm={"name": "#%%\n"}
# Specifc part : Select one of two anlysis here by un/commenting
selected_feature = "KPIDemo"
# selected_feature = "ModeId"

# Generic Part: request analysis and wait for results
analysis_request = session.request_analysis(SOURCE_ID, selected_feature)
print(f"Waiting for {analysis_request}")
session.wait_for_analyses([analysis_request["request_id"]])

# Generic Part: Displaying unparsed results
raw_result = session.get_analysis_results(analysis_request["request_id"])
raw_result

# + [markdown] pycharm={"name": "#%% md\n"}
# ### Showing and Browsing the results using analysis_classes
# To make the results more accessible, we'll use the analysis_classes. The parse_results function will take the raw_results of (any) analysis and represent them in a python object with a number of convenience methods for summarising, plotting and exporting. For the full list of provided methods check __[the documentation](https://vikinganalytics.github.io/mvg/content/utilities_reference/analysis_classes.html)__.
#
# The parse function will automatically determine the kind (feature) of analysis based on the raw_results.
# Once the results are parsed, we can summarize them using the summary() method *irrespective of which analysis them stem from*. To verify this you can rerun the cell above by selecting another feature for the analysis.
#
# #### Timestamps
# The Vibration API requires timestamps to be represented in EPOCH time. To display human interpertable timestamps a timezone and a time unit (specifying if the timestamps are seconds 's' or milliseconds 'ms' from EPOCH). This information can be given in the parse_results calls 2nd and 3rd argument). If they are left blank EPOCH times are kept.
# When exporting the results to a DataFrame, a column called "datetime" will be appended to show the human interpretable times.

# + pycharm={"name": "#%%\n"}
# Parse
result = parse_results(raw_result, "Europe/Stockholm", "s")
# result = parse_results(raw_result) # show only raw timestamps
# Show summary
summary = result.summary()
# -

# ### Plotting
# For visual representation of the results there is the 'plot' method:
#
# Please not that when plotting the results for the KPIDemo feature, one selects the KPI to be displayed by passing the parameter `"kpi"`. If this parameter is not included, the plot function will display the results of the first KPI after the timestamps, which is the RMS value.

# + pycharm={"name": "#%%\n"}
result.plot()

# + [markdown] pycharm={"name": "#%% md\n"}
# ### Export results to DataFrame
# The to_df() method will export results to a DataFrame. Note that the format of the DataFrame depends on the specific analysis and that not all of the results can be represented as a data frame.

# + pycharm={"name": "#%%\n"}
result.to_df()

# + [markdown] pycharm={"name": "#%% md\n"}
# ### Full results
# In case the full server results are needed in the form they were returned, we can obtain them with the results() method:

# + pycharm={"name": "#%%\n"}
result.results()
# -

# ## Black Sheep Analysis example
#
# The BlackSheep is a population analysis and has a somewhat different call signature as it requires a number of assets to be submitted to analysis.

# + pycharm={"name": "#%%\n"}
# Specific signature for BlackSheep
POPULATION_SOURCES = ["u0001","u0001","u0001","u0001","u0001","u0001","u0001","u0001","u0001","u0004","u0002","u0003","u0001"]
analysis_request = session.request_population_analysis(POPULATION_SOURCES, "BlackSheep", parameters={"atypical_threshold": 0.15})

# Generic part, same as above
print(f"Waiting for {analysis_request}")
session.wait_for_analyses([analysis_request["request_id"]])
raw_result = session.get_analysis_results(analysis_request["request_id"])
raw_result
 

# + [markdown] pycharm={"name": "#%% md\n"}
# ### Using the analysis classes
# We use exactly the same code as above to inspect the results:
# -

# Parse
blacksheep_result = analysis_classes.parse_results(raw_result, "Europe/Stockholm", "s")
# Show summary
blacksheep_result.summary()
blacksheep_result.plot()

# ### Serializing
# Finally, we can save the object including the results to pickle. If no name is given it is saved under the name `"<request_id>.pkl"`.

# + pycharm={"name": "#%%\n"}
blacksheep_result.save_pkl()

StarcoderdataJupyterScriptsDedupFiltered