{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":82611,"databundleVersionId":9553358,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-11-27T07:03:38.192202Z","iopub.execute_input":"2024-11-27T07:03:38.192613Z","iopub.status.idle":"2024-11-27T07:03:39.384356Z","shell.execute_reply.started":"2024-11-27T07:03:38.192575Z","shell.execute_reply":"2024-11-27T07:03:39.383052Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport numpy as np","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T07:03:59.922530Z","iopub.execute_input":"2024-11-27T07:03:59.923281Z","iopub.status.idle":"2024-11-27T07:04:00.060137Z","shell.execute_reply.started":"2024-11-27T07:03:59.923226Z","shell.execute_reply":"2024-11-27T07:04:00.059257Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/brist1d/train.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T07:04:14.300148Z","iopub.execute_input":"2024-11-27T07:04:14.300542Z","iopub.status.idle":"2024-11-27T07:04:27.291748Z","shell.execute_reply.started":"2024-11-27T07:04:14.300505Z","shell.execute_reply":"2024-11-27T07:04:27.290645Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def time_to_minutes(time_str):\n    \"\"\"Convert time string 'h:mm' to minutes\"\"\"\n    hours, minutes = map(int, time_str.split(':'))\n    return -(hours * 60 + minutes)  # negative because it's historical data\n\ndef plot_random_samples(df, num_samples=3):\n    # Get random row indices\n    random_indices = np.random.choice(df.index, size=num_samples, replace=False)\n    \n    # Create subplots\n    fig = make_subplots(rows=num_samples, cols=1,\n                        subplot_titles=[f\"Sample {i+1}\" for i in range(num_samples)],\n                        vertical_spacing=0.1)\n    \n    for idx, row_idx in enumerate(random_indices, 1):\n        # Get blood glucose columns and values\n        bg_cols = sorted([col for col in df.columns if col.startswith('bg-')],\n                        key=lambda x: time_to_minutes(x[len(\"bg-\"):]))  # sort by time\n        bg_values = df.loc[row_idx, bg_cols]\n        \n        # Get insulin columns and values\n        ins_cols = sorted([col for col in df.columns if col.startswith('insulin-')],\n                         key=lambda x: time_to_minutes(x[len(\"insulin-\"):]))  # sort by time\n        ins_values = df.loc[row_idx, ins_cols]\n        \n        # Convert column names to minutes for x-axis\n        bg_time_points = [time_to_minutes(col[len(\"bg-\"):]) for col in bg_cols]\n        ins_time_points = [time_to_minutes(col[len(\"insulin-\"):]) for col in ins_cols]\n        \n        # Add blood glucose trace\n        fig.add_trace(\n            go.Scatter(x=bg_time_points, y=bg_values,\n                      name='Blood Glucose',\n                      mode='lines+markers',\n                      line=dict(color='blue'),\n                      showlegend=(idx==1)),\n            row=idx, col=1\n        )\n        \n        # Add insulin trace\n        fig.add_trace(\n            go.Scatter(x=ins_time_points, y=ins_values,\n                      name='Insulin',\n                      mode='lines+markers',\n                      line=dict(color='red'),\n                      yaxis='y2',\n                      showlegend=(idx==1)),\n            row=idx, col=1\n        )\n        \n        # Add target point\n        target_value = df.loc[row_idx, 'bg+1:00']\n        fig.add_trace(\n            go.Scatter(x=[60], y=[target_value],\n                      name='Target BG',\n                      mode='markers',\n                      marker=dict(color='green', size=10),\n                      showlegend=(idx==1)),\n            row=idx, col=1\n        )\n    \n    # Update layout\n    fig.update_layout(\n        height=300*num_samples,\n        title_text=\"Random Samples of Blood Glucose and Insulin Readings\",\n        showlegend=True\n    )\n    \n    # Update x and y axes\n    for i in range(num_samples):\n        fig.update_xaxes(title_text=\"Time (minutes)\", \n                        row=i+1, col=1,\n                        tickmode='array',\n                        tickvals=[-300, -240, -180, -120, -60, 0, 60],  # 5 hours to +1 hour\n                        ticktext=['5h', '4h', '3h', '2h', '1h', 'now', '+1h'])\n        \n        fig.update_yaxes(title_text=\"Blood Glucose\", row=i+1, col=1)\n        # Add secondary y-axis for insulin\n        fig.update_yaxes(title_text=\"Insulin\", \n                        row=i+1, col=1, \n                        secondary_y=True)\n\n        for idx, row_idx in enumerate(random_indices, 1):\n            fig.add_annotation(\n                text=f\"Data from Row {row_idx}\",\n                xref=f\"x{idx}\",\n                yref=f\"y{idx}\",\n                x=-300,  # Position at the leftmost part\n                y=df.loc[row_idx, bg_cols].max(),  # Position at the top of the glucose values\n                showarrow=False,\n                font=dict(size=10),\n                bgcolor=\"rgba(255, 255, 255, 0.8)\",\n                bordercolor=\"black\",\n                borderwidth=1,\n                borderpad=4\n            )\n    \n    fig.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T07:04:40.808987Z","iopub.execute_input":"2024-11-27T07:04:40.809907Z","iopub.status.idle":"2024-11-27T07:04:40.825186Z","shell.execute_reply.started":"2024-11-27T07:04:40.809865Z","shell.execute_reply":"2024-11-27T07:04:40.824102Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_random_samples(df, num_samples=3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T07:04:46.779919Z","iopub.execute_input":"2024-11-27T07:04:46.780272Z","iopub.status.idle":"2024-11-27T07:04:47.513698Z","shell.execute_reply.started":"2024-11-27T07:04:46.780242Z","shell.execute_reply":"2024-11-27T07:04:47.512697Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}