# ---
# 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
# ---

# + [markdown] id="s8bciTgq-ZDr"
# # Human Activity Recognition from Wearable Inertial Sensor Networks Part 2

# + colab={"base_uri": "https://localhost:8080/"} id="Aqxr_F---pHr" outputId="f5ebc957-52ad-49d9-9d40-5fb2cdc87779"
from google.colab import drive
drive.mount('/content/drive')

# + [markdown] id="_8pEwRqb-ZDy"
# # Table of Contents
#  
# - [Import library and define visualization parameters](#Import-library-and-define-visualization-parameters)
# - [Declaration of functions used](#Declaration-of-functions-used)
# - [Import data](#Import-data)
# - [Feature engineering](#Feature-engineering)
# - [Save data in pickle format in google drive](#Save-data-in-pickle-format-in-google-drive)

# + [markdown] id="8wqRyh88-ZD0"
# # Import library and define visualization parameters

# + id="cQ3JtcQ1-ZD1"
from __future__ import print_function
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
from matplotlib import cm
# %matplotlib inline
from math import pi
import numpy as np
import pandas as pd
from pandas import DataFrame
from typing import List
import seaborn as sns
from scipy import stats

from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder

import warnings 
warnings.filterwarnings('ignore')

# Display several outputs on a notebook output
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

# + id="I82GAHQz-ZD5"
# Define certain standard parameters at the outset
pd.options.display.float_format = '{: .4f}'. format
np.set_printoptions(precision=4)
plt.style.use ('ggplot')
# Files
path_to_file = '/content/drive/MyDrive/myproject/outputdata'


# + [markdown] id="JYbZyeQS-ZD6"
# # Declaration of functions used

# + id="5OvNLkix8t-7"
def mad(x):
  mad = x.mad()
  return mad


# + id="vsgzSpwV_vMn"
def ran(x):
  range = x.max() - x.min()
  return range


# + id="y8mui9fA_5w0"
# Define a function to compute acceleration spherical coordinates
def add_accelero_spherical_coordinates(df:DataFrame) -> DataFrame:
  """Generate normal acceleration, colalitude and longitude from imu data.

  Args:
    df (DataFrame): IMU data required!

  Returns:
    DataFrame: The IMU DataFrame with normal acceleration, colalitude and longitude.
  """

  df['acc_norm'] = np.sqrt((df.acc_rf_x)**2 + (df.acc_rf_y)**2 + (df.acc_rf_z)**2)
  df["colat_acc"] = np.arccos(df["acc_rf_z"]/df["acc_norm"])
  df["long_acc"] = np.arctan2(df["acc_rf_y"],df["acc_rf_x"])

  return df


# + id="VAVnrPkL_8RB"
# Define a function to compute gyrometer spherical coordinates
def add_gyro_spherical_coordinates(df:DataFrame) -> DataFrame:
  """Generate normal gyrometer, colalitude and longitude from imu data.

  Args:
    df (DataFrame): IMU data required!

  Returns:
    DataFrame: The IMU DataFrame with normal gyrometer, colalitude and longitude.
  """
  
  df['gyro_norm'] = np.sqrt((df.gyro_rf_x)**2 + (df.gyro_rf_y)**2 + (df.gyro_rf_z)**2)
  df["colat_gyro"] = np.arccos(df["gyro_rf_z"]/df["gyro_norm"])
  df["long_gyro"] = np.arctan2(df["gyro_rf_y"],df["gyro_rf_x"])

  return df


# + id="sgtk36EbABGb"
def add_group_index(df:DataFrame, windows:int=3) -> DataFrame:
  """Generate group index with specific windows for data aggregation.

  Args:
    df (DataFrame): raw data required!
    windows (int, default value is 5 s): The aggregation window.

  Returns:
    DataFrame: The raw DataFrame containing group index for aggregration.
  """

  sample_size = int((679073/11544)*windows)
  index = df.index.tolist()
  group_index = np.cumsum([(id % sample_size) == 0 for id in index]).tolist()
  df['group_index'] = group_index

  return df


# + id="9zPEcnNYAD3L"
def compute_features_stats(df:DataFrame, features_to_stats:List[str] = None) -> DataFrame:
  """Generates the aggregated dataframe with the different statistics on the given variables.

  Args:
    df (DataFrame): The raw DataFrame containing group index for aggregration.
    features_to_stats (List): List of variables whose statistics you want to display after aggregation.

  Returns:
    DataFrame: The aggregated dataframe with the different statistics on the input variables.
  """

  stats_agg = [np.min, np.max, np.mean, np.median, np.std, stats.skew, stats.kurtosis, stats.iqr, stats.median_absolute_deviation, mad, ran]
  dict_agg = {var:stats_agg for var in features_to_stats}
  df_agg = df.groupby(['act','group_index', 'filename']).agg(dict_agg)
  df_agg.columns = ["_".join(x) for x in df_agg.columns.ravel()]
  df_agg = df_agg.reset_index(['act', 'group_index', 'filename'])
  df_agg = df_agg.drop('group_index', axis=1)
  df_agg = df_agg.sort_values("filename")
  df_agg = df_agg.interpolate(method='linear', axis=0).ffill().bfill()

  return df_agg


# + [markdown] id="mVSx5pu9-ZEA"
# # Import data

# + id="i3jrlSAL-ZEB"
# !cp /content/drive/MyDrive/myproject/outputdata/df_1.pkl /tmp/df_1.pkl

# + colab={"base_uri": "https://localhost:8080/", "height": 417} id="55TrS79u8yys" outputId="e6fb14b5-c956-42b1-aa55-25505f142998"
df = pd.read_pickle('/tmp/df_1.pkl')
df

# + [markdown] id="PSORCn7dL-aV"
# # Feature Engineering

# + [markdown] id="3lFthWg8MqEF"
# ## Acceleros and Gyros Features Engineering

# + colab={"base_uri": "https://localhost:8080/", "height": 437} id="l7luIIGgMTKY" outputId="11c8bb7a-f380-49d4-96b8-097ea66e81a5"
df = add_accelero_spherical_coordinates(df)
df = add_gyro_spherical_coordinates(df)
df

# + [markdown] id="TZ2rjKU3NkZV"
# ## Aggregate Data by time windows

# + colab={"base_uri": "https://localhost:8080/", "height": 437} id="8_01vvZwNlTW" outputId="883aff2b-1ddf-4eb0-c678-414f4da698b8"
df = add_group_index(df)
df

# + colab={"base_uri": "https://localhost:8080/"} id="E_Hi5ZgrPHCV" outputId="7f5c2b1b-218e-45d4-bf20-6e49f10842c2"
df = df.astype({"act": np.int64})
df_columns = df.columns.to_list()
features_to_stats = [columns for columns in df_columns if columns not in ('filename','activity','person','group_index','act')]
features_to_stats

# + colab={"base_uri": "https://localhost:8080/"} id="uyNSPNK5Cw6s" outputId="104ad755-e4de-473a-eba5-a55e0bb225c2"
df.dtypes

# + id="WHWQqKGKUrNO" colab={"base_uri": "https://localhost:8080/", "height": 437} outputId="af790f60-41d1-44af-cb6c-dcd99ac176bd"
df_agg = compute_features_stats(df, features_to_stats)
df_agg

# + [markdown] id="0BMRu4gHmoCj"
# # Save data in pickle format in google drive
#

# + id="kcDGYiWOmot7"
df_agg.to_pickle("/tmp/df_2.pkl")

# + id="CW3eNIzfmuq7"
# !cp /tmp/df_2.pkl /content/drive/MyDrive/myproject/outputdata

StarcoderdataJupyterScriptsDedupFiltered