-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
198 lines (143 loc) · 4.81 KB
/
Copy pathutils.py
File metadata and controls
198 lines (143 loc) · 4.81 KB
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
import os
from os.path import join
import random
import numpy as np
from pathlib import Path
import pickle
import torch
import torch.nn as nn
from torch.utils.flop_counter import FlopCounterMode
from tqdm.notebook import tqdm
from glob import glob
from functools import partial
import mne
import cv2
import matplotlib.pyplot as plt
class EarlyStop():
def __init__(self, config):
self.config = config
self.loss_per_epoch = []
self.best_epoch = 0
self.best_ckpt = None
self.stop = False
def update(self, loss):
self.loss_per_epoch.append(loss)
if self.best_epoch==0:
self.best_epoch = 1
else:
interval = self.loss_per_epoch[self.best_epoch-1:]
if loss + self.config.tolerance <= interval[0]:
self.best_epoch = len(self.loss_per_epoch)
elif len(interval)==self.config.patience:
self.stop = True
def flatten(xss):
return [x for xs in xss for x in xs]
def mkdir(p, is_file=False):
if is_file:
p = os.path.dirname(p)
if not os.path.isdir(p):
os.makedirs(p)
def manual_seed(seed, dil=False):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if multi-GPU
torch.backends.cudnn.deterministic = not dil
os.environ["PYTHONHASHSEED"] = str(seed)
def num_params(model, include_frozen=False):
n = 0
for param in model.parameters():
if (not include_frozen and param.requires_grad) or include_frozen:
n += param.numel()
return round(n/1e6, 2)
def no_grad(model):
for p in model.parameters():
p.requires_grad = False
@torch.no_grad()
def get_flops(model, x):
flop_counter = FlopCounterMode(mods=model, display=False, depth=None)
with flop_counter:
model(x)
return flop_counter.get_total_flops()
def power_ratio(a, b):
return (a**2).sum(-1)/((b**2).sum(-1)+1e-8)
def SNR(signal, noise):
return 10*np.log10(power_ratio(signal, noise))
def RRMSE(x_, x):
return power_ratio(x_-x, x)**0.5
def PSD(raw, selected_channel, fmin=0, fmax=np.inf, n_fft=2048, interval=[None,None]):
tmin, tmax = interval
psd = raw.compute_psd(
picks=[selected_channel],
tmin=tmin, tmax=tmax,
fmin=fmin, fmax=fmax, n_fft=n_fft,
verbose='error').get_data()[0]
psd *= 1e6**2
psd = 10*np.log10(np.maximum(psd, np.finfo(float).tiny), out=psd)
return psd
def tensor2raw(x, sr, electrodes, scale=1, ch_types=None):
if ch_types is None:
ch_types=['eeg']*len(electrodes)
return mne.io.RawArray(
x.numpy()/1e6 * scale,
mne.create_info(
electrodes,
sr,
ch_types=ch_types
),
verbose='error'
)
def plot_chart(raw, color, size, save_path):
fig = raw.plot(
duration=raw.n_times//raw.info['sfreq'],
show_scrollbars=False,
show_scalebars=False,
show=False,
color=dict(eeg=color, eog='orange')
)
fig.set_size_inches(*size)
fig.savefig(save_path)
return cv2.imread(save_path)
def plot_overlayed_chart(a, b, save_path, size=[10,5], color='orange'):
a = plot_chart(a, color, size, os.path.dirname(save_path)+'/a.png')
b = plot_chart(b, 'black', size, os.path.dirname(save_path)+'/b.png')
plt.show()
pixel_mean = b.mean(-1,keepdims=True) / 255
ab = (pixel_mean>0.99) * a + b
cv2.imwrite(save_path, ab)
@torch.no_grad()
def chunk_and_apply(f, x, batch_size, chunk_size, overlap_factor=None, single_channel=False):
C, T = x.shape
if overlap_factor is not None:
assert chunk_size%overlap_factor==0
overlap = chunk_size//overlap_factor
x = torch.cat([torch.zeros(*batch_dims, overlap).to(x.device), x], -1)
else:
overlap = 0
gen_size = chunk_size - 2*overlap
pad_size = gen_size - T%gen_size
x = torch.cat([x, torch.zeros(C, pad_size+overlap).to(x.device)], -1)
chunks = []
i = 0
while i < T + pad_size:
chunk = x[..., i:i+chunk_size]
chunks.append(chunk)
i += gen_size
chunks = torch.stack(chunks)
batches = []
i = 0
while i < len(chunks):
batches.append(chunks[i:i+batch_size])
i = i + batch_size
output_chunks = []
for batch in batches:
if single_channel:
batch = batch.reshape(-1,chunk_size)
x = f(x=batch)
if single_channel:
x = x.reshape(-1,C,chunk_size)
if overlap > 0:
x = x[...,overlap:-overlap]
output_chunks += torch.unbind(x.cpu(), 0)
return torch.cat(output_chunks, -1)[...,:-pad_size]