# -- Code Cell --
import pandas as pd
train = pd.read_csv("dataset.csv")

# -- Code Cell --
train

# -- Code Cell --
task1 = len(train.groupby('Timestamp').agg(list))

# -- Code Cell --
groups = train.groupby('Timestamp').agg(list)

# -- Code Cell --
groups['Y'].iloc[0]

# -- Code Cell --
import matplotlib.pyplot as plt
X = groups['X'].iloc[0]
Y = groups['Y'].iloc[0]
plt.scatter(X, Y)

# -- Code Cell --
task2 = 5

# -- Code Cell --
train["Timestamp"] = pd.to_datetime(train["Timestamp"])

# -- Code Cell --
all_points = []
time_stamps = []
y_pred = []

# -- Code Cell --
pd.unique(train['Name'])

# -- Code Cell --
from sklearn.cluster import KMeans
for i, stm in enumerate(pd.unique(train['Name'])):
    train_stm = train[train['Name'] == stm]
    kmn = KMeans(5,random_state=42,n_init=10)
    kmn.fit(train_stm[['X','Y']])
    cnt = kmn.cluster_centers_
    cnt = cnt[cnt[:,0].argsort()]
    time_stamps.extend([(train_stm['Timestamp'].iloc[0] - train['Timestamp'].iloc[0]).total_seconds() for i in range(5)])
    all_points.extend(cnt.tolist())
    y_pred.extend([1,2,3,4,5])

# -- Code Cell --
import numpy as np

# -- Code Cell --
all_points = np.array(all_points)

# -- Code Cell --
plt.scatter(all_points[:,0], all_points[:,1])

# -- Code Cell --
df = pd.DataFrame({
    'X' : all_points[:,0],
    "y": all_points[:,1],
    "time_dif" : time_stamps,
    "class":y_pred
})

# -- Code Cell --
df_1 = df[df['class']==1]

# -- Code Cell --
from datetime import datetime
from sklearn.linear_model import RANSACRegressor,LinearRegression
plt.scatter(df_1['X'], df_1['y'])

# -- Code Cell --
train['Timestamp']

# -- Code Cell --
df_pred_3 = pd.DataFrame()

# -- Code Cell --
oredred_names = list(pd.unique(train['Name']))
name_to_ts = {name:train[train['Name'] == name]['Timestamp'].iloc[0].strftime('%b %d, %Y, %I:%M:%S %p') for name in oredred_names}
for i in range(5):
    df_1 = df[df['class']==i+1].reset_index(drop=True)
    r_x = RANSACRegressor(LinearRegression(), min_samples=2, residual_threshold=0.8, random_state=42)
    r_y = RANSACRegressor(LinearRegression(), min_samples=2, residual_threshold=0.8, random_state=42)
    r_x.fit(df_1[['time_dif']], df_1['X'])
    df_1['X'] = r_x.predict(df_1[['time_dif']])
    r_y.fit(df_1[['time_dif']], df_1['y'])
    df_1['y'] = r_y.predict(df_1[['time_dif']])
    dff = pd.DataFrame({
        "id":[f"{name_to_ts[name]}|{i}" for name in oredred_names],
        'subtaskID':'task3',
        "answer": [f"{df_1['X'].iloc[j]:.4f}|{df_1['y'].iloc[j]:.4f}" for j in range(len(df_1))]
    })
    df_pred_3 = pd.concat([df_pred_3, dff])

# -- Code Cell --
# df_1['time_dif'][245] = 344.0 = 5*60+47-3
df_1.loc[246,'time_dif'] = 497

# -- Code Cell --
df_pred_4 = pd.DataFrame()

# -- Code Cell --
future_X = pd.DataFrame({'time_dif': [497]})

# -- Code Cell --
for i in range(5):
    df_1 = df[df['class']==i+1].reset_index(drop=True)
    r_x = RANSACRegressor(LinearRegression(), min_samples=2, residual_threshold=0.8)
    r_y = RANSACRegressor(LinearRegression(), min_samples=2, residual_threshold=0.8)

    r_x.fit(df_1[['time_dif']], df_1['X'])
    pred_x = r_x.predict(future_X)[0]

    r_y.fit(df_1[['time_dif']], df_1['y'])
    pred_y = r_y.predict(future_X)[0]

    dff = pd.DataFrame({
        "id": [f"Jan 26, 2026, 12:08:20 AM|{i}"],
        "subtaskID": ["task4"],
        "answer": [f"{pred_x:.4f}|{pred_y:.4f}"]
    })

    df_pred_4 = pd.concat([df_pred_4, dff], ignore_index=True)

# -- Code Cell --
df_pred_4

# -- Code Cell --
sub1 = pd.DataFrame({
    "id":["GLOBAL"],
    "subtaskID":["task1"],
    "answer":[task1]
})
sub2 = pd.DataFrame({
    "id":["GLOBAL"],
    "subtaskID":["task2"],
    "answer":[task2]
})

final = pd.concat([sub1,sub2,df_pred_3,df_pred_4]).to_csv("subs.csv",index=False)

# -- Code Cell --


# -- Code Cell --
