File size: 6,195 Bytes
927a2f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset
from typing import Union, List, Tuple, Dict

# written by Shourya Bose

class NRELComstock(Dataset):
    """
    torch Dataset class to load in data from numpy array
    """
    
    def __init__(
        self,
        data_array: np.ndarray, # numpy array of shape (B,L,F). B: number of buildings, L: number of time indices, F: number of features; keep F at 1 for the univariate case (this script)
        num_bldg: int = 12, # number of buildings to consider, should not be greater than first dimension of data_array
        lookback: int = 12, # forecasting lookback window
        lookahead: int = 4, # forecasting lookahead window
        normalize: bool = True, # whether to normalize feature-wise
        dtype: torch.dtype = torch.float32, # data type of outputs
        mean: np.ndarray = None, # if you want to supply your own statistics rather than calculate it in the function, do here. shape (1,1,F)
        std: np.ndarray = None, # if you want to supply your own statistics rather than calculate it in the function, do here. shape (1,1,F)
        transformer: bool = True # if normalize=True, this disables normalization of time indices for xformer embedding - unused for the univariate case (this script)
    ):
        super(NRELComstock, self).__init__()
        
        if data_array.shape[0] < num_bldg:
            raise ValueError('More buildings than present in file!')
        else:
            self.data = data_array[:num_bldg,:,[0]] # UNIVARIATE SELECTION: SELECT THE FIRST OUT OF 8 FEATURES
        self.num_clients = num_bldg
        
        # lookback and lookahead
        self.lookback, self.lookahead = lookback, lookahead
        
        # Calculate statistics
        stacked = self.data.reshape(self.data.shape[0]*self.data.shape[1],self.data.shape[2])
        if (mean is None) or (std is None): # statistics are not provided. Generate it from data
            self.mean = stacked.mean(axis=0,keepdims=True)
            self.std = stacked.std(axis=0,keepdims=True)
        else: # statistics are provided. Use the provided statistics
            self.mean = mean
            self.std = std
            
        # if transformer:
        #     # TRANSFORMER SPECIFIC: do not normalize date and time
        #     self.mean[0,1], self.std[0,1] = 0., 1.
        #     self.mean[0,2], self.std[0,2] = 0., 1.
            
        self.ndata = (self.data-self.mean)/self.std # normalized data
        
        # disambiguating between clients
        len_per_client = self.data.shape[1] - lookback - lookahead + 1
        self.total_len = len_per_client * self.num_clients
        self.splits = np.array_split(np.arange(self.total_len),self.num_clients)
        
        # save whether to normalize, and the data type
        self.normalize = normalize
        self.dtype = dtype
        
        # if normalization is disabled, return to default statistics
        if not self.normalize:
            self.mean = np.zeros_like(self.mean)
            self.std = np.ones_like(self.std)
        
    def _client_and_idx(self, idx):
        
        part_size = self.total_len // self.num_clients
        part_index = idx // part_size
        relative_position = idx % part_size
        
        return relative_position, part_index
    
    def __len__(self):
        
        return self.total_len
    
    def __getitem__(self, idx):
        
        tidx, cidx = self._client_and_idx(idx)
        
        if self.normalize:
            x = self.ndata[cidx,tidx:tidx+self.lookback,0] 
            y = self.ndata[cidx,tidx+self.lookback:tidx+self.lookback+self.lookahead,0]
        else:
            x = self.data[cidx,tidx:tidx+self.lookback,0]
            y = self.data[cidx,tidx+self.lookback:tidx+self.lookback+self.lookahead,0]
            
        x, y = torch.tensor(x,dtype=self.dtype), torch.tensor(y,dtype=self.dtype)
        
        return x,y
    

def get_data_and_generate_train_val_test_sets(
    data_array: np.ndarray, # numpy array of shape (B,L,F). B: number of buildings, L: number of time indices, F: number of features; keep F at 1 for the univariate case (this script)
    split_ratios: Union[List,Tuple], # 3-element list containing the non-negative ratios of train-val-test that add upto 1. for example, [0.8,0.1,0.1]
    dataset_kwargs: Tuple # kwargs dictionary to pass into NRELComstock class, check definition. Do not pass data_array, mean, or std into it since this function does that
) -> Tuple[torch.utils.data.Dataset, torch.utils.data.Dataset, torch.utils.data.Dataset, np.ndarray, np.ndarray]:
    """
    function to create three torch Dataset objects, each corresponding to train, validation, and test sets
    """
    
    assert len(split_ratios) == 3, "The split list must contain three elements."
    assert all(isinstance(i, (int, float)) for i in split_ratios), "List contains non-numeric elements"
    assert sum(split_ratios) <= 1, "Ratios must not sum upto more than 1."
    
    cum_splits = np.cumsum(split_ratios)
    
    train = data_array[:,:int(cum_splits[0]*data_array.shape[1]),:]
    val = data_array[:,int(cum_splits[0]*data_array.shape[1]):int(cum_splits[1]*data_array.shape[1]),:]
    test = data_array[:,int(cum_splits[1]*data_array.shape[1]):,:]
    
    if 0 in train.shape:
        train_set = None
        raise ValueError("Train set is empty. Possibly empty data matrix or 0 ratio for train set has been input.")
    else:
        train_set = NRELComstock(
            data_array = train,
            **dataset_kwargs
        )
        mean, std = train_set.mean, train_set.std
    if 0 in val.shape:
        val_set = None
    else:
        val_set = NRELComstock(
            data_array = val,
            mean = mean,
            std = std,
            **dataset_kwargs
        )
    if 0 in test.shape:
        test_set = None
    else:
        test_set = NRELComstock(
            data_array = test,
            mean = mean,
            std = std,
            **dataset_kwargs
        )
    
    # return the three datasets, as well as the statistics
    return train_set, val_set, test_set, mean, std