File size: 12,098 Bytes
aa0c0b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import numpy as np
from sklearn.preprocessing import StandardScaler
import torch
from Dataset import STDataset,TrafficDataset
import os
# from Dataset import Auxility_dataset
import numpy as np
from torch.utils.data import Dataset, DataLoader,SubsetRandomSampler
from datetime import datetime
import matplotlib.pyplot as plt
from sklearn.metrics import mean_absolute_error, mean_squared_error
import yaml,logging
# # from models.GWNET import gwnet
# from models.MTGNN import MTGNN
# from models import TGCN,ASTGCNCommon,CCRNN,STGCN,AGCRN,STTN,DCRNN
import copy
class CustomStandardScaler:
    def __init__(self, axis=None):
        self.axis = axis
        self.mean = None
        self.std = None

    def fit(self, data):
        if self.axis is None:
            # If axis is not specified, calculate mean and std over the entire data
            self.mean = np.mean(data)
            self.std = np.std(data)
        else:
            # Calculate mean and std along the specified axis
            self.mean = np.mean(data, axis=self.axis)
            self.std = np.std(data, axis=self.axis)

    def transform(self, data):
        if self.mean is None or self.std is None:
            raise ValueError("Scaler has not been fitted. Call 'fit' method first.")
        
        # Standardize the data using the calculated mean and std
        standardized_data = (data - self.mean) / self.std
        return standardized_data
    
    def inverse_transform(self, standardized_data):
        if self.mean is None or self.std is None:
            raise ValueError("Scaler has not been fitted. Call 'fit' method first.")
        
        # Reverse the standardization process
        original_data = standardized_data * self.std + self.mean
        return original_data
