def fst4(nx, ny, dx, dy, f): beta = dx / dy a = -10.0 * (1.0 + beta**2) b = 5.0 - beta**2 c = 5.0 * beta**2 - 1.0 d = 0.5 * (1.0 + beta**2) data = f[1:-1, 1:-1] data = dst(data, axis=1, type=1) data = dst(data, axis=0, type=1) m = np.linspace(1, nx - 1, nx - 1).reshape([-1, 1]) n = np.linspace(1, ny - 1, ny - 1).reshape([1, -1]) data1 = np.zeros((nx - 1, ny - 1)) alpha = a + 2.0*b*np.cos(np.pi*m/nx) + 2.0*c*np.cos(np.pi*n/ny) + \ 4.0*d*np.cos(np.pi*m/nx)*np.cos(np.pi*n/ny) gamma = 8.0 + 2.0 * np.cos(np.pi * m / nx) + 2.0 * np.cos(np.pi * n / ny) data1 = data * (dx**2) * 0.5 * gamma / alpha data1 = idst(data1, axis=1, type=1) data1 = idst(data1, axis=0, type=1) data1 = data1 / ((2.0 * nx) * (2.0 * ny)) ue = np.zeros((nx + 1, ny + 1)) ue[1:-1, 1:-1] = data1 return ue
def extract_dst_features(time_windows, class_attr, n_comps=90): X_matrix = [] y_vect = None if class_attr is not None: y_vect = [] #n_comps = 50 for tw in time_windows: x = tw['x'].values y = tw['y'].values z = tw['z'].values m = mag(x,y,z) dst_x = np.abs(fftpack.dst(x)) dst_y = np.abs(fftpack.dst(y)) dst_z = np.abs(fftpack.dst(z)) dst_m = np.abs(fftpack.dst(m)) v = np.array([]) v = np.concatenate((v, dst_x[:n_comps])) v = np.concatenate((v, dst_y[:n_comps])) v = np.concatenate((v, dst_z[:n_comps])) v = np.concatenate((v, dst_m[:n_comps])) X_matrix.append(v) X_matrix = np.array(X_matrix) if y_vect is not None: y_vect.append(tw[class_attr].iloc[0]) return X_matrix, y_vect
def fst_whole_domain(nx, ny, dx, dy, f): fd = f[2:nx + 3, 2:ny + 3] data = fd[:, :] # e = dst(data, type=2) data = dst(data, axis=1, type=1) data = dst(data, axis=0, type=1) m = np.linspace(1, nx + 1, nx + 1).reshape([-1, 1]) n = np.linspace(1, ny + 1, ny + 1).reshape([1, -1]) data1 = np.zeros((nx + 1, ny + 1)) # for i in range(1,nx): # for j in range(1,ny): alpha = (2.0 / (dx * dx)) * (np.cos(np.pi * m / nx) - 1.0) + (2.0 / (dy * dy)) * (np.cos(np.pi * n / ny) - 1.0) data1 = data / alpha # u = idst(data1, type=2)/((2.0*nx)*(2.0*ny)) data1 = idst(data1, axis=1, type=1) data1 = idst(data1, axis=0, type=1) u = data1 / ((2.0 * nx) * (2.0 * ny)) ue = np.zeros((nx + 5, ny + 5)) ue[2:nx + 3, 2:ny + 3] = u return ue
def fst4c(nx, ny, dx, dy, f): alpha_ = 1.0 / 10.0 a = (-12.0 / 5.0) * (1.0 / dx**2 + 1.0 / dy**2) b = (6.0 / 25.0) * (5.0 / dx**2 - 1 / (dy**2)) c = (6.0 / 25.0) * (5.0 / dy**2 - 1 / (dx**2)) d = (3.0 / 25.0) * (1.0 / dx**2 + 1.0 / dy**2) data = f[1:-1, 1:-1] data = dst(data, axis=1, type=1) data = dst(data, axis=0, type=1) m = np.linspace(1, nx - 1, nx - 1).reshape([-1, 1]) n = np.linspace(1, ny - 1, ny - 1).reshape([1, -1]) data1 = np.zeros((nx - 1, ny - 1)) beta = a + 2.0*b*np.cos(np.pi*m/nx) + 2.0*c*np.cos(np.pi*n/ny) + \ 4.0*d*np.cos(np.pi*m/nx)*np.cos(np.pi*n/ny) gamma = 1.0 + 2.0*alpha_*np.cos(np.pi*m/nx) + 2.0*alpha_*np.cos(np.pi*n/ny) + \ 4.0*(alpha_**2)*np.cos(np.pi*m/nx)*np.cos(np.pi*n/ny) data1 = data * gamma / (beta) data1 = idst(data1, axis=1, type=1) data1 = idst(data1, axis=0, type=1) data1 = data1 / ((2.0 * nx) * (2.0 * ny)) ue = np.zeros((nx + 1, ny + 1)) ue[1:-1, 1:-1] = data1 return ue
def fste(nx, ny, dx, dy, f): data = f[1:-1, 1:-1] # e = dst(data, type=2) data = dst(data, axis=1, type=1) data = dst(data, axis=0, type=1) m = np.linspace(1, nx - 1, nx - 1).reshape([-1, 1]) n = np.linspace(1, ny - 1, ny - 1).reshape([1, -1]) data1 = np.zeros((nx - 1, ny - 1)) # for i in range(1,nx): # for j in range(1,ny): alpha = (2.0 / (dx * dx)) * (np.cos(np.pi * m / nx) - 1.0) + (2.0 / (dy * dy)) * (np.cos(np.pi * n / ny) - 1.0) data1 = data / alpha # u = idst(data1, type=2)/((2.0*nx)*(2.0*ny)) data1 = idst(data1, axis=1, type=1) data1 = idst(data1, axis=0, type=1) u = data1 / ((2.0 * nx) * (2.0 * ny)) return u
def _fast_poisson(self, gx, gy): ydim, xdim = np.shape(gx) gxx = np.zeros((ydim, xdim)) gyy = np.zeros((ydim, xdim)) f = np.zeros((ydim, xdim)) gyy[1:ydim, 0:xdim - 1] = gy[1:ydim, 0:xdim - 1] - gy[0:ydim - 1, 0:xdim - 1] gxx[0:ydim - 1, 1:xdim] = gx[0:ydim - 1, 1:xdim] - gx[0:ydim - 1, 0:xdim - 1] f = gxx + gyy height, width = f.shape[:2] f2 = f[1:height - 1, 1:width - 1] tt = dst(f2.T, type=1).T / 2 f2sin = (dst(tt, type=1) / 2) x, y = np.meshgrid(np.arange(1, xdim - 1), np.arange(1, ydim - 1)) denom = (2 * np.cos(np.pi * x / (xdim - 1)) - 2) + (2 * np.cos(np.pi * y / (ydim - 1)) - 2) f3 = f2sin / denom tt = np.real(idst(f3, type=1, axis=0)) / (f3.shape[0] + 1) img_tt = (np.real(idst(tt.T, type=1, axis=0)) / (tt.T.shape[0] + 1)).T img_direct = np.zeros((ydim, xdim)) height, width = img_direct.shape[:2] img_direct[1:height - 1, 1:width - 1] = img_tt return img_direct
def super_lhsf(x0, tracer, factor=2): ## Extend sinogram to [0,2pi) m0, n0 = x0.shape n0_h = np.int(0.5 * n0) s_2pi = extend_full_period(x0) ig = np.unique(np.argwhere(s_2pi != tracer)[:, 1]) ib = np.unique(np.argwhere(s_2pi == tracer)[:, 1]) print(ig.shape) print(s_2pi.shape) print(s_2pi[:, ig].shape) print(n0_h) ## Resample each projection at cosinusoidal nodes s_2pi = s_2pi[:, ig].reshape(2 * m0, n0_h) sc_a = resampling_cosine_nodes(s_2pi) dis.plot(sc_a, 'SC') sc = np.zeros((2 * m0, 2 * sc_a.shape[1]), dtype=myfloat) print(sc.shape) print(sc_a.shape) sc[:, ::2] = sc_a sc[:, 1::2] = 0.0 dis.plot(sc, 'SC') m1, n1 = sc.shape mh1 = int(m1 * 0.5) nh1 = int(n1 * 0.5) ## Indexes for Fourier-Chebyshev filtering ic = get_ind_zerout(n1, m0) ## Get traced and non-traced elements sx = sc.copy() #sx[:,ib] = 0.0 nc = n1 norm = np.sqrt(1.0 / (2.0 * (nc + 1))) ## Decomposition and filter c = norm * fp.dst(sx, type=1, axis=1) b = np.fft.fftshift(np.fft.fft(c, axis=0), axes=0) b[ic[:, 0], ic[:, 1]] = 0.0 ## Reconstruction c[:] = np.real(np.fft.ifft(np.fft.ifftshift(b, axes=0), axis=0)) ci = np.imag(np.fft.ifft(np.fft.ifftshift(b, axes=0), axis=0)) sx_r = norm * fp.dst(c, type=1, axis=1) sx_i = norm * fp.dst(ci, type=1, axis=1) sx[:] = np.sqrt(sx_r**2 + sx_i**2) ## Renormalize sx[:] = factor * sx ## Crop original sinogram interval [0,pi) and first channel half (transl. of 1) sx = sx[:mh1, :] ## Interpolate back on equispaced nodes x = resampling_equisp_nodes(sx, n0) print('\n') return x
def _fourier(self, Bf, solve): N = self.N AD_len = self.AD_len assert N == Bf.shape[0] + 1 h = AD_len / N if self.eigenvals is None: self.calc_eigenvals() scoef = np.zeros((N - 1, N - 1), dtype=complex) for i in range(1, N): scoef[i - 1, :] = dst(Bf[i - 1, :], type=1) for j in range(1, N): scoef[:, j - 1] = dst(scoef[:, j - 1], type=1) scoef *= h ** 2 / 2 if solve: # When solving the AP fourier_coef_sol = scoef / self.eigenvals else: # When applying L fourier_coef_sol = scoef * self.eigenvals u_f = np.zeros((N - 1, N - 1), dtype=complex) for i in range(1, N): u_f[i - 1, :] = dst(fourier_coef_sol[i - 1, :], type=1) for j in range(1, N): u_f[:, j - 1] = dst(u_f[:, j - 1], type=1) u_f /= 2 * AD_len ** 2 return u_f
def fst(nx, ny, dx, dy, f): data = f[1:-1, 1:-1] # e = dst(data, type=2) data = dst(data, axis=1, type=1) data = dst(data, axis=0, type=1) m = np.linspace(1, nx - 1, nx - 1).reshape([-1, 1]) n = np.linspace(1, ny - 1, ny - 1).reshape([1, -1]) data1 = np.zeros((nx - 1, ny - 1)) alpha = (2.0 / (dx * dx)) * (np.cos(np.pi * m / nx) - 1.0) + (2.0 / (dy * dy)) * (np.cos(np.pi * n / ny) - 1.0) data1 = data / alpha data1 = idst(data1, axis=1, type=1) data1 = idst(data1, axis=0, type=1) u = data1 / ((2.0 * nx) * (2.0 * ny)) ue = np.zeros((nx + 1, ny + 1)) ue[1:-1, 1:-1] = u return ue
def fst6(nx, ny, dx, dy, f): lambda_ = 1.0 / 10.0 a = (-12.0 / 5.0) * (1.0 / dx**2 + 1.0 / dy**2) b = (6.0 / 25.0) * (5.0 / dx**2 - 1 / (dy**2)) c = (6.0 / 25.0) * (5.0 / dy**2 - 1 / (dx**2)) d = (3.0 / 25.0) * (1.0 / dx**2 + 1.0 / dy**2) alpha_ = 2.0 / 11.0 center = (-51.0 / 22.0) * (1.0 / dx**2 + 1.0 / dy**2) ew = (1.0 / 11.0) * (12.0 / dx**2 - alpha_ * 51.0 / (2.0 * dy**2)) ns = (1.0 / 11.0) * (12.0 / dy**2 - alpha_ * 51.0 / (2.0 * dx**2)) corners = alpha_ * (12.0 / 11.0) * (1.0 / dx**2 + 1.0 / dy**2) ew_far = alpha_ * 3.0 / (44.0 * dx**2) ns_far = alpha_ * 3.0 / (44.0 * dy**2) data = f[1:-1, 1:-1] data = dst(data, axis=1, type=1) data = dst(data, axis=0, type=1) m = np.linspace(1, nx - 1, nx - 1).reshape([-1, 1]) n = np.linspace(1, ny - 1, ny - 1).reshape([1, -1]) data1 = np.zeros((nx - 1, ny - 1)) data2 = np.zeros((nx - 1, ny - 1)) data3 = np.zeros((nx - 1, ny - 1)) beta = a + 2.0*b*np.cos(np.pi*m/nx) + 2.0*c*np.cos(np.pi*n/ny) + \ 4.0*d*np.cos(np.pi*m/nx)*np.cos(np.pi*n/ny) gamma = 1.0 + 2.0*lambda_*np.cos(np.pi*m/nx) + 2.0*lambda_*np.cos(np.pi*n/ny) + \ 4.0*(lambda_**2)*np.cos(np.pi*m/nx)*np.cos(np.pi*n/ny) data2 = data * gamma / (beta) lhs_near = center + 2.0*ew*np.cos(np.pi*m/nx) + 2.0*ns*np.cos(np.pi*n/ny) + \ 4.0*corners*np.cos(np.pi*m/nx)*np.cos(np.pi*n/ny) lhs_far = 2.0*ew_far*(1.0 + 2.0*np.cos(np.pi*n/ny))*np.cos(2.0*np.pi*m/nx) + \ 2.0*ns_far*(1.0 + 2.0*np.cos(np.pi*m/nx))*np.cos(2.0*np.pi*n/ny) rhs = 1.0 + 2.0*alpha_*np.cos(np.pi*m/nx) + 2.0*alpha_*np.cos(np.pi*n/ny) + \ 4.0*(alpha_**2)*np.cos(np.pi*m/nx)*np.cos(np.pi*n/ny) data3 = data * rhs / (lhs_near + lhs_far) data1 = np.copy(data2) data1[1:-1, 1:-1] = np.copy(data3[1:-1, 1:-1]) data1 = idst(data1, axis=1, type=1) data1 = idst(data1, axis=0, type=1) data1 = data1 / ((2.0 * nx) * (2.0 * ny)) ue = np.zeros((nx + 1, ny + 1)) ue[1:-1, 1:-1] = data1 return ue
def solve_min_laplacian(boundary_image): (H, W) = np.shape(boundary_image) # Laplacian f = np.zeros((H, W)) # boundary image contains image intensities at boundaries boundary_image[1:-1, 1:-1] = 0 j = np.arange(2, H)-1 k = np.arange(2, W)-1 f_bp = np.zeros((H, W)) f_bp[np.ix_(j, k)] = -4*boundary_image[np.ix_(j, k)] + boundary_image[np.ix_(j, k+1)] + boundary_image[np.ix_(j, k-1)] + boundary_image[np.ix_(j-1, k)] + boundary_image[np.ix_(j+1, k)] del(j, k) f1 = f - f_bp # subtract boundary points contribution del(f_bp, f) # DST Sine Transform algo starts here f2 = f1[1:-1,1:-1] del(f1) # compute sine tranform if f2.shape[1] == 1: tt = fftpack.dst(f2, type=1, axis=0)/2 else: tt = fftpack.dst(f2, type=1)/2 if tt.shape[0] == 1: f2sin = np.transpose(fftpack.dst(np.transpose(tt), type=1, axis=0)/2) else: f2sin = np.transpose(fftpack.dst(np.transpose(tt), type=1)/2) del(f2) # compute Eigen Values [x, y] = np.meshgrid(np.arange(1, W-1), np.arange(1, H-1)) denom = (2*np.cos(np.pi*x/(W-1))-2) + (2*np.cos(np.pi*y/(H-1)) - 2) # divide f3 = f2sin/denom del(f2sin, x, y) # compute Inverse Sine Transform if f3.shape[0] == 1: tt = fftpack.idst(f3*2, type=1, axis=1)/(2*(f3.shape[1]+1)) else: tt = fftpack.idst(f3*2, type=1, axis=0)/(2*(f3.shape[0]+1)) del(f3) if tt.shape[1] == 1: img_tt = np.transpose(fftpack.idst(np.transpose(tt)*2, type=1)/(2*(tt.shape[0]+1))) else: img_tt = np.transpose(fftpack.idst(np.transpose(tt)*2, type=1, axis=0)/(2*(tt.shape[1]+1))) del(tt) # put solution in inner points; outer points obtained from boundary image img_direct = boundary_image img_direct[1:-1, 1:-1] = 0 img_direct[1:-1, 1:-1] = img_tt return img_direct
def dst2(u): f = [] M = len(u) for i in range(M): f.append(dst(u[i], 1) / 2) f = np.array(f) U = [] for i in range(M): U.append(dst(f[:, i], 1) / 2) return np.array(U)
def dst2(y): M = y.shape[0] N = y.shape[1] a = np.empty([M, N], float) b = np.empty([M, N], float) for i in range(M): a[i, :] = dst(y[i, :], type=1) for j in range(N): b[:, j] = dst(a[:, j], type=1) return b
def inverseATA(self, divergence): div = divergence.div div = 0.5*fft.dst(div, type=1, axis=0) div = 0.5*fft.dst(div, type=1, axis=1) div = div / self.eigvalues div = fft.dst(div, type=1, axis=0) / ( self.N + 2. ) div = fft.dst(div, type=1, axis=1) / ( self.P + 2. ) divergence.div = div return divergence
def inverseATA(self, divergence): div = divergence.div div = 0.5 * fft.dst(div, type=1, axis=0) div = 0.5 * fft.dst(div, type=1, axis=1) div = div / self.eigvalues div = fft.dst(div, type=1, axis=0) / (self.N + 2.) div = fft.dst(div, type=1, axis=1) / (self.P + 2.) divergence.div = div return divergence
def gen_ede_Nl_Ell_data(siz, freqidx, freqmag, a_0): #f_r = np.random.uniform(-np.sqrt(3/N),np.sqrt(3/N),[batch_siz,N,1]) #f_i = np.zeros_like(f_r) #f = np.reshape(np.concatenate((f_r,f_i),axis=2),(batch_siz,-1,1),order='C') #print(f[0,:,0]) N = len(freqmag) N_0 = 2**10 K = len(freqidx) l = 1/N freqmag = np.tile(np.reshape(freqmag,[1,N]),(siz,1)) y = np.random.uniform(-np.sqrt(l),np.sqrt(l),[siz,N]) #y = np.ones([siz,N]) y = y*freqmag*N #print("y") #print(y[0,:]) zerof = np.zeros([siz,1]) f = np.concatenate((zerof,fftpack.dst(y[:,1:],1,N_0-1,axis = 1)),axis=1)/2/N #f = np.concatenate((zerof,np.random.uniform(-np.sqrt(l),np.sqrt(l),[siz,N_0-1])),axis=1) f_0 = np.reshape(f,(siz,N_0,1)) f = f_0[:,0::N_0//N,:] fdata_r = np.concatenate((f,np.zeros([siz,1,1]),-f[:,-1:0:-1]),axis=1) fdata_i = np.zeros_like(fdata_r) fdata = np.reshape(np.concatenate((fdata_r,fdata_i),axis = 2),(siz,-1,1)) #print("f") #print(fdata[0,:,0]) ydata_r = np.concatenate((zerof,fftpack.dst(f[:,1:,0],1,N-1,axis = 1)),axis=1) ydata_r = np.reshape(ydata_r[:,freqidx],(siz,K,1)) ydata_i = np.zeros_like(ydata_r) ydata = np.reshape(np.concatenate((ydata_r,ydata_i),axis = 2),(siz,-1,1)) print("ydata") print(ydata[0,:,0]) ynorm = np.squeeze(np.linalg.norm(ydata,2,1)) u_0 = np.zeros((siz,N_0,1)) mat = InvSineElliptic(a_0,N_0) #print(mat.shape) mat = np.tile(mat,(siz,1,1)) u_0[:,1:,:] = np.matmul(mat, f_0[:,1:]) u = u_0[:,::N_0//N,:] #print("u") #print(u[0,:,0]) fnorm = np.squeeze(np.linalg.norm(fdata,2,1))/np.sqrt(2) unorm = np.squeeze(np.linalg.norm(u,2,1)) #print(np.mean(unorm)) fdata = np.float32(fdata) udata = np.float32(u) ydata = np.float32(ydata) return fdata, ydata, udata, fnorm, ynorm, unorm
def fourier_extended_to_extended( params: FourierExtendedParams) -> ExtendedParams: out = deepcopy(params) out.__class__ = ExtendedParams out.betas = dct(params.v, n=out.n_steps, axis=0) out.gammas_singles = dst(params.u_singles, n=out.n_steps, axis=0) out.gammas_pairs = dst(params.u_pairs, n=out.n_steps, axis=0) # and clean up del out.__u_singles del out.__u_pairs del out.__v del out.q return out
def fourier_w_bias_to_standard_w_bias( params: FourierWithBiasParams) -> StandardWithBiasParams: out = deepcopy(params) out.__class__ = StandardWithBiasParams out.betas = dct(params.v, n=out.n_steps) out.gammas_singles = dst(params.u_singles, n=out.n_steps) out.gammas_pairs = dst(params.u_pairs, n=out.n_steps) # and clean up del out.__u_singles del out.__u_pairs del out.__v del out.q return out
def inverseATA(self, divTempBound): divTempBound.applyGaussForward() div = divTempBound.divergence.div div = 0.5 * fft.dct(div, axis=1) div = 0.5 * fft.dst(div, axis=0, type=1) div = div / self.eigvalues div = fft.idct(div, axis=1) / (self.P + 1.) div = fft.dst(div, axis=0, type=1) / (self.N + 2.) divTempBound.divergence.div = div divTempBound.applyGaussBackward() return divTempBound
def calc_Fr2(Q, Qi_Q, QmaxIntegrate): """Function to calculate F(r) (eq. 20) arguments: r: radius - array Q: momentum transfer - array Qi_Q: Qi(Q) - array returns: F_r: F(r) - array """ DeltaQ = np.diff(Q) # mask = np.where(Q<=QmaxIntegrate) # print(len(mask[0])) # print(len(Qi_Q)) # zeroPad = np.zeros(2**275) # Qi_Q = np.concatenate([Qi_Q, zeroPad]) # F_r2 = np.fft.fft(Qi_Q) F_r2 = fftpack.fft(Qi_Q, 2**12) F_r2 = np.imag(F_r2) F_r2 *= DeltaQ[0] *2/np.pi F_r3 = fftpack.dst(Qi_Q, type=2, n=2**11) F_r3 *= DeltaQ[0] * 2/np.pi # for i in range(len(F_r2)): # print(F_r2[i], "----", F_r2imag[i], "----", F_r3[i]) return (F_r2, F_r3)
def compute_IDST(N): plt.figure() t = np.linspace(0,20,N) x = np.exp(-t/3)*np.cos(2*t) y = dst(x, norm='ortho') window = np.zeros(N) window[:20] = 1 yr = idst(y*window, norm='ortho') sum(abs(x-yr)**2) / sum(abs(x)**2) plt.plot(t, x, '-bx') plt.plot(t, yr, 'ro') window = np.zeros(N) window[:15] = 1 yr = idst(y*window, norm='ortho') sum(abs(x-yr)**2) / sum(abs(x)**2) # 0.0718818065008 plt.plot(t, yr, 'g+') plt.legend(['x', '$x_{20}$', '$x_{15}$']) if not os.path.isdir('static'): os.mkdir('static') else: # Remove old plot files for filename in glob.glob(os.path.join('static', '*.png')): os.remove(filename) # Use time since Jan 1, 1970 in filename in order make # a unique filename that the browser has not chached plotfile = os.path.join('static', str(time.time()) + '.png') #Name of file - unique and uncached by the browser plt.savefig(plotfile) return plotfile
def SineCurvature(FILE,aspect_ratio=1): dd = loadtxt(FILE+'/curvature.txt') dd_SS = loadtxt(FILE+'/material_point.txt') Y = dd_SS nrowcol=dd_SS.shape nsnap=nrowcol[0] Np=nrowcol[1] # Now normalize the material point coordinate for isnap in range(0,nsnap-1,1): Y[isnap,:] = Y[isnap,:]/Y[isnap,-1] Z = dd[:,1:Np+1] #Removed the first entry Zsine=zeros((nsnap,Np)) # for isnap in range(0,nsnap): Zsine[isnap,:] = dst(Z[isnap,:],type=1) timeAxis = loadtxt(FILE+'/time.txt') IndexAxis = arange(Np) # heightAxis = ndimage.rotate(heightAxis,90) # imshow(heightAxis,cmap=plt.cm.gray) # colorbar() (IndexAxis,X) = meshgrid(IndexAxis, timeAxis) fig = figure() ax = fig.add_subplot(111) # surf = ax.contourf(X,Y,heightAxis,vmin=10**(-5),vmax=10**5,cmap='plasma') surf = ax.contourf(X,Y,Zsine) cbar = colorbar(surf) # ax.set_aspect(aspect_ratio) ax.set_xlabel('time') ax.set_ylabel('material_point') plt.show() plt.savefig('sinecurvature.eps') close()
def test_dstRandom(self): N = 4 x = torch.empty(N, N, dtype=dtype).uniform_(0, 10.0) #x = Variable(torch.tensor([[1, 2, 7, 9, 20, 31], [4, 5, 9, 2, 1, 6]], dtype=dtype)) import scipy from scipy import fftpack #golden_value = discrete_spectral_transform.dst(x).data.numpy() golden_value = torch.from_numpy(fftpack.dst( x.data.numpy())).data.numpy() / N print("golden_value") print(golden_value) # test cpu #pdb.set_trace() custom = dct.DST() dst_value = custom.forward(x) print("dst_value") print(dst_value.data.numpy()) np.testing.assert_allclose(dst_value.data.numpy(), golden_value, rtol=1e-5) # test gpu custom = dct.DST() dst_value = custom.forward(x.cuda()).cpu() print("dst_value cuda") print(dst_value.data.numpy()) np.testing.assert_allclose(dst_value.data.numpy(), golden_value, rtol=1e-5)
def cveD(x, dt, scale): """Computes the covariance-based estimator for D and localizationVariance, as well as variance in D, SNR, and Pxk Keyword arguments: x -- a 1Dnumpy array of particle track data in pixels dt -- the time step of data scale -- um per pixel for x Returns: [D, localizationVariance, varianceD, SNR], Pxk """ # For details, see [1] # Note that R is hard coded to 1/6, which should be the usual value for a shutter that is kept open during the entire time lapse [1] R = 1./6 N = x.size dx = np.diff(scale*x) #(has N - 1 elements) #An array of elements (deltaX_n)*(deltaX_n-1) (should have N - 2 elements so just do the calculation and then truncate) dxn_dxn1 = dx*np.roll(dx,-1) dxn_dxn1 = dxn_dxn1[0:-1] # If the localization variance is known, D can be computed using eq [1].16, which also changes the calculation for the variance in D. # This function does not currently support that functionality. D = np.mean(dx**2)/2/dt + np.mean(dxn_dxn1)/dt localizationVariance = R*np.mean(dx**2) + (2*R - 1)*np.mean(dxn_dxn1) ep = localizationVariance/D/dt - 2*R varianceD = D**2*((6 + 4*ep + 2*ep**2)/N + 4*(1+ep)**2/N**2) SNR = np.sqrt(D*dt/localizationVariance) dxk = dt/2*dst(dx,1) Pxk = 2*dxk**2/(N + 1)/dt return np.array([D, localizationVariance, varianceD, SNR]), Pxk
def inverseATA(self, divTempBound): divTempBound.applyGaussForward() div = divTempBound.divergence.div div = 0.5*fft.dct(div, axis=1) div = 0.5*fft.dst(div, axis=0, type=1) div = div / self.eigvalues div = fft.idct(div, axis=1) / ( self.P + 1. ) div = fft.dst(div, axis=0, type=1) / ( self.N + 2. ) divTempBound.divergence.div = div divTempBound.applyGaussBackward() return divTempBound
def ft_autocorrelation_function_fft(self, k): """compute the fourier transform of the autocorrelation function via fft Args: k: array of wave vector magnitude values, ordered, and non-negative """ k_abs = np.abs(k) #assert((np.diff(k) > 0).all()) # check k is sorted #assert((k > -np.finfo(float).eps).all()) # check k is non-negative # re-sampling # number of fourier auxiliary grid points, presently fixed N = 4096 # grid resolution, fraction of the unique characteristic scale dr = self.inv_slope_at_origin / 20.0 # compute correlation function and auxiliary wave vector arrray points = np.arange(N) r = dr * points C = self.autocorrelation_function(r) L = N * dr delta_k = np.pi / L k_resampled = delta_k * points # fft for auxiliary wave vector array ft_resampled = np.empty_like(C) ft_resampled[1:] = dst(4 * np.pi * C[1:] * r[1:], type=1) / (2 / dr * k_resampled[1:]) ft_resampled[0] = dr * 4 * np.pi * np.sum(C * r**2) # get ft values for input k-values by linear interpolation ft = np.interp(k_abs, k_resampled, ft_resampled) return ft
def DST4(samples): """ Method to create DST4 transformation using DST3 Arguments : samples : (1D Array) Input samples to be transformed Returns : y : (1D Array) Transformed output samples """ # Initialize samplesup = np.zeros(2 * N, dtype=np.float32) # Upsample signal # Reverse order to obtain DST4 out of DCT4: #samplesup[1::2]=np.flipud(samples) samplesup[0::2] = samples y = spfft.dst(samplesup, type=3, norm='ortho') * np.sqrt(2) #/2 # Flip sign of every 2nd subband to obtain DST4 out of DCT4 #y=(y[0:N])*(((-1)*np.ones(N, dtype = np.float32))**range(N)) return y[0:N]
def autocorrelation_function_invfft(self, r): """Compute the autocorrelation function from an analytically known FT via fft Args: r: array of lag vector magnitude values, ordered, non-negative """ assert ((np.diff(r) > 0).all()) # check if r is sorted assert ((r > -np.finfo(float).eps).all()) # check if r is non-negative # re-sampling if np.isclose(r[0], 0): r_spacing = r[1] # alternative: np.min(diff(r)) else: r_spacing = r[0] no_points = (np.max(r) - np.min(r)) / r_spacing points = np.arange(no_points) r_resampled = r_spacing * points dk = np.pi / (no_points * r_spacing) k = dk * points ft = self.ft_autocorrelation_function(k) C_resampled = np.empty_like(ft) C_resampled[1:] = dst(4 * np.pi * ft[1:] * k[1:], type=1) / (2 / (dk / (2 * np.pi)**3) * r_resampled[1:]) C_resampled[0] = (dk / (2 * np.pi)**3) * 4 * np.pi * np.sum(ft * k**2) # get invft values corresponding to input r-values by linear interpolation C = np.interp(r, r_resampled, C_resampled) return C
def cveD(x, dt, scale): """Computes the covariance-based estimator for D and localizationVariance, as well as variance in D, SNR, and Pxk Keyword arguments: x -- a 1Dnumpy array of particle track data in pixels dt -- the time step of data scale -- um per pixel for x Returns: [D, localizationVariance, varianceD, SNR], Pxk """ # For details, see [1] # Note that R is hard coded to 1/6, which should be the usual value for a shutter that is kept open during the entire time lapse [1] R = 1. / 6 N = x.size dx = np.diff(scale * x) #(has N - 1 elements) #An array of elements (deltaX_n)*(deltaX_n-1) (should have N - 2 elements so just do the calculation and then truncate) dxn_dxn1 = dx * np.roll(dx, -1) dxn_dxn1 = dxn_dxn1[0:-1] # If the localization variance is known, D can be computed using eq [1].16, which also changes the calculation for the variance in D. # This function does not currently support that functionality. D = np.mean(dx**2) / 2 / dt + np.mean(dxn_dxn1) / dt localizationVariance = R * np.mean(dx**2) + (2 * R - 1) * np.mean(dxn_dxn1) ep = localizationVariance / D / dt - 2 * R varianceD = D**2 * ((6 + 4 * ep + 2 * ep**2) / N + 4 * (1 + ep)**2 / N**2) SNR = np.sqrt(D * dt / localizationVariance) dxk = dt / 2 * dst(dx, 1) Pxk = 2 * dxk**2 / (N + 1) / dt return np.array([D, localizationVariance, varianceD, SNR]), Pxk
def hr_to_cr(bins, rho, data, radius, error=None, axis=1): """ This function takes h(r) and uses the OZ equation to find c(r) this is done via a 3D fourier transform that is detailed in LADO paper. The transform is the the DST of f(r)*r. The function is rearranged in fourier space to find c(k) and then the inverse transform is taken to get back to c(r). """ # setup scales dk = np.pi / radius[-1] k = dk * np.arange(1, bins + 1, dtype=np.float) # Transform into fourier components FT = dst(data * radius[0:bins], type=1, axis=axis) normalisation = 2 * np.pi * radius[0] / k H_k = normalisation * FT # Rearrange to find direct correlation function C_k = H_k / (1 + rho * H_k) # # Transform back to real space iFT = idst(C_k * k, type=1) normalisation = k[-1] / (4 * np.pi**2 * radius[0:bins]) / (bins + 1) c_r = normalisation * iFT return c_r, radius
def lhif_onestep(x0, tracer, factor=2): ## Extend sinogram to [0,2pi) m0, n0 = x0.shape s_2pi = extend_full_period(x0) ig = np.unique(np.argwhere(s_2pi != tracer)[:, 0]) ib = np.unique(np.argwhere(s_2pi == tracer)[:, 0]) ## Resample each projection at cosinusoidal nodes sc = resampling_cosine_nodes(s_2pi) sc[ib, :] = tracer m1, n1 = sc.shape mh1 = int(m1 * 0.5) nh1 = int(n1 * 0.5) ## Indexes for Fourier-Chebyshev filtering ic = get_ind_zerout(n1, m0) ## Get traced and non-traced elements sx = sc.copy() sx[ib, :] = 0.0 nc = n1 norm = np.sqrt(1.0 / (2.0 * (nc + 1))) ## Decomposition and filter c = norm * fp.dst(sx, type=1, axis=1) b = np.fft.fftshift(np.fft.fft(c, axis=0), axes=0) b[ic[:, 0], ic[:, 1]] = 0.0 ## Reconstruction c[:] = np.real(np.fft.ifft(np.fft.ifftshift(b, axes=0), axis=0)) ci = np.imag(np.fft.ifft(np.fft.ifftshift(b, axes=0), axis=0)) sx_r = norm * fp.dst(c, type=1, axis=1) sx_i = norm * fp.dst(ci, type=1, axis=1) sx[:] = np.sqrt(sx_r**2 + sx_i**2) ## Renormalize sx[:] = factor * sx ## Crop original sinogram interval [0,pi) and first channel half (transl. of 1) sx = sx[:mh1, :] ## Interpolate back on equispaced nodes x = resampling_equisp_nodes(sx, n0) return x
def inverseDiscreteSineTransform(array): # normalization factor f = 1.0 / (2 * len(array)) result = dst(array, type=3) result = [k * f for k in result] return result
def fn(t, F): xs = np.arange(0, L, 1) fF = dst(F) for x in xs: xs[x] = 0 for n in range(0, F.shape[0]): xs[x] += fF[x] * cos(c * pi * n * t) * sin(pi * n * x / L) return xs
def f2d(self, q, iQ, r): # DKeen[2001](EQ.26) # D(r) = 2/pi \sum Qi(Q)sin(Qr)dQ QiQ = q*iQ factor = 2/math.pi dR = np.array(fft.dst(QiQ,type=2,norm='ortho')) dR = dR*factor #dR = self.dst(q,iQ,r) return dR
def hankelTransform(f, delta_r): numberOfSamplingPoints = f.shape[0] lr = np.arange(numberOfSamplingPoints).astype('float') lr += 1.0 f_hat = dst(f * lr, type=1) f_hat /= lr delta_q = np.pi / ((numberOfSamplingPoints + 1.0) * delta_r) f_hat *= 2 * np.pi * delta_r**2 / delta_q return f_hat
def hankelTransform(self, f, delta_r): numberOfSamplingPoints = f.shape[0] lr = np.arange(numberOfSamplingPoints).astype('float') lr += 1.0 #Division by zero (see over-next line, this is the reason why the grid starts at delta_r, not zero....) f_hat = dst(f*lr, type=1) #...but the formula is also correct (implemented as 5.18, 5.19 in SASfit docu, see also...) f_hat /= lr # ..comment: it is important to mention that first elements equal delta_r, delta_q (and not at 0.0!) delta_q = np.pi/((numberOfSamplingPoints + 1.0)*delta_r) f_hat *= 2*np.pi*delta_r**2/delta_q return f_hat
def hankelTransform(f, delta_r): numberOfSamplingPoints = f.shape[0] lr = np.arange(numberOfSamplingPoints).astype("float") lr += 1.0 f_hat = dst(f * lr, type=1) f_hat /= lr delta_q = np.pi / ((numberOfSamplingPoints + 1.0) * delta_r) f_hat *= 2 * np.pi * delta_r ** 2 / delta_q return f_hat
def get_v_error(self): N = self.N errors = [] for m in range(1, N): r = self.polarfd.get_r(m) expected = np.zeros(N-1) for l in range(1, N): th = self.polarfd.get_th(l) expected[l-1] = self.problem.eval_v(r, th) to_dst = expected - self.v[m, 1:N] fourier = dst(to_dst, type=1)[:self.M] / N errors.append(np.max(np.abs(fourier))) return max(errors)
def dst2d(X): return fft.dst(fft.dst(X,1, axis = 1),1,axis = 0)
def get_local_feature_one_vertebra_one_slice_one_sigma(img, s): from scipy.fftpack import fft2 from scipy.fftpack import dct from scipy.fftpack import dst from scipy.ndimage.filters import gaussian_filter from scipy.stats import skew from scipy.stats import kurtosis filtered_dim = get_filtered_dim(s) height = img.shape[0] width = img.shape[1] window_size = (2*s, 2*s) fl = 2*s * 2*s idx = 0 filtered = np.empty((height, width, filtered_dim), dtype=np.float) filtered[:, :, idx] = gaussian_filter(img, sigma=s, order=0) idx += 1 filtered[:, :, idx] = gaussian_filter(img, sigma=s, order=[0, 1])# Lx idx += 1 filtered[:, :, idx] = gaussian_filter(img, sigma=s, order=[1, 0])# Ly idx += 1 filtered[:, :, idx] = gaussian_filter(img, sigma=s, order=[1, 1])# Lxy idx += 1 filtered[:, :, idx] = gaussian_filter(img, sigma=s, order=[0, 2])# Lxx idx += 1 filtered[:, :, idx] = gaussian_filter(img, sigma=s, order=[2, 0])# Lyy idx += 1 # here we use gaussian_filter size as window size for linear transform # this will give you sliding windows # windows shape is (I.WIDTH-2s+1, I.HEIGHT-2s+1, 2s, 2s) windows = rolling_window(img, window_size).astype(np.float32) h, w, wh, ww = windows.shape windows_dct = dct(windows).reshape(h, w, fl) filtered[:, :, idx: idx + fl] = np.lib.pad(windows_dct, ((2*s-1, 0), (2*s-1, 0), (0,0)), 'reflect') idx += fl windows_dst = dst(windows).reshape(h, w, fl) filtered[:, :, idx: idx + fl] = np.lib.pad(windows_dst, ((2*s-1, 0), (2*s-1, 0), (0,0)), 'reflect') idx += fl windows_fft = fft2(windows).reshape(h, w, fl) filtered[:, :, idx: idx + fl] = np.lib.pad(windows_fft, ((2*s-1, 0), (2*s-1, 0), (0,0)), 'reflect') idx += fl feature = np.zeros((height, width, filtered_dim*moment), dtype=np.float) for j in range(filtered_dim): # j is feature_num windows = rolling_window(filtered[:, :, j], window_size) h, w, wh, ww = windows.shape windows = windows.reshape(h, w, fl) for m in range(moment): if m == 0: feature[:, :, j * moment + 0] = np.lib.pad(windows.mean(axis=-1), ((2*s-1, 0), (2*s-1, 0)), 'reflect') elif m == 1: feature[:, :, j * moment + 1] = np.lib.pad(windows.std(axis=-1), ((2*s-1, 0), (2*s-1, 0)), 'reflect') elif m == 2: feature[:, :, j * moment + 2] = np.lib.pad(skew(windows, axis=-1), ((2*s-1, 0), (2*s-1, 0)), 'reflect') else: feature[:, :, j * moment + 3] = np.lib.pad(kurtosis(windows, axis=-1), ((2*s-1, 0), (2*s-1, 0)), 'reflect') return feature
def arc_dst(a, func, N=2048): # The slice at the end removes the endpoints th_data = np.linspace(a, 2 * np.pi, N + 2)[1:-1] discrete_func = np.array([func(th) for th in th_data]) return dst(discrete_func, type=1) / (N + 1)