File size: 15,933 Bytes
f3972ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import numpy as np
import pickle
from torch.utils.data import Dataset, DataLoader
import os
import torch
from copy import deepcopy
from blimpy import Waterfall
from tqdm import tqdm
from copy import deepcopy
from sigpyproc.readers import FilReader
from torch import nn


def load_pickled_data(file_path):
    with open(file_path, 'rb') as f:
        data = pickle.load(f)
    return data

# Custom dataset class
class CustomDataset(Dataset):
    def __init__(self, data_dir, bit8=False, transform=None):
        self.data_dir = data_dir
        self.transform = transform
        self.images = []
        self.labels = []
        self.classes = os.listdir(data_dir)
        self.class_to_idx = {cls: idx for idx, cls in enumerate(self.classes)}
        self.bit8 = bit8
        # Load images and labels
        for cls in self.classes:
            class_dir = os.path.join(data_dir, cls)
            for image_name in os.listdir(class_dir):
                image_path = os.path.join(class_dir, image_name)
                self.images.append(image_path)
                self.labels.append(self.class_to_idx[cls])

    def __len__(self):
        return len(self.images)

    def __getitem__(self, idx):
        image_path = self.images[idx]
        label = self.labels[idx]
        # Load image
        image = load_pickled_data(image_path)
        if self.transform is not None:
            if self.bit8 == True:
                new_image = self.transform(torch.from_numpy(image['8_data']).type(torch.float32))
            else:
                new_image = self.transform(torch.from_numpy(image['data']))
            # new_image = self.transform(image['data'])
        return new_image, label

# Custom dataset class
class CustomDataset_Masked(Dataset):
    def __init__(self, data_dir, transform=None):
        self.data_dir = data_dir
        self.transform = transform
        self.images = []
        self.labels = []
        self.classes = os.listdir(data_dir)
        self.class_to_idx = {cls: idx for idx, cls in enumerate(self.classes)}

        # Load images and labels
        for cls in self.classes:
            class_dir = os.path.join(data_dir, cls)
            for image_name in os.listdir(class_dir):
                image_path = os.path.join(class_dir, image_name)
                self.images.append(image_path)
                self.labels.append(self.class_to_idx[cls])
        
    def __len__(self):
        return len(self.images)

    def __getitem__(self, idx):
        image_path = self.images[idx]
        
        label = self.labels[idx]
        # Load image
        image = load_pickled_data(image_path)
        if self.transform is not None:
            if image['burst'].max() ==0:
                new_burst = torch.from_numpy(image['burst'])
            else:
                new_burst = torch.from_numpy(image['burst']/image['burst'].max())
            ind = new_burst > 0.1
            ind_not = new_burst <= 0.1
            new_burst[ind] = 1
            new_burst[ind_not] = 0
            new_image = self.transform(torch.from_numpy(image['data'].data))
            new_burst_arr = torch.zeros_like(new_image)
            new_burst_arr[ 0, :,:] =   new_burst 
            new_burst_arr[ 1, :,:] =   new_burst 
            new_burst_arr[ 2, :,:] =   new_burst 
        return new_image, label, new_burst_arr

# Custom dataset class
class TestingDataset(Dataset):
    def __init__(self, data_dir, bit8=False, transform=None):
        self.data_dir = data_dir
        self.transform = transform
        self.images = []
        self.labels = []
        self.classes = os.listdir(data_dir)
        self.class_to_idx = {cls: idx for idx, cls in enumerate(self.classes)}
        self.bit8 = bit8
        # Load images and labels
        for cls in self.classes:
            class_dir = os.path.join(data_dir, cls)
            for image_name in os.listdir(class_dir):
                image_path = os.path.join(class_dir, image_name)
                self.images.append(image_path)
                self.labels.append(self.class_to_idx[cls])

    def __len__(self):
        return len(self.images)

    def __getitem__(self, idx):
        image_path = self.images[idx]
        label = self.labels[idx]
        # Load image
        image = load_pickled_data(image_path)
        params = image['params']
        if self.transform is not None:
            params = image['params']
            if self.bit8 == True:
                new_image = self.transform(torch.from_numpy(image['8_data']).type(torch.float32))
            else:
                new_image = self.transform(torch.from_numpy(image['data']))
        params['labels'] = label
        return new_image, (label, params['dm'], params['freq_ref'], params['snr'],  params['boxcard'])

