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as as pd
|
| 4 |
+
from torch.utils.data import Dataset
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
import h5py
|
| 7 |
+
|
| 8 |
+
class TrajectoryDataset(Dataset):
|
| 9 |
+
"""Dataset for loading trajectory data from HDF5 files."""
|
| 10 |
+
def __init__(self, file_paths, traj_length):
|
| 11 |
+
self.samples = []
|
| 12 |
+
self.load_samples(file_paths, traj_length)
|
| 13 |
+
|
| 14 |
+
def load_samples(self, file_paths, traj_length):
|
| 15 |
+
for file_path in tqdm(file_paths, desc="Loading files", unit="file"):
|
| 16 |
+
with h5py.File(file_path, 'r') as h5_file:
|
| 17 |
+
for user_id in h5_file.keys(): # Iterate over users in the HDF5 file
|
| 18 |
+
user_group = h5_file[user_id]
|
| 19 |
+
latitudes = user_group['latitudes'][:]
|
| 20 |
+
longitudes = user_group['longitudes'][:]
|
| 21 |
+
hours = user_group['hours'][:]
|
| 22 |
+
|
| 23 |
+
# Create samples by sliding a window of traj_length over the user's trajectory
|
| 24 |
+
if len(latitudes) > traj_length:
|
| 25 |
+
for j in range(len(latitudes) - traj_length + 1):
|
| 26 |
+
self.samples.append((hours[j:j+traj_length], latitudes[j:j+traj_length], longitudes[j:j+traj_length]))
|
| 27 |
+
elif len(latitudes) == traj_length:
|
| 28 |
+
self.samples.append((hours[:], latitudes[:], longitudes[:]))
|
| 29 |
+
|
| 30 |
+
def __len__(self):
|
| 31 |
+
return len(self.samples)
|
| 32 |
+
|
| 33 |
+
def __getitem__(self, idx):
|
| 34 |
+
hours, latitudes, longitudes = self.samples[idx]
|
| 35 |
+
return torch.tensor(hours, dtype=torch.float32), torch.tensor(latitudes, dtype=torch.float32), torch.tensor(longitudes, dtype=torch.float32)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class PatternDataset:
|
| 39 |
+
"""Dataset for loading trajectory patterns, possibly for prototype learning."""
|
| 40 |
+
def __init__(self, file_paths):
|
| 41 |
+
self.trajectories = []
|
| 42 |
+
self.load_samples(file_paths)
|
| 43 |
+
|
| 44 |
+
def load_samples(self, file_paths):
|
| 45 |
+
for file_path in tqdm(file_paths, desc="Loading files", unit="file"):
|
| 46 |
+
with pd.HDFStore(file_path, 'r') as store: # Using pandas HDFStore
|
| 47 |
+
data = store['data']
|
| 48 |
+
for i in range(len(data)):
|
| 49 |
+
abs_time_list = np.array(data['ABS_TIME'][i])
|
| 50 |
+
lat_list = np.array(data['LAT'][i])
|
| 51 |
+
lng_list = np.array(data['LNG'][i])
|
| 52 |
+
trajectory = list(zip(abs_time_list, lat_list, lng_list))
|
| 53 |
+
self.trajectories.append(trajectory)
|
| 54 |
+
|
| 55 |
+
def get_all_trajectories(self):
|
| 56 |
+
return self.trajectories
|
| 57 |
+
|
| 58 |
+
def pad_trajectories(self):
|
| 59 |
+
max_length = max(len(traj) for traj in self.trajectories)
|
| 60 |
+
padded_samples = []
|
| 61 |
+
|
| 62 |
+
for traj in self.trajectories:
|
| 63 |
+
if len(traj) < max_length:
|
| 64 |
+
# Pad shorter trajectories with their last point
|
| 65 |
+
last_point = traj[-1]
|
| 66 |
+
padding = [last_point] * (max_length - len(traj))
|
| 67 |
+
padded_traj = traj + padding
|
| 68 |
+
else:
|
| 69 |
+
padded_traj = traj
|
| 70 |
+
padded_samples.append(padded_traj)
|
| 71 |
+
|
| 72 |
+
return padded_samples
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class MinMaxScaler:
|
| 76 |
+
"""Min-Max Scaler for trajectory data with global normalization support."""
|
| 77 |
+
def __init__(self, global_params_file=None):
|
| 78 |
+
self.min_val = None
|
| 79 |
+
self.max_val = None
|
| 80 |
+
self.global_params_file = global_params_file
|
| 81 |
+
self.is_global = global_params_file is not None
|
| 82 |
+
|
| 83 |
+
if self.is_global:
|
| 84 |
+
self._load_global_params()
|
| 85 |
+
|
| 86 |
+
def _load_global_params(self):
|
| 87 |
+
"""Load global normalization parameters from file."""
|
| 88 |
+
import json
|
| 89 |
+
import torch
|
| 90 |
+
|
| 91 |
+
with open(self.global_params_file, 'r') as f:
|
| 92 |
+
params = json.load(f)
|
| 93 |
+
|
| 94 |
+
# Convert to tensor format: [hours, latitudes, longitudes]
|
| 95 |
+
min_vals = [
|
| 96 |
+
params['hours']['min'],
|
| 97 |
+
params['latitudes']['min'],
|
| 98 |
+
params['longitudes']['min']
|
| 99 |
+
]
|
| 100 |
+
max_vals = [
|
| 101 |
+
params['hours']['max'],
|
| 102 |
+
params['latitudes']['max'],
|
| 103 |
+
params['longitudes']['max']
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
# Shape: (1, 1, 3) to match data format (batch_size, traj_length, 3)
|
| 107 |
+
self.min_val = torch.tensor(min_vals, dtype=torch.float32).view(1, 1, 3)
|
| 108 |
+
self.max_val = torch.tensor(max_vals, dtype=torch.float32).view(1, 1, 3)
|
| 109 |
+
|
| 110 |
+
def fit(self, data):
|
| 111 |
+
"""Fit scaler to data. If using global params, this does nothing."""
|
| 112 |
+
if not self.is_global:
|
| 113 |
+
self.min_val = data.amin(dim=(0, 1), keepdim=True)
|
| 114 |
+
self.max_val = data.amax(dim=(0, 1), keepdim=True)
|
| 115 |
+
|
| 116 |
+
def transform(self, data):
|
| 117 |
+
"""Transform data to [0, 1] range."""
|
| 118 |
+
if self.min_val is None or self.max_val is None:
|
| 119 |
+
raise ValueError("Scaler not fitted. Call fit() first.")
|
| 120 |
+
|
| 121 |
+
# Move tensors to same device as data
|
| 122 |
+
min_val = self.min_val.to(data.device)
|
| 123 |
+
max_val = self.max_val.to(data.device)
|
| 124 |
+
|
| 125 |
+
# Avoid division by zero
|
| 126 |
+
range_val = max_val - min_val
|
| 127 |
+
range_val = torch.where(range_val == 0, torch.ones_like(range_val), range_val)
|
| 128 |
+
|
| 129 |
+
# Clamp input data to avoid extreme values
|
| 130 |
+
if self.is_global:
|
| 131 |
+
data_clamped = torch.clamp(data, min_val, max_val)
|
| 132 |
+
else:
|
| 133 |
+
data_clamped = data
|
| 134 |
+
|
| 135 |
+
return (data_clamped - min_val) / range_val
|
| 136 |
+
|
| 137 |
+
def inverse_transform(self, data):
|
| 138 |
+
"""Transform data back to original scale."""
|
| 139 |
+
if self.min_val is None or self.max_val is None:
|
| 140 |
+
raise ValueError("Scaler not fitted. Call fit() first.")
|
| 141 |
+
|
| 142 |
+
# Move tensors to same device as data
|
| 143 |
+
min_val = self.min_val.to(data.device)
|
| 144 |
+
max_val = self.max_val.to(data.device)
|
| 145 |
+
|
| 146 |
+
return data * (max_val - min_val) + min_val
|
| 147 |
+
|