-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils_np.py
More file actions
273 lines (233 loc) · 6.7 KB
/
Copy pathutils_np.py
File metadata and controls
273 lines (233 loc) · 6.7 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
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
import numpy as np
import torch
import os
sqrt = np.sqrt
from numpy.fft import fft, fft2, ifft2, ifft
import torch.fft as FFT
def fftc(x, axis=-1, norm='ortho'):
''' expect x as m*n matrix '''
return fftshift(fft(ifftshift(x, axes=axis), axis=axis, norm=norm), axes=axis)
def ifftc(x, axis=-1, norm='ortho'):
''' expect x as m*n matrix '''
return fftshift(ifft(ifftshift(x, axes=axis), axis=axis, norm=norm), axes=axis)
def ifftshift(x, axes=None):
assert torch.is_tensor(x) == True
if axes is None:
axes = tuple(range(x.ndim))
shift = [-(dim // 2) for dim in x.shape]
elif isinstance(axes, int):
shift = -(x.shape[axes] // 2)
else:
shift = [-(x.shape[axis] // 2) for axis in axes]
return torch.roll(x, shift, axes)
def fftshift(x, axes=None):
assert torch.is_tensor(x) == True
if axes is None:
axes = tuple(range(x.ndim()))
shift = [dim // 2 for dim in x.shape]
elif isinstance(axes, int):
shift = x.shape[axes] // 2
else:
shift = [x.shape[axis] // 2 for axis in axes]
return torch.roll(x, shift, axes)
def FFT2c(x):
'''
Centered fft
Note: fft2 applies fft to last 2 axes by default
:param x: 2D onwards. e.g: if its 3d, x.shape = (n,row,col). 4d:x.shape = (n,slice,row,col)
:return:
'''
# axes = (len(x.shape)-2, len(x.shape)-1) # get last 2 axes
axes = (-2, -1) # get last 2 axes
res = fftshift(fft2(ifftshift(x, axes=axes), norm='ortho'), axes=axes)
return res
def IFFT2c(x):
'''
Centered ifft
Note: fft2 applies fft to last 2 axes by default
:param x: 2D onwards. e.g: if its 3d, x.shape = (n,row,col). 4d:x.shape = (n,slice,row,col)
:return:
'''
axes = (-2, -1) # get last 2 axes
res = fftshift(ifft2(ifftshift(x, axes=axes), norm='ortho'), axes=axes)
return res
def fourier_matrix(rows, cols):
'''
parameters:
rows: number or rows
cols: number of columns
return unitary (rows x cols) fourier matrix
'''
# from scipy.linalg import dft
# return dft(rows,scale='sqrtn')
col_range = np.arange(cols)
row_range = np.arange(rows)
scale = 1 / np.sqrt(cols)
coeffs = np.outer(row_range, col_range)
fourier_matrix = np.exp(coeffs * (-2. * np.pi * 1j / cols)) * scale
return fourier_matrix
def inverse_fourier_matrix(rows, cols):
return np.array(np.matrix(fourier_matrix(rows, cols)).getH())
def flip(m, axis):
"""
==== > Only in numpy 1.12 < =====
Reverse the order of elements in an array along the given axis.
The shape of the array is preserved, but the elements are reordered.
.. versionadded:: 1.12.0
Parameters
----------
m : array_like
Input array.
axis : integer
Axis in array, which entries are reversed.
Returns
-------
out : array_like
A view of `m` with the entries of axis reversed. Since a view is
returned, this operation is done in constant time.
See Also
--------
flipud : Flip an array vertically (axis=0).
fliplr : Flip an array horizontally (axis=1).
Notes
-----
flip(m, 0) is equivalent to flipud(m).
flip(m, 1) is equivalent to fliplr(m).
flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n.
Examples
--------
>>> A = np.arange(8).reshape((2,2,2))
>>> A
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> flip(A, 0)
array([[[4, 5],
[6, 7]],
[[0, 1],
[2, 3]]])
>>> flip(A, 1)
array([[[2, 3],
[0, 1]],
[[6, 7],
[4, 5]]])
>>> A = np.random.randn(3,4,5)
>>> np.all(flip(A,2) == A[:,:,::-1,...])
True
"""
if not hasattr(m, 'ndim'):
m = np.asarray(m)
indexer = [slice(None)] * m.ndim
try:
indexer[axis] = slice(None, None, -1)
except IndexError:
raise ValueError("axis=%i is invalid for the %i-dimensional input array"
% (axis, m.ndim))
return m[tuple(indexer)]
def rot90_nd(x, axes=(-2, -1), k=1):
"""Rotates selected axes"""
def flipud(x):
return flip(x, axes[0])
def fliplr(x):
return flip(x, axes[1])
x = np.asanyarray(x)
if x.ndim < 2:
raise ValueError("Input must >= 2-d.")
k = k % 4
if k == 0:
return x
elif k == 1:
return fliplr(x).swapaxes(*axes)
elif k == 2:
return fliplr(flipud(x))
else:
# k == 3
return fliplr(x.swapaxes(*axes))
def r2c(x):
re, im = torch.chunk(x,2,1)
x = torch.complex(re, im)
return x
def c2r(x):
x = torch.cat([torch.real(x), torch.imag(x)], 1)
return x
def ifft2c(x):
device = x.device
nb, nc, nx, ny = x.size()
ny = torch.Tensor([ny])
ny = ny.to(device)
nx = torch.Tensor([nx])
nx = nx.to(device)
x = ifftshift(x, axes=2)
x = torch.transpose(x, 2, 3)
x = FFT.ifft(x)
x = torch.transpose(x, 2, 3)
x = torch.mul(fftshift(x, axes=2), torch.sqrt(nx))
x = ifftshift(x, axes=3)
x = FFT.ifft(x)
x = torch.mul(fftshift(x, axes=3), torch.sqrt(ny))
return x
def fft2c(x):
device = x.device
nb, nc, nx, ny = x.size()
ny = torch.Tensor([ny]).to(device)
nx = torch.Tensor([nx]).to(device)
x = ifftshift(x, axes=2)
x = torch.transpose(x, 2, 3)
x = FFT.fft(x)
x = torch.transpose(x, 2, 3)
x = torch.div(fftshift(x, axes=2), torch.sqrt(nx))
x = ifftshift(x, axes=3)
x = FFT.fft(x)
x = torch.div(fftshift(x, axes=3), torch.sqrt(ny))
return x
def Emat_xyt(b, inv, csm, mask):
if csm == None:
if inv:
b = r2c(b) * mask
b = ifft2c(b)
x = c2r(b)
else:
b = r2c(b)
b = fft2c(b)*mask
x = c2r(b)
else:
if inv:
x = r2c(b) * mask
x = ifft2c(x)
x = x * torch.conj(csm)
x = torch.sum(x, 1)
x = torch.unsqueeze(x, 1)
x = c2r(x)
else:
b = r2c(b)
b = b*csm
b = fft2c(b)
x = mask*b
x = c2r(x)
return x
def Emat_xyt_np(b, inv, csm, mask):
if csm == None:
if inv:
b = r2c(b) * mask
b = ifft2c(b)
x = c2r(b)
else:
b = r2c(b)
b = fft2c(b)*mask
x = c2r(b)
else:
if inv:
x = r2c(b) * mask
x = ifft2c(x)
x = x * torch.conj(csm)
x = torch.sum(x, 1)
x = torch.unsqueeze(x, 1)
x = c2r(x)
else:
b = r2c(b)
b = b*csm
b = fft2c(b)
x = mask*b
x = c2r(x)
return x