{"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 os\nimport math\nimport gc\nimport seaborn as sns\nimport matplotlib.pyplot as plt\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":"2022-11-08T14:13:19.759352Z","iopub.execute_input":"2022-11-08T14:13:19.760047Z","iopub.status.idle":"2022-11-08T14:13:21.121247Z","shell.execute_reply.started":"2022-11-08T14:13:19.759903Z","shell.execute_reply":"2022-11-08T14:13:21.120181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-11-08T14:13:21.123809Z","iopub.execute_input":"2022-11-08T14:13:21.124255Z","iopub.status.idle":"2022-11-08T14:13:21.260953Z","shell.execute_reply.started":"2022-11-08T14:13:21.124210Z","shell.execute_reply":"2022-11-08T14:13:21.258950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def is_it_drafting_1 (cum_distance_1:float, edge_distance_1:float, cum_distance_2:float, edge_distance_2:float, track_head_diff_1:float):\n    # straight part\n    draft_area = False\n    cum_diff = cum_distance_1 - cum_distance_2\n    edge_diff = abs(edge_distance_1 - edge_distance_2)       \n    delta_distance = math.sqrt(cum_diff**2 + edge_diff**2)\n    theta = math.atan(cum_diff/edge_diff)\n    track_head_diff_1 = track_head_diff_1 * math.pi/180\n    #print (delta_distance)\n    if (delta_distance <= 16.4042):\n        gamma = ((math.pi/2) - theta) + track_head_diff_1\n        if (gamma >= 0.):            \n            projected_dist_pt2 = delta_distance * math.cos(theta - track_head_diff_1)\n            projected_dist_draft = delta_distance * math.cos(80.*math.pi/180.)\n            if (projected_dist_pt2 <= projected_dist_draft):\n                draft_area = True\n                #case = I \n        else:\n            projected_dist_pt2 = delta_distance * math.cos(theta + track_head_diff_1)\n            projected_dist_draft = delta_distance * math.cos(80.*math.pi/180.)\n            if (projected_dist_pt2 <= projected_dist_draft):\n                draft_area = True\n                #case = II \n        \n    return draft_area\n","metadata":{"execution":{"iopub.status.busy":"2022-11-08T14:13:21.262693Z","iopub.execute_input":"2022-11-08T14:13:21.263099Z","iopub.status.idle":"2022-11-08T14:13:21.275605Z","shell.execute_reply.started":"2022-11-08T14:13:21.263050Z","shell.execute_reply":"2022-11-08T14:13:21.274063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def is_it_drafting_2 (cum_distance_1:float, edge_distance_1:float, cum_distance_2:float, edge_distance_2:float, track_head_diff_1:float, region:str, radius_1:float, radius_2:float, beta:float):\n    # THREE AXES SOLUTION\n    beta = beta*math.pi/180. # changing degrees in to radian  \n    track_heading_diff_1 = track_head_diff_1*math.pi/180.\n    arch_length = cum_distance_1 - cum_distance_2\n    draft_area = False\n    if (region == 'I'):\n        theta = arch_length / radius_1\n        radius = radius_1\n    elif (region == 'III'):\n        theta = arch_length / radius_2 # theta is in radian\n        radius = radius_2\n\n    ctr_pt1 = radius + edge_distance_1\n    ctr_pt2 = radius + edge_distance_2\n\n    ctr_pt2_projection = ctr_pt2*math.cos(theta)\n    if (ctr_pt2_projection <= ctr_pt1):\n        pt1_pt2_adj = ctr_pt1 - ctr_pt2_projection\n        pt1_pt2_opp = ctr_pt2 * math.sin(theta)\n        delta_distance = math.sqrt(pt1_pt2_adj**2 + pt1_pt2_opp**2)\n        #print (delta_distance)\n        if (delta_distance <= 16.4042):\n            gamma = math.atan(pt1_pt2_opp/pt1_pt2_adj) # angle bn pt1_pt2 line and radial line\n            alpha = beta + track_heading_diff_1 + (math.pi/2 - gamma)\n            if (alpha >= 0.):\n                projected_dist_pt2 = math.cos(gamma - (beta + track_heading_diff_1)) * delta_distance # pi/2 - alpha\n                projected_dist_draft =  math.cos(80.*math.pi/180.) * delta_distance\n                if (projected_dist_pt2 <= projected_dist_draft):\n                    draft_area = True  \n            else:\n                projected_dist_pt2 = math.cos((math.pi - gamma) + (beta + track_heading_diff_1)) * delta_distance # pi/2 - alpha\n                projected_dist_draft =  math.cos(80.*math.pi/180.) * delta_distance\n                if (projected_dist_pt2 <= projected_dist_draft):\n                    draft_area = True  \n                    \n    elif (ctr_pt2_projection > ctr_pt1):  \n        pt1_pt2_adj =  ctr_pt2_projection - ctr_pt1\n        pt1_pt2_opp = ctr_pt2 * math.sin(theta)\n        delta_distance = math.sqrt(pt1_pt2_adj**2 + pt1_pt2_opp**2)\n        #print (delta_distance)\n        if (delta_distance <= 16.4042):\n            gamma = math.atan(pt1_pt2_opp/pt1_pt2_adj) # angle bn pt1_pt2 line and radial line\n            alpha = (math.pi/2 - gamma) - (beta + track_heading_diff_1)\n            if (alpha >= 0.):\n                projected_dist_pt2 = math.cos(gamma + beta + track_heading_diff_1) * delta_distance # \n                projected_dist_draft =  math.cos(80.*math.pi/180.) * delta_distance\n                if (projected_dist_pt2 <= projected_dist_draft):\n                    draft_area = True \n            else:\n                projected_dist_pt2 = math.cos(math.pi - (gamma + beta + track_heading_diff_1)) * delta_distance # \n                projected_dist_draft =  math.cos(80.*math.pi/180.) * delta_distance\n                if (projected_dist_pt2 <= projected_dist_draft):\n                    draft_area = True  \n\n    return draft_area ","metadata":{"execution":{"iopub.status.busy":"2022-11-08T14:13:21.277251Z","iopub.execute_input":"2022-11-08T14:13:21.277626Z","iopub.status.idle":"2022-11-08T14:13:21.296914Z","shell.execute_reply.started":"2022-11-08T14:13:21.277595Z","shell.execute_reply":"2022-11-08T14:13:21.295424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def radii_generator (parent_folder:str):\n    #dir_list = os.listdir('../input/pvt-tables')\n    x = parent_folder\n\n    if (x[:4] == 'aqud'):\n        radius_1 = 467.65301061106595\n        radius_2 = 467.65301061106595\n    elif (x[:4] == 'aquo'):\n        radius_1 = 361.555520694114 \n        radius_2 = 344.3731723149623 \n    elif (x[:4] == 'aqut'):\n        radius_1 = 266. \n        radius_2 = 251. \n    elif (x[:4] == 'sari'):\n        radius_1 = 307. \n        radius_2 = 307. \n    elif (x[:4] == 'sart'):\n        radius_1 = 394.72 \n        radius_2 = 395.31 \n    elif (x[:4] == 'sarm'):\n        radius_1 = 307. \n        radius_2 = 307.\n    elif (x[:4] == 'sard'):\n        radius_1 = 468.76 \n        radius_2 = 470. \n    elif (x[:4] == 'beld'):\n        radius_1 = 635.51 \n        radius_2 = 635.51\n    elif (x[:4] == 'belt'):\n        radius_1 = 528. \n        radius_2 = 528.\n    elif (x[:4] == 'beli'):        \n        radius_1 = 418. \n        radius_2 = 421.\n    elif (x[:4] == 'belm'):\n        radius_1 = 418. \n        radius_2 = 421.  \n    \n    return radius_1, radius_2","metadata":{"execution":{"iopub.status.busy":"2022-11-08T14:13:21.301094Z","iopub.execute_input":"2022-11-08T14:13:21.301521Z","iopub.status.idle":"2022-11-08T14:13:21.318647Z","shell.execute_reply.started":"2022-11-08T14:13:21.301489Z","shell.execute_reply":"2022-11-08T14:13:21.317061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"parent_list = os.listdir('../input/pvt-tables')\n#parent_list = os.listdir('../input/pvt-tables/belmcomplete')\nfor x in parent_list:\n    #print(x[:4])\n    #print(radii_generator (x))\n    radius_1, radius_2 = radii_generator (x)\n    dir_path_1 = os.path.join('./draft', x)\n    if not os.path.exists(dir_path_1):\n        os.makedirs(dir_path_1)\n    parent_folder_path = os.path.join('../input/pvt-tables', x)\n    print(parent_folder_path)\n    file_lists = os.listdir(parent_folder_path)\n    for file_i in file_lists:\n        file_path = os.path.join(parent_folder_path, file_i)\n        drafting_df = pd.DataFrame()\n        print(file_path)\n        df = pd.read_csv(file_path)\n        column_list = list(df.columns)    \n        cols_suffix = [k for k in column_list if 'region' in k]\n        for i in range(len(cols_suffix)):\n            cols_suffix[i] = cols_suffix[i].split(sep='_')[-1]\n        cum_distance_cols = pd.Series(dtype=str)\n        region_cols = pd.Series(dtype=str)\n        edge_cols = pd.Series(dtype=str)\n        head_diff_cols = pd.Series(dtype=str)\n        beta_cols = pd.Series(dtype=str)\n        \n        for cd in range(len(cols_suffix)):\n            str_1 = 'draft_{}'.format(cols_suffix[cd])\n            exec(str_1 + \" = []\")\n        \n        \n        for j in range(len(df)): \n            print('\\n  \\n {}'.format(j))\n            for y in cols_suffix:\n                cum_distance_cols['cum_distance_{}'.format(y)] = 'cum_distance_{}'.format(y) \n                region_cols['cum_distance_{}'.format(y)]= 'region_{}'.format(y)\n                edge_cols['cum_distance_{}'.format(y)] = 'edge_distance_{}'.format(y)\n                head_diff_cols['cum_distance_{}'.format(y)] = 'track_heading_diff_{}'.format(y)\n                beta_cols['cum_distance_{}'.format(y)] = 'beta_{}'.format(y) \n            \n            cum_distance_series = df.loc[j,list(cum_distance_cols)]\n            cum_distance_series = cum_distance_series.sort_values(ascending=False)\n            cum_distance_start = cum_distance_series > df['run_up_distance'][0]\n            #cum_distance_stop = cum_distance_series > df['distance_id'][0]\n            #display(cum_distance_start)\n            #display(cum_distance_stop)\n            col_new_idx = list(cum_distance_series.index)\n            cum_distance_cols = cum_distance_cols.reindex(col_new_idx)\n            region_cols = region_cols.reindex(col_new_idx)\n            edge_cols = edge_cols.reindex(col_new_idx)\n            head_diff_cols = head_diff_cols.reindex(col_new_idx)\n            beta_cols = beta_cols.reindex(col_new_idx)\n            #print('im here')\n            #display(beta_cols)\n            #print(edge_cols.index)\n            \n                \n            for ef in range(len(col_new_idx)):\n                str_1 = 'draft2_{}'.format(col_new_idx[ef].split(sep='_')[-1])\n                exec(str_1 + \" = []\")\n            \n            \n            for kx in range(len(cum_distance_start)):\n                if ((cum_distance_start[kx] == False) or ((kx+1)==len(cum_distance_start))): # kx+1 out of bound\n                    print('either starting or out of bound')\n                    break\n                else:\n                    cum_distance_cols_2 = cum_distance_cols[kx+1:]\n                    region_cols_2 = region_cols[kx+1:]\n                    edge_cols_2 = edge_cols[kx+1:]\n                    cum_distance_start_2 = cum_distance_start[kx+1:]\n                    \n                    #head_diff_cols_2 = head_diff_cols[kx+1:]\n                    #beta_cols_2 = beta_cols[kx+1:]\n                    for kx_2 in range(len(cum_distance_cols_2)):\n                        region = df.loc[j,region_cols_2[kx_2]] # kx+1\n                        print(region)\n                        if (cum_distance_start_2[kx_2] == False):\n                            print('there is no second other element with cum_distance > run_up')\n                            break\n                        else: \n                            print('found other element and calling for is_it_drafting')\n                            cum_distance_1 = df.loc[j,cum_distance_cols[kx]]\n                            edge_distance_1 = df.loc[j,edge_cols[kx]]  \n                            cum_distance_2 = df.loc[j,cum_distance_cols_2[kx_2]]\n                            edge_distance_2 = df.loc[j,edge_cols_2[kx_2]]\n                            track_head_diff_1 = df.loc[j,head_diff_cols[kx]]\n                            print('the two elements being: {} {}'.format(cum_distance_cols[kx], cum_distance_cols_2[kx_2]))\n                            if ((region=='I') or (region=='III')):                                \n                                beta = df.loc[j,beta_cols[kx]]\n                                drafting_bool = is_it_drafting_2 (cum_distance_1=cum_distance_1, edge_distance_1=edge_distance_1, cum_distance_2=cum_distance_2, edge_distance_2=edge_distance_2, \n                                                  track_head_diff_1=track_head_diff_1, region=region, radius_1=radius_1, radius_2=radius_2, beta=beta)   \n                                print('region_{} drafting = {}'.format(region, drafting_bool))\n                            else:\n                                drafting_bool = is_it_drafting_1 (cum_distance_1=cum_distance_1, edge_distance_1=edge_distance_1, cum_distance_2=cum_distance_2, edge_distance_2=edge_distance_2, track_head_diff_1=track_head_diff_1)\n                                print('region_{} drafting = {}'.format(region, drafting_bool))\n                                \n                            str_suffix_1 = cum_distance_start.index[kx].split(sep='_')[-1]\n                            str_suffix_2 = cum_distance_start_2.index[kx_2].split(sep='_')[-1]\n                            \n                            str_ab = 'draft2_{}'.format(str_suffix_1)\n                            exec(str_ab + \".append(False)\")\n                            str_cd = 'draft2_{}'.format(str_suffix_2)\n                            exec(str_cd + \".append(drafting_bool)\")\n            \n            for ef in range(len(cols_suffix)):\n                str_12 = 'draft2_{}'.format(cols_suffix[ef])\n                str_aa = 'draft_{}'.format(cols_suffix[ef])                \n                sum_12 = sum(eval(str_12))\n                if (sum_12 > 0.):\n                    exec(str_aa + \".append(True)\")\n                    print('{} drafting on line {} : {}'.format(cols_suffix[ef], j, True))\n                else:\n                    exec(str_aa + \".append(False)\")\n                    print('{} drafting on line {} : {}'.format(cols_suffix[ef], j, False))\n            #break    \n        #display(df.index)\n        for gh in range(len(cols_suffix)):\n            #region_series_name = 'region_{}'.format(cols_suffix[gh])\n            cum_distance_name = 'cum_distance_{}'.format(cols_suffix[gh])\n            #region_series_1 = df[region_series_name] \n            cum_distance_series_1 = df[cum_distance_name]\n            for ix in range(len(cum_distance_series_1)):\n                if (cum_distance_series_1[ix] >= df['run_up_distance'][0]):\n                    start_idx = ix\n                    break\n            stop_idx = len(cum_distance_series_1.dropna())\n            for iz in range(len(cum_distance_series_1)):\n                if (cum_distance_series_1[iz] >= (df['run_up_distance'][0] + df['distance_id'][0])):\n                    stop_idx = iz\n                    break\n            str_bb = 'draft_{}'.format(cols_suffix[gh])                \n            draft_list = eval(str_bb)\n            draft_list = draft_list[start_idx:stop_idx+1]\n            exec(str_bb + \"= {}\".format(draft_list))\n            try:\n                draft_time_percentage = sum(draft_list) / len(draft_list)\n            except ZeroDivisionError:\n                draft_time_percentage = 0.\n            pg_no = cols_suffix[gh]\n            row_to_app = {'program_number': pg_no, 'draft_time_percentage': draft_time_percentage}\n            drafting_df = drafting_df.append(row_to_app, ignore_index=True)\n        display(drafting_df)\n        file_path_pvt = file_path.replace(\"../input/pvt-tables\", \"../input/path-eff-and-fp/eff_pos\")\n        print(file_path_pvt)\n        efficiency_df = pd.read_csv(file_path_pvt)\n        efficiency_df.program_number = [str(x) for x in efficiency_df.program_number]\n        drafting_df = pd.merge(efficiency_df, drafting_df, how='left', left_on=['program_number'], right_on = ['program_number'])\n        display(drafting_df)\n        drafting_df['jockey_efficiency'] = ((drafting_df['path_efficiency'] * 0.8) + (drafting_df['draft_time_percentage'] *0.2))\n        #../input/path-eff-and-fp/eff_pos/aqudcomplete/AQU-2019-01-01-1.csv\n        display(drafting_df)\n        display(file_path)\n        #file_path = '../input/pvt-tables/saricomplete/SAR-2019-08-30-8.csv' \n        #dir_path_1 = os.path.join('./draft', x)\n        #saving_path_1 = file_path.replace(\"../input/pvt-tables/saricomplete\", dir_path_1)\n        saving_path_1 = os.path.join(dir_path_1, file_path.split(sep='/')[-1])\n        print(saving_path_1)\n        drafting_df.to_csv(saving_path_1, index=False)\n        #break\n    #break\n            \n            ","metadata":{"execution":{"iopub.status.busy":"2022-11-08T14:13:21.321190Z","iopub.execute_input":"2022-11-08T14:13:21.322443Z","iopub.status.idle":"2022-11-08T14:13:26.479254Z","shell.execute_reply.started":"2022-11-08T14:13:21.322323Z","shell.execute_reply":"2022-11-08T14:13:26.478257Z"},"trusted":true},"execution_count":null,"outputs":[]}]}