{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"The function **plot_times_series** takes in a filename and several optional parameters to detect different types of events in the data and plot the acceleration values against time for each event period.\n\n* **filename**: (string) Name of the CSV file to read\n* **T**: (Boolean) To detect Turn (default is True)\n* **SH**: (Boolean) To detect start hesitation (default is False)\n* **W**: (Boolean) To detect walking (default is False)\n* **start_time**: (integer) Start time to plot from (default is 0)\n* **end_time**: (integer) End time to plot until (default is end of the file)\n* **interval**:  determines the length of time to include before and after each detected event period (default is 300)\n","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef plot_times_series(filename, T=True, SH=False, W=False, start_time=0, end_time=None, interval=300):\n    i=1\n    df = pd.read_csv(filename)\n\n    def detect_periods(df,Type):\n        # Charger le fichier CSV en tant que dataframe pandas\n        df = df\n\n        # Initialiser la liste des périodes détectées\n        turn_periods = []\n\n        # Initialiser les variables de début et de fin de période\n        period_start = None\n        period_end = None\n\n        # Parcourir chaque ligne du dataframe\n        for i, row in df.iterrows():\n            # Si la colonne \"Turn\" prend la valeur 1 pour la première fois, initialiser la période\n            if row[Type] == 1 and period_start is None:\n                period_start = row[\"Time\"]\n\n            # Si la colonne \"Turn\" prend la valeur 0 après avoir été à 1, terminer la période\n            elif row[Type] == 0 and period_start is not None:\n                period_end = row[\"Time\"] - 1  # soustraire 1 pour inclure la dernière ligne de la période\n                turn_periods.append((period_start, period_end))\n                period_start = None\n                period_end = None\n\n        # Si la dernière période n'a pas été terminée, la terminer jusqu'à la fin du dataframe\n        if period_start is not None:\n            period_end = df.iloc[-1][\"Time\"]\n            turn_periods.append((period_start, period_end))\n\n        # Retourner la liste des périodes détectées\n        return turn_periods\n\n\n    #Turn detection\n    if T == True:\n        turn_periods = detect_periods(df,Type='Turn')\n        for period in turn_periods:\n            start, end = period\n            message = f'{i}: start of the turn --> {start}, end of turn --> {end}'\n            print(message)\n            i+=1\n\n        for period in turn_periods:\n            start, end = period\n\n            if start - interval < 0:\n                start = 0\n            else:\n                start -= interval\n\n            if end + interval > df['Time'].iloc[-1]:\n                end = df['Time'].iloc[-1]\n            else:\n                end += interval\n            period_df = df[(df['Time'] >= start) & (df['Time'] <= end)]\n\n            fig, ax = plt.subplots(figsize=(12, 6))\n\n            ax.plot(period_df['Time'], period_df['AccV'], label='AccV')\n            ax.plot(period_df['Time'], period_df['AccML'], label='AccML')\n            ax.plot(period_df['Time'], period_df['AccAP'], label='AccAP')\n            ax.fill_between(period_df['Time'], period_df['StartHesitation'], label='StartHesitation', alpha=0.5)\n            ax.fill_between(period_df['Time'], period_df['Turn'], label='Turn', alpha=0.5)\n            ax.fill_between(period_df['Time'], period_df['Walking'], label='Walking', alpha=0.5)\n\n            ax.set_xlabel('Time')\n            ax.set_ylabel('Acceleration')\n            ax.set_title('Acceleration vs Time (Period from {} to {})'.format(start, end))\n            ax.legend()\n\n            plt.show()\n\n    #Start hesitation detection\n    elif SH == True:\n        turn_periods = detect_periods(df,'StartHesitation')\n        for period in turn_periods:\n            start, end = period\n            message = f'{i}: start of start hesitation --> {start}, end of start hesitation --> {end}'\n            print(message)\n            i+=1\n\n        for period in turn_periods:\n            start, end = period\n\n            if start - interval < 0:\n                start = 0\n            else:\n                start -= interval\n\n            if end + interval > df['Time'].iloc[-1]:\n                end = df['Time'].iloc[-1]\n            else:\n                end += interval\n            period_df = df[(df['Time'] >= start) & (df['Time'] <= end)]\n\n            fig, ax = plt.subplots(figsize=(12, 6))\n\n            ax.plot(period_df['Time'], period_df['AccV'], label='AccV')\n            ax.plot(period_df['Time'], period_df['AccML'], label='AccML')\n            ax.plot(period_df['Time'], period_df['AccAP'], label='AccAP')\n            ax.fill_between(period_df['Time'], period_df['StartHesitation'], label='StartHesitation', alpha=0.5)\n            ax.fill_between(period_df['Time'], period_df['Turn'], label='Turn', alpha=0.5)\n            ax.fill_between(period_df['Time'], period_df['Walking'], label='Walking', alpha=0.5)\n\n            ax.set_xlabel('Time')\n            ax.set_ylabel('Acceleration')\n            ax.set_title('Acceleration vs Time (Period from {} to {})'.format(start, end))\n            ax.legend()\n\n            plt.show()\n\n    #Walking detection\n    elif W == True:\n        turn_periods = detect_periods(df,'Walking')\n        for period in turn_periods:\n            start, end = period\n            message = f'{i}: start of walking --> {start}, end of walking --> {end}'\n            print(message)\n            i+=1\n\n        for period in turn_periods:\n            start, end = period\n\n            if start - interval < 0:\n                start = 0\n            else:\n                start -= interval\n\n            if end + interval > df['Time'].iloc[-1]:\n                end = df['Time'].iloc[-1]\n            else:\n                end += interval\n            period_df = df[(df['Time'] >= start) & (df['Time'] <= end)]\n\n            fig, ax = plt.subplots(figsize=(12, 6))\n\n            ax.plot(period_df['Time'], period_df['AccV'], label='AccV')\n            ax.plot(period_df['Time'], period_df['AccML'], label='AccML')\n            ax.plot(period_df['Time'], period_df['AccAP'], label='AccAP')\n            ax.fill_between(period_df['Time'], period_df['StartHesitation'], label='StartHesitation', alpha=0.5)\n            ax.fill_between(period_df['Time'], period_df['Turn'], label='Turn', alpha=0.5)\n            ax.fill_between(period_df['Time'], period_df['Walking'], label='Walking', alpha=0.5)\n\n            ax.set_xlabel('Time')\n            ax.set_ylabel('Acceleration')\n            ax.set_title('Acceleration vs Time (Period from {} to {})'.format(start, end))\n            ax.legend()\n\n            plt.show()\n\n    else:\n\n        if end_time is not None:\n            df = df[(df['Time'] >= start_time) & (df['Time'] <= end_time)]\n        else:\n            df = df[df['Time'] >= start_time]\n\n        fig, ax = plt.subplots(figsize=(12, 6))\n        ax.plot(df['Time'], df['AccV'], label='AccV')\n        ax.plot(df['Time'], df['AccML'], label='AccML')\n        ax.plot(df['Time'], df['AccAP'], label='AccAP')\n        ax.fill_between(df['Time'], df['StartHesitation'], label='StartHesitation', alpha=0.5)\n        ax.fill_between(df['Time'], df['Turn'], label='Turn', alpha=0.5)\n        ax.fill_between(df['Time'], df['Walking'], label='Walking', alpha=0.5)\n\n        ax.set_xlabel('Time')\n        ax.set_ylabel('Acceleration')\n        ax.set_title('Acceleration vs Time (Period from {} to {})'.format(start_time, end_time))\n        ax.legend()\n\n        plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-04-23T22:09:14.135426Z","iopub.execute_input":"2023-04-23T22:09:14.135818Z","iopub.status.idle":"2023-04-23T22:09:14.842549Z","shell.execute_reply.started":"2023-04-23T22:09:14.135783Z","shell.execute_reply":"2023-04-23T22:09:14.841336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_times_series('/kaggle/input/tlvmc-parkinsons-freezing-gait-prediction/train/tdcsfog/2855712333.csv',interval=500)","metadata":{"execution":{"iopub.status.busy":"2023-04-23T22:09:21.650620Z","iopub.execute_input":"2023-04-23T22:09:21.651007Z","iopub.status.idle":"2023-04-23T22:09:22.932175Z","shell.execute_reply.started":"2023-04-23T22:09:21.650975Z","shell.execute_reply":"2023-04-23T22:09:22.930845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}