# Custom dataset class
class SearchDataset(Dataset):
    def __init__(self, data_dir, transform=None, pickle_data=False):
        self.window_size = 2048
        
        if pickle_data:
            with open(data_dir, 'rb') as f:
                self.d = pickle.load(f)
            self.header = self.d['header']
            self.images = self.crop(self.d['data'][:,0,:], self.window_size)
        else:
            self.obs = Waterfall(data_dir, max_load = 50)
            self.header = self.obs.header
            self.images = self.crop(self.obs.data[:,0,:], self.window_size)
        self.transform = transform
        self.SEC_PER_DAY = 86400
        
    def crop(self, data, window_size = 2048):
        n_samp = data.shape[0]//window_size
        new_data = np.zeros((n_samp, window_size, 192 ))
        for i in range(n_samp):
            new_data[i, :,:] = data[ i*window_size : (i+1)*window_size, :]
        return new_data
        
    def __len__(self):
        return self.images.shape[0]
    def __getitem__(self, idx):
        data = self.images[idx, :, :].T 
        tindex = idx * self.window_size
        time = self.header['tsamp'] * tindex / self.SEC_PER_DAY + self.header['tstart']
        if self.transform is not None:
            new_image = self.transform(data)
        return new_image, idx

# Custom dataset class
class SearchDataset_Sigproc(Dataset):
    def __init__(self, data_dir, transform=None):
        self.window_size = 2048
        fil = FilReader(data_dir)
        self.header = fil.header
        # print("check shape ",fil.read_block(0, fil.header.nsamples).shape)
        read_data = fil.read_block(0, fil.header.nsamples)[:,1024:-1024]
        read_data = np.swapaxes(read_data, 0,-1)
        self.images = self.crop(read_data, self.window_size) 
        self.transform = transform
        self.SEC_PER_DAY = 86400
        
    def crop(self, data, window_size = 2048):
        n_samp = data.shape[0]//window_size
        new_data = np.zeros((n_samp, window_size, 192 ))
        for i in range(n_samp):
            new_data[i, :,:] = data[ i*window_size : (i+1)*window_size, :]
        return new_data
        
    def __len__(self):
        return self.images.shape[0]
        
    def __getitem__(self, idx):
        data = self.images[idx, :, :].T 
        tindex = idx * self.window_size
        time = self.header.tsamp * tindex / self.SEC_PER_DAY + self.header.tstart
        if self.transform is not None:
            new_image = self.transform(torch.from_numpy(data))
        return new_image, idx

# def renorm(data):
#     shifted = data - data.min()
#     shifted = shifted/shifted.max()
#     return shifted

def renorm(data):
    mean = torch.mean(data)
    std = torch.std(data)
    # Standardize the data
    standardized_data = (data - mean) / std
    return standardized_data

def transform(data):
    copy_data = data.detach().clone()
    rms = torch.std(data)
    mean = torch.mean(data)
    masks_rms = [-1, 5]
    new_data = torch.zeros((len(masks_rms)+1, data.shape[0], data.shape[1]))
    new_data[0,:,:] = renorm(torch.log10(copy_data+1e-10))  
    for i in range(1, len(masks_rms)+1):
        scale = masks_rms[i-1]
        copy_data = data.detach().clone() #deepcopy(data)
        if scale < 0:
            ind = copy_data < abs(scale) * rms  + mean
            copy_data[ind] = 0
        else:
            ind = copy_data > (scale) * rms + mean
            copy_data[ind] = 0
        new_data[i,:,:] = renorm(torch.log10(copy_data+1e-10))
    new_data = new_data.type(torch.float32)
    slices = torch.chunk(new_data, 8, dim=-1)  # dim=1 is the height dimension
    new_data = torch.stack(slices, dim=1)  # New axis is inserted at dim=1
    new_data = new_data.view(-1, new_data.size(2), new_data.size(3))
    return new_data


def renorm_batched(data):
    mean = torch.mean(data, dim=tuple(range(1, data.ndim)), keepdim=True)
    std = torch.std(data, dim=tuple(range(1, data.ndim)), keepdim=True)
    standardized_data = (data - mean) / std
    return standardized_data

