{"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":"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)\nimport polars as pl\nimport datetime\nfrom matplotlib import pyplot as plt\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","execution":{"iopub.status.busy":"2023-11-09T16:03:08.731316Z","iopub.execute_input":"2023-11-09T16:03:08.732007Z","iopub.status.idle":"2023-11-09T16:03:09.318452Z","shell.execute_reply.started":"2023-11-09T16:03:08.731971Z","shell.execute_reply":"2023-11-09T16:03:09.317339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#df_submission = pd.read_csv('/kaggle/input/child-mind-institute-detect-sleep-states/sample_submission.csv')\n#df_pq_test = pd.read_parquet('/kaggle/input/child-mind-institute-detect-sleep-states/test_series.parquet')\n#df_pq_train = pd.read_parquet('/kaggle/input/child-mind-institute-detect-sleep-states/train_series.parquet')\ndf_train_events = pl.read_csv(\"/kaggle/input/child-mind-institute-detect-sleep-states/train_events.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:09.320359Z","iopub.execute_input":"2023-11-09T16:03:09.320806Z","iopub.status.idle":"2023-11-09T16:03:09.491712Z","shell.execute_reply.started":"2023-11-09T16:03:09.320778Z","shell.execute_reply":"2023-11-09T16:03:09.490764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train_events = df_train_events.with_columns(\n    pl.col(\"timestamp\").apply(lambda x: x[-5:]).alias(\"timezone_offset\"),\n    pl.col(\"timestamp\").apply(lambda x: datetime.datetime.strptime(str(x), '%Y-%m-%dT%H:%M:%S%z')).alias(\"timestamp\"),\n)","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:09.498772Z","iopub.execute_input":"2023-11-09T16:03:09.499330Z","iopub.status.idle":"2023-11-09T16:03:09.693718Z","shell.execute_reply.started":"2023-11-09T16:03:09.499297Z","shell.execute_reply":"2023-11-09T16:03:09.692312Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Analyzing data in night column","metadata":{}},{"cell_type":"code","source":"df_train_events['night'].describe()","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:09.694632Z","iopub.execute_input":"2023-11-09T16:03:09.694971Z","iopub.status.idle":"2023-11-09T16:03:09.728164Z","shell.execute_reply.started":"2023-11-09T16:03:09.694946Z","shell.execute_reply":"2023-11-09T16:03:09.726999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(figsize=[20,10])\ndata = df_train_events[\"night\"].to_numpy()\nhist, edges = np.histogram(data, bins=20)\nfreq = hist / sum(hist)\ncolors = plt.cm.rainbow(freq)\nplt.bar(edges[:-1], hist, width=np.diff(edges), color=colors, alpha=0.7)\nplt.title(\"Nights vs Sensor Count\")\nplt.xlabel(\"Nights\")\nplt.ylabel(\"Number of Sensors\")\nplt.xlim([0,100]) ","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:09.729247Z","iopub.execute_input":"2023-11-09T16:03:09.729805Z","iopub.status.idle":"2023-11-09T16:03:10.095900Z","shell.execute_reply.started":"2023-11-09T16:03:09.729775Z","shell.execute_reply":"2023-11-09T16:03:10.094495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"hour distribution","metadata":{}},{"cell_type":"code","source":"def show_df(df, num=3, tail=True):\n    print(df.shape)\n    display(df.head(num))\n    if tail:\n        display(df.tail(num))\nshow_df(df_train_events)","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:10.097672Z","iopub.execute_input":"2023-11-09T16:03:10.098819Z","iopub.status.idle":"2023-11-09T16:03:10.115653Z","shell.execute_reply.started":"2023-11-09T16:03:10.098784Z","shell.execute_reply":"2023-11-09T16:03:10.113762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train_events = df_train_events.with_columns(\n    df_train_events['timestamp'].apply(lambda x: x.year).alias(\"year\"),\n    df_train_events['timestamp'].apply(lambda x: x.month).alias(\"month\"),\n    df_train_events['timestamp'].apply(lambda x: x.day).alias(\"day\"),\n    df_train_events['timestamp'].apply(lambda x: x.hour).alias(\"hour\"),\n    df_train_events['timestamp'].apply(lambda x: x.minute).alias(\"minute\"),\n    df_train_events['timestamp'].apply(lambda x: x.second).alias(\"second\"),\n)\n\nshow_df(df_train_events)","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:10.117497Z","iopub.execute_input":"2023-11-09T16:03:10.117912Z","iopub.status.idle":"2023-11-09T16:03:10.216637Z","shell.execute_reply.started":"2023-11-09T16:03:10.117874Z","shell.execute_reply":"2023-11-09T16:03:10.215198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_hist(df:pd.DataFrame, col:str, title:str=None, xlim:list=[None,None], bins=20)->None:\n    \"\"\"show histgram\n\n    Args:\n        df (pl.DataFrame): input data\n        col (str): show column\n        title (str, optional): title. Defaults to None.\n        xlim (list, optional): range of x-axis. Defaults to [None,None].\n    \"\"\"\n    fig = plt.figure(figsize=[20,4])\n    tmp = df[col].to_numpy()\n    plt.hist(tmp, alpha=0.5, range=(xlim[0], xlim[1]), bins=bins)  # 範囲とビンの数を指定\n    plt.title(title) # カラム名をタイトルとして設定\n    plt.xlabel(col)\n    plt.xlim(xlim)","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:10.221388Z","iopub.execute_input":"2023-11-09T16:03:10.221793Z","iopub.status.idle":"2023-11-09T16:03:10.229410Z","shell.execute_reply.started":"2023-11-09T16:03:10.221759Z","shell.execute_reply":"2023-11-09T16:03:10.228213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# hour distribution\nfor _event in [\"wakeup\", \"onset\"]:\n    show_hist(df_train_events.filter(pl.col(\"event\")==_event), \"hour\", f\"{_event} of hour distribution\", [0,24], 24)","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:10.233214Z","iopub.execute_input":"2023-11-09T16:03:10.234027Z","iopub.status.idle":"2023-11-09T16:03:10.774241Z","shell.execute_reply.started":"2023-11-09T16:03:10.233981Z","shell.execute_reply":"2023-11-09T16:03:10.773379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"series_id = df_train_events[\"series_id\"].unique()\nprint(f\"Number of series_id : {len(series_id)}\")\nprint(series_id)","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:10.775640Z","iopub.execute_input":"2023-11-09T16:03:10.776294Z","iopub.status.idle":"2023-11-09T16:03:10.786545Z","shell.execute_reply.started":"2023-11-09T16:03:10.776265Z","shell.execute_reply":"2023-11-09T16:03:10.785464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def ts_vs_night_lineplot(df, xlabel, ylabel, title=None):\n    _onset = df.filter(pl.col(\"event\")== 'onset')['timestamp'].to_numpy()\n    _wakeup = df.filter(pl.col(\"event\")== 'wakeup')['timestamp'].to_numpy()\n    \n    plt.figure(figsize=(20, 4))\n    plt.plot(df[xlabel], df[ylabel], marker='x', linestyle='-', color='g')\n    for onset in _onset:\n        plt.axvline(x=onset, color='r', linestyle='--', label='onset')\n    for wakeup in _wakeup:\n        plt.axvline(x=wakeup, color='b', linestyle='--', label='wakeup')\n\n\n    plt.title(title)\n    plt.xlabel(xlabel)\n    plt.ylabel(ylabel)\n\n   \n    plt.grid(True)\n    plt.show()\n\nfor ids in range(5):\n    tmp = df_train_events.filter(df_train_events['series_id'] == series_id[ids])\n    ts_vs_night_lineplot(tmp, \"timestamp\", \"night\", \"timestamp vs night for each series id\")\n","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:10.788371Z","iopub.execute_input":"2023-11-09T16:03:10.788717Z","iopub.status.idle":"2023-11-09T16:03:12.483682Z","shell.execute_reply.started":"2023-11-09T16:03:10.788670Z","shell.execute_reply":"2023-11-09T16:03:12.482313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nplt.rcParams[\"figure.figsize\"] = [12.00, 5]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndf = pd.DataFrame(dict(day=np.array(df_train_events[\"day\"].take_every(12*60))))\n\nax = sns.countplot(x=\"day\", data=df)\n\nfor p in ax.patches:\n   ax.annotate('{:.1f}'.format(p.get_height()), (p.get_x()+0.25, p.get_height()+0.01))\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-09T16:03:12.485385Z","iopub.execute_input":"2023-11-09T16:03:12.485744Z","iopub.status.idle":"2023-11-09T16:03:14.291853Z","shell.execute_reply.started":"2023-11-09T16:03:12.485714Z","shell.execute_reply":"2023-11-09T16:03:14.290590Z"},"trusted":true},"execution_count":null,"outputs":[]}]}