def setElbowMask(self, center_x=50 * 10**-7, center_y=50 * 10**-7, center_z=2.5 * 10**-7, r_s=15 * 10**-7, r_l=20 * 10**-7, l_z=4 * 10**-7, phi_start=0, phi_end=90): self.center_x = center_x # x axis position of cylindrical geometry [unit: m] self.center_y = center_y # y axis position of cylindrical geometry [unit: m] self.center_z = center_z # z axis position of cylindrical geometry [unit: m] self.r_s = r_s self.r_l = r_l self.l_z = l_z self.phi_start = phi_start self.phi_end = phi_end Z, Y, X = np.ogrid[:self.nz, :self.ny, :self.nx] X = (X + 0.5) * self.lcx - self.center_x Y = (Y + 0.5) * self.lcy - self.center_y Z = (Z + 0.5) * self.lcz - self.center_z X = X.round(decimals=16) Y = Y.round(decimals=16) Z = Z.round(decimals=16) self.phiJ = np.arctan2(Y, X) deg = math.pi / 180 self.mask = (X**2 + Y**2 > r_s**2) & (X**2 + Y**2 < r_l**2) & ( np.abs(Z) < l_z / 2) & (np.arctan2( Y, X) > phi_start * deg) & (np.arctan2(Y, X) < phi_end * deg) self.generateMask()
def kernel_crossphase_cu(fft_data, ch_it, fft_config): """Kernel that calculates the cross-phase between two channels. Args: fft_data (ndarray, complex): Holds the fourier-transformed data. dim0: channel, dim1: Fourier Coefficients, dim2: STFT (bins in fluctana code) ch_it (iterable): Iterator over a list of channels we wish to perform our computation on Returns: Axy (array, float): Cross phase """ fft_data_cu = cp.asarray(fft_data) # Gather results on device, since Pxy = cp.zeros([len(ch_it), fft_data.shape[1], fft_data.shape[2]], dtype=fft_data.dtype) # The result of the call to mean() is another cupy array. Gather the # results in Pxy which needs to by a cupy array. Copy to host once # loop is done for idx, ch_pair in enumerate(ch_it): Pxy[idx, :, :] = fft_data_cu[ch_pair.ch1.get_idx( ), :, :] * fft_data_cu[ch_pair.ch2.get_idx(), :, :].conj() crossphase = cp.asnumpy(cp.arctan2(Pxy.imag, Pxy.real).mean(axis=2)) np.savez("crossphase_cu.npz", crossphase=crossphase) return (crossphase)
def initCoords(self): size=self.vol_dim[0]/2 x, y=np.meshgrid(np.arange(-size+1,size+1),np.arange(-size+1,size+1)) #temp=np.arctan2(y, x) #temp=np.reshape(temp,(size*2,size*2,1)) #self.radmatrix=np.repeat(temp, size*2, axis=2) self.radmatrix=np.remainder(np.arctan2(x, y)+2*np.pi,2*np.pi)-2*np.pi self.zline=np.arange(-size+1,size+1)
def avoid_point(): if not SlimeWorld.avoid: return diff_from_avoid_pos = SlimeWorld.slime_pos - SlimeWorld.avoid_pos dist_from_avoid_pos = cp.linalg.norm(diff_from_avoid_pos, axis=-1) angle_to_avoid_pos = cp.arctan2(diff_from_avoid_pos[:, 0], diff_from_avoid_pos[:, 1]) mask = dist_from_avoid_pos < SlimeWorld.avoid_dist SlimeWorld.slime_angle[mask] = angle_to_avoid_pos[mask]
def _compute_phasediff(cross_correlation_max): """ Compute global phase difference between the two images (should be zero if images are non-negative). Parameters ---------- cross_correlation_max : complex The complex value of the cross correlation at its maximum point. """ return cp.arctan2(cross_correlation_max.imag, cross_correlation_max.real)
def atan2(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arctan2 <numpy.arctan2>`. See its docstring for more information. """ if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in atan2") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.arctan2(x1._array, x2._array))
def update_plot(self, i, scat): if self.n_obj > self.flock.n_obj: self.flock.add_new_objs(self.n_obj - self.flock.n_obj) self.flock.n_obj = self.n_obj elif self.n_obj < self.flock.n_obj: self.flock.delete_objs(self.flock.n_obj - self.n_obj) self.flock.n_obj = self.n_obj distances = self.flock.calc_distance_matrix() self.flock.update_v(distances) self.flock.update_r() c = cp.arctan2(self.flock.state[:, 2], self.flock.state[:, 3]) / cp.pi / 2 + 0.5 scat.set_color(plt.get_cmap('hsv')(c.get())) scat.set_offsets(self.flock.state[:, :2].get()) return scat,
def _swirl_mapping(xy, center, rotation, strength, radius): x, y = xy.T x0, y0 = center xdiff = x - x0 ydiff = y - y0 rho = cp.sqrt(xdiff * xdiff + ydiff * ydiff) # Ensure that the transformation decays to approximately 1/1000-th # within the specified radius. radius = radius / 5 * math.log(2) theta = rotation + strength * cp.exp(-rho / radius) theta += cp.arctan2(ydiff, xdiff) xy[..., 0] = x0 + rho * cp.cos(theta) xy[..., 1] = y0 + rho * cp.sin(theta) return xy
def animate(self, n_iter): fig, ax = plt.subplots(figsize=(10, 5)) fig.suptitle('Flocking simulation') numframes = n_iter plt.gca().set_facecolor('black') plt.xlim((self.flock.x_min, self.flock.x_max)) plt.ylim((self.flock.y_min, self.flock.y_max)) plt.xticks([]) plt.yticks([]) c = cp.arctan2(self.flock.state[:, 2], self.flock.state[:, 3]) / cp.pi / 2 + 0.5 scat = plt.scatter(self.flock.state[:, 0].get(), self.flock.state[:, 1].get(), s=10, c=c.get()) plt.subplots_adjust(left=0.5, bottom=0) sliders = [] for i, slider in enumerate(self.sliders_meta): ax = plt.axes([0.23, 0.2 + 0.05 * i, 0.2, 0.03]) slider_widget = Slider( ax=ax, label=self.sliders_meta[slider]['label'], valmin=self.sliders_meta[slider]['bounds'][0], valmax=self.sliders_meta[slider]['bounds'][1], valinit=self.sliders_meta[slider]['default_value']) slider_widget.on_changed(self.update_slider(slider)) sliders.append(slider_widget) ani = animation.FuncAnimation(fig, self.update_plot, frames=range(numframes), fargs=(scat, ), interval=10, repeat=True) plt.show() return ani
def move_slimes(): slime_dir = cp.array( [cp.sin(SlimeWorld.slime_angle), cp.cos(SlimeWorld.slime_angle)]).T SlimeWorld.slime_pos += slime_dir # Change direction if out of bounds xoob = (SlimeWorld.slime_pos[:, 0] < 0) | (SlimeWorld.slime_pos[:, 0] > SlimeWorld.WIDTH - 1) yoob = (SlimeWorld.slime_pos[:, 1] < 0) | (SlimeWorld.slime_pos[:, 1] > SlimeWorld.HEIGHT - 1) # Bounce off walls if cp.any(xoob): slime_dir[xoob, 0] *= -1 if cp.any(yoob): slime_dir[yoob, 1] *= -1 if cp.any(xoob | yoob): SlimeWorld.slime_angle = cp.arctan2(slime_dir[:, 0], slime_dir[:, 1]) # Clip if out of bounds SlimeWorld.clip(SlimeWorld.slime_pos)
def createWedge(self, subunit_num=0): ###Initialize the location of the protofilament to remove theta0=np.arctan2(self.com[0], self.com[1])+\ np.deg2rad(subunit_num*self.twist_per_subunit) z0=(self.com[2]+self.rise_per_subunit*subunit_num)/self.pixel_size ###Define the length along the protofilament in terms of subunits zsubunits=(self.zline.copy()-z0)*self.pixel_size/self.dimer_repeat_dist ###Define the angle of the center of the protofilament along the length of the segment theta=np.deg2rad((-self.helical_twist)*zsubunits)+theta0 ###Initialize the wedge mask wedge=np.zeros(self.vol_dim.tolist()) ###Define the size of the wedgemask fudge=np.deg2rad(360.0/(self.num_pfs*2)) ###Generate the wedge mask for i in range(len(theta)): temp1=np.remainder(theta[i]-fudge+2*np.pi,2*np.pi)-2*np.pi temp2=np.remainder(theta[i]+fudge+2*np.pi,2*np.pi)-2*np.pi angles=[temp1, temp2] if max(angles)-min(angles)>2*fudge+.2: above=max(angles) below=min(angles) inds=np.logical_or(self.radmatrix>above,self.radmatrix<below) else: above=min(angles) below=max(angles) inds=np.logical_and(self.radmatrix>above,self.radmatrix<below) wedge[i,:,:][inds]=1 return wedge
def _coeff_smooth(lam): xi = 1 - 96 * lam + 24 * lam * sqrt(3 + 144 * lam) omeg = arctan2(sqrt(144 * lam - 1), sqrt(xi)) rho = (24 * lam - 1 - sqrt(xi)) / (24 * lam) rho = rho * sqrt((48 * lam + 24 * lam * sqrt(3 + 144 * lam)) / xi) return rho, omeg
sim_k=int(t_step.sum()) sim_k=sim_k+1 #print(sim_k) mac_ang,mac_spd,dmac_ang,dmac_spd,pelect=cp.zeros((5,sim_k,ngen),dtype=cp.float64) eprime=cp.zeros((sim_k,ngen),dtype=cp.complex128) theta=cp.radians(b_ang) bus_volt=V*cp.exp(jay*theta) mva=basmva/g_m tst1=bus_int[g_bus-1].astype(cp.int) eterm=V[tst1-1] # terminal bus voltage pelect[0]=b_pg[tst1-1] # BUS_pg qelect=b_qg[tst1-1] # BUS_qg #compute the initial values for generator dynamics curr=cp.hypot(pelect[0],qelect)/(eterm*mva) phi=cp.arctan2(qelect,pelect[0]) v=eterm*cp.exp(jay*theta[tst1-1]) curr=curr*cp.exp(jay*(theta[tst1-1]-phi)) eprime[0]=v+jay*g_dtr*curr mac_ang[0]=cp.arctan2(eprime[0].imag,eprime[0].real) mac_spd[0]=1.0 rot=jay*cp.exp(-jay*mac_ang[0]) eprime[0]=eprime[0]*rot edprime=cp.copy(eprime[0].real) eqprime=cp.copy(eprime[0].imag) pmech=cp.copy(pelect[0]*mva) steps3=int(t_step.sum()) steps2=int(t_step[:2].sum()) steps1=int(t_step[0]) h_sol1=t_width[0]
def _calibrate(self, img, findCarrier = True, useCupy = False): assert len(img) > 2 self.N = len(img[0, :, :]) if self.N != self._lastN: self._allocate_arrays() ''' define k grids ''' self._dx = self.pixelsize / self.magnification # Sampling in image plane self._res = self.wavelength / (2 * self.NA) self._oversampling = self._res / self._dx self._dk = self._oversampling / (self.N / 2) # Sampling in frequency plane self._k = np.arange(-self._dk * self.N / 2, self._dk * self.N / 2, self._dk, dtype=np.double) self._dx2 = self._dx / 2 self._kr = np.sqrt(self._k ** 2 + self._k[:,np.newaxis] ** 2, dtype=np.single) kxbig = np.arange(-self._dk * self.N, self._dk * self.N, self._dk, dtype=np.single) kybig = kxbig[:,np.newaxis] '''Sum input images if there are more than 3''' if len(img) > 3: imgs = np.zeros((3, self.N, self.N), dtype=np.single) for i in range(3): imgs[i, :, :] = np.sum(img[i:(len(img) // 3) * 3:3, :, :], 0, dtype = np.single) else: imgs = np.single(img) '''Separate bands into DC and 1 high frequency band''' M = exp(1j * 2 * pi / 3) ** ((np.arange(0, 2)[:, np.newaxis]) * np.arange(0, 3)) sum_prepared_comp = np.zeros((2, self.N, self.N), dtype=np.complex64) wienerfilter = np.zeros((2 * self.N, 2 * self.N), dtype=np.single) for k in range(0, 2): for l in range(0, 3): sum_prepared_comp[k, :, :] = sum_prepared_comp[k, :, :] + imgs[l, :, :] * M[k, l] if findCarrier: # minimum search radius in k-space mask1 = (self._kr > 1.9 * self.eta) if useCupy: self.kx, self.ky = self._coarseFindCarrier_cupy(sum_prepared_comp[0, :, :], sum_prepared_comp[1, :, :], mask1) else: self.kx, self.ky = self._coarseFindCarrier(sum_prepared_comp[0, :, :], sum_prepared_comp[1, :, :], mask1) if useCupy: ckx, cky, p, ampl = self._refineCarrier_cupy(sum_prepared_comp[0, :, :], sum_prepared_comp[1, :, :], self.kx, self.ky) else: ckx, cky, p, ampl = self._refineCarrier(sum_prepared_comp[0, :, :], sum_prepared_comp[1, :, :], self.kx, self.ky) self.kx = ckx # store found kx, ky, p and ampl values self.ky = cky self.p = p self.ampl = ampl if self.debug: print(f'kx = {ckx}') print(f'ky = {cky}') print(f'p = {p}') print(f'a = {ampl}') ph = np.single(2 * pi * self.NA / self.wavelength) xx = np.arange(-self._dx2 * self.N, self._dx2 * self.N, self._dx2, dtype=np.single) yy = xx if self.usemodulation: A = ampl else: A = 1 for idx_p in range(0, 3): pstep = idx_p * 2 * pi / 3 if useCupy: self._reconfactor[idx_p, :, :] = ( 1 + 4 / A * cp.outer(cp.exp(cp.asarray(1j * (ph * cky * yy - pstep + p))), cp.exp(cp.asarray(1j * ph * ckx * xx))).real).get() else: self._reconfactor[idx_p, :, :] = ( 1 + 4 / A * np.outer(np.exp(1j * (ph * cky * yy - pstep + p)), np.exp(1j * ph * ckx * xx)).real) # calculate pre-filter factors mask2 = (self._kr < 2) self._prefilter = np.single((self._tfm(self._kr, mask2) * self._attm(self._kr, mask2))) self._prefilter = fft.fftshift(self._prefilter) mtot = np.full((2 * self.N, 2 * self.N), False) krbig = sqrt((kxbig - ckx) ** 2 + (kybig - cky) ** 2) mask = (krbig < 2) mtot = mtot | mask wienerfilter[mask] = wienerfilter[mask] + (self._tf(krbig[mask]) ** 2) * self._att(krbig[mask]) krbig = sqrt((kxbig + ckx) ** 2 + (kybig + cky) ** 2) mask = (krbig < 2) mtot = mtot | mask wienerfilter[mask] = wienerfilter[mask] + (self._tf(krbig[mask]) ** 2) * self._att(krbig[mask]) krbig = sqrt(kxbig ** 2 + kybig ** 2) mask = (krbig < 2) mtot = mtot | mask wienerfilter[mask] = wienerfilter[mask] + (self._tf(krbig[mask]) ** 2) * self._att(krbig[mask]) self.wienerfilter = wienerfilter if self.debug: plt.figure() plt.title('WienerFilter') plt.imshow(wienerfilter) th = np.linspace(0, 2 * pi, 360, dtype = np.single) inv = np.geterr()['invalid'] np.seterr(invalid = 'ignore') kmaxth = np.fmax(2, np.fmax(ckx * np.cos(th) + cky * np.sin(th) + np.sqrt(4 - (ckx * np.sin(th)) ** 2 - (cky * np.cos(th)) ** 2 + ckx * cky * np.sin(2 * th)), - ckx * np.cos(th) - cky * np.sin(th) + np.sqrt(4 - (ckx * np.sin(th)) ** 2 - (cky * np.cos(th)) ** 2 + ckx * cky * np.sin(2 * th)))) np.seterr(invalid = inv) if useCupy and 'interp' in dir(cp): # interp not available in cupy version < 9.0.0 kmax = cp.interp(cp.arctan2(cp.asarray(kybig), cp.asarray(kxbig)), cp.asarray(th), cp.asarray(kmaxth), period=2 * pi).astype(np.single).get() else: kmax = np.interp(np.arctan2(kybig, kxbig), th, kmaxth, period=2 * pi).astype(np.single) wienerfilter = mtot * (1 - krbig * mtot / kmax) / (wienerfilter * mtot + self.w ** 2) self._postfilter = fft.fftshift(wienerfilter) if opencv: self._reconfactorU = [cv2.UMat(self._reconfactor[idx_p, :, :]) for idx_p in range(0, 3)] self._prefilter_ocv = np.single(cv2.dft(fft.ifft2(self._prefilter).real)) pf = np.zeros((self.N, self.N, 2), dtype=np.single) pf[:, :, 0] = self._prefilter pf[:, :, 1] = self._prefilter self._prefilter_ocvU = cv2.UMat(np.single(pf)) self._postfilter_ocv = np.single(cv2.dft(fft.ifft2(self._postfilter).real)) pf = np.zeros((2 * self.N, 2 * self.N, 2), dtype=np.single) pf[:, :, 0] = self._postfilter pf[:, :, 1] = self._postfilter self._postfilter_ocvU = cv2.UMat(np.single(pf)) if cupy: self._postfilter_cp = cp.asarray(self._postfilter)
def approximate_polygon(coords, tolerance): """Approximate a polygonal chain with the specified tolerance. It is based on the Douglas-Peucker algorithm. Note that the approximated polygon is always within the convex hull of the original polygon. Parameters ---------- coords : (N, 2) array Coordinate array. tolerance : float Maximum distance from original points of polygon to approximated polygonal chain. If tolerance is 0, the original coordinate array is returned. Returns ------- coords : (M, 2) array Approximated polygonal chain where M <= N. References ---------- .. [1] https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm """ if tolerance <= 0: return coords chain = cp.zeros(coords.shape[0], "bool") # pre-allocate distance array for all points dists = cp.zeros(coords.shape[0]) chain[0] = True chain[-1] = True pos_stack = [(0, chain.shape[0] - 1)] end_of_chain = False while not end_of_chain: start, end = pos_stack.pop() # determine properties of current line segment r0, c0 = cp.asnumpy(coords[start, :]) r1, c1 = cp.asnumpy(coords[end, :]) dr = r1 - r0 dc = c1 - c0 segment_angle = -cp.arctan2(dr, dc) segment_dist = c0 * cp.sin(segment_angle) + r0 * cp.cos(segment_angle) # select points in-between line segment segment_coords = coords[start + 1:end, :] segment_dists = dists[start + 1:end] # check whether to take perpendicular or euclidean distance with # inner product of vectors # vectors from points -> start and end dr0 = segment_coords[:, 0] - r0 dc0 = segment_coords[:, 1] - c0 dr1 = segment_coords[:, 0] - r1 dc1 = segment_coords[:, 1] - c1 # vectors points -> start and end projected on start -> end vector projected_lengths0 = dr0 * dr + dc0 * dc projected_lengths1 = -dr1 * dr - dc1 * dc perp = cp.logical_and(projected_lengths0 > 0, projected_lengths1 > 0) eucl = cp.logical_not(perp) segment_dists[perp] = cp.abs( segment_coords[perp, 0] * cp.cos(segment_angle) + segment_coords[perp, 1] * cp.sin(segment_angle) - segment_dist) segment_dists[eucl] = cp.minimum( # distance to start point cp.sqrt(dc0[eucl]**2 + dr0[eucl]**2), # distance to end point cp.sqrt(dc1[eucl]**2 + dr1[eucl]**2), ) if cp.any(segment_dists > tolerance): # select point with maximum distance to line new_end = start + cp.argmax(segment_dists) + 1 pos_stack.append((new_end, end)) pos_stack.append((start, new_end)) chain[new_end] = True if len(pos_stack) == 0: end_of_chain = True return coords[chain, :]
def RenderingUserViewLF_AllinOne5K(LF=None, LFDisparity=None, FB=None, viewpoint=None, DIR=None): sphereW = Params.WIDTH sphereH = Params.HEIGHT CENTERx = viewpoint.lon CENTERy = viewpoint.lat # output view is 3:4 ratio new_imgW = cp.floor(viewpoint.diag * 4 / 5 + 0.5) new_imgH = cp.floor(viewpoint.diag * 3 / 5 + 0.5) new_imgW = int(new_imgW) new_imgH = int(new_imgH) OutView = cp.zeros((new_imgH, new_imgW, 3)) TYwarp, TXwarp = cp.mgrid[0:new_imgH, 0:new_imgW] TX = TXwarp TY = TYwarp TX = (TX - 0.5 - new_imgW / 2) TY = (TY - 0.5 - new_imgH / 2) #의심 TX = TX + 1 TY = TY + 1 r = (viewpoint.diag / 2) / cp.tan(viewpoint.fov / 2) R = cp.sqrt(TY**2 + r**2) # Calculate LF_n ANGy = cp.arctan(-TY / r) ANGy = ANGy + CENTERy if (FB == 1): ANGn = cp.cos(ANGy) * cp.arctan(TX / r) ANGn = ANGn + CENTERx Pn = (Params.LFU_W / 2 - viewpoint.pos_y ) * cp.tan(ANGn) + viewpoint.pos_x + (3 * Params.LFU_W / 2) elif (FB == 2): ANGn = cp.cos(ANGy) * cp.arctan(-TX / r) ANGn = ANGn - CENTERx Pn = (Params.LFU_W / 2 + viewpoint.pos_y ) * cp.tan(ANGn) + viewpoint.pos_x + (3 * Params.LFU_W / 2) X = cp.sin(ANGy) * R Y = -cp.cos(ANGy) * R Z = TX ANGx = cp.arctan2(Z, -Y) RZY = cp.sqrt(Z**2 + Y**2) ANGy = cp.arctan(X / RZY) #or ANGy = atan2(X, RZY); RATIO = 1 ANGy = ANGy * RATIO ANGx = ANGx + CENTERx ANGx[abs(ANGy) > pi / 2] = ANGx[abs(ANGy) > pi / 2] + pi ANGx[ANGx > pi] = ANGx[ANGx > pi] - 2 * pi ANGy[ANGy > pi / 2] = pi / 2 - (ANGy[ANGy > pi / 2] - pi / 2) ANGy[ANGy < -pi / 2] = -pi / 2 + (ANGy[ANGy < -pi / 2] + pi / 2) Px = (ANGx + pi) / (2 * pi) * sphereW + 0.5 Py = ((-ANGy) + pi / 2) / pi * sphereH + 0.5 if (DIR == 2): Px = Px + Params.WIDTH / 4 elif (DIR == 3): Px = Px + Params.WIDTH / 2 elif (DIR == 4): Px = Px - Params.WIDTH / 4 Px[Px < 1] = Px[Px < 1] + Params.WIDTH Px[Px > Params.WIDTH] = Px[Px > Params.WIDTH] - Params.WIDTH INDxx = cp.argwhere(Px < 1) Px[INDxx] = Px[INDxx] + sphereW Pn0 = cp.floor(Pn) Pn1 = cp.ceil(Pn) Pnr = Pn - Pn0 Px0 = cp.floor(Px) Px1 = cp.ceil(Px) Pxr = Px - Px0 Py0 = cp.floor(Py) Py1 = cp.ceil(Py) Pyr = Py - Py0 Pnr = cp.rint((Pnr * 10000)) Pnr = Pnr / 10000 Pxr = cp.rint((Pxr * 10000)) Pxr = Pxr / 10000 Pyr = cp.rint((Pyr * 10000)) Pyr = Pyr / 10000 #210->012 rgb #cv2 사용 안하면 그대로 OutView[:, :, 2] = inter8_mat5K(LF, Pnr, Pn0, Pn1, Pxr, Px0, Px1, Pyr, Py0, Py1, 1) OutView[:, :, 1] = inter8_mat5K(LF, Pnr, Pn0, Pn1, Pxr, Px0, Px1, Pyr, Py0, Py1, 2) OutView[:, :, 0] = inter8_mat5K(LF, Pnr, Pn0, Pn1, Pxr, Px0, Px1, Pyr, Py0, Py1, 3) OutFlow = inter8_mat_flow5K(LFDisparity, Pnr, Pn0, Pn1, Pxr, Px0, Px1, Pyr, Py0, Py1) Py = cp.pad(Py, [(1, 1), (0, 0)], mode='edge') Py = cp.ceil((Py * 10000)) Py = Py / 10000 My = 2 / (Py[2:cp.size(Py, 0), :] - Py[0:(cp.size(Py, 0) - 2), :]) My[0, :] = My[0, :] / 2 My[cp.size(My, 0) - 1, :] = My[cp.size(My, 0) - 1, :] / 2 OutFlow = My * OutFlow return OutView, OutFlow
def daisy(image, step=4, radius=15, rings=3, histograms=8, orientations=8, normalization='l1', sigmas=None, ring_radii=None, visualize=False): """Extract DAISY feature descriptors densely for the given image. DAISY is a feature descriptor similar to SIFT formulated in a way that allows for fast dense extraction. Typically, this is practical for bag-of-features image representations. The implementation follows Tola et al. [1]_ but deviate on the following points: * Histogram bin contribution are smoothed with a circular Gaussian window over the tonal range (the angular range). * The sigma values of the spatial Gaussian smoothing in this code do not match the sigma values in the original code by Tola et al. [2]_. In their code, spatial smoothing is applied to both the input image and the center histogram. However, this smoothing is not documented in [1]_ and, therefore, it is omitted. Parameters ---------- image : (M, N) array Input image (grayscale). step : int, optional Distance between descriptor sampling points. radius : int, optional Radius (in pixels) of the outermost ring. rings : int, optional Number of rings. histograms : int, optional Number of histograms sampled per ring. orientations : int, optional Number of orientations (bins) per histogram. normalization : [ 'l1' | 'l2' | 'daisy' | 'off' ], optional How to normalize the descriptors * 'l1': L1-normalization of each descriptor. * 'l2': L2-normalization of each descriptor. * 'daisy': L2-normalization of individual histograms. * 'off': Disable normalization. sigmas : 1D array of float, optional Standard deviation of spatial Gaussian smoothing for the center histogram and for each ring of histograms. The array of sigmas should be sorted from the center and out. I.e. the first sigma value defines the spatial smoothing of the center histogram and the last sigma value defines the spatial smoothing of the outermost ring. Specifying sigmas overrides the following parameter. ``rings = len(sigmas) - 1`` ring_radii : 1D array of int, optional Radius (in pixels) for each ring. Specifying ring_radii overrides the following two parameters. ``rings = len(ring_radii)`` ``radius = ring_radii[-1]`` If both sigmas and ring_radii are given, they must satisfy the following predicate since no radius is needed for the center histogram. ``len(ring_radii) == len(sigmas) + 1`` visualize : bool, optional Generate a visualization of the DAISY descriptors Returns ------- descs : array Grid of DAISY descriptors for the given image as an array dimensionality (P, Q, R) where ``P = ceil((M - radius*2) / step)`` ``Q = ceil((N - radius*2) / step)`` ``R = (rings * histograms + 1) * orientations`` descs_img : (M, N, 3) array (only if visualize==True) Visualization of the DAISY descriptors. References ---------- .. [1] Tola et al. "Daisy: An efficient dense descriptor applied to wide- baseline stereo." Pattern Analysis and Machine Intelligence, IEEE Transactions on 32.5 (2010): 815-830. .. [2] http://cvlab.epfl.ch/software/daisy """ check_nD(image, 2, "img") image = img_as_float(image) # Validate parameters. if sigmas is not None and ring_radii is not None \ and len(sigmas) - 1 != len(ring_radii): raise ValueError('`len(sigmas)-1 != len(ring_radii)`') if ring_radii is not None: rings = len(ring_radii) radius = ring_radii[-1] if sigmas is not None: rings = len(sigmas) - 1 if sigmas is None: sigmas = [radius * (i + 1) / float(2 * rings) for i in range(rings)] if ring_radii is None: ring_radii = [radius * (i + 1) / float(rings) for i in range(rings)] if normalization not in ['l1', 'l2', 'daisy', 'off']: raise ValueError('Invalid normalization method.') # Compute image derivatives. dx = cp.zeros(image.shape) dy = cp.zeros(image.shape) dx[:, :-1] = cp.diff(image, n=1, axis=1) dy[:-1, :] = cp.diff(image, n=1, axis=0) # Compute gradient orientation and magnitude and their contribution # to the histograms grad_mag = dx * dx grad_mag += dy * dy cp.sqrt(grad_mag, out=grad_mag) grad_ori = cp.arctan2(dy, dx) pi = cp.pi orientation_kappa = orientations / pi orientation_angles = [ 2 * o * pi / orientations - pi for o in range(orientations) ] hist = cp.empty((orientations, ) + image.shape, dtype=float) for i, o in enumerate(orientation_angles): # Weigh bin contribution by the circular normal distribution hist[i, :, :] = cp.exp(orientation_kappa * cp.cos(grad_ori - o)) # Weigh bin contribution by the gradient magnitude hist[i, :, :] = cp.multiply(hist[i, :, :], grad_mag) # Smooth orientation histograms for the center and all rings. sigmas = [sigmas[0]] + sigmas hist_smooth = cp.empty((rings + 1, ) + hist.shape, dtype=float) for i in range(rings + 1): for j in range(orientations): hist_smooth[i, j, :, :] = gaussian_filter(hist[j, :, :], sigma=sigmas[i]) # Assemble descriptor grid. theta = [2 * pi * j / histograms for j in range(histograms)] desc_dims = (rings * histograms + 1) * orientations descs = cp.empty( (desc_dims, image.shape[0] - 2 * radius, image.shape[1] - 2 * radius)) descs[:orientations, :, :] = hist_smooth[0, :, radius:-radius, radius:-radius] idx = orientations for i in range(rings): for j in range(histograms): y_min = radius + int(round(ring_radii[i] * math.sin(theta[j]))) y_max = descs.shape[1] + y_min x_min = radius + int(round(ring_radii[i] * math.cos(theta[j]))) x_max = descs.shape[2] + x_min descs[idx:idx + orientations, :, :] = hist_smooth[i + 1, :, y_min:y_max, x_min:x_max] idx += orientations descs = descs[:, ::step, ::step] descs = descs.swapaxes(0, 1).swapaxes(1, 2) # Normalize descriptors. if normalization != 'off': descs += 1e-10 if normalization == 'l1': descs /= cp.sum(descs, axis=2)[:, :, cp.newaxis] elif normalization == 'l2': descs /= cp.sqrt(cp.sum(descs * descs, axis=2))[:, :, cp.newaxis] elif normalization == 'daisy': for i in range(0, desc_dims, orientations): norms = descs[:, :, i:i + orientations] norms = norms * norms norms = norms.sum(axis=2) cp.sqrt(norms, out=norms) descs[:, :, i:i + orientations] /= norms[:, :, cp.newaxis] if visualize: from skimage import draw from skimage.color import gray2rgb image = cp.asnumpy(image) descs_img = gray2rgb(image) for i in range(descs.shape[0]): for j in range(descs.shape[1]): # Draw center histogram sigma color = [1, 0, 0] desc_y = i * step + radius desc_x = j * step + radius rows, cols, val = draw.circle_perimeter_aa( desc_y, desc_x, int(sigmas[0])) draw.set_color(descs_img, (rows, cols), color, alpha=val) max_bin = float(cp.max(descs[i, j, :])) for o_num, o in enumerate(orientation_angles): # Draw center histogram bins bin_size = descs[i, j, o_num] / max_bin dy = sigmas[0] * bin_size * math.sin(o) dx = sigmas[0] * bin_size * math.cos(o) rows, cols, val = draw.line_aa(desc_y, desc_x, int(desc_y + dy), int(desc_x + dx)) draw.set_color(descs_img, (rows, cols), color, alpha=val) for r_num, r in enumerate(ring_radii): color_offset = float(1 + r_num) / rings color = (1 - color_offset, 1, color_offset) for t_num, t in enumerate(theta): # Draw ring histogram sigmas hist_y = desc_y + int(round(r * math.sin(t))) hist_x = desc_x + int(round(r * math.cos(t))) rows, cols, val = draw.circle_perimeter_aa( hist_y, hist_x, int(sigmas[r_num + 1])) draw.set_color(descs_img, (rows, cols), color, alpha=val) for o_num, o in enumerate(orientation_angles): # Draw histogram bins bin_size = descs[i, j, orientations + r_num * histograms * orientations + t_num * orientations + o_num] bin_size /= max_bin dy = sigmas[r_num + 1] * bin_size * math.sin(o) dx = sigmas[r_num + 1] * bin_size * math.cos(o) rows, cols, val = draw.line_aa( hist_y, hist_x, int(hist_y + dy), int(hist_x + dx)) draw.set_color(descs_img, (rows, cols), color, alpha=val) return descs, descs_img else: return descs
def _calibrate(self, img, findCarrier=True, useCupy=False): assert len(img) > 6 self.N = len(img[0, :, :]) if self.N != self._lastN: self._allocate_arrays() ''' define k grids ''' self._dx = self.pixelsize / self.magnification # Sampling in image plane self._res = self.wavelength / (2 * self.NA) self._oversampling = self._res / self._dx self._dk = self._oversampling / (self.N / 2 ) # Sampling in frequency plane self._k = np.arange(-self._dk * self.N / 2, self._dk * self.N / 2, self._dk, dtype=np.double) self._dx2 = self._dx / 2 self._kr = np.sqrt(self._k**2 + self._k[:, np.newaxis]**2, dtype=np.single) kxbig = np.arange(-self._dk * self.N, self._dk * self.N, self._dk, dtype=np.single) kybig = kxbig[:, np.newaxis] '''Sum input images if there are more than 7''' if len(img) > 7: imgs = np.zeros((7, self.N, self.N), dtype=np.single) for i in range(7): imgs[i, :, :] = np.sum(img[i:(len(img) // 7) * 7:7, :, :], 0, dtype=np.single) else: imgs = np.single(img) '''Separate bands into DC and 3 high frequency bands''' M = np.complex64( exp(1j * 2 * pi / 7)**((np.arange(0, 4)[:, np.newaxis]) * np.arange(0, 7))) wienerfilter = np.zeros((2 * self.N, 2 * self.N), dtype=np.single) if useCupy: sum_prepared_comp = cp.dot(cp.asarray(M), cp.asarray(imgs).transpose( (1, 0, 2))).get() else: sum_prepared_comp = np.zeros((4, self.N, self.N), dtype=np.complex64) for k in range(0, 4): for l in range(0, 7): sum_prepared_comp[k, :, :] = sum_prepared_comp[ k, :, :] + imgs[l, :, :] * M[k, l] # find parameters ckx = np.zeros((3, 1), dtype=np.single) cky = np.zeros((3, 1), dtype=np.single) p = np.zeros((3, 1), dtype=np.single) ampl = np.zeros((3, 1), dtype=np.single) if findCarrier: # minimum search radius in k-space mask1 = (self._kr > 1.9 * self.eta) for i in range(0, 3): if useCupy: self.kx[i], self.ky[i] = self._coarseFindCarrier_cupy( sum_prepared_comp[0, :, :], sum_prepared_comp[i + 1, :, :], mask1) else: self.kx[i], self.ky[i] = self._coarseFindCarrier( sum_prepared_comp[0, :, :], sum_prepared_comp[i + 1, :, :], mask1) for i in range(0, 3): if useCupy: ckx[i], cky[i], p[i], ampl[i] = self._refineCarrier_cupy( sum_prepared_comp[0, :, :], sum_prepared_comp[i + 1, :, :], self.kx[i], self.ky[i]) else: ckx[i], cky[i], p[i], ampl[i] = self._refineCarrier( sum_prepared_comp[0, :, :], sum_prepared_comp[i + 1, :, :], self.kx[i], self.ky[i]) self.kx = ckx # store found kx, ky, p and ampl values self.ky = cky self.p = p self.ampl = ampl if self.debug: print(f'kx = {ckx[0]}, {ckx[1]}, {ckx[2]}') print(f'ky = {cky[0]}, {cky[1]}, {cky[2]}') print(f'p = {p[0]}, {p[1]}, {p[2]}') print(f'a = {ampl[0]}, {ampl[1]}, {ampl[2]}') ph = np.single(2 * pi * self.NA / self.wavelength) xx = np.arange(-self._dx2 * self.N, self._dx2 * self.N, self._dx2, dtype=np.single) yy = xx if self.usemodulation: A = [float(ampl[i]) for i in range(3)] else: if self.axial: A = [6.0 for i in range(3)] else: A = [12.0 for i in range(3)] for idx_p in range(0, 7): pstep = idx_p * 2 * pi / 7 if useCupy: self._reconfactor[idx_p, :, :] = ( 1 + 4 / A[0] * cp.outer( cp.exp( cp.asarray(1j * (ph * cky[0] * yy - pstep + p[0]))), cp.exp(cp.asarray(1j * ph * ckx[0] * xx))).real + 4 / A[1] * cp.outer( cp.exp( cp.asarray(1j * (ph * cky[1] * yy - 2 * pstep + p[1]))), cp.exp(cp.asarray(1j * ph * ckx[1] * xx))).real + 4 / A[2] * cp.outer( cp.exp( cp.asarray(1j * (ph * cky[2] * yy - 3 * pstep + p[2]))), cp.exp(cp.asarray(1j * ph * ckx[2] * xx))).real).get() else: self._reconfactor[idx_p, :, :] = (1 + 4 / A[0] * np.outer( np.exp(1j * (ph * cky[0] * yy - pstep + p[0])), np.exp(1j * ph * ckx[0] * xx)).real + 4 / A[1] * np.outer( np.exp(1j * (ph * cky[1] * yy - 2 * pstep + p[1])), np.exp( 1j * ph * ckx[1] * xx)).real + 4 / A[2] * np.outer( np.exp(1j * (ph * cky[2] * yy - 3 * pstep + p[2])), np.exp(1j * ph * ckx[2] * xx)).real) # calculate pre-filter factors mask2 = (self._kr < 2) self._prefilter = np.single( (self._tfm(self._kr, mask2) * self._attm(self._kr, mask2))) self._prefilter = fft.fftshift(self._prefilter) mtot = np.full((2 * self.N, 2 * self.N), False) th = np.linspace(0, 2 * pi, 360, dtype=np.single) inv = np.geterr()['invalid'] kmaxth = 2 for i in range(0, 3): krbig = sqrt((kxbig - ckx[i])**2 + (kybig - cky[i])**2) mask = (krbig < 2) mtot = mtot | mask wienerfilter[mask] = wienerfilter[mask] + (self._tf( krbig[mask])**2) * self._att(krbig[mask]) krbig = sqrt((kxbig + ckx[i])**2 + (kybig + cky[i])**2) mask = (krbig < 2) mtot = mtot | mask wienerfilter[mask] = wienerfilter[mask] + (self._tf( krbig[mask])**2) * self._att(krbig[mask]) np.seterr(invalid='ignore' ) # Silence sqrt warnings for kmaxth calculations kmaxth = np.fmax( kmaxth, np.fmax( ckx[i] * np.cos(th) + cky[i] * np.sin(th) + np.sqrt(4 - (ckx[i] * np.sin(th))**2 - (cky[i] * np.cos(th))**2 + ckx[i] * cky[i] * np.sin(2 * th)), -ckx[i] * np.cos(th) - cky[i] * np.sin(th) + np.sqrt(4 - (ckx[i] * np.sin(th))**2 - (cky[i] * np.cos(th))**2 + ckx[i] * cky[i] * np.sin(2 * th)))) np.seterr(invalid=inv) if self.debug: plt.figure() plt.plot(th, kmaxth) krbig = sqrt(kxbig**2 + kybig**2) mask = (krbig < 2) mtot = mtot | mask wienerfilter[mask] = ( wienerfilter[mask] + self._tf(krbig[mask])**2 * self._att(krbig[mask])) self.wienerfilter = wienerfilter if useCupy and 'interp' in dir( cp): # interp not available in cupy version < 9.0.0 kmax = cp.interp(cp.arctan2(cp.asarray(kybig), cp.asarray(kxbig)), cp.asarray(th), cp.asarray(kmaxth), period=2 * pi).astype(np.single).get() else: kmax = np.interp(np.arctan2(kybig, kxbig), th, kmaxth, period=2 * pi).astype(np.single) if self.debug: plt.figure() plt.title('WienerFilter') plt.imshow(wienerfilter) wienerfilter = mtot * (1 - krbig * mtot / kmax) / ( wienerfilter * mtot + self.w**2) self._postfilter = fft.fftshift(wienerfilter) if self.cleanup: imgo = self.reconstruct_fftw(img) kernel = np.ones((5, 5), np.uint8) mask_tmp = abs(fft.fftshift(fft.fft2(imgo))) > ( 10 * gaussian_filter(abs(fft.fftshift(fft.fft2(imgo))), 5)) mask = scipy.ndimage.morphology.binary_dilation( np.single(mask_tmp), kernel) mask[self.N - 12:self.N + 13, self.N - 12:self.N + 13] = np.full( (25, 25), False) mask_shift = (fft.fftshift(mask)) self._postfilter[mask_shift.astype(bool)] = 0 if opencv: self._reconfactorU = [ cv2.UMat(self._reconfactor[idx_p, :, :]) for idx_p in range(0, 7) ] self._prefilter_ocv = np.single( cv2.dft(fft.ifft2(self._prefilter).real)) pf = np.zeros((self.N, self.N, 2), dtype=np.single) pf[:, :, 0] = self._prefilter pf[:, :, 1] = self._prefilter self._prefilter_ocvU = cv2.UMat(np.single(pf)) self._postfilter_ocv = np.single( cv2.dft(fft.ifft2(self._postfilter).real)) pf = np.zeros((2 * self.N, 2 * self.N, 2), dtype=np.single) pf[:, :, 0] = self._postfilter pf[:, :, 1] = self._postfilter self._postfilter_ocvU = cv2.UMat(np.single(pf)) if cupy: self._postfilter_cp = cp.asarray(self._postfilter)
def slope_aspect_gpu(dem, resolution_x, resolution_y, ve_factor=1, output_units="radian"): """ Procedure can return terrain slope and aspect in radian units (default) or in alternative units (if specified). Slope is defined as 0 for Hz plane and pi/2 for vertical plane. Aspect iz defined as geographic azimuth: clockwise increasing, 0 or 2pi for the North direction. Currently applied finite difference method. Parameters ---------- dem : input dem 2D cupy array resolution_x : dem resolution in X direction resolution_y : DEM resolution in Y direction ve_factor : vertical exaggeration factor (must be greater than 0) output_units : percent, degree, radians Returns ------- {"slope": slope_out, "aspect": aspect_out} : dictionaries with 2D numpy arrays """ if ve_factor <= 0: raise Exception( "rvt.vis.slope_aspect: ve_factor must be a positive number!") if resolution_x < 0 or resolution_y < 0: raise Exception( "rvt.vis.slope_aspect: resolution must be a positive number!") dem = dem.astype(np.float32) if ve_factor != 1: dem = dem * ve_factor # add frame of 0 (additional row up bottom and column left right) dem = cp.pad(dem, pad_width=1, mode="constant", constant_values=0) # derivatives in X and Y direction dzdx = ((cp.roll(dem, 1, axis=1) - cp.roll(dem, -1, axis=1)) / 2) / resolution_x dzdy = ((cp.roll(dem, -1, axis=0) - cp.roll(dem, 1, axis=0)) / 2) / resolution_y tan_slope = cp.sqrt(dzdx**2 + dzdy**2) # Compute slope if output_units == "percent": slope_out = tan_slope * 100 elif output_units == "degree": slope_out = cp.rad2deg(np.arctan(tan_slope)) elif output_units == "radian": slope_out = cp.arctan(tan_slope) else: raise Exception( "rvt.vis.calculate_slope: Wrong function input 'output_units'!") # compute Aspect # aspect identifies the down slope direction of the maximum rate of change in value from each cell to its neighbors: # 0 # 270 90 # 180 dzdy[ dzdy == 0] = 10e-9 # important for numeric stability - where dzdy is zero, make tangens to really high value aspect_out = cp.arctan2(dzdx, dzdy) # atan2 took care of the quadrants if output_units == "degree": aspect_out = cp.rad2deg(aspect_out) # remove the frame (padding) slope_out = slope_out[1:-1, 1:-1] aspect_out = aspect_out[1:-1, 1:-1] # edges to -1 slope_out[:, 0] = -1 slope_out[0, :] = -1 slope_out[:, -1] = -1 slope_out[-1, :] = -1 aspect_out[:, 0] = -1 aspect_out[0, :] = -1 aspect_out[:, -1] = -1 aspect_out[-1, :] = -1 return {"slope": slope_out, "aspect": aspect_out}
def pred_traj(ncomb,b_xfc,b_yfc,b_zfc,rho,a,d_ij,alpha_ij,beta_ij,lambda_xij,lambda_yij,lambda_zij,Afc,P,beq_x,beq_y,beq_z,cost_mat_inv_x,cost_mat_inv_y,cost_mat_inv_z): term1 = b_xfc + a*cp.ones(ncomb*n_samples)*d_ij*cp.cos(alpha_ij)*cp.sin(beta_ij)-lambda_xij/rho term2 = b_yfc + a*cp.ones(ncomb*n_samples)*d_ij*cp.sin(alpha_ij)*cp.sin(beta_ij)-lambda_yij/rho term3 = b_zfc + a*cp.ones(ncomb*n_samples)*d_ij*cp.cos(beta_ij)-lambda_zij/rho aug_term = cp.vstack((term1,term2,term3)) rhs_top = -rho*cp.dot(Afc.T,aug_term.T).T lincost_mat = cp.hstack((-rhs_top, cp.vstack((beq_x,beq_y,beq_z)))) sol_x = cp.dot(cost_mat_inv_x, lincost_mat[0]) sol_y = cp.dot(cost_mat_inv_y, lincost_mat[1]) sol_z = cp.dot(cost_mat_inv_z, lincost_mat[2]) nvar = 21 trunc_shape = nbot*nvar # sol_x = cp.dot(cost_mat_inv_x, rhs_x) # rhs_top = rho*cp.dot(Afc.T,b_yfc) # rhs_y = cp.hstack((rhs_top,beq_y)) # sol_y = cp.dot(cost_mat_inv_y,rhs_y) # rhs_top = rho*cp.dot(Afc.T,b_zfc) # rhs_z = cp.hstack((rhs_top,beq_z)) # sol_z = cp.dot(cost_mat_inv_z,rhs_z) primal_x = sol_x[:trunc_shape] primal_y = sol_y[:trunc_shape] primal_z = sol_z[:trunc_shape] # print (primal_y) # print (primal_z) coeff_x = primal_x[:trunc_shape] cx = coeff_x.reshape(nbot,nvar) coeff_y = primal_y[:trunc_shape] cy = coeff_y.reshape(nbot,nvar) coeff_z = primal_z[:trunc_shape] cz = coeff_z.reshape(nbot,nvar) x_pred = cp.dot(P,cx.T).T y_pred = cp.dot(P,cy.T).T z_pred = cp.dot(P,cz.T).T xij = cp.dot(Afc, primal_x)-b_xfc ### xi-xj ### WHYYYYY???????????? yij = cp.dot(Afc, primal_y)-b_yfc ### yi-yj zij = cp.dot(Afc, primal_z)-b_zfc ### zi-zj alpha_ij = cp.arctan2(yij,xij) tij = xij/cp.cos(alpha_ij) beta_ij = cp.arctan2(tij,zij) c2_d = (lambda_xij*cp.cos(alpha_ij)*cp.sin(beta_ij) + lambda_yij*cp.sin(alpha_ij)*cp.sin(beta_ij) + lambda_zij*cp.cos(beta_ij)+ rho*xij*cp.cos(alpha_ij)*cp.sin(beta_ij) + rho*yij*cp.sin(alpha_ij)*cp.sin(beta_ij) +rho*zij*cp.cos(beta_ij)) d_temp_1 = c2_d[:ncomb*n_samples]/float(a*rho) d_ij = cp.maximum(cp.ones(ncomb*n_samples), d_temp_1) res_x = xij-a*d_ij*cp.cos(alpha_ij)*cp.sin(beta_ij) res_y = yij-a*d_ij*cp.sin(alpha_ij)*cp.sin(beta_ij) res_z = zij-a*d_ij*cp.cos(beta_ij) lambda_xij += rho*res_x lambda_yij += rho*res_y lambda_zij += rho*res_z return x_pred,y_pred,z_pred,res_x,res_y,res_z, lambda_xij,lambda_yij,lambda_zij,d_ij,alpha_ij,beta_ij, xij, yij, zij, tij
def phasecong100(im, nscale=2, norient=2, minWavelength=7, mult=2, sigmaOnf=0.65): rows, cols = im.shape imagefft = fft2(im) zero = cp.zeros(shape=(rows, cols)) EO = dict() EnergyV = cp.zeros((rows, cols, 3)) x_range = cp.linspace(-0.5, 0.5, num=cols, endpoint=True) y_range = cp.linspace(-0.5, 0.5, num=rows, endpoint=True) x, y = cp.meshgrid(x_range, y_range) radius = cp.sqrt(x**2 + y**2) theta = cp.arctan2(-y, x) radius = ifftshift(radius) theta = ifftshift(theta) radius[0, 0] = 1. sintheta = cp.sin(theta) costheta = cp.cos(theta) lp = lowpass_filter((rows, cols), 0.45, 15) logGabor = [] for s in range(1, nscale + 1): wavelength = minWavelength * mult**(s - 1.) fo = 1.0 / wavelength logGabor.append( cp.exp((-(cp.log(radius / fo))**2) / (2 * cp.log(sigmaOnf)**2))) logGabor[-1] *= lp logGabor[-1][0, 0] = 0 # The main loop... for o in range(1, norient + 1): angl = (o - 1.) * cp.pi / norient ds = sintheta * cp.cos(angl) - costheta * cp.sin(angl) dc = costheta * cp.cos(angl) + sintheta * cp.sin(angl) dtheta = cp.abs(cp.arctan2(ds, dc)) dtheta = cp.minimum(dtheta * norient / 2., cp.pi) spread = (cp.cos(dtheta) + 1.) / 2. sumE_ThisOrient = zero.copy() sumO_ThisOrient = zero.copy() for s in range(0, nscale): filter_ = logGabor[s] * spread EO[(s, o)] = ifft2(imagefft * filter_) sumE_ThisOrient = sumE_ThisOrient + cp.real(EO[(s, o)]) sumO_ThisOrient = sumO_ThisOrient + cp.imag(EO[(s, o)]) EnergyV[:, :, 0] = EnergyV[:, :, 0] + sumE_ThisOrient EnergyV[:, :, 1] = EnergyV[:, :, 1] + cp.cos(angl) * sumO_ThisOrient EnergyV[:, :, 2] = EnergyV[:, :, 2] + cp.sin(angl) * sumO_ThisOrient OddV = cp.sqrt(EnergyV[:, :, 0]**2 + EnergyV[:, :, 1]**2) featType = cp.arctan2(EnergyV[:, :, 0], OddV) return featType
def create_adj(P, filter_type): # convolution function fZ = cp.fft.fftshift( fzeta_loop_weights_adj(P.Ntheta, P.Nrho, 2 * P.beta, P.g - np.log(P.am), 0, 4)) # (C2lp1,C2lp2), transformed Cartesian to log-polar coordinates [x1, x2] = cp.meshgrid(cp.linspace(-1, 1, P.N), cp.linspace(-1, 1, P.N)) x1 = x1.flatten() x2 = x2.flatten() x2 = x2 * (-1) # adjust for tomopy cids = cp.where(x1**2 + x2**2 <= 1)[0] C2lp1 = [None] * P.Nspan C2lp2 = [None] * P.Nspan for k in range(0, P.Nspan): z1 = P.aR * (x1[cids] * cp.cos(k * P.beta + P.beta / 2) + x2[cids] * cp.sin(k * P.beta + P.beta / 2)) + (1 - P.aR) z2 = P.aR * (-x1[cids] * cp.sin(k * P.beta + P.beta / 2) + x2[cids] * cp.cos(k * P.beta + P.beta / 2)) C2lp1[k] = cp.arctan2(z2, z1) C2lp2[k] = cp.log(cp.sqrt(z1**2 + z2**2)) # (lp2p1,lp2p2), transformed log-polar to polar coordinates [z1, z2] = cp.meshgrid(P.thsp, cp.exp(P.rhosp)) z1 = z1.flatten() z2 = z2.flatten() z2n = z2 - (1 - P.aR) * cp.cos(z1) z2n = z2n / P.aR lpids = cp.where((z1 >= -P.beta / 2) & (z1 < P.beta / 2) & (abs(z2n) <= 1))[0] lp2p1 = [None] * P.Nspan lp2p2 = [None] * P.Nspan for k in range(P.Nspan): lp2p1[k] = (z1[lpids] + k * P.beta) lp2p2[k] = z2n[lpids] # (lp2p1w,lp2p2w), transformed log-polar to polar coordinates (wrapping) # right side wids = cp.where(cp.log(z2) > +P.g)[0] z2n = cp.exp(cp.log(z2[wids]) + cp.log(P.am) - P.g) - (1 - P.aR) * cp.cos(z1[wids]) z2n = z2n / P.aR lpidsw = cp.where((z1[wids] >= -P.beta / 2) & (z1[wids] < P.beta / 2) & (abs(z2n) <= 1))[0] # left side wids2 = cp.where( cp.log(z2) < cp.log(P.am) - P.g + (P.rhosp[1] - P.rhosp[0]))[0] z2n2 = cp.exp(cp.log(z2[wids2])-cp.log(P.am)+P.g) - \ (1-P.aR)*cp.cos(z1[wids2]) z2n2 = z2n2 / P.aR lpidsw2 = cp.where((z1[wids2] >= -P.beta / 2) & (z1[wids2] < P.beta / 2) & (abs(z2n2) <= 1))[0] lp2p1w = [None] * P.Nspan lp2p2w = [None] * P.Nspan for k in range(P.Nspan): lp2p1w[k] = (z1[cp.concatenate((lpidsw, lpidsw2))] + k * P.beta) lp2p2w[k] = cp.concatenate((z2n[lpidsw], z2n2[lpidsw2])) # join for saving wids = cp.concatenate((wids[lpidsw], wids2[lpidsw2])) # pids, index in polar grids after splitting by spans pids = [None] * P.Nspan for k in range(P.Nspan): pids[k] = cp.where((P.proj >= k * P.beta - P.beta / 2) & (P.proj < k * P.beta + P.beta / 2))[0] # first angle and length of spans proj0 = [None] * P.Nspan projl = [None] * P.Nspan for k in range(P.Nspan): proj0[k] = P.proj[pids[k][0]] projl[k] = P.proj[pids[k][-1]] - P.proj[pids[k][0]] #shift in angles projp = (P.Nproj - 1) / (proj0[P.Nspan - 1] + projl[P.Nspan - 1] - proj0[0]) # adapt for interpolation for k in range(P.Nspan): lp2p1[k] = (lp2p1[k]-proj0[k])/projl[k] * \ (len(pids[k])-1)+(proj0[k]-proj0[0])*projp lp2p1w[k] = (lp2p1w[k]-proj0[k])/projl[k] * \ (len(pids[k])-1)+(proj0[k]-proj0[0])*projp lp2p2[k] = (lp2p2[k] + 1) / 2 * (P.N - 1) lp2p2w[k] = (lp2p2w[k] + 1) / 2 * (P.N - 1) C2lp1[k] = (C2lp1[k] - P.thsp[0]) / (P.thsp[-1] - P.thsp[0]) * (P.Ntheta - 1) C2lp2[k] = (C2lp2[k] - P.rhosp[0]) / (P.rhosp[-1] - P.rhosp[0]) * (P.Nrho - 1) const = (P.N + 1) * (P.N - 1) / P.N**2 / 2 * np.sqrt( P.osangles * P.Nproj / P.N / 2) fZgpu = fZ[:, :P.Ntheta // 2 + 1] * const if (P.interp_type == 'cubic'): fZgpu = fZgpu / (P.B3com[:, :P.Ntheta // 2 + 1]) # filter if (filter_type != 'none'): filter = take_filter(P.N, filter_type) else: filter = None Padj0 = Padj(fZgpu, lp2p1, lp2p2, lp2p1w, lp2p2w, C2lp1, C2lp2, cids, lpids, wids, filter) # array representation parsi, parsf = savePadjpars(Padj0) return (Padj0, parsi, parsf)
p = 0. # Linear Zeeman q = 0 # Quadratic Zeeman c0 = 5000 c2 = np.where(Z <= 0, 1000, -250) c4 = 1000 # Time steps, number and wavefunction save variables Nt = 2500 Nframe = 50 # Saves data every Nframe time steps dt = -1j * 1e-2 # Time step t = 0. # -------------------------------------------------------------------------------------------------------------------- # Generating initial state: # -------------------------------------------------------------------------------------------------------------------- phi = cp.arctan2(Y, X) # Phase is azimuthal angle around the core Tf = sm.get_TF_density_3d(c0, c2, X, Y, Z, N=1) eta = np.where(Z <= 0, 0, -1) # Parameter used to interpolate between states # Generate initial wavefunctions: psiP2 = cp.sqrt(Tf) * 1 / cp.sqrt(3) * cp.sqrt((1 + eta)) psiP1 = cp.zeros((Nx, Ny, Nz)) psi0 = cp.zeros((Nx, Ny, Nz)) psiM1 = cp.sqrt(Tf) * 1 / cp.sqrt(3) * cp.sqrt((2 - eta)) psiM2 = cp.zeros((Nx, Ny, Nz)) Psi = [psiP2, psiP1, psi0, psiM1, psiM2] # Full 5x1 wavefunction # Spin rotation on wavefunction:
def osg(aR, theta): t = cp.linspace(-cp.pi / 2, cp.pi / 2, 1000) w = aR * cp.cos(t) + (1 - aR) + 1j * aR * cp.sin(t) g = max( cp.log(abs(w)) + cp.log(cp.cos(theta - cp.arctan2(w.imag, w.real)))) return g