def transform_batched(data):
    copy_data = data.detach().clone()
    rms = torch.std(data, dim=tuple(range(1, data.ndim)), keepdim=True)  # Batch-wise std
    mean = torch.mean(data, dim=tuple(range(1, data.ndim)), keepdim=True)  # Batch-wise mean
    masks_rms = [-1, 5]
    
    # Prepare the new_data tensor
    num_masks = len(masks_rms) + 1
    new_data = torch.zeros((num_masks, *data.shape), device=data.device)  # Shape: (num_masks, batch_size, ..., ...)

    # First layer: Apply renorm(log10(copy_data + epsilon))
    new_data[0] = renorm_batched(torch.log10(copy_data + 1e-10))
    for i, scale in enumerate(masks_rms, start=1):
        copy_data = data.detach().clone()
        
        # Apply masking based on the scale
        if scale < 0:
            ind = copy_data < abs(scale) * rms + mean
        else:
            ind = copy_data > scale * rms + mean
        copy_data[ind] = 0
        
        # Renormalize and log10 transform
        new_data[i] = renorm_batched(torch.log10(copy_data + 1e-10))
    
    # Convert to float32
    new_data = new_data.type(torch.float32)

    # Chunk along the last dimension and stack
    slices = torch.chunk(new_data, 8, dim=-1)  # Adjust for batch-wise slicing
    new_data = torch.stack(slices, dim=2)  # Insert a new axis at dim=1
    new_data = torch.swapaxes(new_data, 0,1)
    # Reshape into final format
    new_data = new_data.reshape( new_data.size(0), 24,  new_data.size(3), new_data.size(4))  # Flatten batch and mask dimensions
    return new_data



class preproc(nn.Module):
    def forward(self, x, flip=True):
        if flip:
            transform_batched(torch.flip(x, dims = (-2,)))
        else:
            transform_batched(x)
        return template
        
# class preproc_debug(nn.Module):
#     def forward(self, x):
#         template = torch.zeros((32, 24, 192, 256))
#         # for i in torch.arange(x.shape[0]):  # Use a tensor-based range
#         template[0,:,:,:] = transform_debug(torch.flip(x[0,:,:], dims = (0,)))
#         template[1,:,:,:] = transform_debug(torch.flip(x[1,:,:], dims = (0,)))
#         template[2,:,:,:] = transform_debug(torch.flip(x[2,:,:], dims = (0,)))
#         template[3,:,:,:] = transform_debug(torch.flip(x[3,:,:], dims = (0,)))
#         template[4,:,:,:] = transform_debug(torch.flip(x[4,:,:], dims = (0,)))
#         template[5,:,:,:] = transform_debug(torch.flip(x[5,:,:], dims = (0,)))
#         template[6,:,:,:] = transform_debug(torch.flip(x[6,:,:], dims = (0,)))
#         template[7,:,:,:] = transform_debug(torch.flip(x[7,:,:], dims = (0,)))
#         template[8,:,:,:] = transform_debug(torch.flip(x[8,:,:], dims = (0,)))
#         template[9,:,:,:] = transform_debug(torch.flip(x[9,:,:], dims = (0,)))
#         template[10,:,:,:] = transform_debug(torch.flip(x[10,:,:], dims = (0,)))
#         template[11,:,:,:] = transform_debug(torch.flip(x[11,:,:], dims = (0,)))
#         template[12,:,:,:] = transform_debug(torch.flip(x[12,:,:], dims = (0,)))
#         template[13,:,:,:] = transform_debug(torch.flip(x[13,:,:], dims = (0,)))
#         template[14,:,:,:] = transform_debug(torch.flip(x[14,:,:], dims = (0,)))
#         template[15,:,:,:] = transform_debug(torch.flip(x[15,:,:], dims = (0,)))
#         template[16,:,:,:] = transform_debug(torch.flip(x[16,:,:], dims = (0,)))
#         template[17,:,:,:] = transform_debug(torch.flip(x[17,:,:], dims = (0,)))
#         template[18,:,:,:] = transform_debug(torch.flip(x[18,:,:], dims = (0,)))
#         template[19,:,:,:] = transform_debug(torch.flip(x[19,:,:], dims = (0,)))
#         template[20,:,:,:] = transform_debug(torch.flip(x[20,:,:], dims = (0,)))
#         template[21,:,:,:] = transform_debug(torch.flip(x[21,:,:], dims = (0,)))
#         template[22,:,:,:] = transform_debug(torch.flip(x[22,:,:], dims = (0,)))
#         template[23,:,:,:] = transform_debug(torch.flip(x[23,:,:], dims = (0,)))
#         template[24,:,:,:] = transform_debug(torch.flip(x[24,:,:], dims = (0,)))
#         template[25,:,:,:] = transform_debug(torch.flip(x[25,:,:], dims = (0,)))
#         template[26,:,:,:] = transform_debug(torch.flip(x[26,:,:], dims = (0,)))
#         template[27,:,:,:] = transform_debug(torch.flip(x[27,:,:], dims = (0,)))
#         template[28,:,:,:] = transform_debug(torch.flip(x[28,:,:], dims = (0,)))
#         template[29,:,:,:] = transform_debug(torch.flip(x[29,:,:], dims = (0,)))
#         template[30,:,:,:] = transform_debug(torch.flip(x[30,:,:], dims = (0,)))
#         template[31,:,:,:] = transform_debug(torch.flip(x[31,:,:], dims = (0,)))
#         return template
        
