def scale_all(op, num_qubits, skip_last=False): """Generate a matrix that applies 'op' to all qubits (skip_last means last qubit is I).""" scaled = op for repeat in range(num_qubits - (2 if skip_last else 1)): scaled = cp.kron(scaled, op) if skip_last: scaled = cp.kron(scaled, cp.eye(2)) return scaled
def sampler(self, w, gamma, pi, xi, z, alpha, u, N, T, y, x, beta, sigma_v_sqr, sigma_alpha_sqr, eta, H, delta): NT = N * T # sample u from N(mu_u, V_u) my_mean = cp.asarray(np.dot(w, z)) my_std = cp.asarray(np.exp(np.dot(w, gamma))**0.5) a, b = -my_mean / my_std, cp.inf * cp.ones([ N, ]) # eta_particles = truncnorm.rvs(a,b,loc = my_mean, scale = my_std, size = (H,N)) eta_particles = TruncNormal.rvs(a, b, my_mean, my_std, (H, N)) eta_particles = cp.concatenate( [eta_particles, cp.asarray(eta).reshape(-1, 1).T], axis=0) my_mean = cp.asarray(np.dot(pi, delta)) my_std = cp.asarray(np.exp(np.dot(pi, xi))**0.5) a, b = -my_mean / my_std, cp.inf * cp.ones([ NT, ]) u_particles = TruncNormal.rvs(a, b, my_mean, my_std, (H, NT)) u_particles = cp.concatenate( [u_particles, cp.asarray(u).reshape(-1, 1).T], axis=0) # alpha_particles = norm.rvs(0, sigma_alpha_sqr ** 0.5, size=(H,N)) # alpha_particles = np.asarray(alpha_particles) # alpha_particles = np.concatenate([alpha_particles, alpha.reshape(-1,1).T], axis=0) alpha_particles = cp.random.normal(0, sigma_alpha_sqr**0.5, size=(H, N)) alpha_particles = cp.concatenate( [alpha_particles, cp.asarray(alpha).reshape(-1, 1).T], axis=0) inv_sqrt_2pi = 0.3989422804014327 W = inv_sqrt_2pi * cp.exp(-cp.square( ((cp.asarray(y - np.dot(x, beta)) - cp.kron(alpha_particles + eta_particles, cp.ones([ T, ])) - u_particles) / (sigma_v_sqr**0.5))) / 2) / (sigma_v_sqr**0.5) #x_ = ((cp.asarray(y - np.dot(x,beta))-alpha_particles_)/(sigma_v_sqr**0.5)) #del alpha_particles_ #w = gpu_normal_pdf(x_) w_ = W.reshape([H + 1, N, T]).prod(axis=2) w_ = w_ / w_.sum(axis=0) index = self._vectorized(w_) new_alpha = alpha_particles[index, cp.arange(N)].get() new_eta = eta_particles[index, cp.arange(N)].get() new_u = u_particles[cp.kron(index, cp.ones([ T, ])).astype(int), cp.arange(N * T)].get() return new_eta, new_alpha, new_u
def __init__(self,basis_number,extended_basis_number,t_start = 0,t_end=1,mempool=None): self.basis_number = basis_number self.extended_basis_number = extended_basis_number self.basis_number_2D = (2*basis_number-1)*basis_number self.basis_number_2D_ravel = (2*basis_number*basis_number-2*basis_number+1) self.basis_number_2D_sym = (2*basis_number-1)*(2*basis_number-1) self.extended_basis_number_2D = (2*extended_basis_number-1)*extended_basis_number self.extended_basis_number_2D_sym = (2*extended_basis_number-1)*(2*extended_basis_number-1) self.t_end = t_end self.t_start = t_start self.verbose = True if mempool is None: mempool = cp.get_default_memory_pool() # pinned_mempool = cp.get_default_pinned_memory_pool() # self.ix = cp.zeros((2*self.basis_number-1,2*self.basis_number-1),dtype=cp.int32) # self.iy = cp.zeros((2*self.basis_number-1,2*self.basis_number-1),dtype=cp.int32) temp = cp.arange(-(self.basis_number-1),self.basis_number,dtype=cp.int32) # for i in range(2*self.basis_number-1): # self.ix[i,:] = temp # self.iy[:,i] = temp self.ix,self.iy = cp.meshgrid(temp,temp) if self.verbose: print("Used bytes so far, after creating ix and iy {}".format(mempool.used_bytes())) self.Ddiag = -(2*util.PI)**2*(self.ix.ravel(ORDER)**2+self.iy.ravel(ORDER)**2) self.OnePerDdiag = 1/self.Ddiag self.Dmatrix = cpx.scipy.sparse.diags(self.Ddiag,dtype=cp.float32) if self.verbose: print("Used bytes so far, after creating Dmatrix {}".format(mempool.used_bytes())) # self.Imatrix = cp.eye((2*self.basis_number-1)**2,dtype=cp.int8) self.Imatrix = cpx.scipy.sparse.identity((2*self.basis_number-1)**2,dtype=cp.float32) self.Imatrix_dense = cp.eye((2*self.basis_number-1)**2,dtype=cp.float32) if self.verbose: print("Used bytes so far, after creating Imatrix {}".format(mempool.used_bytes())) #K matrix --> 1D fourier index to 2D fourier index ones_temp = cp.ones_like(temp) self.Kmatrix = cp.vstack((cp.kron(temp,ones_temp),cp.kron(ones_temp,temp))) if self.verbose: print("Used bytes so far, after creating Kmatrix {}".format(mempool.used_bytes())) #implement fft plan here self._plan_fft2 = None # self._fft2_axes = (-2, -1) self._plan_ifft2 = None x = np.concatenate((np.arange(self.basis_number)+1,np.zeros(self.basis_number-1))) toep = sla.toeplitz(x) self._Umask = cp.asarray(np.kron(toep,toep),dtype=cp.int16)
def kron(self, other): # Kronecker product if self.__cuda: if cupy_is_available: result = cp.kron(self.__matrix, other.get()) else: result = np.kron(self.__matrix, other.get()) else: result = TensorProduct(self.__matrix, other.get()) return Matrix(result, self.__cuda)
def kron_each_cupy(wf1s, wf2s): nwf = int(wf1s.shape[1]) # int to convert TensorFlow dimension into integer if nwf != int(wf2s.shape[1]): raise ValueError("Inconsistent number of input wavefunctions.") owfs = empty(shape=(wf1s.shape[0] * wf2s.shape[0], wf1s.shape[1]), dtype=wf1s.dtype) for idx in range(wf1s.shape[1]): owfs[:, idx] = kron(wf1s[:, idx], wf2s[:, idx]) return owfs
def get_tensor(vectors): """Compute the tensor product of all vectors in the given list.""" tensor = vectors[0] start = timer() for vector in vectors[1:]: tensor = cp.kron(tensor, vector) end = timer() out_file.write("{},".format(end - start)) return tensor.transpose()
def Run(Dict): global BasePath global Works Works = Works + 1 (RGB,Alpha) = Dict (RGB,Alpha,OutPut) = (BasePath + "/" + RGB,BasePath + "/" + Alpha,BasePath + "/OutPut/" + RGB) RGBImage = cp.array(cv2.imread(RGB,cv2.IMREAD_UNCHANGED))#cv2.IMREAD_UNCHANGED AlphaImage = cp.array(cv2.imread(Alpha)) if(RGBImage.shape[0] > AlphaImage.shape[0]): AlphaImage = cp.kron(AlphaImage, cp.ones((2,2,1))) elif(RGBImage.shape[0] < AlphaImage.shape[0]): RGBImage = cp.kron(RGBImage, cp.ones((2,2,1))) NewAlpha = cp.ones((RGBImage.shape[0],RGBImage.shape[0],1)) NewAlpha[:,:,0] = ((AlphaImage[:,:,0] + AlphaImage[:,:,1] + AlphaImage[:,:,2]) / 3) RGBImage[:,:,3:] = AlphaImage[:,:,:1] #im = Image.fromarray(cp.asnumpy(RGBImage)) #im = Image.fromarray(RGBImage) #del RGBImage,AlphaImage,RGBImage #im.save(OutPut) cv2.imwrite(OutPut,cp.asnumpy(RGBImage))
def PMCMC_eta(w,gamma,pi,xi,z,alpha,u,N,T,y,x,beta,sigma_v_sqr,sigma_alpha_sqr,eta): H = 10000-1 # particle numbers # sample u from N(mu_u, V_u) V_eta = np.exp(np.dot(w, gamma)) mu_eta = np.dot(w, z) myclip_a = 0 my_mean = mu_eta my_std = V_eta** 0.5 a, b = (myclip_a - my_mean) / my_std, np.inf * np.ones([N,]) eta_particles = truncnorm.rvs(a,b,loc = my_mean, scale = my_std, size = (H,N)) eta_particles = cp.asarray(eta_particles) eta_particles = cp.concatenate([eta_particles,cp.asarray(eta).reshape(-1,1).T], axis=0) eta_particles_ = cp.kron(eta_particles, cp.ones([T,])) alpha_particles = cp.random.normal(0, sigma_alpha_sqr ** 0.5, size=(H,N)) alpha_particles = cp.concatenate([alpha_particles,cp.asarray(alpha).reshape(-1,1).T], axis=0) alpha_particles_ = cp.kron(alpha_particles, cp.ones([T,])) V_u = np.exp(np.dot(pi, xi)) mu_u = np.dot(pi, delta) myclip_a = 0 my_mean = mu_u my_std = V_u** 0.5 a, b = (myclip_a - my_mean) / my_std, np.inf * np.ones([NT,]) u_particles = truncnorm.rvs(a,b,loc = my_mean, scale = my_std, size = (H,NT)) u_particles = cp.asarray(u_particles) u_particles = cp.concatenate([u_particles, cp.asarray(u).reshape(-1,1).T], axis=0) x_ = (cp.asarray(y)-cp.dot(cp.asarray(x), cp.asarray(beta))-alpha_particles_-eta_particles_-u_particles)/(sigma_v_sqr**0.5) w = gpu_normal_pdf(x_) w_ = w.reshape([H+1,N,T]).prod(axis=2) w_ = w_/w_.sum(axis=0) index = apply_along_axis(func1d=choice, axis=0, arr=w_,h=H) new_alpha = alpha_particles[index,cp.arange(N)].get() new_eta = eta_particles[index, cp.arange(N)].get() new_u = u_particles[cp.kron(index, cp.ones([T,])).astype(int),cp.arange(N*T)].get() return new_eta.flatten(), new_alpha.flatten(), new_u.flatten()
def load_state_into_mqb_start_from_lqb_cupy(states, m, l=0) -> cupy.ndarray: """ Loads states (columns of wavefunctions) from the smaller, and initialise the new qubits to 0. """ # performs parameter check assert m > l >= 0 assert m >= 1 # the Hilbert spaces are divided into three parts # h1: dim = 2^n1 # h2: states', dim = h2dim = 2^m # h3: dim = 2^n2 # 2^(n1 + m + n2) = big_h_dim h1dim = 2 ** l h2dim, nwf = states.shape big_h_dim = 2 ** m h3dim = big_h_dim // (h1dim * h2dim) assert h3dim >= 1 dtype = states.dtype if h1dim == 1: h1states = ones(shape=(1, nwf), dtype=dtype) else: h1states = zeros(shape=(h1dim, nwf), dtype=dtype) h1states[0, :] = 1 if h3dim == 1: h3states = ones(shape=(1, nwf), dtype=dtype) else: h3states = zeros(shape=(h3dim, nwf), dtype=dtype) h3states[0, :] = 1 overall = empty(shape=(big_h_dim, nwf), dtype=dtype) for wfidx in range(nwf): overall[:, wfidx] = kron( kron(h1states[:, wfidx], states[:, wfidx]), h3states[:, wfidx] ) return overall
def test_zoom_grid_by_int_order0(self): # When grid_mode is True, order 0 zoom should be the same as # replication via a Kronecker product. The only exceptions to this are # the non-grid modes 'constant' and 'wrap'. size = numpy.prod(self.shape) x = cupy.arange(size, dtype=float).reshape(self.shape) testing.assert_array_almost_equal( cupyx.scipy.ndimage.zoom(x, self.zoom, order=0, mode=self.mode, grid_mode=True), cupy.kron(x, cupy.ones(self.zoom)), )
def scale(qnum, op, num_qubits): """Generate a matrix that only applies gate 'op' to its respective qubit.""" gate_list = [cp.eye(2) for i in range(num_qubits)] # all qubits go through I gate_list[qnum] = op # this is the only qubit that has a gate that isn't I scaled = gate_list[0] # start scaling from the 1st qubit # get the kronecker product of all gates in gate_list start = timer() for quantum_gate in gate_list[1:]: scaled = cp.kron(scaled, quantum_gate) end = timer() out_file.write("{},".format(end - start)) return scaled