-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReSiDe_M_brain_inference.py
200 lines (160 loc) · 6.56 KB
/
ReSiDe_M_brain_inference.py
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
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 00:37:34 2023
@author: sizhu
"""
import sys
# sys.path.append('/')
import logging
import pathlib
import random
import shutil
import time
import os
import h5py
import numpy as np
import torch
import torchvision
from torch.nn import functional as F
from torch.utils.data import DataLoader
from scipy.io import loadmat, savemat
import torch.nn as nn
import torch
import torch.nn.init as init
#from torch.utils import data
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import MultiStepLR
import os, glob, re
import torch.optim as optim
from pMRI_2D import pMRI_2D
from skimage.restoration import (denoise_wavelet, estimate_sigma)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def NMSE(true,b):
y = 20*np.log10(np.linalg.norm(true-b)/np.linalg.norm(true))
return y
class MeanOnlyBatchNorm(nn.Module):
def __init__(self, num_features, momentum=0.1):
super(MeanOnlyBatchNorm, self).__init__()
self.num_features = num_features
self.momentum = momentum
self.bias = nn.Parameter(torch.zeros(num_features))
# self.running_mean = torch.zeros(num_features)
self.register_buffer('running_mean', torch.zeros(num_features))
def forward(self, inp):
size = list(inp.size())
beta = self.bias.view(1, self.num_features, 1, 1)
if self.training:
avg = torch.mean(inp, dim=3)
avg = torch.mean(avg, dim=2)
avg = torch.mean(avg, dim=0)
self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * avg
else:
avg = self.running_mean.repeat(size[0], 1)
output = inp - avg.view(1, self.num_features, 1, 1)
output = output + beta
return output
def extra_repr(self):
return '{num_features}, momentum={momentum} '.format(**self.__dict__)
class BasicNet(nn.Module):
def __init__(self):
layers = []
imchannel = 2
filternum = 128
filtersize = 3
depth = 3
super(BasicNet, self).__init__()
layers.append(nn.utils.spectral_norm(nn.Conv2d(imchannel, filternum, filtersize, padding=1, bias=True), n_power_iterations=20))
layers.append(nn.ReLU(inplace=True))
for _ in range(depth):
layers.append(nn.utils.spectral_norm(nn.Conv2d(filternum, filternum, filtersize, padding=1, bias=False), n_power_iterations=20))
layers.append(MeanOnlyBatchNorm(filternum,momentum=0.95))
layers.append(nn.ReLU(inplace=True))
layers.append(nn.utils.spectral_norm(nn.Conv2d(filternum, imchannel, filtersize, padding=1, bias=False), n_power_iterations=20))
self.cnn = nn.Sequential(*layers)
self.init_weights()
def forward(self,x):
y = x
out = self.cnn(x)
return y-out
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
init.xavier_normal_(m.weight)
if m.bias is not None:
init.constant_(m.bias, 0)
def powerite(pMRI, n):
q = np.random.randn(*n)
q = q/np.linalg.norm(q.flatten())
th = 1e-3
err = np.inf
uest = np.inf
while err > th:
q = pMRI.multTr(pMRI.mult(q))
unew = np.linalg.norm(q.flatten())
err = abs(np.log(uest/unew))
uest = unew
q = q/np.linalg.norm(q.flatten())
return uest
def apply_denoiser(x,model):
x = np.fft.ifftshift(np.fft.ifftshift(x,axes=1),axes = 0)
x_norm = np.expand_dims(x,axis = 0)
x_im = np.expand_dims(x_norm ,axis = 1)
x_im = np.concatenate((np.real(x_im),np.imag(x_im)),1)
x_im = np.array(x_im,dtype = 'float32')
x_im = torch.from_numpy(x_im).cuda()
w = model(x_im).cpu()
w = w.detach().numpy().astype(np.float32)
w = np.squeeze(w[:,0,:,:]+1j*w[:,1,:,:])
w = np.fft.fftshift(np.fft.fftshift(w,axes=0),axes = 1)
return w
#if __name__ == '__main__':
savenmse = []
i=21
k_full = loadmat(os.getcwd()+'Brain/T1/data_for_testing/kspace_and_true_images/k_'+str(i)+'.mat')['k_full']
S = np.squeeze(loadmat(os.getcwd()+'Brain/T1/data_for_testing/GRO_samp_and_sens_maps/r4_gro_map_k'+str(i)+'.mat')['map'])
imtrue = loadmat(os.getcwd()+'Brain/T1/data_for_testing/kspace_and_true_images/im_'+str(i)+'.mat')['imtrue']
samp = loadmat(os.getcwd()+'Brain/T1/data_for_testing/GRO_samp_and_sens_maps/R4_gro'+str(i)+'.mat')['samp']
k_samp = k_full*np.expand_dims(samp,axis=2)
k_shifted = np.fft.fftshift(np.fft.fftshift(k_samp,axes = 0), axes = 1)
samp = np.fft.fftshift(np.fft.fftshift(samp,axes = 0), axes = 1)
samp_shifted = np.tile(np.expand_dims(samp,axis=2),[1,1,np.size(k_full,2)])
kdata = k_shifted.flatten('F')
kdata = kdata[np.where(samp_shifted.flatten('F')>0)]
S = np.fft.fftshift(np.fft.fftshift(S,axes = 0), axes = 1)
pMRI = pMRI_2D(S, samp)
x = pMRI.multTr(kdata)
rho = 1
w = np.fft.fftshift(np.fft.fftshift(x,axes=0),axes = 1)
z = pMRI.mult(x)-kdata
p = powerite(pMRI,x.shape)
gamma_p = rho*p
device = torch.device('cuda:0')
for ite in range(80):
model = BasicNet()
model = torch.load(os.getcwd()+'Brain/T1/data_for_testing/pymodel_%03d.pth' % (ite+1))
model = model.to(device)
model.eval()
xold = x
midvar = xold-rho*pMRI.multTr(z)
midvar = np.fft.ifftshift(np.fft.ifftshift(midvar,axes=1),axes = 0)
midvar_norm = midvar/np.abs(np.real(midvar)).max()
midvar_norm = np.expand_dims(midvar_norm,axis = 0)
midvar_im = np.expand_dims(midvar_norm ,axis = 1)
midvar_im = np.concatenate((np.real(midvar_im),np.imag(midvar_im)),1)
midvar_im = np.array(midvar_im,dtype = 'float32')
midvar_im = torch.from_numpy(midvar_im).cuda()
w = model(midvar_im).cpu()
w = w.detach().numpy().astype(np.float32)
w = np.squeeze(w[:,0,:,:]+1j*w[:,1,:,:])
w = w* np.abs(np.real(midvar)).max()
x = np.fft.fftshift(np.fft.fftshift(w,axes=0),axes = 1)
s = 2*x-xold
z = gamma_p/(1+gamma_p)*z+1/(1+gamma_p)*(pMRI.mult(s)-kdata)
nmse_i = NMSE(imtrue,w)
print(nmse_i)
savenmse.append(nmse_i)
# savemat('sigma.mat',{'sigma':savesigma})
file_name = os.getcwd()+'Brain/T1/data_for_testing/reside_m_k'+str(i)+'_auto/im_'+str(ite)+'.mat'
savemat(file_name,{'x':w})
savemat(os.getcwd()+'Brain/T1/data_for_testing/reside_m_k'+str(i)+'_auto/nmse.mat',{'nmse':savenmse})