# def transform_debug(data):
#     copy_data = data.detach().clone()
#     rms = torch.std(data)
#     mean = torch.mean(data)
#     masks_rms = [-1, 5]
#     new_data = torch.zeros((len(masks_rms)+1, data.shape[0], data.shape[1]))
#     new_data[0,:,:] = renorm(torch.log10(copy_data+1e-10))  
#     for i in range(1, len(masks_rms)+1):
#         scale = masks_rms[i-1]
#         copy_data = data.detach().clone()
#         if scale < 0:
#             ind = copy_data < abs(scale) * rms  + mean
#             copy_data[ind] = 0
#         else:
#             ind = copy_data > (scale) * rms + mean
#             copy_data[ind] = 0
#         new_data[i,:,:] = renorm(torch.log10(copy_data+1e-10))
#     new_data = new_data.type(torch.float32)
#     slices = torch.chunk(new_data, 8, dim=-1)  # dim=1 is the height dimension
#     new_data = torch.stack(slices, dim=1)  # New axis is inserted at dim=1
#     new_data = new_data.view(-1, new_data.size(2), new_data.size(3))
#     return new_data
    
def renorm_batched(data):
    mins = torch.amin(data, (-2, -1))
    mins = mins.unsqueeze(1).unsqueeze(2)
    mins = mins.expand(data.shape[0], 192, 2048)
    shifted = data - mins
    maxs = torch.amax(shifted, (-2, -1))
    maxs = maxs.unsqueeze(1).unsqueeze(2)
    maxs = maxs.expand(data.shape[0], 192, 2048)
    shifted = shifted/maxs
    return shifted
    

def transform_mask(data):
    copy_data = deepcopy(data)
    shift = copy_data - copy_data.min()
    normalized_data = shift / shift.max()
    new_data = np.zeros((3, data.shape[0], data.shape[1]))
    for i in range(3):
        new_data[i,:,:] = normalized_data 
    new_data = new_data.astype(np.float32)
    return new_data


#Function to Convert to ONNX 
def Convert_ONNX(model, saveloc, input_data_mock): 
    print("Saving to ONNX")
    # set the model to inference mode 
    model.eval()

    # Let's create a dummy input tensor  
    dummy_input = torch.autograd.Variable(input_data_mock)

    # Export the model   
    torch.onnx.export(model,         # model being run 
         dummy_input,       # model input (or a tuple for multiple inputs) 
         saveloc,       # where to save the model  
         input_names = ['modelInput'],   # the model's input names 
         output_names = ['modelOutput'], # the model's output names 
         dynamic_axes={'modelInput' : {0 : 'batch_size'},    # variable length axes
                    'modelOutput' : {0 : 'batch_size'}} ) 
    print(" ") 
    print('Model has been converted to ONNX')