def to_node_day_hour(arr):
    """Normalize raw npy to (nodes, days, 24, feat). Hour-first 3D is (hours, nodes, feat)."""
    if arr.ndim == 4:
        return arr
    if arr.ndim != 3:
        raise ValueError(f"Expected 3D or 4D array, got shape {arr.shape}")
    hours = (arr.shape[0] // 24) * 24
    arr = arr[:hours]
    n_nodes = arr.shape[1]
    return arr.transpose(1, 0, 2).reshape(n_nodes, -1, 24, arr.shape[2])


def paper_valid_grid(train_data):
    """Paper Sec 5.1.1: drop zones whose training-period mean demand is <= 2."""
    train4 = to_node_day_hour(train_data)
    return np.where(train4.mean(axis=(1, 2, 3)) > 2)[0]


_PKG_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
PAPER_DATASET_ROOT = os.path.join(_PKG_ROOT, 'dataset')
PAPER_MODEL_ROOT = os.path.join(_PKG_ROOT, 'saved_models')


def resolve_dataset_dir(config):
    """Prefer the original paper dump when present; otherwise ./dataset/<name>."""
    name = config['dataset_name']
    if config.get('dataset_root'):
        return os.path.join(config['dataset_root'], name)
    paper_dir = os.path.join(PAPER_DATASET_ROOT, name)
    if os.path.isfile(os.path.join(paper_dir, 'train.npy')):
        return paper_dir
    return os.path.join('dataset', name)


def load_paper_adj(config, valid_grid):
    ds_dir = config.get('resolved_dataset_dir') or resolve_dataset_dir(config)
    adj = np.load(os.path.join(ds_dir, 'adj_mx.npy')).astype(np.float32)
    n = int(np.max(valid_grid)) + 1
    if adj.shape[0] < n:
        padded = np.zeros((n, n), dtype=np.float32)
        padded[: adj.shape[0], : adj.shape[1]] = adj
        adj = padded
    return adj[valid_grid][:, valid_grid]


def resolve_model_path(model_name, dataset_name, config=None):
    if config and config.get('model_path'):
        return config['model_path']
    paper = os.path.join(PAPER_MODEL_ROOT, f'{model_name}_{dataset_name}_final_model.pth')
    local = os.path.join('saved_models', f'{model_name}_{dataset_name}_final_model.pth')
    if os.path.isfile(paper):
        return paper
    return local


def filter_data(data):
    daily_totals = np.sum(data, axis=(0,2, 3))
    
    # 找到总数不为0的天的索引
    valid_days_idx = np.where(daily_totals > 0)[0]
    
    # 根据索引创建新的data数组
    return data[:,valid_days_idx]
def time_add(data, week_start, interval=5, weekday_only=False, holiday_list=None, day_start=0, hour_of_day=24):
    # day and week
    if weekday_only:
        week_max = 5
    else:
        week_max = 7
    time_slot = hour_of_day * 60 // interval
    day_data = np.zeros_like(data)
    week_data = np.zeros_like(data)
    holiday_data = np.zeros_like(data)
    day_init = day_start
    week_init = week_start
    holiday_init = 1

    for index in range(day_start//interval, data.shape[0]+day_start//interval):
        if (index) % time_slot == 0 and index!=0:
            day_init = 0
        day_init = day_init + interval
        if (index) % time_slot == 0 and index !=0:
            week_init = week_init + 1
        if week_init > week_max:
            week_init = 1
        if day_init < 6:
            holiday_init = 1
        else:
            holiday_init = 2

        day_data[index:index + 1, :] = day_init
        week_data[index:index + 1, :] = week_init
        holiday_data[index:index + 1, :] = holiday_init

    if holiday_list is None:
        k = 1
    else:
        for j in holiday_list :
            holiday_data[j-1 * time_slot:j * time_slot, :] = 2
    return day_data, week_data, holiday_data

def load_data( config):
    # List all the available files in the data directory


    # Sort the files by name to ensure chronological order
    # config=vars(config)


    ds_dir = resolve_dataset_dir(config)
    config['resolved_dataset_dir'] = ds_dir
    train_data = np.load(os.path.join(ds_dir, 'train.npy'))
    val_data = np.load(os.path.join(ds_dir, 'val.npy'))
    test_data = np.load(os.path.join(ds_dir, 'test.npy'))
    # print(train_data.shape)
    
    # Paper Sec 5.1.1: keep zones with training-period mean demand > 2.
    # Accept both hour-first 3D (hours, nodes, 2) and 4D (nodes, days, 24, 2).
    train_data = to_node_day_hour(train_data)
    val_data = to_node_day_hour(val_data)
    test_data = to_node_day_hour(test_data)
    valid_grid = paper_valid_grid(train_data)
    train_data, val_data, test_data = train_data[valid_grid], val_data[valid_grid], test_data[valid_grid]
    
    




   
    
   
        
    scaler = CustomStandardScaler()  # Specify the axis over which to calculate mean and std
    scaler.fit(train_data)

    # Standardize the data
    train_data = scaler.transform(train_data)
    val_data = scaler.transform(val_data)
    test_data = scaler.transform(test_data)
    if 'tc_num_heads' in config.keys():
        test_data=test_data.transpose(1,2,0,3)
        test_data=test_data.reshape(test_data.shape[0]*test_data.shape[1],-1)
        week_start = 3
        interval = 5
        week_day = 7
        holiday_list = None
        interval = 60
  
        day_data, week_data, holiday_data = time_add(test_data, week_start, interval=interval, weekday_only=False, holiday_list=holiday_list)
        test_data= np.expand_dims(test_data, axis=-1)
        day_data = np.expand_dims(day_data, axis=-1).astype(int)
        week_data = np.expand_dims(week_data, axis=-1).astype(int)
        # holiday_data = np.expand_dims(holiday_data, axis=-1).astype(int)
        test_data = np.concatenate([test_data, day_data, week_data], axis=-1)
        train_data=train_data.transpose(1,2,0,3)
        train_data=train_data.reshape(train_data.shape[0]*train_data.shape[1],-1)
        day_data, week_data, holiday_data = time_add(train_data, 2, interval=interval, weekday_only=False, holiday_list=holiday_list)
        train_data= np.expand_dims(train_data, axis=-1)
        day_data = np.expand_dims(day_data, axis=-1).astype(int)
        week_data = np.expand_dims(week_data, axis=-1).astype(int)
        # holiday_data = np.expand_dims(holiday_data, axis=-1).astype(int)
        train_data = np.concatenate([train_data, day_data, week_data], axis=-1)



    return train_data, val_data, test_data, scaler,valid_grid

def get_datasets( config):
    # Load and preprocess the data using load_data function
    train_data, val_data, test_data, scaler,valid_gird = load_data( config)
    # if config.model=='iVAE':
    #     train_dataset=iVAE.iVAEDataset(train_data,config)
    #     val_dataset=iVAE.iVAEDataset(val_data,config)
    #     test_dataset=iVAE.iVAEDataset(test_data,config)
    #     return train_dataset, val_dataset, test_dataset, scaler,valid_gird

    # Create datasets using the STDataset class
    train_dataset = STDataset(train_data, config)
    val_dataset = STDataset(val_data, config,if_train=False,index=len(train_dataset)//(30*24))
    if 'tc_num_heads' in config.keys():
        test_dataset=TrafficDataset(test_data,batch_size=1)
        train_dataset=TrafficDataset(train_data,batch_size=1)
    else:
        test_dataset = STDataset(test_data, config,if_train=False,index=len(train_dataset)//(30*24))

    return train_dataset, val_dataset, test_dataset, scaler,valid_gird

def expand_adjacency_matrix(adj_matrix, m):
    n = adj_matrix.shape[0]
    
    if m < n:
        m=n
    
    expanded_adj_matrix = np.zeros((m, m), dtype=int)
    expanded_adj_matrix[:n, :n] = adj_matrix
    
    # Add self-loops
    np.fill_diagonal(expanded_adj_matrix, 1)
    
    return expanded_adj_matrix-np.eye(len(expanded_adj_matrix))
from typing import Union
class Dataset_Recent(Dataset):
    def __init__(self, dataset, gap: Union[int, tuple, list], recent_num=1, take_post=0, strength=0, **kwargs):
        super().__init__()
        self.more = gap - recent_num + 1
        self.dataset = dataset
        self.gap = gap
        self.recent_num = recent_num
        if strength:
            print("Modify time series with strength =", strength)
            for i in range(3, len(self.dataset.data_y)):
                self.dataset.data_x[i] *= 1 + 0.1 * (i // 24 % strength)

    def _stack(self, data):
        if isinstance(data[0], np.ndarray):
            return np.vstack(data)
        else:
            return torch.stack(data, 0)

    def __getitem__(self, index):
        if self.recent_num == 1:
            return self.dataset[index], self.dataset[index + self.gap]
        else:
            current_data = self.dataset[index + self.gap + self.recent_num - 1]
            if not isinstance(current_data, tuple):
                recent_data = tuple(self.dataset[index + n] for n in range(self.recent_num))
                recent_data = self._stack(recent_data)
                return current_data, recent_data
            else:
                recent_data = tuple([] for _ in range(len(current_data)))
                for past in range(self.recent_num):
                    for j, past_data in enumerate(self.dataset[index + past]):
                        recent_data[j].append(past_data)
                recent_data = tuple(self._stack(recent_d) for recent_d in recent_data)
            return recent_data, current_data

    def __len__(self):
        return len(self.dataset) - self.more
# def align_data(data):
#     # align  data to have the same mean and variance of data[:,:360,:,:]
#     #data (node_number,day_number,24,2)
    
#     target_mean = data[:,-365:].mean()
#     target_std = data[:,:-365:].std()
#     day_number=data.shape[1]
    
#     for i in range(day_number//365):
#         this_mean = data[:,i*365:(i+1)*365,:,:].mean()
#         this_std = data[:,i*365:(i+1)*365,:,:].std()
        
#         data[:,i*365:(i+1)*365,:,:] = (data[:,i*365:(i+1)*365,:,:]-this_mean)/this_std*target_std+target_mean
        
#     return data

# if __name__ == '__main__':
#     # Test the functions
#     with open('models\config2.yaml', 'r') as f:
#         config = yaml.safe_load(f)
#     train_data, val_data, test_data, scaler,valid_grid=load_data(config['data_dir'],config)
#     align_data(train_data)