def inverse(self, spectrum, in_phase=None): if in_phase is None: in_phase = self.phase else: in_phase = cp.array(in_phase) spectrum = cp.array(spectrum) self.spectrum_buffer[:, -1] = spectrum * in_phase self.absolute_buffer[:, -1] = spectrum for _ in range(self.loop_num): self.overwrap_buf *= 0 waves = cp.fft.ifft(self.spectrum_buffer, axis=2).real last = self.spectrum_buffer for i in range(self.buffer_size): self.overwrap_buf[:, i * self.wave_dif:i * self.wave_dif + self.wave_len] += waves[:, i] waves = cp.stack([ self.overwrap_buf[:, i * self.wave_dif:i * self.wave_dif + self.wave_len] * self.window for i in range(self.buffer_size) ], axis=1) spectrum = cp.fft.fft(waves, axis=2) self.spectrum_buffer = self.absolute_buffer * spectrum / ( cp.abs(spectrum) + 1e-10) self.spectrum_buffer += 0.5 * (self.spectrum_buffer - last) dst = cp.asnumpy(self.spectrum_buffer[:, 0]) self.absolute_buffer = cp.roll(self.absolute_buffer, -1, axis=1) self.spectrum_buffer = cp.roll(self.spectrum_buffer, -1, axis=1) return dst
def refocus(self, alpha, imgs, size): output = [] center = (size[0] // 2, size[1] // 2) for i in range(size[0]): for j in range(size[1]): dx = (i - center[0]) * (-1 if order else 1) dy = (j - center[1]) * -1 if (not order): shiftx = np.roll(imgs[(size[0] - 1 - i) * size[1] + size[1] - j - 1], int(alpha * dx), axis=0) shifty = np.roll(shiftx, int(alpha * dy), axis=1) else: shiftx = np.roll(imgs[(i) * size[1] + j], int(alpha * dx), axis=0) shifty = np.roll(shiftx, int(alpha * dy), axis=1) output.append(shifty) sys.stdout.write( "\r" + "Refocusing" + "." * (int((i * size[1] + j) / (size[0] * size[1]) * 10)) + " " + str(int((i * size[1] + j + 1) / (size[0] * size[1]) * 100)) + "%") # sys.stdout.write("\nList casting again...") # self.output = np.array(self.output) # sys.stdout.write("\nList casting done!") return np.mean(output, axis=0)
def imgshift_cupy(img_cupy,dxy): imgout_cupy=cp.copy(img_cupy) imgout_cupy=cp.roll(imgout_cupy,int(dxy[0]),axis=0) imgout_cupy=cp.roll(imgout_cupy,int(dxy[1]),axis=1) return imgout_cupy
def convective(matrix): dxp1 = np.roll(matrix, 1, axis=0) dxm1 = np.roll(matrix, -1, axis=0) dyp1 = np.roll(matrix, 1, axis=1) dym1 = np.roll(matrix, -1, axis=1) dmdx = (dxp1-dxm1)/(2 * ds) dmdy = (dyp1-dym1)/(2 * ds) return dmdx*matrix[:, :, :-1] + dmdy*matrix[:, :, 1:]
def divergence(matrix): dxp1 = np.roll(matrix, 1, axis=0) dxm1 = np.roll(matrix, -1, axis=0) dyp1 = np.roll(matrix, 1, axis=1) dym1 = np.roll(matrix, -1, axis=1) dmdx = (dxp1-dxm1)/(2 * ds) dmdy = (dyp1-dym1)/(2 * ds) return dmdx[:, :, 0] + dmdy[:, :, 1]
def laplacian(matrix): dxp1 = np.roll(matrix, 1, axis=0) dxm1 = np.roll(matrix, -1, axis=0) dyp1 = np.roll(matrix, 1, axis=1) dym1 = np.roll(matrix, -1, axis=1) dm2dx2 = (dxp1 - 2 * matrix + dxm1)/(2 * ds) dm2dy2 = (dyp1 - 2 * matrix + dym1)/(2 * ds) return dm2dx2[:, :, 0] + dm2dy2[:, :, 1]
def check_vertical_flux(self, conv_crit): vert_flux = abs(self.conc - cp.roll(self.conc, 1, 1)) vert_flux[self.conc == 0] = 0 vert_flux[cp.roll(self.conc, 1, 1) == 0] = 0 fl = cp.sum(vert_flux, (0, 2, 3))[3:-2] err = (fl.max() - fl.min())*2/(fl.max() + fl.min()) if err < conv_crit or np.isnan(err): return True if fl.min() == 0: return 'zero_flux'
def surface_area(img, phases, periodic=False): """ Calculate interfacial surface area between two phases or the total surface area of one phase :param img: :param phases: list of phases to calculate SA, if lenght 1 calculate total SA, if length 2 calculate inerfacial SA :return: the surface area in faces per unit volume """ shape = img.shape int_not_in_img = np.unique(img).min() - 1 dim = len(shape) img = cp.asarray(img) # finding an int that is not in the img for padding: if periodic: pad = [(int(not x), int(not x)) for x in periodic] img = cp.pad(img, pad, 'constant', constant_values=int_not_in_img) else: img = cp.pad(img, 1, 'constant', constant_values=int_not_in_img) periodic = [0] * dim SA_map = cp.zeros_like(img) if not isinstance(phases, list): phases = [phases] for i in range(dim): for j in [1, -1]: i_rolled = cp.roll(img, j, i) if len(phases) == 2: SA_map[(i_rolled == phases[0]) & (img == phases[1])] += 1 else: SA_map[(i_rolled == phases[0]) & (img != phases[0])] += 1 # remove padding if not periodic[0]: SA_map = SA_map[1:-1, :] if not periodic[1]: SA_map = SA_map[:, 1:-1] x, y = shape[0], shape[1] # scale factor calculated by taking into account edges periodic_mask = [not x for x in periodic] if dim == 3: z = shape[2] if not periodic[2]: SA_map = SA_map[:, :, 1:-1] sf = cp.sum( cp.array([x, y, z])[periodic_mask] * cp.roll(cp.array([x, y, z])[periodic_mask], 1)) total_faces = 3 * (x * y * z) - sf elif dim == 2: sf = cp.sum(cp.array([x, y])[periodic_mask]) total_faces = 2 * (x + 1) * (y + 1) - (x + 1) - (y + 1) - 2 * sf else: total_faces = SA_map.size sa = cp.sum(SA_map) / total_faces return sa
def shift(a, x, y): b = cp.roll(a, x, axis=1) if x >= 0: b[:, 0:x] = cp.zeros((a.shape[0], abs(x))) else: b[:, x:] = cp.zeros((a.shape[0], abs(x))) b = cp.roll(b, y, axis=0) if y >= 0: b[0:y, :] = cp.zeros((abs(y), a.shape[1])) else: b[y:, :] = cp.zeros((abs(y), a.shape[1])) return b
def triple_phase_boundary(img): phases = cp.unique(cp.asarray(img)) if len(phases) != 3: return None shape = img.shape dim = len(shape) ph_maps = [] img = cp.pad(cp.asarray(img), 1, 'constant', constant_values=-1) if dim == 2: x, y = shape total_edges = (x - 1) * (y - 1) for ph in phases: ph_map = cp.zeros_like(img) ph_map_temp = cp.zeros_like(img) ph_map_temp[img == ph] = 1 for i in [0, 1]: for j in [0, 1]: ph_map += cp.roll(cp.roll(ph_map_temp, i, 0), j, 1) ph_maps.append(ph_map) tpb_map = cp.ones_like(img) for ph_map in ph_maps: tpb_map *= ph_map tpb_map[tpb_map > 1] = 1 tpb_map = tpb_map[1:-1, 1:-1] tpb = np.sum(tpb_map) else: tpb = 0 x, y, z = shape total_edges = z * (x - 1) * (y - 1) + x * (y - 1) * (z - 1) + y * ( x - 1) * (z - 1) print(total_edges) for d in range(dim): ph_maps = [] for ph in phases: ph_map = cp.zeros_like(img) ph_map_temp = cp.zeros_like(img) ph_map_temp[img == ph] = 1 for i in [0, 1]: for j in [0, 1]: d1 = (d + 1) % 3 d2 = (d + 2) % 3 ph_map += cp.roll(cp.roll(ph_map_temp, i, d1), j, d2) ph_maps.append(ph_map) tpb_map = cp.ones_like(img) for ph_map in ph_maps: tpb_map *= ph_map tpb_map[tpb_map > 1] = 1 tpb_map = tpb_map[1:-1, 1:-1, 1:-1] tpb += np.sum(tpb_map) return tpb / total_edges
def normals_to_height(image, grid_steps, iterations=2000, intensity=1.0): # A = image[..., 3] ih, iw = image.shape[0], image.shape[1] u = cup.ones((ih, iw), dtype=np.float32) * 0.5 vectors = nmap_to_vectors(image) # vectors[..., 0] = 0.5 - image[..., 0] # vectors[..., 1] = image[..., 1] - 0.5 vectors *= intensity t = np.empty_like(u, dtype=np.float32) for k in range(grid_steps, -1, -1): # multigrid k = 2**k print("grid step:", k) n = cup.roll(vectors[..., 0], k, axis=1) n -= cup.roll(vectors[..., 0], -k, axis=1) n += cup.roll(vectors[..., 1], k, axis=0) n -= cup.roll(vectors[..., 1], -k, axis=0) n *= 0.125 for ic in range(iterations): if ic % 100 == 0: print(ic) # roll k, axis=0 t[:-k, :] = u[k:, :] t[-k:, :] = u[:k, :] # roll -k, axis=0 t[k:, :] += u[:-k, :] t[:k, :] += u[-k:, :] # roll k, axis=1 t[:, :-k] += u[:, k:] t[:, -k:] += u[:, :k] # roll -k, axis=1 t[:, k:] += u[:, :-k] t[:, :k] += u[:, -k:] t *= 0.25 u = t + n # zero alpha = zero height # u = u * A + cup.max(u) * (1 - A) u = -u u -= cup.min(u) u /= cup.max(u) return cup.dstack([u, u, u, image[..., 3]])
def locate_points( mesh_prefix: str = None, pts_prefix: str = None, chunk_size: int = None, bounding_box: dict = None) -> [cp.ndarray, cp.ndarray, cp.ndarray]: # # Load data tris, verts, vert_normals = load_mesh(mesh_prefix) all_pts = load_query_points(pts_prefix) vertices = verts[tris[:, :]] # # Fix common dimensions num_verts = vertices.shape[0] # # Compute static information about # the triangles # # ==================== # EDGE ORDER # [:, 0, :] = v # [:, 1, :] = -u # [:, 2, :] = -w # ==================== edges = cp.roll(vertices, 1, axis=1) - vertices # (p3-p1, p1-p2, p2-p3) # # Correct edge signs and ordering edges[:, 1, :] = edges[:, 1, :] * -1 edges[:, 2, :] = edges[:, 2, :] * -1 edges = cp.roll(edges, 2, axis=1) tmp = edges[:, 1, :].copy() edges[:, 1, :] = edges[:, 2, :] edges[:, 2, :] = tmp # # Compute normals and lengths normals = cp.cross(edges[:, 0], edges[:, 1]) norms = cp.linalg.norm(normals, axis=1) normssq = cp.square(norms) # return _locate_points(all_pts=all_pts, vertices=vertices, edges=edges, normals=normals, norms=norms, normssq=normssq, chunk_size=chunk_size, num_verts=num_verts, tris=tris, vertex_normals=vert_normals, bounding_box=bounding_box)
def __init__(self, photons_file, num_pix, need_scaling=False): self.powder = None mpool = cp.get_default_memory_pool() init_mem = mpool.used_bytes() self.photons_file = photons_file self.num_pix = num_pix with h5py.File(self.photons_file, 'r') as fptr: if self.num_pix != fptr['num_pix'][...]: raise AttributeError( 'Number of pixels in photons file does not match') self.num_data = fptr['place_ones'].shape[0] try: self.ones = cp.array(fptr['ones'][:]) except KeyError: self.ones = cp.array([ len(fptr['place_ones'][i]) for i in range(self.num_data) ]).astype('i4') self.ones_accum = cp.roll(self.ones.cumsum(), 1) self.ones_accum[0] = 0 self.place_ones = cp.array(np.hstack(fptr['place_ones'][:])) try: self.multi = cp.array(fptr['multi'][:]) except KeyError: self.multi = cp.array([ len(fptr['place_multi'][i]) for i in range(self.num_data) ]).astype('i4') self.multi_accum = cp.roll(self.multi.cumsum(), 1) self.multi_accum[0] = 0 self.place_multi = cp.array(np.hstack(fptr['place_multi'][:])) self.count_multi = np.hstack(fptr['count_multi'][:]) self.mean_count = float( (self.place_ones.shape[0] + self.count_multi.sum()) / self.num_data) if need_scaling: self.counts = self.ones + cp.array([ self.count_multi[m_a:m_a + m].sum() for m, m_a in zip(self.multi.get(), self.multi_accum.get()) ]) self.count_multi = cp.array(self.count_multi) try: self.bg = cp.array(fptr['bg'][:]).ravel() print('Using background model with %.2f photons/frame' % self.bg.sum()) except KeyError: self.bg = cp.zeros(self.num_pix) self.mem = mpool.used_bytes() - init_mem
def flux_map(self, lay=0): """ Plots a flux map perpendicular to the direction of flow :param lay: depth to plot :return: 3D flux map """ flux = cp.zeros_like(self.conc) ph_map = self.pad(self.pad(cp.array(self.cpu_img)))[:, :, 2:-2, 2:-2] for dim in range(1, 4): for dr in [1, -1]: flux += abs(cp.roll(self.conc, dr, dim) - self.conc) * cp.roll(ph_map, dr, dim) flux = flux[0, 2:-2].get() flux[self.cpu_img[0] == 0] = 0 plt.imshow(flux[:, :, lay]) return flux
def delight_simple(image, dd, iterations=500): A = image[..., 3] u = cup.ones_like(image[..., 0]) grads = cup.zeros((image.shape[0], image.shape[1], 2), dtype=cup.float32) grads[..., 0] = (cup.roll(image[..., 0], 1, axis=0) - image[..., 0]) * dd grads[..., 1] = (image[..., 0] - cup.roll(image[..., 0], 1, axis=1)) * dd # grads[..., 0] = (image[..., 0] - 0.5) * (dd) # grads[..., 1] = (image[..., 0] - 0.5) * (dd) for k in range(5, -1, -1): # multigrid k = 2**k print("grid step:", k) n = cup.roll(grads[..., 0], k, axis=1) n -= cup.roll(grads[..., 0], -k, axis=1) n += cup.roll(grads[..., 1], k, axis=0) n -= cup.roll(grads[..., 1], -k, axis=0) n *= 0.125 * image[..., 3] for ic in range(iterations): if ic % 100 == 0: print(ic) t = cup.roll(u, -k, axis=0) t += cup.roll(u, k, axis=0) t += cup.roll(u, -k, axis=1) t += cup.roll(u, k, axis=1) t *= 0.25 # zero alpha = zero height u = t + n u = u * A + cup.max(u) * (1 - A) u = -u u -= cup.min(u) u /= cup.max(u) # u *= image[..., 3] # u -= cup.mean(u) # u /= max(abs(cup.min(u)), abs(cup.max(u))) # u *= 0.5 # u += 0.5 # u = 1.0 - u # return cup.dstack([(u - image[..., 0]) * 0.5 + 0.5, u, u, image[..., 3]]) u = (image[..., 0] - u) * 0.5 + 0.5 return cup.dstack([u, u, u, image[..., 3]])
def create_surrogate(data): res = cp.zeros_like(data) for i in range(data.shape[0]): idx = np.random.randint(data.shape[1] - 1) res[i] = cp.roll(data[i], idx) return res
def get_measurement_matrix(self,ix,iy): shifted_theta = self.theta+self.theta[1] theta_grid,r_grid = cp.meshgrid(shifted_theta*util.PI/180,self.r) #Because theta will be on the x axis, and r will be on the y axis # theta_grid = theta_grid[:,::-1] H = cp.zeros((r_grid.size,ix.size),dtype=cp.complex64) if not self.use_skimage: #launch CUDA kernel if cuda.is_available(): bpg=((H.shape[0]+TPBn-1)//TPBn,(H.shape[1]+TPBn-1)//TPBn) print("Cuda is available, now running CUDA kernel with Thread perblock = {}, Block Per Grids = {}, and H shape {}".format(TPB,bpg,H.shape)) util._calculate_H_Tomography[bpg,TPB](r_grid.ravel(ORDER),theta_grid.ravel(ORDER),ix,iy,H) ratio = self.n_r/(2*(self.n_r//2)) H *= ratio #Some Temporary Fixing nPart=4 n_theta = self.n_theta n_r = self.n_r for i in range(n_theta//nPart): H[i*n_r:(i+1)*n_r,:] = cp.roll(H[i*n_r:(i+1)*n_r,:],1,axis=0) # util.calculate_H_Tomography(r_grid.ravel(ORDER),theta_grid.ravel(ORDER),ix,iy,H) #due to some problem the resulted H is flipped upside down #hence # H = cp.flipud(H) # norm_ratio = (self.n_r/2)/(self.n_r//2) else: H_n = cp.asnumpy(H) util.calculate_H_Tomography_skimage(cp.asnumpy(self.theta),cp.asnumpy(ix),cp.asnumpy(iy),H_n,self.target_image.shape[0]) H = cp.asarray(H_n) return H.astype(cp.complex64)
def __call__(self, signal: Signals, device): if self.sps is None: self.sps = signal.sps self.delay = int(self.span / 2 * self.sps) self.h = self.rcosdesign() self.h = np.atleast_2d(self.h) self.to(device) signal.samples = np.zeros( (signal.pol_number, signal.symbol_length * signal.sps), dtype=np.complex) signal.samples[:, ::self.sps] = signal.symbol signal.to(device) from sigdsp import conv signal.samples = conv(self.h, signal.samples, self.device) # compensate the delay and cut off the sample if device == 'cuda': from cupy import roll else: from numpy import roll signal.samples = roll(signal.samples, -self.delay, axis=-1)[:, :signal.symbol_length * signal.sps] return signal
def Cu_FastHankel_prod_mat_vec_2dt(prod_vect, k, Q): """ Compute product of Hankel matrix (gene_vect) by vector prod_vect. H is not computed M is the length of the result k =0 initializes cuda for gene_vect """ #print('*** Je suis dans Cu_FastHankel_prod_mat_vec_2dt ***') global fft0 N = len( prod_vect) # length of the vector that is multiplied by the matrix. cu_gene_vect = cupy.concatenate( (cupy.zeros(N - 1), cupy.asarray(Q[:, k]), cupy.zeros(N - 1))) # generator vector for Toeplitz matrix L = len(cu_gene_vect) # length of generator vector M = L - N + 1 cu_prod_vect = cupy.asarray(prod_vect) cu_prod_vect_zero = cupy.concatenate( (cupy.zeros(M - 1), cu_prod_vect[::-1])) # prod_vect is completed with zero to length L fft0, fft1 = cupy.fft.fft(cu_gene_vect), cupy.fft.fft( cu_prod_vect_zero) # FFT transforms of generator vector and cu_prod = fft0 * fft1 # FFT product performing the convolution product. c = cupy.fft.ifft(cu_prod) # IFFT for going back return cupy.roll(c, +1)[:M]
def init_nn(self, img): #conductivity map img2 = cp.zeros_like(img) for ph in self.cond: c = self.cond[ph] img2[img == ph] = c img2 = self.pad(self.pad(img2)) img2[:, 1] = img2[:, 2] img2[:, -2] = img2[:, -3] nn = cp.zeros_like(img2, dtype=self.precision) # iterate through shifts in the spatial dimensions nn_list = [] for dim in range(1, 4): for dr in [1, -1]: shift = cp.roll(img2, dr, dim) sum = img2 + shift sum[shift==0] = 0 sum[img2==0] = 0 sum = 1/sum sum[sum == cp.inf] = 0 nn += sum nn_list.append(self.crop(sum, 1)) # remove the two paddings nn = self.crop(nn, 2) # avoid div 0 errors nn[img == 0] = cp.inf nn[nn == 0] = cp.inf nn_list.insert(0, nn) return nn_list
def init_cb(self, img): bs, x, y, z = img.shape cb = np.zeros([x, y, z]) a, b, c = np.meshgrid(range(x), range(y), range(z), indexing='ij') cb[(a + b + c) % 2 == 0] = 1 cb *= self.w return [cp.roll(cp.array(cb), sh, 0) for sh in [0, 1]]
def solve(self, iter_limit=5000, verbose=True, conv_crit=2*10**-2, D_0=1): """ run a solve simulation :param iter_limit: max iterations before aborting, will attempt double for the same no. iterations if initialised as singles :param verbose: Whether to print tau. Can be set to 'per_iter' for more feedback :param conv_crit: convergence criteria, minimum percent difference between max and min flux through a given layer :return: tau """ start = timer() while not self.converged: out = cp.zeros_like(self.conc) for dim in range(1, 4): for dr in [1, -1]: out += cp.roll(self.conc, dr, dim) out = out[:, 2:-2] out /= self.nn if self.iter % 50 == 0: lt = abs(cp.sum(out[:, 0]) - self.ph_top) lb = abs(cp.sum(out[:, -1]) - self.ph_bot) self.converged, D_rel = self.check_convergence(lt, lb, verbose, conv_crit, start, iter_limit) out -= self.conc[:, 2:-2] out *= self.cb[self.iter % 2] self.conc[:, 2:-2] += out self.iter += 1 self.D_mean=D_0 self.tau = self.VF/D_rel if D_rel !=0 else cp.inf self.D_eff=D_0*D_rel self.end_simulation(iter_limit, verbose, start) return self.tau
def train(inweights, v, variables, leak, bs, steps, testflag, s, count): T = len(s) N = 1024 M = 1024 x1 = cp.zeros(N * layerscales["L1"], dtype=np.float32) gradient = dict() softerr1 = 0 err1 = 0 skipfirst = 0 t = step tm1 = (T - 1 - t - skipfirst) for k in range(skipfirst): step1 = s[t - step] x1 = (1.0 - leak) * x1 + leak * (inweights["U1"][:, step1] + cp.roll(x1, 1)) x1 = x1 / cp.linalg.norm(x1) t += 1 for b1 in range(tm1): step1 = s[t - step] x1 = (1.0 - leak) * x1 + leak * (inweights["U1"][:, step1] + cp.roll(x1, 1)) x1 = x1 / cp.linalg.norm(x1) wx = cp.dot(variables["W1"], x1) wx = wx - cp.max(wx) p = cp.exp(wx) p1 = p / cp.sum(p) pred1 = cp.argmax(p1) target = s[t+1] target_prob1 = p1[target] softerr1 += 1 - target_prob1 err1 = err1 + (pred1 != target) if testflag == 0: gradient["W1"] = cp.outer(v[:, target] - p1, x1) SGD.update_state(gradient) delta = SGD.get_delta() SGD.update_with_L1_regularization(variables, delta, L1) t += 1 softerrors = dict() prederrors = dict() softerrors["lay1"] = softerr1 / (tm1) prederrors["lay1"] = err1 * 100.0 / (tm1) return prederrors, softerrors, variables
def train_kcpa(inweights, v, variables, leak, bs, step, s, cpstates): T = len(s) N = 1024 M = 1024 x1 = cp.zeros(N * layerscales["L1"], dtype=np.float32) # gradient = dict() # softerr1 = 0 # err1 = 0 skipfirst = 1 t = step tm1 = (T - 1 - t - skipfirst) for k in range(skipfirst): current = s[t - step] x1 = (1.0 - leak) * x1 + leak * (inweights["U1"][:, current] + cp.roll(x1, 1)) x1 = x1 / cp.linalg.norm(x1) # wx = cp.dot(variables["W1"], x1) # wx = wx - cp.max(wx) # p = cp.exp(wx) # p1 = p / cp.sum(p) t += 1 for b1 in range(tm1): current = s[t - step] x1 = (1.0 - leak) * x1 + leak * (inweights["U1"][:, current] + cp.roll(x1, 1)) x1 = x1 / cp.linalg.norm(x1) # wx = cp.dot(variables["W1"], x1) # wx = wx - cp.max(wx) # p = cp.exp(wx) # p1 = p / cp.sum(p) cpstates = cp.concatenate( (cpstates, x1.reshape((1, N * layerscales["L1"])))) # target = s[t+1] # gradient["W1"] = cp.outer(v[:, target] - p1, x1) # SGD.update_state(gradient) # delta = SGD.get_delta() # SGD.update_with_L1_regularization(variables, delta, L1) t += 1 return variables, cpstates
def convolution(ssp, intens, sfil): # source, intensity, convolution matrix tpx = cup.zeros(ssp.shape, dtype=float) ysz, xsz = sfil.shape[0], sfil.shape[1] ystep = int(4 * ssp.shape[1]) for y in range(ysz): for x in range(xsz): tpx += cup.roll(ssp, (x - xsz // 2) * 4 + (y - ysz // 2) * ystep) * sfil[y, x] return tpx
def getNabla_psiy(self): f = cp.zeros((H, W)) psi_with_block = copy.deepcopy(self.psi) psi_with_block[self.block_mask] = psi_wall temp = cp.hstack((self.left_wall, cp.hstack((psi_with_block, self.right_wall)))) # temp = np.vstack((self.top_bottom_wall, np.vstack((temp, self.top_bottom_wall)))) for i in range(9): if i == 2: f += 4 * cp.roll(temp, -1, axis=0)[:, 1:-1] elif i == 4: f += -4 * cp.roll(temp, 1, axis=0)[:, 1:-1] elif i == 5: f += cp.roll(cp.roll(temp, -1, axis=1), -1, axis=0)[:, 1:-1] elif i == 6: f += cp.roll(cp.roll(temp, 1, axis=1), -1, axis=0)[:, 1:-1] elif i == 7: f += - cp.roll(cp.roll(temp, 1, axis=1), 1, axis=0)[:, 1:-1] elif i == 8: f += - cp.roll(cp.roll(temp, -1, axis=1), 1, axis=0)[:, 1:-1] return f / 12
def roll(tensor, shift, axis): """Rolls the elements of a tensor along an axis. Args: tensor (tensor): tensor to roll shift (tensor): offset to roll axis (tensor): axis to shift by Returns: [type]: [description] """ return cp.roll(tensor, shift, axis)
def init_nn(self, img): img2 = self.pad(self.pad(img, [2, 2]))[:, :, 2:-2, 2:-2] nn = cp.zeros_like(img2, dtype=self.precision) # iterate through shifts in the spatial dimensions for dim in range(1, 4): for dr in [1, -1]: nn += cp.roll(img2, dr, dim) # avoid div 0 errors nn = nn[:, 2:-2] nn[img == 0] = cp.inf nn[nn == 0] = cp.inf return nn
def delay(x, period): # window是> if abs(period) >= len(x): return cp.full(len(x), cp.nan) #period 和 window的区别,这里不再减1 prefix = cp.full(abs(period), cp.nan) # 只有float才能加cp.nan, 否则int就会变成-2147483648 result = cp.roll(x, period).astype(float) if period >= 0: result[:period] = prefix else: result[period:] = prefix return result
def ht3(x, ax, shift, thresh): C = 1. / np.sqrt(2.) if shift == True: x = np.roll(x, -1, axis=ax) if ax == 0: w1 = C * (x[1::2, :, :] + x[0::2, :, :]) w2 = soft_py(C * (x[1::2, :, :] - x[0::2, :, :]), thresh) elif ax == 1: w1 = C * (x[:, 1::2, :] + x[:, 0::2, :]) w2 = soft_py(C * (x[:, 1::2, :] - x[:, 0::2, :]), thresh) elif ax == 2: w1 = C * (x[:, :, 1::2] + x[:, :, 0::2]) w2 = soft_py(C * (x[:, :, 1::2] - x[:, :, 0::2]), thresh) return w1, w2