application_vnd.jupyter.stderr_output_2.png text_html_output_1.png text_plain_output_1.png
from shapely.geometry import Point

from shapely.geometry.polygon import Polygon

import numpy as np # linear algebra

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import pymap3d as pm

nyra_tracking = pd.read_csv('/kaggle/input/big-data-derby-2022/nyra_tracking_table.csv')
nyra_start = pd.read_csv('/kaggle/input/big-data-derby-2022/nyra_start_table.csv')
nyra_race = pd.read_csv('/kaggle/input/big-data-derby-2022/nyra_race_table.csv')

track_id = 'SAR'
race_date = '2019-07-24'
race_number = 5
target_tracking = nyra_tracking.query('track_id == @track_id & race_date == @race_date & race_number == @race_number').sort_values('trakus_index')
target_tracking

dtime = 0.25
if track_id == 'AQU':
    elevation = 3
elif track_id == 'BEL':
    elevation = 20
elif track_id == 'SAR':
    elevation = 93
target_trackings = []
for number, group in target_tracking.groupby('program_number'):
    ecef = np.array(pm.geodetic2ecef(group['latitude'].values, group['longitude'].values, np.array([elevation] * len(group)))).T
    v_ecef = np.sqrt(np.sum(np.diff(ecef, axis=0) ** 2, axis=1)) * 3.6 / dtime
    group['time'] = group['trakus_index'] * dtime - dtime
    group['speed'] = np.insert(v_ecef, 0, 0)
    target_trackings.append(group)
target_tracking = pd.concat(target_trackings)
target_tracking

poly = [[43.071833, -73.770353], [43.071685, -73.770699], [43.07247, -73.77113], [43.072486, -73.77086]]
df_poly = pd.DataFrame(poly, columns=['Lat', 'Lon'], dtype=float)
polygon = Polygon([tuple(x) for x in df_poly[['Lat', 'Lon']].to_numpy()])
target_tracking['Within'] = target_tracking.apply(lambda target_tracking: polygon.contains(Point(target_tracking['latitude'], target_tracking['longitude'])), axis=1)
new_df = target_tracking.query('Within == True')
new_df = new_df[new_df.trakus_index > 100]
new_df.sort_values(by=['trakus_index'], inplace=True)
new_df.drop_duplicates(subset='program_number', keep='first', inplace=True)

def cross(row):
    x1 = 43.071816
    y1 = -73.77039
    x2 = 43.07248
    y2 = -73.770883
    return (row['latitude'] - x1) * (y2 - y1) - (row['longitude'] - y1) * (x2 - x1)
target_tracking['crossed'] = target_tracking.apply(cross, axis=1)
df2 = target_tracking[(target_tracking['Within'] == True) & (target_tracking['crossed'] > 0)]
df2.drop_duplicates(subset='program_number', keep='last', inplace=True)
df2.sort_values(by=['trakus_index', 'crossed'], ascending=[True, False], inplace=True)
print('Results')
print('Track:', track_id, 'Date:', race_date, 'Race:', race_number)
df2