def solve_sylvester (tfms1, tfms2): """ Solves the system of Sylvester's equations to find the calibration transform. Returns the calibration transform from sensor 1 (corresponding to tfms1) to sensor 2. """ assert len(tfms1) == len(tfms2) and len(tfms1) >= 2 I = np.eye(4) M_final = np.empty((0,16)) s1_t0_inv = np.linalg.inv(tfms1[0]) s2_t0_inv = np.linalg.inv(tfms2[0]) for i in range(1,len(tfms1)): M = np.kron(I, s1_t0_inv.dot(tfms1[i])) - np.kron(s2_t0_inv.dot(tfms2[i]).T,I) M_final = np.r_[M_final, M] # add the constraints on the last row of the transformation matrix to be == [0,0,0,1] for i in [3,7,11,15]: t = np.zeros((1,16)) t[0,i] = 1 M_final = np.r_[M_final,t] L_final = np.zeros(M_final.shape[0]) L_final[-1] = 1 X = np.linalg.lstsq(M_final,L_final)[0] print M_final.dot(X) tt = np.reshape(X,(4,4),order='F') return tt
def __init__(self, featureDimension, lambda_, eta_, userNum, windowSize =20): self.windowSize = windowSize self.counter = 0 self.userNum = userNum self.lambda_ = lambda_ # Basic stat in estimating Theta self.A = lambda_*np.identity(n = featureDimension*userNum) self.b = np.zeros(featureDimension*userNum) self.UserTheta = np.zeros(shape = (featureDimension, userNum)) #self.UserTheta = np.random.random((featureDimension, userNum)) self.AInv = np.linalg.inv(self.A) #self.W = np.random.random((userNum, userNum)) self.W = np.identity(n = userNum) self.Wlong = vectorize(self.W) self.batchGradient = np.zeros(userNum*userNum) self.CoTheta = np.dot(self.UserTheta, self.W) self.BigW = np.kron(np.transpose(self.W), np.identity(n=featureDimension)) self.CCA = np.identity(n = featureDimension*userNum) self.BigTheta = np.kron(np.identity(n=userNum) , self.UserTheta) self.W_X_arr = [] self.W_y_arr = [] for i in range(userNum): self.W_X_arr.append([]) self.W_y_arr.append([])
def balanceTrials(n_trials, randomize, factors, use_type='int'): n_factors = len(factors) n_levels = [0] * n_factors min_trials = 1.0 #needs to be float or the later ceiling operation will fail for f in range(0, n_factors): n_levels[f] = len(factors[f]) min_trials *= n_levels[f] #simulates use of prod(n_levels) in the original code N = math.ceil(n_trials / min_trials) output = [] len1 = min_trials len2 = 1 index = numpy.random.uniform(0, 1, N * min_trials).argsort() for level, factor in zip(n_levels, factors): len1 /= level factor = numpy.array(factor, dtype=use_type) out = numpy.kron(numpy.ones((N, 1)), numpy.kron(numpy.ones((len1, len2)), factor).reshape(min_trials,)).astype(use_type).reshape(N*min_trials,) if randomize: out = [out[i] for i in index] len2 *= level output.append(out) return output
def pansharpen(imname, inDir, outDir): """Create pansharpened images from EO-1 scene directory.""" pan = gdal.Open(inDir + '/' + imname + '_B' + digits % 1 + '_L1T.TIF') bigPan = pan.ReadAsArray()[:-1, :-1] bandNums = [] srcs = [] dests = [] driver = gdal.GetDriverByName("GTiff") driver.Register() for bandNum in range(2, 11): tif = gdal.Open(inDir+'/'+imname + '_B' + digits % bandNum + '_L1T.TIF') if tif is None: print "WARNING: Band %d not found." % bands continue bandNums.append(bandNum) srcs.append(tif) dests.append(driver.CreateCopy(outDir + '/' + imname + '_B' + digits % bandNum + '_L1T.TIF', pan, 0)) imgs = [np.float64(src.ReadAsArray()[:-1, :-1]) for src in srcs] smoothPan = np.kron(sum(imgs) / len(imgs), np.ones([3, 3])) + 1e-9 for img, dest in zip(imgs, dests): newimg = bigPan / smoothPan * np.kron(img, np.ones([3, 3])) #newimg[newimg > 255] = 255 band = dest.GetRasterBand(1) band.WriteArray(newimg) dest = None dests = None
def updateParameters(self, articlePicked, click, userID): self.counter +=1 self.Wlong = vectorize(self.W) featureDimension = len(articlePicked.featureVector) T_X = vectorize(np.outer(articlePicked.featureVector, self.W.T[userID])) self.A += np.outer(T_X, T_X) self.b += click*T_X self.AInv = np.linalg.inv(self.A) self.UserTheta = matrixize(np.dot(self.AInv, self.b), len(articlePicked.featureVector)) Xi_Matirx = np.zeros(shape = (featureDimension, self.userNum)) Xi_Matirx.T[userID] = articlePicked.featureVector W_X = vectorize( np.dot(np.transpose(self.UserTheta), Xi_Matirx)) self.batchGradient +=evaluateGradient(W_X, click, self.Wlong, self.lambda_, self.regu ) if self.counter%self.windowSize ==0: self.Wlong -= 1/(float(self.counter/self.windowSize)+1)*self.batchGradient self.W = matrixize(self.Wlong, self.userNum) self.W = normalize(self.W, axis=0, norm='l1') #print 'SVD', self.W self.batchGradient = np.zeros(self.userNum*self.userNum) # Use Ridge regression to fit W ''' plt.pcolor(self.W_b) plt.colorbar plt.show() ''' if self.W.T[userID].any() <0 or self.W.T[userID].any()>1: print self.W.T[userID] self.CoTheta = np.dot(self.UserTheta, self.W) self.BigW = np.kron(np.transpose(self.W), np.identity(n=len(articlePicked.featureVector))) self.CCA = np.dot(np.dot(self.BigW , self.AInv), np.transpose(self.BigW)) self.BigTheta = np.kron(np.identity(n=self.userNum) , self.UserTheta)
def test_regularized(self): np.random.seed(3453) exog = np.random.normal(size=(400, 5)) groups = np.kron(np.arange(100), np.ones(4)) expected_endog = exog[:, 0] - exog[:, 2] endog = expected_endog + np.kron(np.random.normal(size=100), np.ones(4)) + np.random.normal(size=400) # L1 regularization md = MixedLM(endog, exog, groups) mdf1 = md.fit_regularized(alpha=1.0) mdf1.summary() # L1 regularization md = MixedLM(endog, exog, groups) mdf2 = md.fit_regularized(alpha=10 * np.ones(5)) mdf2.summary() # L2 regularization pen = penalties.L2() mdf3 = md.fit_regularized(method=pen, alpha=0.0) mdf3.summary() # L2 regularization pen = penalties.L2() with warnings.catch_warnings(): warnings.simplefilter("ignore") mdf4 = md.fit_regularized(method=pen, alpha=100.0) mdf4.summary() # Pseudo-Huber regularization pen = penalties.PseudoHuber(0.3) mdf5 = md.fit_regularized(method=pen, alpha=1.0) mdf5.summary()
def act(self, qubits, index=1): """Performs the action of a quantum gate on a qubit system. Operates in-place on the system "qubits", so the original system is changed by interaction with the gate. This avoids violations of the no- cloning theorem. Args: qubits: A system of qubits for the gate to act on. index: Starting index of the first qubit in the system for the gate to act one. E.g. if the gate acts on two qubits and index = 3, then the gate would act on the 3rd and 4th qubits in the system (where qubits are indexed starting at one). Raises: ValueError if there is a dimension mismatch between the gate and the qubits to be operated on. RuntimeError if the matrix is not unitary. """ if index <= 0 or index + self.n() - 1 > qubits.n(): raise ValueError('Dimension mismatch with gate and qubit system') if not is_unitary(self.__matrix): raise RuntimeError('Non-unitary matrix') # construct a matrix to operate only on the desired qubits G = copy(self.__matrix) if index > 1: G = numpy.kron(eye(2**(index - 1)), G) if index + self.n() - 1 < qubits.n(): G = numpy.kron(G, eye(2**(qubits.n() - (index + self.n() -1)))) qubits._QubitSystem__coeffs = numpy.dot(G, qubits._QubitSystem__coeffs)
def test_profile_inference(self): # Smoke test np.random.seed(9814) k_fe = 2 gsize = 3 n_grp = 100 exog = np.random.normal(size=(n_grp * gsize, k_fe)) exog_re = np.ones((n_grp * gsize, 1)) groups = np.kron(np.arange(n_grp), np.ones(gsize)) vca = np.random.normal(size=n_grp * gsize) vcb = np.random.normal(size=n_grp * gsize) errors = 0 g_errors = np.kron(np.random.normal(size=100), np.ones(gsize)) errors += g_errors + exog_re[:, 0] rc = np.random.normal(size=n_grp) errors += np.kron(rc, np.ones(gsize)) * vca rc = np.random.normal(size=n_grp) errors += np.kron(rc, np.ones(gsize)) * vcb errors += np.random.normal(size=n_grp * gsize) endog = exog.sum(1) + errors vc = {"a": {}, "b": {}} for k in range(n_grp): ii = np.flatnonzero(groups == k) vc["a"][k] = vca[ii][:, None] vc["b"][k] = vcb[ii][:, None] rslt = MixedLM(endog, exog, groups=groups, exog_re=exog_re, exog_vc=vc).fit() rslt.profile_re(0, vtype="re", dist_low=1, num_low=3, dist_high=1, num_high=3) rslt.profile_re("b", vtype="vc", dist_low=0.5, num_low=3, dist_high=0.5, num_high=3)
def test_vcomp_3(self): # Test a model with vcomp but no other random effects, using formulas. import scipy v = scipy.__version__.split(".")[1] v = int(v) if v < 16: return np.random.seed(4279) x1 = np.random.normal(size=400) groups = np.kron(np.arange(100), np.ones(4)) slopes = np.random.normal(size=100) slopes = np.kron(slopes, np.ones(4)) * x1 y = slopes + np.random.normal(size=400) vc_fml = {"a": "0 + x1"} df = pd.DataFrame({"y": y, "x1": x1, "groups": groups}) model = MixedLM.from_formula("y ~ 1", groups="groups", vc_formula=vc_fml, data=df) result = model.fit() result.summary() assert_allclose(result.resid.iloc[0:4], np.r_[-1.180753, 0.279966, 0.578576, -0.667916], rtol=1e-3) assert_allclose(result.fittedvalues.iloc[0:4], np.r_[-0.101549, 0.028613, -0.224621, -0.126295], rtol=1e-3)
def haar_matrix_2(n): level = int(math.log(n, 2)) h = np.array([1], dtype="double") nc = 1 / math.sqrt(2) lp = np.array([1, 1], dtype="double") hp = np.array([1, -1], dtype="double") hs = [h] for i in range(level): lp2 = np.kron(h, lp) one_eyed = np.reshape(np.eye(2 ** i), (1, (2 ** i) ** 2))[0] hp2 = np.kron(one_eyed, hp) print lp2 print hp2 h = nc * np.hstack((lp2, hp2)) hs.append(h) h = np.reshape(h, (2 ** level, 2 ** level)) # coeffs = [] # for i in reversed(range(level)): # h1 = hs[i + 1] # h2 = hs[i] # d = h2.shape[0] # h22 = np.vstack((np.hstack((h2, np.zeros((d, d)))), np.hstack((np.zeros((d, d)), np.eye(d))))) # coeffs.append(h22.I * h1) # return (h, coeffs) return h
def expand(A): M,N = A.shape t = np.kron(A.flatten(),np.ones(N)) u = np.triu(np.ones((N,N))).flatten() v = np.kron(np.ones(M),u) w = t * v return(w.reshape(M,N,N).swapaxes(1,2))
def super_operator(H, jump_operators): #print "Constructing super-operator..." I = np.eye(H.shape[0], H.shape[1], dtype='complex') L = -1.j * (np.kron(H, I) - np.kron(I, H)) if jump_operators: L += incoherent_super_operator(jump_operators) return L
def _make_pairs(self, i, j): """ Create arrays containing all unique ordered pairs of i, j. The arrays i and j must be one-dimensional containing non-negative integers. """ mat = np.zeros((len(i) * len(j), 2), dtype=np.int32) # Create the pairs and order them f = np.ones(len(j)) mat[:, 0] = np.kron(f, i).astype(np.int32) f = np.ones(len(i)) mat[:, 1] = np.kron(j, f).astype(np.int32) mat.sort(1) # Remove repeated rows try: dtype = np.dtype((np.void, mat.dtype.itemsize * mat.shape[1])) bmat = np.ascontiguousarray(mat).view(dtype) _, idx = np.unique(bmat, return_index=True) except TypeError: # workaround for old numpy that can't call unique with complex # dtypes rs = np.random.RandomState(4234) bmat = np.dot(mat, rs.uniform(size=mat.shape[1])) _, idx = np.unique(bmat, return_index=True) mat = mat[idx, :] return mat[:, 0], mat[:, 1]
def test_formulas(self): np.random.seed(2410) exog = np.random.normal(size=(300, 4)) exog_re = np.random.normal(size=300) groups = np.kron(np.arange(100), [1, 1, 1]) g_errors = exog_re * np.kron(np.random.normal(size=100), [1, 1, 1]) endog = exog.sum(1) + g_errors + np.random.normal(size=300) mod1 = MixedLM(endog, exog, groups, exog_re) # test the names assert_(mod1.data.xnames == ["x1", "x2", "x3", "x4"]) assert_(mod1.data.exog_re_names == ["x_re1"]) assert_(mod1.data.exog_re_names_full == ["x_re1 RE"]) rslt1 = mod1.fit() # Fit with a formula, passing groups as the actual values. df = pd.DataFrame({"endog": endog}) for k in range(exog.shape[1]): df["exog%d" % k] = exog[:, k] df["exog_re"] = exog_re fml = "endog ~ 0 + exog0 + exog1 + exog2 + exog3" re_fml = "0 + exog_re" mod2 = MixedLM.from_formula(fml, df, re_formula=re_fml, groups=groups) assert_(mod2.data.xnames == ["exog0", "exog1", "exog2", "exog3"]) assert_(mod2.data.exog_re_names == ["exog_re"]) assert_(mod2.data.exog_re_names_full == ["exog_re RE"]) rslt2 = mod2.fit() assert_almost_equal(rslt1.params, rslt2.params) # Fit with a formula, passing groups as the variable name. df["groups"] = groups mod3 = MixedLM.from_formula(fml, df, re_formula=re_fml, groups="groups") assert_(mod3.data.xnames == ["exog0", "exog1", "exog2", "exog3"]) assert_(mod3.data.exog_re_names == ["exog_re"]) assert_(mod3.data.exog_re_names_full == ["exog_re RE"]) rslt3 = mod3.fit(start_params=rslt2.params) assert_allclose(rslt1.params, rslt3.params, rtol=1e-4) # Check default variance structure with non-formula model # creation, also use different exog_re that produces a zero # estimated variance parameter. exog_re = np.ones(len(endog), dtype=np.float64) mod4 = MixedLM(endog, exog, groups, exog_re) with warnings.catch_warnings(): warnings.simplefilter("ignore") rslt4 = mod4.fit() from statsmodels.formula.api import mixedlm mod5 = mixedlm(fml, df, groups="groups") assert_(mod5.data.exog_re_names == ["groups"]) assert_(mod5.data.exog_re_names_full == ["groups RE"]) with warnings.catch_warnings(): warnings.simplefilter("ignore") rslt5 = mod5.fit() assert_almost_equal(rslt4.params, rslt5.params)
def test_symm_algorithm_equivalence(): """Test different stabilization methods in the computation of modes, in the presence and/or absence of the discrete symmetries.""" np.random.seed(400) for n in (12, 20, 40): for sym in kwant.rmt.sym_list: # Random onsite and hopping matrices in symmetry class h_cell = kwant.rmt.gaussian(n, sym) # Hopping is an offdiagonal block of a Hamiltonian. We rescale it # to ensure that there are modes at the Fermi level. h_hop = 10 * kwant.rmt.gaussian(2*n, sym)[:n, n:] if kwant.rmt.p(sym): p_mat = np.array(kwant.rmt.h_p_matrix[sym]) p_mat = np.kron(np.identity(n // len(p_mat)), p_mat) else: p_mat = None if kwant.rmt.t(sym): t_mat = np.array(kwant.rmt.h_t_matrix[sym]) t_mat = np.kron(np.identity(n // len(t_mat)), t_mat) else: t_mat = None if kwant.rmt.c(sym): c_mat = np.kron(np.identity(n // 2), np.diag([1, -1])) else: c_mat = None check_equivalence(h_cell, h_hop, n, sym=sym, particle_hole=p_mat, chiral=c_mat, time_reversal=t_mat)
def mk_Loss(cfg, is_near_v): t = beg('Loss') n_pos_ham = cfg.n_bits + 1 # num possible Hamming distances x = n_pos_ham - cfg.rho neigh_loss = np.concatenate([np.zeros(cfg.rho), np.arange(x)]) / x y = cfg.rho + 1 non_neigh_loss = np.concatenate([np.arange(y,0,-1), np.zeros(cfg.n_bits-cfg.rho)]) / y my_assert (lambda : len(neigh_loss) == n_pos_ham) my_assert (lambda : len(non_neigh_loss) == n_pos_ham) # For each pair of corresponding cells, one should be 0. my_assert (lambda : not np.any(neigh_loss * non_neigh_loss)) NeighLoss = np.kron(is_near_v, neigh_loss.reshape(n_pos_ham, 1)) my_assert (lambda : NeighLoss.shape == (n_pos_ham, cfg.batch_size) ) NonNeighLoss = np.kron(is_near_v == False, non_neigh_loss.reshape(n_pos_ham, 1)) my_assert (lambda : NonNeighLoss.shape == (n_pos_ham, cfg.batch_size) ) # For each pair of corresponding cells, one should be 0. my_assert (lambda : not np.any(NeighLoss * NonNeighLoss)) Loss = NeighLoss + NonNeighLoss my_assert (lambda : (all(Loss.flat >= 0.0) and all(Loss.flat <= 1.0))) end(t) return Loss
def txest_vcomp_1(self): """ Fit the same model using constrained random effects and variance components. """ np.random.seed(4279) exog = np.random.normal(size=(400, 1)) exog_re = np.random.normal(size=(400, 2)) groups = np.kron(np.arange(100), np.ones(4)) slopes = np.random.normal(size=(100, 2)) slopes[:, 1] *= 2 slopes = np.kron(slopes, np.ones((4, 1))) * exog_re errors = slopes.sum(1) + np.random.normal(size=400) endog = exog.sum(1) + errors free = MixedLMParams(1, 2, 0) free.fe_params = np.ones(1) free.cov_re = np.eye(2) free.vcomp = np.zeros(0) model1 = MixedLM(endog, exog, groups, exog_re=exog_re) result1 = model1.fit(free=free) exog_vc = {"a": {}, "b": {}} for k,group in enumerate(model1.group_labels): ix = model1.row_indices[group] exog_vc["a"][group] = exog_re[ix, 0:1] exog_vc["b"][group] = exog_re[ix, 1:2] model2 = MixedLM(endog, exog, groups, exog_vc=exog_vc) result2 = model2.fit() result2.summary() assert_allclose(result1.fe_params, result2.fe_params, atol=1e-4) assert_allclose(np.diag(result1.cov_re), result2.vcomp, atol=1e-2, rtol=1e-4) assert_allclose(result1.bse[[0, 1, 3]], result2.bse, atol=1e-2, rtol=1e-2)
def prepareTransitionalMat(self): #create sigma_x matrix sigmax = np.matrix(self.sigma_x) #non changing channel self.H = self.p0*np.identity(2**self.size) # not changing states # nearest-neighbour changing channel for i in range(self.size-1): Tmatrix = np.identity(1) for j in range(self.size): if j == i or j == i+1: Tmatrix = np.kron(Tmatrix, sigmax) else: Tmatrix = np.kron(Tmatrix, np.identity(2)) self.H = np.add(self.H, Tmatrix * self.p1) # second-neighbour changing channel for i in range(self.size-2): Tmatrix = np.identity(1) for j in range(self.size): if j == i or j == i+2: Tmatrix = np.kron(Tmatrix, sigmax) else: Tmatrix = np.kron(Tmatrix, np.identity(2)) self.H = np.add(self.H, Tmatrix * self.p2)
def _update_indicator(self,K,L): """ update the indicator """ _update = {'term': self.n_terms*np.ones((K,L)).T.ravel(), 'row': np.kron(np.arange(K)[:,np.newaxis],np.ones((1,L))).T.ravel(), 'col': np.kron(np.ones((K,1)),np.arange(L)[np.newaxis,:]).T.ravel()} for key in _update.keys(): self.indicator[key] = np.concatenate([self.indicator[key],_update[key]])
def test_measurement_state_update(num_prefix_qubits): np.random.seed(3) with xmon_stepper.Stepper(num_qubits=3, num_prefix_qubits=num_prefix_qubits, min_qubits_before_shard=0) as s: # 1/sqrt(2)(I+iX) gate. for i in range(3): s.simulate_w(i, -0.5, 0) # Check state before measurements. single_qubit_state = np.array([1, 1j]) / np.sqrt(2) two_qubit_state = np.kron(single_qubit_state, single_qubit_state) expected = np.kron(two_qubit_state, single_qubit_state).flatten() np.testing.assert_almost_equal(expected, s.current_state) assert not s.simulate_measurement(0) # Check state after collapse of first qubit state. expected = np.kron(two_qubit_state, np.array([1, 0])).flatten() np.testing.assert_almost_equal(expected, s.current_state) assert not s.simulate_measurement(1) # Check state after collapse of second qubit state. expected = np.kron(single_qubit_state, np.array([1, 0, 0, 0])).flatten() np.testing.assert_almost_equal(expected, s.current_state, decimal=6) assert s.simulate_measurement(2) expected = np.array([0, 0, 0, 0, 1j, 0, 0, 0]) # Check final state after collapse of third qubit state. np.testing.assert_almost_equal(expected, s.current_state)
def test_count_blocks(self): def gold(A,bs): R,C = bs I,J = A.nonzero() return len( set( zip(I//R,J//C) ) ) mats = [] mats.append( [[0]] ) mats.append( [[1]] ) mats.append( [[1,0]] ) mats.append( [[1,1]] ) mats.append( [[0,1],[1,0]] ) mats.append( [[1,1,0],[0,0,1],[1,0,1]] ) mats.append( [[0],[0],[1]] ) for A in mats: for B in mats: X = kron(A,B) Y = csr_matrix(X) for R in range(1,6): for C in range(1,6): assert_equal(spfuncs.count_blocks(Y, (R, C)), gold(X, (R, C))) X = kron([[1,1,0],[0,0,1],[1,0,1]],[[1,1]]) Y = csc_matrix(X) assert_equal(spfuncs.count_blocks(X, (1, 2)), gold(X, (1, 2))) assert_equal(spfuncs.count_blocks(Y, (1, 2)), gold(X, (1, 2)))
def SENSOR(d1=0.1, d2=0.1, d3=0.1): L1, L2, L3 = Ls(d1, d2, d3) LL1 = np.dot(PDIAG, np.kron(L1, L1)) LL2 = np.dot(PDIAG, np.kron(L2, L2)) LL3 = np.dot(PDIAG, np.kron(L3, L3)) SENSOR = np.r_[LL1[[0, 4, 8], :], LL2[[0, 4, 8], :], LL3[[0, 4, 8], :]] return SENSOR
def getU(J,hx,hz,t): """ Time evolution operator acting on 2 spins. Parameters ---------- J : float Pair-wise interaction energy. hx : float Magnetic energy of each spin with dipole moment mu in field B. t : float Timestep of each iteration. Returns ------- U : (2,2,2,2) ndarray Non-unitary time evolution operator. """ I = s(0) X = s(1) Z = s(3) hamiltonian = -J*np.kron(Z,Z)\ -(np.kron(X,I)+np.kron(I,X))*hx*0.5\ -(np.kron(Z,I)+np.kron(I,Z))*hz*0.5 U = expm(-hamiltonian*t) return np.reshape(U,(2,2,2,2))
def test_qubit_order_to_wavefunction_order_matches_np_kron(scheduler): simulator = cg.XmonSimulator() zero = [1, 0] one = [0, 1] result = simulate(simulator, cirq.Circuit.from_ops(cirq.X(Q1)), scheduler, qubit_order=[Q1, Q2]) assert cirq.allclose_up_to_global_phase( result.final_state, np.kron(one, zero)) result = simulate(simulator, cirq.Circuit.from_ops(cirq.X(Q1)), scheduler, qubit_order=[Q2, Q1]) assert cirq.allclose_up_to_global_phase( result.final_state, np.kron(zero, one)) result = simulate(simulator, cirq.Circuit.from_ops(cirq.X(Q1)), scheduler, qubit_order=cirq.QubitOrder.sorted_by(repr)) assert cirq.allclose_up_to_global_phase( result.final_state, np.array(one)) result = simulate(simulator, cirq.Circuit.from_ops(cirq.X(Q1), cirq.Z(Q2)), scheduler, qubit_order=cirq.QubitOrder.sorted_by(repr)) assert cirq.allclose_up_to_global_phase( result.final_state, np.kron(one, zero))
def test_summary(self): # smoke test np.random.seed(34234) time = 50 * np.random.uniform(size=200) status = np.random.randint(0, 2, 200).astype(np.float64) exog = np.random.normal(size=(200,4)) mod = PHReg(time, exog, status) rslt = mod.fit() smry = rslt.summary() strata = np.kron(np.arange(50), np.ones(4)) mod = PHReg(time, exog, status, strata=strata) rslt = mod.fit() smry = rslt.summary() msg = "3 strata dropped for having no events" assert_(msg in str(smry)) groups = np.kron(np.arange(25), np.ones(8)) mod = PHReg(time, exog, status) rslt = mod.fit(groups=groups) smry = rslt.summary() entry = np.random.uniform(0.1, 0.8, 200) * time mod = PHReg(time, exog, status, entry=entry) rslt = mod.fit() smry = rslt.summary() msg = "200 observations have positive entry times" assert_(msg in str(smry))
def gen_crossed_logit_pandas(nc, cs, s1, s2): np.random.seed(3799) a = np.kron(np.arange(nc), np.ones(cs)) b = np.kron(np.ones(cs), np.arange(nc)) fe = np.ones(nc * cs) vc = np.zeros(nc * cs) for i in np.unique(a): ii = np.flatnonzero(a == i) vc[ii] += s1*np.random.normal() for i in np.unique(b): ii = np.flatnonzero(b == i) vc[ii] += s2*np.random.normal() lp = -0.5 * fe + vc pr = 1 / (1 + np.exp(-lp)) y = 1*(np.random.uniform(size=nc*cs) < pr) ident = np.zeros(2*nc, dtype=np.int) ident[nc:] = 1 df = pd.DataFrame({"fe": fe, "a": a, "b": b, "y": y}) return df
def liouvillian(self, chi=None): sys_hamiltonian = ( np.kron(self.electronic_hamiltonian(), np.eye(self.vib_basis_size)) + np.kron(np.eye(3), self.vibrational_hamiltonian()) + self.el_vib_interaction_hamiltonian() ) L = os.super_operator(sys_hamiltonian, self.lead_operators() + self.vib_damping_operators()) if chi: L_jump = self.jump_liouvillian() for i, row in enumerate(L_jump): for j, v in enumerate(row): if v != 0: L[i, j] *= np.exp(chi) if self.remove_elements: L = np.delete(L, self.element_indices_to_remove, 0) L = np.delete(L, self.element_indices_to_remove, 1) # check physicality of Liouvillian, only need to check that columns related to populations add to 1 (maybe there is a rule for coherences too?) dv_pops = np.eye(3 * self.vib_basis_size).flatten() dv_pops = np.delete(dv_pops, self.element_indices_to_remove, 0) trans_L = L.T for i, el in enumerate(dv_pops): if el == 1: sum = np.sum(trans_L[i]) if not -1.0e-6 < sum < 1.0e-6: print "Liouvillian not physical!" if chi != 0: print "but chi is non zero" print sum return L
def pauli(paulis,positions,N): """ N-qubit Pauli operator given paulis and positions. Parameters ---------- paulis : list List of integers denoting type of Pauli matrix at each site. positions : list List of positions for each corresponding element in paulis. N : int Total number of sites. Returns ------- pauli : (2**N,2**N) ndarray Pauli operator as 2^N by 2^N matrix. """ mat = 1+0j identity = s(0) for i in xrange(N): if i in positions: mat = np.kron(mat,s(paulis[positions.index(i)])) else: mat = np.kron(mat,identity) return mat
def generate_inequalities_constraints_mat(N, nx, nu, xmin, xmax, umin, umax): """ generate matrices of inequalities constrints return G, h """ G = np.zeros((0, (nx + nu) * N)) h = np.zeros((0, 1)) if umax is not None: tG = np.hstack([np.eye(N * nu), np.zeros((N * nu, nx * N))]) th = np.kron(np.ones((N * nu, 1)), umax) G = np.vstack([G, tG]) h = np.vstack([h, th]) if umin is not None: tG = np.hstack([np.eye(N * nu) * -1.0, np.zeros((N * nu, nx * N))]) th = np.kron(np.ones((N, 1)), umin * -1.0) G = np.vstack([G, tG]) h = np.vstack([h, th]) if xmax is not None: tG = np.hstack([np.zeros((N * nx, nu * N)), np.eye(N * nx)]) th = np.kron(np.ones((N, 1)), xmax) G = np.vstack([G, tG]) h = np.vstack([h, th]) if xmin is not None: tG = np.hstack([np.zeros((N * nx, nu * N)), np.eye(N * nx) * -1.0]) th = np.kron(np.ones((N, 1)), xmin * -1.0) G = np.vstack([G, tG]) h = np.vstack([h, th]) return G, h
def find_activity_intervals(C, Npeaks=5, tB=-3, tA=10, thres=0.3): # todo todocument import peakutils K, T = np.shape(C) L = [] for i in range(K): if np.sum(np.abs(np.diff(C[i, :]))) == 0: L.append([]) print('empyty component at:' + str(i)) continue indexes = peakutils.indexes(C[i, :], thres=thres) srt_ind = indexes[np.argsort(C[i, indexes])][::-1] srt_ind = srt_ind[:Npeaks] L.append(srt_ind) LOC = [] for i in range(K): if len(L[i]) > 0: interval = np.kron(L[i], np.ones(int(np.round(tA - tB)), dtype=int)) + \ np.kron(np.ones(len(L[i]), dtype=int), np.arange(tB, tA)) interval[interval < 0] = 0 interval[interval > T - 1] = T - 1 LOC.append(np.array(list(set(interval)))) else: LOC.append(None) return LOC
def test_subsystem_restriction(self): r"""Test behavior of subsystem_list subsystem restriction""" total_samples = 100 # set coupling term and drive channels to 0 frequency j = 0.5 / total_samples omega_d = 0. subsystem_list = [0, 2] y0 = np.kron(np.array([1., 0.]), np.array([0., 1.])) system_model = self._system_model_3Q(j, subsystem_list=subsystem_list) pulse_sim = PulseSimulator(system_model=system_model) schedule = self._3Q_constant_sched(total_samples, u_idx=0, subsystem_list=subsystem_list) qobj = assemble([schedule], backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[omega_d, omega_d, omega_d], memory_slots=2, shots=1) result = pulse_sim.run(qobj, initial_state=y0).result() pulse_sim_yf = result.get_statevector() yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0 self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5)) y0 = np.kron(np.array([1., 0.]), np.array([1., 0.])) result = pulse_sim.run(qobj, initial_state=y0).result() pulse_sim_yf = result.get_statevector() yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0 self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5)) subsystem_list = [1, 2] system_model = self._system_model_3Q(j, subsystem_list=subsystem_list) y0 = np.kron(np.array([1., 0.]), np.array([0., 1.])) pulse_sim.set_options(system_model=system_model) schedule = self._3Q_constant_sched(total_samples, u_idx=1, subsystem_list=subsystem_list) qobj = assemble([schedule], backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[omega_d, omega_d, omega_d], memory_slots=2, shots=1) result = pulse_sim.run(qobj, initial_state=y0).result() pulse_sim_yf = result.get_statevector() yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0 self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5)) y0 = np.kron(np.array([1., 0.]), np.array([1., 0.])) pulse_sim.set_options(initial_state=y0) result = pulse_sim.run(qobj).result() pulse_sim_yf = result.get_statevector() yf = expm(-1j * 0.5 * 2 * np.pi * np.kron(self.X, self.Z) / 4) @ y0 self.assertGreaterEqual(state_fidelity(pulse_sim_yf, yf), 1 - (10**-5))
def gate_product_tabulation( base_gate: np.ndarray, max_infidelity: float, *, sample_scaling: int = 50, allow_missed_points: bool = True, random_state: cirq.RANDOM_STATE_OR_SEED_LIKE = None, ) -> GateTabulation: r"""Generate a GateTabulation for a base two qubit unitary. Args: base_gate: The base gate of the tabulation. max_infidelity: Sets the desired density of tabulated product unitaries. The typical nearest neighbor Euclidean spacing (of the KAK vectors) will be on the order of $\sqrt{max\_infidelity}$. Thus the number of tabulated points will scale as $max\_infidelity^{-3/2}$. sample_scaling: Relative number of random gate products to use in the tabulation. The total number of random local unitaries scales as ~ $max\_infidelity^{-3/2} * sample\_scaling$. Must be positive. random_state: Random state or random state seed. allow_missed_points: If True, the tabulation is allowed to conclude even if not all points in the Weyl chamber are expected to be compilable using 2 or 3 base gates. Otherwise an error is raised in this case. Returns: A GateTabulation object used to compile new two-qubit gates from products of the base gate with 1-local unitaries. """ rng = value.parse_random_state(random_state) assert 1 / 2 > max_infidelity > 0 spacing = np.sqrt(max_infidelity / 3) mesh_points = weyl_chamber_mesh(spacing) # Number of random gate products to sample over in constructing the # tabulation. This has to be at least the number of mesh points, as # a single product can only be associated with one mesh point. assert sample_scaling > 0, 'Input sample_scaling must positive.' num_mesh_points = mesh_points.shape[0] num_samples = num_mesh_points * sample_scaling # include the base gate itself kak_vecs = [cirq.kak_vector(base_gate, check_preconditions=False)] sq_cycles: List[Tuple[_SingleQubitGatePair, ...]] = [()] # Tabulate gates that are close to gates in the mesh u_locals_0 = random_qubit_unitary((num_samples, ), rng=rng) u_locals_1 = random_qubit_unitary((num_samples, ), rng=rng) tabulated_kak_inds = np.zeros((num_mesh_points, ), dtype=bool) tabulation_cutoff = 0.5 * spacing out = _tabulate_kak_vectors( already_tabulated=tabulated_kak_inds, base_gate=base_gate, max_dist=tabulation_cutoff, kak_mesh=mesh_points, local_unitary_pairs=[(u_locals_0, u_locals_1)], ) kak_vecs.extend(out.kept_kaks) sq_cycles.extend(out.kept_cycles) # Will be used later for getting missing KAK vectors. kak_vecs_single = np.array(kak_vecs) sq_cycles_single = list(sq_cycles) summary = (f'Fraction of Weyl chamber reached with 2 gates' f': {tabulated_kak_inds.sum() / num_mesh_points :.3f}') # repeat for double products # Multiply by the same local unitary in the gate product out = _tabulate_kak_vectors( already_tabulated=tabulated_kak_inds, base_gate=base_gate, max_dist=tabulation_cutoff, kak_mesh=mesh_points, local_unitary_pairs=[(u_locals_0, u_locals_1)] * 2, ) kak_vecs.extend(out.kept_kaks) sq_cycles.extend(out.kept_cycles) summary += (f'\nFraction of Weyl chamber reached with 2 gates and 3 gates' f'(same single qubit): ' f'{tabulated_kak_inds.sum() / num_mesh_points :.3f}') # If all KAK vectors in the mesh have been tabulated, return. missing_vec_inds = np.logical_not(tabulated_kak_inds).nonzero()[0] if not np.any(missing_vec_inds): # coverage: ignore return GateTabulation(base_gate, np.array(kak_vecs), sq_cycles, max_infidelity, summary, ()) # Run through remaining KAK vectors that don't have products and try to # correct them u_locals_0p = random_qubit_unitary((100, ), rng=rng) u_locals_1p = random_qubit_unitary((100, ), rng=rng) u_locals = vector_kron(u_locals_0p, u_locals_1p) # Loop through the mesh points that have not yet been tabulated. # Consider their nonlocal parts A and compute products of the form # base_gate^\dagger k A # Compare the KAK vector of any of those products to the already tabulated # KAK vectors from single products of the form # base_gate k0 base_gate. # If they are close, then base_gate^\dagger k A ~ base_gate k0 base_gate # So we may compute the outer local unitaries kL, kR such that # base_gate^\dagger k A = kL base_gate k0 base_gate kR # A = k^\dagger base_gate kL base_gate k0 base_gate kR # the single-qubit unitary kL is the one we need to get the desired # KAK vector. missed_points = [] base_gate_dag = base_gate.conj().T for ind in missing_vec_inds: missing_vec = mesh_points[ind] # Unitary A we wish to solve for missing_unitary = kak_vector_to_unitary(missing_vec) # Products of the from base_gate^\dagger k A products = np.einsum('ab,...bc,cd', base_gate_dag, u_locals, missing_unitary) # KAK vectors for these products kaks = cirq.kak_vector(products, check_preconditions=False) kaks = kaks[..., np.newaxis, :] # Check if any of the product KAK vectors are close to a previously # tabulated KAK vector dists2 = np.sum((kaks - kak_vecs_single)**2, axis=-1) min_dist_inds = np.unravel_index(dists2.argmin(), dists2.shape) min_dist = np.sqrt(dists2[min_dist_inds]) if min_dist < tabulation_cutoff: # If so, compute the single qubit unitary k_L such that # base_gate^\dagger k A = kL base_gate k0 base_gate kR # where k0 is the old (previously tabulated) single qubit unitary # and k is one of the single qubit unitaries used above. # Indices below are for k, k0 respectively new_ind, old_ind = min_dist_inds # Special case where the RHS is just base_gate (no single qubit # gates yet applied). I.e. base_gate^\dagger k A ~ base_gate # which implies base_gate^\dagger k A = k_L base_gate k_R new_product = products[new_ind] if old_ind == 0: assert not sq_cycles_single[old_ind] base_product = base_gate _, kL, actual = _outer_locals_for_unitary( new_product, base_product) # Add to the enumeration sq_cycles.append((kL, )) else: # typical case mentioned above assert len(sq_cycles_single[old_ind]) == 1 old_sq_cycle = sq_cycles_single[old_ind][0] old_k = np.kron(*old_sq_cycle) base_product = base_gate @ old_k @ base_gate _, kL, actual = _outer_locals_for_unitary( new_product, base_product) # Add to the enumeration sq_cycles.append((old_sq_cycle, kL)) kak_vecs.append( cirq.kak_vector(base_gate @ actual, check_preconditions=False)) elif not allow_missed_points: raise ValueError( f'Failed to tabulate a KAK vector near {missing_vec}') else: missed_points.append(missing_vec) kak_vecs = np.array(kak_vecs) summary += (f'\nFraction of Weyl chamber reached with 2 gates and 3 gates ' f'(after patchup)' f': {(len(kak_vecs) - 1) / num_mesh_points :.3f}') return GateTabulation(base_gate, kak_vecs, sq_cycles, max_infidelity, summary, tuple(missed_points))
def _tensor(cls, a, b): table = a.table.tensor(b.table) coeffs = np.kron(a.coeffs, b.coeffs) return SparsePauliOp(table, coeffs)
def determine_search_location(A, dims, method='ellipse', min_size=3, max_size=8, dist=3, expandCore=iterate_structure( generate_binary_structure(2, 1), 2).astype(int), dview=None): """ compute the indices of the distance from the cm to search for the spatial component does it by following an ellipse from the cm or doing a step by step dilatation around the cm Parameters: ---------- [parsed] cm[i]: center of mass of each neuron A[:, i]: the A of each components dims: the dimension of each A's ( same usually ) dist: computed distance matrix dims: [optional] tuple x, y[, z] movie dimensions method: [optional] string method used to expand the search for pixels 'ellipse' or 'dilate' expandCore: [optional] scipy.ndimage.morphology if method is dilate this represents the kernel used for expansion min_size: [optional] int max_size: [optional] int dist: [optional] int dims: [optional] tuple x, y[, z] movie dimensions Returns: -------- dist_indicator: np.ndarray distance from the cm to search for the spatial footprint Raise: ------- Exception('You cannot pass empty (all zeros) components!') """ from scipy.ndimage.morphology import grey_dilation # we initialize the values if len(dims) == 2: d1, d2 = dims elif len(dims) == 3: d1, d2, d3 = dims d, nr = np.shape(A) A = csc_matrix(A) dist_indicator = scipy.sparse.csc_matrix((d, nr), dtype=np.float32) if method == 'ellipse': Coor = dict() # we create a matrix of size A.x of each pixel coordinate in A.y and inverse if len(dims) == 2: Coor['x'] = np.kron(np.ones(d2), list(range(d1))) Coor['y'] = np.kron(list(range(d2)), np.ones(d1)) elif len(dims) == 3: Coor['x'] = np.kron(np.ones(d3 * d2), list(range(d1))) Coor['y'] = np.kron(np.kron(np.ones(d3), list(range(d2))), np.ones(d1)) Coor['z'] = np.kron(list(range(d3)), np.ones(d2 * d1)) if not dist == np.inf: # determine search area for each neuron cm = np.zeros((nr, len(dims))) # vector for center of mass Vr = [] # cell(nr,1); dist_indicator = [] pars = [] # for each dim for i, c in enumerate(['x', 'y', 'z'][:len(dims)]): # mass center in this dim = (coor*A)/sum(A) cm[:, i] = old_div(np.dot(Coor[c], A[:, :nr].todense()), A[:, :nr].sum(axis=0)) # parrallelizing process of the construct ellipse function for i in range(nr): pars.append([ Coor, cm[i], A[:, i], Vr, dims, dist, max_size, min_size, d ]) if dview is None: res = list(map(construct_ellipse_parallel, pars)) else: if 'multiprocessing' in str(type(dview)): res = dview.map_async(construct_ellipse_parallel, pars).get(4294967) else: res = dview.map_sync(construct_ellipse_parallel, pars) for r in res: dist_indicator.append(r) dist_indicator = (np.asarray(dist_indicator)).squeeze().T else: raise Exception('Not implemented') dist_indicator = True * np.ones((d, nr)) elif method == 'dilate': for i in range(nr): A_temp = np.reshape(A[:, i].toarray(), dims[::-1]) if len(expandCore) > 0: if len(expandCore.shape) < len(dims): # default for 3D expandCore = iterate_structure( generate_binary_structure(len(dims), 1), 2).astype(int) A_temp = grey_dilation(A_temp, footprint=expandCore) else: A_temp = grey_dilation(A_temp, [1] * len(dims)) dist_indicator[:, i] = scipy.sparse.coo_matrix( np.squeeze(np.reshape(A_temp, (d, 1)))[:, None] > 0) else: raise Exception('Not implemented') dist_indicator = True * np.ones((d, nr)) return dist_indicator
def random_walk_inner(Gx, Gy,lamda=0.1, method_type="sylvester"): """ This is a function that implements the random walk kernel. Gx, Gy: are two graph type objects representing relevant graphs to be compared. Their format is a square array. lamda: the factor concerning summation method_type: "simple" [O(|V|^6)] or "sylvester" [O(|V|^3)] """ Gx.desired_format("adjacency") Gy.desired_format("adjacency") X = Gx.adjacency_matrix Y = Gy.adjacency_matrix if(method_type == "simple"): # calculate the product graph XY = np.kron(X,Y) # algorithm presented in [Kashima et al., 2003; Gartner et al., 2003] # complexity of O(|V|^6) # XY is a square matrix s = XY.shape[0] I = np.identity(s) k = np.dot(np.dot(np.ones(s),inv(I - lamda*XY)).T,np.ones(shape=(s))) elif(method_type == "sylvester"): # algorithm presented in [Vishwanathan et al., 2006] # complexity of O(|V|^3) X_dimension = X.shape[0] Y_dimension = Y.shape[0] # For efficiency reasons multiply lambda # with the smallest e_{x,y} in dimension e_x = np.ones(shape=(X_dimension,1)) e_y = np.ones(shape=(1,Y_dimension)) # Prepare parameters for sylvester equation A = Y try: B = np.divide(inv(X.T), -lamda) except np.linalg.LinAlgError as err: if 'Singular matrix' in err.message: raise ValueError('Adjacency matrix of the first graph is not invertible') else: raise C = -np.dot(e_x ,np.dot(e_y,B)) try: R = solve_sylvester(A, B, C) except np.linalg.LinAlgError as err: raise ValueError('Solution was not found for the Sylvester Equation. Check Input!') # calculate kernel k = - np.sum(np.sum(R,axis=1),axis=0) else: pass # raise exception? # such method does not exist return k
dp = np.diff(points, axis=0) dist = dp**2 dist = np.round(np.sqrt(dist[:, 0] + dist[:, 1])) # distance ang = np.arctan2(dp[:, 1], dp[:, 0]) # orientation ang = np.array([ang]).T NumberOfDataPoints = np.sum(dist) T = 0.5 # [s] Sampling time interval v_set = 2 * np.hstack((np.cos(ang), np.sin(ang))) idx = 0 v = np.kron(np.ones((dist[idx], 1)), v_set[idx, :]) for idx in range(1, nSegments): v = np.vstack((v, np.kron(np.ones((dist[idx], 1)), v_set[idx, :]))) # ==motion generation==================================================== A = np.array([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]], dtype=float) B = np.array([[T, 0], [1, 0], [0, T], [0, 1]], dtype=float) G = np.array([[T**2 / 2, 0], [T, 0], [0, T**2 / 2], [0, T]], dtype=float) w_x = np.random.normal(0.0, np.sqrt(Q1), NumberOfDataPoints) # noise in x-direction w_y = np.random.normal(0.0, np.sqrt(Q2),
def __init__(self,collclass,dt,nq,M=3,K=3,q=-1,c=1,**kwargs): self.collclass = collclass coll = self.collclass(M,0,1) self.K = K self.M = M self.nodes = coll._getNodes self.weights = coll._getWeights(coll.tleft,coll.tright) #Get M nodes and weights self.Qmat = coll._gen_Qmatrix #Generate q_(m,j), i.e. the large weights matrix self.Smat = coll._gen_Smatrix #Generate s_(m,j), i.e. the large node-to-node weights matrix self.delta_m = coll._gen_deltas #Generate vector of node spacings self.Qmat *= dt self.Smat *= dt self.delta_m *= dt self.ssi = 1 self.nq = nq self.qe = q self.c = c #Collocation solution stuff Ix = np.array([1,0]) Iv = np.array([0,1]) Ixv = np.array([[0,1],[0,0]]) Id = np.identity(nq*3) I2d = np.identity(nq*3*2) self.Ix = Ix self.Iv = Iv self.Ixv = Ixv self.Id = Id Qtil = self.Qmat[1:,1:] I3M = np.identity(3*M) self.Q = np.kron(np.identity(2),np.kron(Qtil,Id)) #Define required calculation matrices QE = np.zeros((M+1,M+1),dtype=np.float) QI = np.zeros((M+1,M+1),dtype=np.float) QT = np.zeros((M+1,M+1),dtype=np.float) SX = np.zeros((M+1,M+1),dtype=np.float) for i in range(0,M): QE[(i+1):,i] = self.delta_m[i] QI[(i+1):,i+1] = self.delta_m[i] QT = 1/2 * (QE + QI) QX = QE @ QT + (QE*QE)/2 SX[:,:] = QX[:,:] SX[1:,:] = QX[1:,:] - QX[0:-1,:] self.SX = SX self.SQ = self.Smat @ self.Qmat d = 3*nq self.x0 = np.zeros((M+1,nq,3),dtype=np.float) self.x = np.zeros((M+1,nq,3),dtype=np.float) self.xn = np.zeros((M+1,nq,3),dtype=np.float) self.u0 = np.zeros((M+1,nq,3),dtype=np.float) self.u = np.zeros((M+1,nq,3),dtype=np.float) self.un = np.zeros((M+1,nq,3),dtype=np.float) self.F = np.zeros((M+1,nq,3),dtype=np.float) self.Fn = np.zeros((M+1,nq,3),dtype=np.float) self.x_con = np.zeros((K,M)) self.x_res = np.zeros((K,M)) self.u_con = np.zeros((K,M)) self.u_res = np.zeros((K,M)) self.Rx = np.zeros((K+1,M),dtype=np.float) self.Rv = np.zeros((K+1,M),dtype=np.float)
def max_pooling_test(): c10_mux = np.array([[1, 0.5577475, 0.5009727, 0.4026691], [0.5577475, 1, 0.4065749, 0.5003257], [0.5009727, 0.4065749, 1, 0.5579081], [0.4026691, 0.5003257, 0.5579081, 1]]) #cifar-10, maj: c10_maj = np.array([[1., 0.67944996, 0.62174328, 0.48456234], [0.67944996, 1., 0.48993862, 0.62174656], [0.62174328, 0.48993862, 1., 0.67977668], [0.48456234, 0.62174656, 0.67977668, 1.]]) #mnist, mux: mn_mux = np.array([[1., 0.97971839, 0.97992029, 0.97461759], [0.97971839, 1., 0.97835297, 0.97989071], [0.97992029, 0.97835297, 1., 0.9797036], [0.97461759, 0.97989071, 0.9797036, 1.]]) mn_maj = np.array([[1., 0.98499708, 0.98510411, 0.97760448], [0.98499708, 1., 0.98132139, 0.98508932], [0.98510411, 0.98132139, 1., 0.98496749], [0.97760448, 0.98508932, 0.98496749, 1.]]) cmats = [c10_mux, c10_maj, mn_mux, mn_maj] mf1 = get_func_mat(max_pool_l1, 4, 2) mf2 = get_func_mat(np.bitwise_or, 2, 1) mf = mf1 @ mf2 for idx, c in enumerate(cmats): cavg = np.sum(np.tril(c, -1)) / 6 err0, err1, err2, err3 = 0, 0, 0, 0 iter_cnt = 0 b1 = B_mat(1) b2 = B_mat(2) c1_a = b1.T @ mf.T c2_a = b2.T @ mf1.T c2_a2 = b1.T @ mf2.T gen = get_pins(idx) for pin in gen: vin = (1 - cavg) * get_vin_mc0(pin) + cavg * get_vin_mc1(pin) vin_reco = (1 - cavg) * np.kron(get_vin_mc1( pin[0:2]), get_vin_mc1(pin[2:4])) + cavg * get_vin_mc1(pin) p_ideal = np.max(pin) #case 0 err0 += np.abs(p_ideal - c1_a @ vin) #case 1 c1_p_reco = c1_a @ vin_reco err1 += np.abs(p_ideal - c1_p_reco) #case 2 c2_p1 = c2_a @ vin c2_vin_reco = get_vin_mc1(c2_p1) c2_p_reco = c2_a2 @ c2_vin_reco err2 += np.abs(p_ideal - c2_p_reco) #case 3 c3_p_reco = c2_a @ vin_reco c3_vin_reco = get_vin_mc1(c3_p_reco) c3_p_reco2 = c2_a2 @ c3_vin_reco err3 += np.abs(p_ideal - c3_p_reco2) iter_cnt += 1 print("case: 0, iter: {}: {}".format(idx, err0 / iter_cnt)) print("case: 1, iter: {}: {}".format(idx, err1 / iter_cnt)) print("case: 2, iter: {}: {}".format(idx, err2 / iter_cnt)) print("case: 3, iter: {}: {}".format(idx, err3 / iter_cnt))
ans = np.linspace(0, (end - begin)**(1.0/curve), num) ** (curve) + begin ans[-1] = end #so that the last element is exactly end return ans agrid2 = curvedspace(0., 100., 2., 40) # kapgrid2 = curvedspace(0., 1., 2., 20) zgrid2 = np.load('./input_data/zgrid.npy') ** 2. #determine bgrid and prob_ bgrid2 = np.array([0., 0.1]) prob_b = np.array([[0.8, 0.2], [0.2, 0.8]]) prob_base = np.load('./input_data/transition_matrix.npy') prob2 = np.kron(prob_b, prob_base) ###codes to generate shocks### num_s = prob2.shape[0] num_pop_assigned = 100_000 sim_time = 2000 data_i_s_elem = np.ones((num_pop_assigned, sim_time), dtype = int) * (-1) data_i_s_elem[:, 0] = 7 @nb.jit(nopython = True) def transit(i, r): if r <= prob2[i,0]: return 0
def _tensor(cls, a, b): paulis = a.paulis.tensor(b.paulis) coeffs = np.kron(a.coeffs, b.coeffs) return SparsePauliOp(paulis, coeffs, copy=False)
def qubit_and_resonator(d_r=30): """Qubit coupled to a microwave resonator demo. Simulates a qubit coupled to a microwave resonator. Reproduces plots from the experiment in :cite:`Hofheinz`. """ # Ville Bergholm 2010-2014 print('\n\n=== Qubit coupled to a single-mode microwave resonator ===\n') if d_r < 10: d_r = 10 # truncated resonator dim #omega0 = 1e9 # Energy scale/\hbar, Hz #T = 0.025 # K # omega_r = 2*pi* 6.570 # GHz, resonator angular frequency # qubit-resonator detuning Delta(t) = omega_q(t) -omega_r Omega = 2 * pi * 19e-3 # GHz, qubit-resonator coupling Delta_off = -2 * pi * 463e-3 # GHz, detuning at off-resonance point Omega_q = 2 * pi * 0.5 # GHz, qubit microwave drive amplitude # Omega << |Delta_off| < Omega_q << omega_r # decoherence times #T1_q = 650e-9 # s #T2_q = 150e-9 # s #T1_r = 3.5e-6 # s #T2_r = 2*T1_r # s # TODO heat bath and couplings #bq = markov.bath('ohmic', omega0, T) #[H, Dq] = fit(bq, Delta_off, T1_q, T2_q) #[H, Dr] = fit_ho(bq, ???, T1_r, T2_r???) #D = kron(eye(d_r), D) # +kron(Dr, qit.I) #================================= # Hamiltonians etc. # qubit raising and lowering ops sp = 0.5 * (sx - 1j * sy) sm = sp.conj().transpose() # resonator annihilation op a = boson_ladder(d_r) # resonator identity op I_r = eye(d_r) # qubit H Hq = kron(I_r, dot(sp, sm)) # resonator H #Hr = kron(a'*a, I_q) # coupling H, rotating wave approximation Hint = Omega / 2 * (kron(a, sp) + kron(a.conj().transpose(), sm)) # microwave control H HOq = lambda ampl, phase: kron( I_r, ampl * 0.5 * Omega_q * (cos(phase) * sx + sin(phase) * sy)) #Q = ho.position(d_r) #P = ho.momentum(d_r) #HOr = lambda ampl, phase: kron(ampl*Omega_r/sqrt(2)*(cos(phase)*Q +sin(phase)*P), qit.I) # system Hamiltonian, in rotating frame defined by H0 = omega_r * (Hq + Hr) # D = omega_q - omega_r is the detuning between the qubit and the resonator H = lambda D, ampl, phase: D * Hq + Hint + HOq(ampl, phase) # readout: qubit in excited state? readout = lambda s, h: s.ev(kron(I_r, p1)) s0 = state(0, (d_r, 2)) # resonator + qubit, ground state #================================= # Rabi test t = linspace(0, 500, 100) detunings = linspace(0, 2 * pi * 40e-3, 100) # GHz out = empty((len(detunings), len(t))) #L = markov.superop(H(0, 1, 0), D, bq) L = H(0, 1, 0) # zero detuning, sx pulse for k, d in enumerate(detunings): s = s0.propagate(L, (2 / Omega_q) * pi / 2) # Q (pi pulse for the qubit) #LL = markov.superop(H(d, 0, 0), D, bq) LL = H(d, 0, 0) # detuned propagation out[k, :] = s.propagate(LL, t, out_func=readout) plt.figure() plot.pcolor(out, t, detunings / (2 * pi * 1e-3)) #plt.colorbar(orientation = 'horizontal') plt.xlabel('Interaction time $\\tau$ (ns)') plt.ylabel('Detuning, $\\Delta/(2\\pi)$ (MHz)') plt.title( 'One photon Rabi-swap oscillations between qubit and resonator, $P_e$') #figure #f = fft(out, [], 2) #pcolor(abs(fftshift(f, 2))) #================================= # state preparation def demolish_state(targ): """Convert a desired (possibly truncated) resonator state ket into a program for constructing that state. State preparation in reverse, uses approximate idealized Hamiltonians. """ # Ideal H without interaction A = lambda D, ampl, phase: D * Hq + HOq(ampl, phase) # resonator ket into a full normalized qubit+resonator state n = len(targ) targ = state(r_[targ, zeros(d_r - n)], (d_r, )).normalize().tensor(state(0, (2, ))) t = deepcopy(targ) n = n - 1 # highest excited level in resonator prog = zeros((n, 4)) for k in reversed(range(n)): # |k+1,g> to |k,e> dd = targ.data.reshape(d_r, 2) prog[k, 3] = (angle(dd[k, 1]) - angle(dd[k + 1, 0]) - pi / 2 + 2 * pi) / -Delta_off targ = targ.propagate(A(-Delta_off, 0, 0), prog[k, 3]) # Z dd = targ.data.reshape(d_r, 2) prog[k, 2] = (2 / (sqrt(k + 1) * Omega)) * arctan2( abs(dd[k + 1, 0]), abs(dd[k, 1])) targ = targ.propagate(-Hint, prog[k, 2]) # S # |k,e> to |k,g> dd = targ.data.reshape(d_r, 2) phi = angle(dd[k, 1]) - angle(dd[k, 0]) + pi / 2 prog[k, 1] = phi prog[k, 0] = (2 / Omega_q) * arctan2(abs(dd[k, 1]), abs(dd[k, 0])) targ = targ.propagate(A(0, -1, phi), prog[k, 0]) # Q return prog, t def prepare_state(prog): """Prepare a state according to the program.""" s = s0 # start with ground state #s = tensor(ho.coherent_state(0.5, d_r), state(0, 2)) # coherent state for k in prog: # Q, S, Z s = s.propagate(H(0, 1, k[1]), k[0]) # Q s = s.propagate(H(0, 0, 0), k[2]) # S s = s.propagate(H(Delta_off, 0, 0), k[3]) # Z return s #================================= # readout plot (not corrected for limited visibility) prog, dummy = demolish_state([0, 1, 0, 1]) # |1> + |3> s1 = prepare_state(prog) prog, dummy = demolish_state([0, 1, 0, 1j]) # |1> + i|3> s2 = prepare_state(prog) t = linspace(0, 350, 200) out1 = s1.propagate(H(0, 0, 0), t, readout) out2 = s2.propagate(H(0, 0, 0), t, readout) plt.figure() plt.plot(t, out1, 'b-', t, out2, 'r-') plt.xlabel('Interaction time $\\tau$ (ns)') plt.ylabel('$P_e$') plt.title('Resonator readout through qubit.') plt.legend(('$|1\\rangle + |3\\rangle$', '$|1\\rangle + i|3\\rangle$')) #================================= # Wigner spectroscopy if False: # "voodoo cat" targ = zeros(d_r) for k in range(0, d_r, 3): targ[k] = (2**k) / sqrt(factorial(k)) else: targ = [1, 0, 0, exp(1j * pi * 3 / 8), 0, 0, 1] # calculate the pulse sequence for constructing targ prog, t = demolish_state(targ) s = prepare_state(prog) print('Trying to prepare the state') print(t) print('Fidelity of prepared state with target state: {0:g}'.format( fidelity(s, t))) print('Time required for state preparation: {0:g} ns'.format( np.sum(prog[:, [0, 2, 3]]))) print('\nComputing the Wigner function...') s = s.ptrace((1, )) W, a, b = ho.wigner(s, res=(80, 80), lim=(-2.5, 2.5, -2.5, 2.5)) plt.figure() plot.pcolor(W, a, b, (-1, 1)) plt.title('Wigner function $W(\\alpha)$') plt.xlabel('Re($\\alpha$)') plt.ylabel('Im($\\alpha$)')
def train_model(train_data): td = train_data summaries = tf.summary.merge_all() RestoreSession = False if not RestoreSession: td.sess.run(tf.global_variables_initializer()) # lrval = FLAGS.learning_rate_start learning_rate_start = myParams.myDict['learning_rate_start'] lrval = myParams.myDict['learning_rate_start'] start_time = time.time() last_summary_time = time.time() last_checkpoint_time = time.time() done = False batch = 0 print("lrval %f" % (lrval)) # assert FLAGS.learning_rate_half_life % 10 == 0 # Cache test features and labels (they are small) test_feature, test_label = td.sess.run([td.test_features, td.test_labels]) G_LossV = np.zeros((1000000), dtype=np.float32) filename = os.path.join(myParams.myDict['train_dir'], 'TrainSummary.mat') feed_dictOut = {td.gene_minput: test_feature} gene_output = td.sess.run(td.gene_moutput, feed_dict=feed_dictOut) _summarize_progress(td, test_feature, test_label, gene_output, batch, 'out') feed_dict = {td.learning_rate: lrval} opsx = [td.gene_minimize, td.gene_loss] _, gene_loss = td.sess.run(opsx, feed_dict=feed_dict) # opsy = [td.gene_loss] # gene_loss = td.sess.run(opsy, feed_dict=feed_dict) # ops = [td.gene_minimize, td.disc_minimize, td.gene_loss, td.disc_real_loss, td.disc_fake_loss] # _, _, gene_loss, disc_real_loss, disc_fake_loss = td.sess.run(ops, feed_dict=feed_dict) batch += 1 gene_output = td.sess.run(td.gene_moutput, feed_dict=feed_dictOut) _summarize_progress(td, test_feature, test_label, gene_output, batch, 'out') feed_dict = {td.learning_rate: lrval} # ops = [td.gene_minimize, td.disc_minimize, td.gene_loss, td.disc_real_loss, td.disc_fake_loss] opsx = [td.gene_minimize, td.gene_loss] _, gene_loss = td.sess.run(opsx, feed_dict=feed_dict) batch += 1 gene_output = td.sess.run(td.gene_moutput, feed_dict=feed_dictOut) _summarize_progress(td, test_feature, test_label, gene_output, batch, 'out') # load model #saver.restore(sess,tf.train.latest_checkpoint('./')) # running model on data:test_feature RunOnData = False if RunOnData: filenames = tf.gfile.ListDirectory('DataAfterpMat') filenames = sorted(filenames) #filenames = [os.path.join('DataAfterpMat', f) for f in filenames] Ni = len(filenames) OutBase = myParams.myDict['SessionName'] + '_OutMat' tf.gfile.MakeDirs(OutBase) #pdb.set_trace() for index in range(Ni): print(index) print(filenames[index]) CurData = scipy.io.loadmat( os.path.join('DataAfterpMat', filenames[index])) Data = CurData['CurData'] Data = Data.reshape((1, 64, 64, 1)) test_feature = np.kron(np.ones((16, 1, 1, 1)), Data) #test_feature = np.array(np.random.choice([0, 1], size=(16,64,64,1)), dtype='float32') feed_dictOut = {td.gene_minput: test_feature} gene_output = td.sess.run(td.gene_moutput, feed_dict=feed_dictOut) filenameOut = os.path.join(OutBase, filenames[index][:-4] + '_out.mat') SOut = {} SOut['X'] = gene_output[0] scipy.io.savemat(filenameOut, SOut) # pdb.set_trace() #_summarize_progress(td, test_feature, test_label, gene_output, batch, 'out') # to get value of var: # ww=td.sess.run(td.gene_var_list[1]) if myParams.myDict['ShowRealData'] > 0: # ifilename=os.path.join('RealData', 'b.mat') ifilename = myParams.myDict['RealDataFN'] RealData = scipy.io.loadmat(ifilename) RealData = RealData['Data'] if RealData.ndim == 2: RealData = RealData.reshape( (RealData.shape[0], RealData.shape[1], 1, 1)) if RealData.ndim == 3: RealData = RealData.reshape( (RealData.shape[0], RealData.shape[1], RealData.shape[2], 1)) Real_feature = RealData if myParams.myDict['InputMode'] == 'RegridTry1': # FullData=scipy.io.loadmat('/media/a/f38a5baa-d293-4a00-9f21-ea97f318f647/home/a/TF/NMapIndTesta.mat') FullData = scipy.io.loadmat(myParams.myDict['NMAP_FN']) NMapCR = FullData['NMapCR'] batch_size = myParams.myDict['batch_size'] Real_feature = np.reshape(RealData[0], [RealData.shape[1]]) Real_feature = np.take(Real_feature, NMapCR) Real_feature = np.tile(Real_feature, (batch_size, 1, 1, 1)) Real_dictOut = {td.gene_minput: Real_feature} # LearningDecayFactor=np.power(2,(-1/FLAGS.learning_rate_half_life)) learning_rate_half_life = myParams.myDict['learning_rate_half_life'] LearningDecayFactor = np.power(2, (-1 / learning_rate_half_life)) # train_time=FLAGS.train_time train_time = myParams.myDict['train_time'] QuickFailureTimeM = myParams.myDict['QuickFailureTimeM'] QuickFailureThresh = myParams.myDict['QuickFailureThresh'] summary_period = myParams.myDict['summary_period'] # in Minutes checkpoint_period = myParams.myDict['checkpoint_period'] # in Minutes DiscStartMinute = myParams.myDict['DiscStartMinute'] while not done: batch += 1 gene_loss = disc_real_loss = disc_fake_loss = -1.234 # elapsed = int(time.time() - start_time)/60 CurTime = time.time() elapsed = (time.time() - start_time) / 60 # Update learning rate lrval *= LearningDecayFactor if (learning_rate_half_life < 1000): # in minutes lrval = learning_rate_start * np.power( 0.5, elapsed / learning_rate_half_life) #print("batch %d gene_l1_factor %f' " % (batch,FLAGS.gene_l1_factor)) # if batch==200: if elapsed > DiscStartMinute: FLAGS.gene_l1_factor = 0.9 RunDiscriminator = FLAGS.gene_l1_factor < 0.999 feed_dict = {td.learning_rate: lrval} if RunDiscriminator: ops = [ td.gene_minimize, td.disc_minimize, td.gene_loss, td.disc_real_loss, td.disc_fake_loss ] _, _, gene_loss, disc_real_loss, disc_fake_loss = td.sess.run( ops, feed_dict=feed_dict) else: ops = [td.gene_minimize, td.gene_loss, td.MoreOut, td.MoreOut2] _, gene_loss, MoreOut, MoreOut2 = td.sess.run(ops, feed_dict=feed_dict) G_LossV[batch] = gene_loss VR = [ v for v in tf.global_variables() if v.name == "gene/GEN_L004/einsum_weightR:0" ][0] VI = [ v for v in tf.global_variables() if v.name == "gene/GEN_L004/einsum_weightI:0" ][0] VRX = td.sess.run(VR) VIX = td.sess.run(VI) HmngWnd = np.power(np.hamming(98), 1) HmngWnd = np.reshape(HmngWnd, [98, 1, 1]) VC = VRX + 1j * VIX FVC = gfft(VC, dim=0) FVC = FVC * HmngWnd VC = gifft(FVC, dim=0) VYR = np.real(VC) VYI = np.imag(VC) VR.load(VYR, td.sess) VI.load(VYI, td.sess) if batch % 10 == 0: # pdb.set_trace() # Show we are alive #print('Progress[%3d%%], ETA[%4dm], Batch [%4d], G_Loss[%3.3f], D_Real_Loss[%3.3f], D_Fake_Loss[%3.3f]' % # (int(100*elapsed/train_time), train_time - int(elapsed), batch, gene_loss, disc_real_loss, disc_fake_loss)) print( 'Progress[%3d%%], ETA[%4dm], Batch [%4d], G_Loss[%3.3f], D_Real_Loss[%3.3f], D_Fake_Loss[%3.3f], MoreOut[%3.3f, %3.3f]' % (int(100 * elapsed / train_time), train_time - int(elapsed), batch, gene_loss, disc_real_loss, disc_fake_loss, MoreOut, MoreOut2)) # VLen=td.gene_var_list.__len__() # for i in range(0, VLen): # print(td.gene_var_list[i].name); # print(VRX.dtype) # print(VRX) # exit() # var_23 = [v for v in tf.global_variables() if v.name == "gene/GEN_L020/C2D_weight:0"][0] # tmp=td.sess.run(td.gene_var_list[i]) # v.load([2, 3], td.sess) if np.isnan(gene_loss): print('NAN!!') done = True # ggg: quick failure test if elapsed > QuickFailureTimeM: if gene_loss > QuickFailureThresh: print('Quick failure!!') done = True else: QuickFailureTimeM = 10000000 # Finished? current_progress = elapsed / train_time if current_progress >= 1.0: done = True StopFN = '/media/a/f38a5baa-d293-4a00-9f21-ea97f318f647/home/a/TF/stop.a' if os.path.isfile(StopFN): print('Stop file used!!') done = True try: tf.gfile.Remove(StopFN) except: pass # Update learning rate # if batch % FLAGS.learning_rate_half_life == 0: # lrval *= .5 # if batch % FLAGS.summary_period == 0: if (CurTime - last_summary_time) / 60 > summary_period: # Show progress with test features # feed_dict = {td.gene_minput: test_feature} gene_output = td.sess.run(td.gene_moutput, feed_dict=feed_dictOut) if myParams.myDict['ShowRealData'] > 0: gene_RealOutput = td.sess.run(td.gene_moutput, feed_dict=Real_dictOut) gene_output[0] = gene_RealOutput[0] Asuffix = 'out_%06.4f' % (gene_loss) _summarize_progress(td, test_feature, test_label, gene_output, batch, Asuffix) last_summary_time = time.time() # if batch % FLAGS.checkpoint_period == 0: SaveCheckpoint_ByTime = (CurTime - last_checkpoint_time) / 60 > checkpoint_period CheckpointFN = '/media/a/f38a5baa-d293-4a00-9f21-ea97f318f647/home/a/TF/save.a' SaveCheckPointByFile = os.path.isfile(CheckpointFN) if SaveCheckPointByFile: tf.gfile.Remove(CheckpointFN) if SaveCheckpoint_ByTime or SaveCheckPointByFile: last_checkpoint_time = time.time() # Save checkpoint _save_checkpoint(td, batch, G_LossV) _save_checkpoint(td, batch, G_LossV) print('Finished training!')
def Rgate(d): r"""R = \sum_{xy} exp(i*2*pi * x*y/prod(dim)) |xy><xy|""" temp = kron(arange(d[0]), arange(d[-1])) / prod(d) return gate.phase(2 * pi * temp, (d[0], d[-1]))
def solver_configuration(A, B=None, verb=True): """Generate a dictionary of SA parameters for an arbitray matrix A. Parameters ---------- A : array, matrix, csr_matrix, bsr_matrix (n x n) matrix to invert, CSR or BSR format preferred for efficiency B : None, array Near null-space modes used to construct the smoothed aggregation solver If None, the constant vector is used If (n x m) array, then B is passed to smoothed_aggregation_solver verb : bool If True, print verbose output during runtime Returns ------- config : dict A dictionary of solver configuration parameters that one uses to generate a smoothed aggregation solver Notes ----- The config dictionary contains the following parameter entries: symmetry, smooth, presmoother, postsmoother, B, strength, max_levels, max_coarse, coarse_solver, aggregate, keep. See smoothed_aggregtion_solver for each parameter's description. Examples -------- >>> from pyamg.gallery import poisson >>> from pyamg import solver_configuration >>> A = poisson((40,40),format='csr') >>> solver_config = solver_configuration(A,verb=False) """ # Ensure acceptable format of A A = make_csr(A) config = {} # Detect symmetry if ishermitian(A, fast_check=True): config['symmetry'] = 'hermitian' if verb: print(' Detected a Hermitian matrix') else: config['symmetry'] = 'nonsymmetric' if verb: print(' Detected a non-Hermitian matrix') # Symmetry dependent parameters if config['symmetry'] == 'hermitian': config['smooth'] = ('energy', { 'krylov': 'cg', 'maxiter': 3, 'degree': 2, 'weighting': 'local' }) config['presmoother'] = ('block_gauss_seidel', { 'sweep': 'symmetric', 'iterations': 1 }) config['postsmoother'] = ('block_gauss_seidel', { 'sweep': 'symmetric', 'iterations': 1 }) else: config['smooth'] = ('energy', { 'krylov': 'gmres', 'maxiter': 3, 'degree': 2, 'weighting': 'local' }) config['presmoother'] = ('gauss_seidel_nr', { 'sweep': 'symmetric', 'iterations': 2 }) config['postsmoother'] = ('gauss_seidel_nr', { 'sweep': 'symmetric', 'iterations': 2 }) # Determine near null-space modes B if B is None: # B is the constant for each variable in a node if isspmatrix_bsr(A) and A.blocksize[0] > 1: bsize = A.blocksize[0] config['B'] = np.kron( np.ones((int(A.shape[0] / bsize), 1), dtype=A.dtype), np.eye(bsize)) else: config['B'] = np.ones((A.shape[0], 1), dtype=A.dtype) elif isinstance(B, np.ndarray): if len(B.shape) == 1: B = B.reshape(-1, 1) if (B.shape[0] != A.shape[0]) or (B.shape[1] == 0): raise TypeError( 'Invalid dimensions of B, B.shape[0] must equal A.shape[0]') config['B'] = np.array(B, dtype=A.dtype) else: raise TypeError('Invalid B') if config['symmetry'] == 'hermitian': config['BH'] = None else: config['BH'] = config['B'].copy() # Set non-symmetry related parameters config['strength'] = ('evolution', { 'k': 2, 'proj_type': 'l2', 'epsilon': 3.0 }) config['max_levels'] = 15 config['max_coarse'] = 500 config['coarse_solver'] = 'pinv' config['aggregate'] = 'standard' config['keep'] = False return config
# http://www.apache.org/licenses/LICENSE-2.0 #Unless required by applicable law or agreed to in writing, software #distributed under the License is distributed on an "AS IS" BASIS, #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #See the License for the specific language governing permissions and #limitations under the License. from __future__ import print_function import json import numpy as np import networkx as nx #Sigma^z*Sigma^z interactions sigmaz = [[1, 0], [0, -1]] mszsz = (np.kron(sigmaz, sigmaz)) #Exchange interactions exchange = np.asarray([[0, 0, 0, 0], [0, 0, 2, 0], [0, 2, 0, 0], [0, 0, 0, 0]]) #Couplings J1 and J2 J = [1, 0.4] L = 20 pars = {} # Define bond operators, labels, and couplings bond_operator = [ (J[0] * mszsz).tolist(), (J[1] * mszsz).tolist(), (-J[0] * exchange).tolist(),
def quantum_walk(steps=7, n=11, p=0.05, n_coin=2): """Quantum random walk demo. Simulates a 1D quantum walker controlled by a unitary quantum coin. On each step the coin is flipped and the walker moves either to the left or to the right depending on the result. After each step, the position of the walker is measured with probability p. p == 1 results in a fully classical random walk, whereas p == 0 corresponds to the "fully quantum" case. """ # Ville Bergholm 2010-2011 from .base import H print('\n\n=== Quantum walk ===\n') # initial state: coin shows heads, walker in center node coin = state('0', n_coin) walker = state(n // 2, n) s = coin.tensor(walker).to_op(inplace=True) # translation operators (wrapping) left = gate.mod_inc(-1, n) right = left.ctranspose() if n_coin == 2: # coin flip operator #C = R_x(pi / 2) C = H # shift operator: heads, move left; tails, move right S = kron(p0, left.data) + kron(p1, right.data) else: C = rand_U(n_coin) S = kron(diag([1, 0, 0]), left.data) + kron(diag( [0, 1, 0]), right.data) + kron(diag([0, 0, 1]), eye(n)) # propagator for a single step (flip + shift) U = dot(S, kron(C, eye(n))) # Kraus ops for position measurement M = [] for k in range(n): temp = zeros((n, n)) temp[k, k] = sqrt(p) M.append(kron(eye(n_coin), temp)) # "no measurement" M.append(sqrt(1 - p) * eye(n_coin * n)) for k in range(steps): s = s.u_propagate(U) #s = s.kraus_propagate(M) s.data = p * diag(diag( s.data)) + (1 - p) * s.data # equivalent but faster... s = s.ptrace([0]) # ignore the coin plt.figure() s.plot() plt.title('Walker state after {0} steps'.format(steps)) plt.figure() plt.bar(arange(n), s.prob(), width=0.8) plt.title( 'Walker position probability distribution after {0} steps'.format( steps)) return s
def deviceFix(self): # Get the device data move = self.ME lick = self.LE[1:, :] photo = self.PE[1:, :] print "devices fixing.." # Define the position codes positionCode = 1 photoStartCode = 2 lickStartCode = 3 photoStopCode = 4 lickStopCode = 6 # Label the position events with positionCodes moveLabels = positionCode * np.ones((move.shape[0], 1), 'double') move = np.hstack((move, moveLabels)) del moveLabels #no longer needed # Define the positions of the devices lickXY = np.array([0.0, 0.0 + 3.0 ]) #Maybe Evan was wrong, this is the Alan measurement photoXY = np.array( [-12.7500 + 0.0, -2.6 + 3.000] ) #according to Evan, this is what the center of mass of an eating mouse should be # Make photobeam break events if photo.shape[0] > 0: photoStartLabels = photoStartCode * np.ones( (photo.shape[0], 1), 'double') photoPositions = np.kron(np.ones((photo.shape[0], 1)), photoXY) temp = np.zeros((photo.shape[0], 1), 'double') temp[:, 0] = photo[:, 0] photoStart = np.hstack((temp, photoPositions, photoStartLabels)) photoStopLabels = photoStopCode * np.ones( (photo.shape[0], 1), 'double') temp[:, 0] = photo[:, 0] + photo[:, 1] + 0.0001 photoStop = np.hstack((temp, photoPositions, photoStopLabels)) else: print "Warning: Device fix just experienced no photo events in the whole day! - mouse%d, day%d" % ( self.individual.mouseNumber, self.dayNumber) photoStart = np.ones( (photo.shape[0], 4), 'double') #hopefully it understands 0 by 4 matrices photoStop = np.ones((photo.shape[0], 4), 'double') # Make lickometer events if lick.shape[0] > 0: lickStartLabels = lickStartCode * np.ones((lick.shape[0], 1), 'double') lickPositions = np.kron(np.ones((lick.shape[0], 1)), lickXY) temp = np.zeros((lick.shape[0], 1), 'double') temp[:, 0] = lick[:, 0] lickStart = np.hstack((temp, lickPositions, lickStartLabels)) lickStopLabels = lickStopCode * np.ones((lick.shape[0], 1), 'double') temp[:, 0] = lick[:, 0] + lick[:, 1] lickStop = np.hstack((temp, lickPositions, lickStopLabels)) else: print "Warning: Device fix just experienced no lick events in the whole day! - mouse%d, day%d" % ( self.individual.mouseNumber, self.dayNumber) lickStart = np.ones( (lick.shape[0], 4), 'double') #hopefully it understands 0 by 4 matrices lickStop = np.ones((lick.shape[0], 4), 'double') # Make the time-sorted list of events allEvents = np.vstack((photoStart, move, photoStop, lickStart, lickStop)) uncorrectedPositions = allEvents[:, 1:3] allEvents = np.hstack( (allEvents, uncorrectedPositions )) # we are going to carry the uncorrected position data with us sortedEvents = allEvents[allEvents[:, 0].argsort()] del allEvents # now that the sortedEvents list is created, allEvents is a liability, so we neutralize temp = np.zeros((sortedEvents.shape[0], 1), 'double') temp[:, 0] = np.array(range(sortedEvents.shape[0]), 'double') sortedEvents = np.hstack((sortedEvents, temp)) numberOfEvents = sortedEvents.shape[0] positionRunStartingIndices = np.zeros(numberOfEvents, 'int') positionRunStopIndices = np.zeros(numberOfEvents, 'int') eventTypes = np.array(sortedEvents[:, 3], 'int') n = 0 k = 0 if eventTypes[0] == positionCode: isThereAnInitialSequenceOfPositions = True else: isThereAnInitialSequenceOfPositions = False isThereAFinalSequenceOfPositions = True while n < numberOfEvents and eventTypes[ n] == positionCode: #this while loop should make n be the index of the first lick or photo event n = n + 1 if n < numberOfEvents: firstNonPositionIndex = n else: exit(1) while True: while n < numberOfEvents and eventTypes[n] != positionCode: #this while loop should make n be the index of the start of a run of positions n = n + 1 lastNonPositionIndex = n - 1 #this will happen many times, but on the last time it will be assigned the correct value if n < numberOfEvents: positionRunStartingIndices[k] = n else: isThereAFinalSequenceOfPositions = False break while n < numberOfEvents and eventTypes[n] == positionCode: n = n + 1 if n < numberOfEvents: positionRunStopIndices[k] = n k = k + 1 #we have found another fully anchored run with a define start and end else: break positionRunStartingIndices = positionRunStartingIndices[:k] positionRunStopIndices = positionRunStopIndices[:k] temp1 = np.zeros((k, 1), 'double') temp1[:, 0] = positionRunStartingIndices temp2 = np.zeros((k, 1), 'double') temp2[:, 0] = positionRunStopIndices runStartAndStopIndices = np.hstack((temp1, temp2)) # Fix the runs so they start and stop at their known positions fixedEvents = sortedEvents.copy() for i in range(k): startIndex = positionRunStartingIndices[i] stopIndex = positionRunStopIndices[i] startEventType = eventTypes[startIndex - 1] stopEventType = eventTypes[stopIndex] supposedStartPosition = sortedEvents[startIndex, 1:3] supposedStopPosition = sortedEvents[stopIndex - 1, 1:3] if startEventType == lickStopCode or startEventType == lickStartCode: knownStartPosition = lickXY elif startEventType == photoStopCode or startEventType == photoStartCode: knownStartPosition = photoXY else: sys.exit(0) if stopEventType == lickStopCode or stopEventType == lickStartCode: knownStopPosition = lickXY elif stopEventType == photoStopCode or stopEventType == photoStartCode: knownStopPosition = photoXY elif stopEventType == lickStopCode or stopEventType == lickStartCode: knownStopPosition = lickXY elif stopEventType == photoStopCode or stopEventType == photoStartCode: knownStopPosition = photoXY else: sys.exit(0) if stopIndex >= startIndex + 2: initiallyTranslateBy = knownStartPosition - supposedStartPosition correctionNeededByEnd = knownStopPosition - (supposedStopPosition + initiallyTranslateBy) timesFromZeroToOne = np.zeros((stopIndex - startIndex, 1), 'double') timesFromZeroToOne[:, 0] = (sortedEvents[startIndex:stopIndex, 0] - sortedEvents[startIndex - 1, 0]) * 1.0 / ( sortedEvents[stopIndex, 0] - sortedEvents[startIndex - 1, 0]) fixedEvents[ startIndex:stopIndex, 1:3] = sortedEvents[startIndex:stopIndex, 1:3] + np.kron( np.ones((stopIndex - startIndex, 1)), initiallyTranslateBy) + np.kron(timesFromZeroToOne, correctionNeededByEnd) if stopIndex == startIndex + 1: fixedEvents[startIndex, 1:3] = knownStartPosition # Fix positions prior to first lick/eat event if isThereAnInitialSequenceOfPositions: initiallyTranslateBy = sortedEvents[firstNonPositionIndex, 1:3] - sortedEvents[ firstNonPositionIndex - 1, 1:3] fixedEvents[:firstNonPositionIndex, 1:3] = sortedEvents[:firstNonPositionIndex, 1:3] + np.kron( np.ones( (firstNonPositionIndex, 1)), initiallyTranslateBy) # Fix positions after the last lick/eat event if isThereAFinalSequenceOfPositions: initiallyTranslateBy = sortedEvents[ lastNonPositionIndex, 1:3] - sortedEvents[lastNonPositionIndex + 1, 1:3] theLengthInQuestion = sortedEvents.shape[0] - lastNonPositionIndex - 1 fixedEvents[ lastNonPositionIndex + 1:, 1:3] = sortedEvents[lastNonPositionIndex + 1:, 1:3] + np.kron( np.ones((theLengthInQuestion, 1)), initiallyTranslateBy) # Store fixed data in numpy array sortedEvents = fixedEvents # Get the movement indices moveInd = mlab.find(sortedEvents[:, 3] == 1) sortedEvents = sortedEvents[moveInd, :] # Get the time and position data Time = sortedEvents[:, 0] deviceFixX = sortedEvents[:, 1] deviceFixY = sortedEvents[:, 2] self.Time = Time self.deviceFixX = deviceFixX self.deviceFixY = deviceFixY #We assume you calculated it because you want to use it / go with it self.CT = self.uncorrectedT self.CX = self.deviceFixX self.CY = self.deviceFixY
# Heisenberg hamiltonian ha = nk.operator.Heisenberg(hilbert=hi) # Symmetric RBM Spin Machine ma = nk.machine.RbmSpinSymm(alpha=1, hilbert=hi) ma.init_random_parameters(seed=1234, sigma=0.01) # defining the custom sampler # here we use two types of moves : 2-spin exchange between two random neighboring sites, # and 4-spin exchanges between 4 random neighboring sites # note that each line and column have to add up to 1.0 (stochastic matrices) one_exchange_operator = [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]] two_exchange_operator = np.kron(one_exchange_operator, one_exchange_operator) ops = [one_exchange_operator] * l + [two_exchange_operator] * l # Single exchange operator acts on pairs of neighboring sites acting_on = [[i, (i + 1) % l] for i in range(l)] # Double exchange operator acts on cluster of 4 neighboring sites acting_on += [[i, (i + 1) % l, (i + 2) % l, (i + 3) % l] for i in range(l)] move_op = nk.operator.LocalOperator(hilbert=hi, operators=ops, acting_on=acting_on) sa = nk.sampler.CustomSampler(machine=ma, move_operators=move_op)
def shift_phase_of_t(index_amplitudes, substring_register_state, pattern_register_state): # This function corresponds to the application of U_f_prime operator to the superposition state # to mark the solution state t by shifting its phase. # Define scratch_register_state # scratch_register_state = [[[0,0],[0,1]],[[0,1],[1,0]],[[1,0],[1,1]],[[1,1],[0,0]]] = # substring_register_state = \ # [[[[1,0], [1,0]], [[1,0], [0,1]]], # [[[1,0], [0,1]], [[0,1], [1,0]]], # [[[0,1], [1,0]], [[0,1], [0,1]]], # [[[0,1], [0,1]], [[1,0], [1,0]]]] # pattern_register_state = [[0, 1], # [1, 0]] # pattern_register_state = [[[1,0],[0,1]], [[0,1],[1,0]]] # scratch_register_state = \ # [[[[1,0], [1,0], [1,0]], [[1,0], [1,0], [1,0]]], # [[[1,0], [1,0], [1,0]], [[1,0], [1,0], [1,0]]], # [[[1,0], [1,0], [1,0]], [[1,0], [1,0], [1,0]]], # [[[1,0], [1,0], [1,0]], [[1,0], [1,0], [1,0]]]] # Construct scratch register substrings_vectors = [] for substring_index in xrange(N): substring_vectors = [] for symbol_index in xrange(M): symbol_vectors = [] for bit_index in xrange(symbol_bit_count+1): symbol_vectors.append(ket_zero) substring_vectors.append(symbol_vectors) substrings_vectors.append(substring_vectors) scratch_register_state = substrings_vectors # Mlog(|E|) CNOT operations: control: substring_register_state as control; target: scratch register (E is read as sigma denoted by Sigma) # print '>> Mlog(|E|) CNOT operations on substring and scratch register' for substring_index in xrange(0, N): # 0...N-1 (count of substrings in T) for symbol_index in xrange(0, M): # 0...M-1 (count of symbols in each substring) for bit_index in xrange(0, symbol_bit_count): # 0...log(|E|)-1 (count of bits in each symbol) # print 'substring_index: ', substring_index, ' symbol_index: ', symbol_index, ' bit_index: ', bit_index # print 'substring_register_state[', substring_index,'][', symbol_index,'][', bit_index,']: ', substring_register_state[substring_index][symbol_index][bit_index] # print 'scratch_register_state[', substring_index, '][', symbol_index,'][', bit_index, ']: ', scratch_register_state[substring_index][symbol_index][bit_index] state_vector = list(kron(substring_register_state[substring_index][symbol_index][bit_index], scratch_register_state[substring_index][symbol_index][bit_index])) new_state_vector = dot(CNOT(), state_vector) # print 'state_vector:', list(state_vector), ' new_state_vector:', list(new_state_vector) if (list(state_vector) != list(new_state_vector)): # print 'state_vector ', state_vector, ' != new_state_vector ', new_state_vector scratch_register_state[substring_index][symbol_index][bit_index] = list(dot(X(), scratch_register_state[substring_index][symbol_index][bit_index])) # else: # print 'state_vector ', state_vector, ' == new_state_vector ', new_state_vector # print 'scratch_register_state[', substring_index, '][', symbol_index, '][', bit_index, ']: ', \ # scratch_register_state[substring_index][symbol_index][bit_index] # print '===============================' # print 'substring register state: ' # for i in xrange(N): # for k in xrange(M): # print substring_register_state[i][k] # # print 'scratch register state: ' # for i in xrange(N): # for k in xrange(M): # print scratch_register_state[i][k], # print # Mlog(|E|) CNOT operations: control: pattern_register_state as control; target: scratch register (E is read as sigma denoted by Sigma) # print '>> Mlog(|E|) CNOT operations on pattern and scratch register' for i in xrange(0, N): # 0...N-1 (count of substrings in T) for k in xrange(0, M): # 0...M-1 (count of symbols in each substring) for j in xrange(0, symbol_bit_count): # 0...log(|E|)-1 (count of bits in each symbol) substring_index = i symbol_index = k bit_index = j # print 'substring_index:', substring_index,' symbol_index: ', symbol_index, ' bit_index: ', bit_index # print 'pattern_register_state[', symbol_index,'][', bit_index,']: ', pattern_register_state[symbol_index][bit_index] # print 'scratch_register_state[', substring_index, '][', symbol_index,'][', bit_index, ']: ', scratch_register_state[substring_index][symbol_index][bit_index] state_vector = list(kron(pattern_register_state[symbol_index][bit_index], scratch_register_state[substring_index][symbol_index][bit_index])) new_state_vector = list(dot(CNOT(), state_vector)) # print 'state_vector:', list(state_vector), ' new_state_vector:', list(new_state_vector) if (list(state_vector) != list(new_state_vector)): # print 'state_vector ', state_vector, ' != new_state_vector ', new_state_vector scratch_register_state[substring_index][symbol_index][bit_index] = list(dot(X(), scratch_register_state[substring_index][symbol_index][bit_index])) # else: # print 'state_vector ', state_vector, ' == new_state_vector ', new_state_vector # print 'scratch_register_state[', substring_index, '][', symbol_index, '][', bit_index, ']: ', \ # scratch_register_state[substring_index][symbol_index][bit_index] # print '===============================' # print 'pattern register state: ' # for k in xrange(M): # print pattern_register_state[k] # # print 'scratch register state: ' # for i in xrange(N): # for k in xrange(M): # print scratch_register_state[i][k], # print # M C^{log(|E|)}NOT operations: control: [k(log(|E|) + 1) + log(|E|)]-th qubits of scratch register; [k(log(|E|) + 1) + log(|E|)]-th qubits of scratch register # print '>> M C^{log(|E|)}NOT operations on scratch register' for substring_index in xrange(N): for symbol_index in xrange(M): scratch_register_state[substring_index][symbol_index].reverse() state_vector = scratch_register_state[substring_index][symbol_index][0] # add state of target bit to state vector for bit_index in xrange(1, symbol_bit_count+1): # construct the state vector for the control bits starting from bit nearest to the target bit scratch_register_state[substring_index][symbol_index][bit_index] = list(dot(X(),scratch_register_state[substring_index][symbol_index][bit_index])) # apply X to control bit state_vector = kron(scratch_register_state[substring_index][symbol_index][bit_index], state_vector) # add state of control bit to state vector scratch_register_state[substring_index][symbol_index][bit_index] = list(dot(X(), scratch_register_state[ substring_index][symbol_index][bit_index])) # apply X to control bit new_state_vector = dot(CkNOT(symbol_bit_count), state_vector) scratch_register_state[substring_index][symbol_index].reverse() if list(state_vector) != list(new_state_vector): # if all control bits are set to 1, apply X to target bit # print 'state_vector: ', state_vector, ' != new_state_vector: ', new_state_vector scratch_register_state[substring_index][symbol_index][symbol_bit_count] = list(dot(X(),scratch_register_state[substring_index][symbol_index][symbol_bit_count])) # else: # print 'state_vector: ', state_vector, ' == new_state_vector: ', new_state_vector # print 'scratch register state: ' # for substring_index in xrange(N): # for symbol_index in xrange(M): # print scratch_register_state[substring_index][symbol_index], # print # 1 C^{M}NOT operation: control: [k(log(|E|) + 1) + log(|E|)]-th qubits of scratch register; target: only qubit of output register # print '>> 1 C^{M}NOT operations on scratch register and output register' # Construct output register state # output_register_state = [[1,0],[1,0],[1,0],[1,0]] output_register_state = [] for i in xrange(N): output_register_state.append(ket_zero) for substring_index in xrange(N): # state_vector = scratch_register_state[substring_index][0][symbol_bit_count] state_vector = output_register_state[substring_index] for symbol_index in xrange(M): state_vector = kron(scratch_register_state[substring_index][symbol_index][symbol_bit_count], state_vector) new_state_vector = dot(CkNOT(M), state_vector) if list(state_vector) != list(new_state_vector): # print 'state_vector: ', state_vector, ' != new_state_vector: ', new_state_vector output_register_state[substring_index] = list(dot(X(), output_register_state[substring_index])) # else: # print 'state_vector: ', state_vector, ' == new_state_vector: ', new_state_vector # print 'output_register_state: ', output_register_state # 1 Z operation: only qubit of output register # print '>> 1 Z operation on output register' for substring_index in xrange(N): output_register_state[substring_index] = list(dot(Z(), output_register_state[substring_index])) # print 'output_register_state: ', output_register_state # index_amplitudes = [1.0 / 2, 1.0 / 2, 1.0 / 2, 1.0 / 2] # print 'index_amplitudes: ', index_amplitudes for substring_index in xrange(N): index_amplitudes[substring_index] = index_amplitudes[substring_index] * sum(output_register_state[substring_index]) # print 'index_amplitudes: ', index_amplitudes return index_amplitudes
def _tensor_unitary(unitary1, unitary0): """Helper function for tensor of two unitary qobj instructions.""" qubits = unitary0['qubits'] + unitary1['qubits'] params = np.kron(unitary1['params'], unitary0['params']) return {'name': 'unitary', 'qubits': qubits, 'params': params}
C3_fftfull = fft.dot(mapping).dot(fft.T.conj()) * 4. for i in range(L ** 2): j = np.where(C3_fft[i] == 1)[0][0] perm.append(j) small_matr.append(C3_fftfull[n_bands * i : n_bands * i + 4, n_bands * j : n_bands * j + 4,]) print(i, j, np.diag(small_matr[-1])) #exit(-1) print(perm) perm = np.array(perm) print(perm[perm[perm]]) K0 = _model_hex_2orb_Koshino(L) U_xy_to_chiral = np.kron(np.eye(K0.shape[0] // 2), np.array([[1, 1], [-1.0j, +1.0j]]) / np.sqrt(2)) K0 = U_xy_to_chiral.conj().T.dot(K0).dot(U_xy_to_chiral) assert np.isclose(np.dot(K0.conj().flatten(), mapping.dot(K0).dot(mapping.T.conj()).flatten()) / np.dot(K0.conj().flatten(), K0.flatten()), 1) assert np.isclose(np.dot(K0.conj().flatten(), Tx.dot(K0).dot(Tx.T.conj()).flatten()) / np.dot(K0.conj().flatten(), K0.flatten()), 1) assert np.isclose(np.dot(K0.conj().flatten(), Ty.dot(K0).dot(Ty.T.conj()).flatten()) / np.dot(K0.conj().flatten(), K0.flatten()), 1) TRS = np.concatenate([np.array([2 * i + 1, 2 * i]) for i in range(K0.shape[0] // 2)]) assert np.allclose(K0, K0.conj().T) K0_TRS = K0[TRS, :] K0_TRS = K0_TRS[:, TRS].conj() assert np.isclose(np.vdot(K0.flatten(), K0_TRS.flatten()) / np.dot(K0.conj().flatten(), K0.flatten()), 1.0) TRS = get_TRS_symmetry_map(L) K0_plus = K0[::2, :]
def _updateR(X, A, R, co_var, lmbdaR, lmbdaRelSimilarity): _log.debug('Updating R (SVD) lambda R: %s' % str(lmbdaR)) rank = A.shape[1] U, S, Vt = svd(A, full_matrices=False) Shat = kron(S, S) updated_R = [] if len(R) == 0 or R is None: updated_R = np.array( [np.random.rand(rank, rank) for i in range(len(X))]) return updated_R #for i in range(len(X)): # Rn = first_term * dot(U.T, X[i].dot(U)) # Rn = dot(Vt.T, dot(Rn, Vt)) # updated_R.append(Rn) #return updated_R #inverse_term = Shat ** 2 + lmbdaR # + lmbdaRelSimilarity * np.sum(co_var[i, :] - 1.0) #Shat = (Shat / inverse_term).reshape(rank, rank) for i in range(len(X)): inverse_term = Shat**2 + lmbdaR + lmbdaRelSimilarity * np.sum( co_var[i, :]) first_term = (Shat / inverse_term).reshape(rank, rank) Rn = first_term * dot(U.T, X[i].dot(U)) Rn = dot(Vt.T, dot(Rn, Vt)) Rn = np.add(Rn, ((lmbdaRelSimilarity * np.sum([ co_var[i][j] * R[j].reshape(rank * rank, ) for j in range(len(X)) ], axis=0)) / inverse_term).reshape(rank, rank)) updated_R.append(Rn) #cij_vec_Rj = #second_term = np.sum(cij_vec_Rj, axis=0) #second_term = lmbdaRelSimilarity * second_term #second_term = second_term / inverse_term #second_term = second_term.reshape(rank, rank) #Rn = first_term_Rn # + second_term #Rn = Shat * dot(U.T, X[i].dot(U)) #Rn = dot(Vt.T, dot(Rn, Vt)) #R.append(Rn #if len(R) == 0: # Rn = Shat * dot(U.T, X[i].dot(U)) #else: # rel_sum_similarity = [] # for k in range(len(R)): # if k == i: # continue # weight = co_var[i][k] # if len(rel_sum_similarity) == 0: # rel_sum_similarity = lmbdaRelSimilarity * weight * R[k] # else: # rel_sum_similarity = rel_sum_similarity + lmbdaRelSimilarity * weight * R[k] # # + rel_sum_similarity #Rn = #R.append(Rn) return updated_R
def _kron(*args): args = list(args) while len(args) != 1: x = args.pop() args[-1] = np.kron(args[-1], x) return args[0]
evaluated_ops = (_embed_operator(base_op, _indices(idx_vals, pp)) for pp, base_op in enumerate(base_ops)) diagram_op = functools.reduce(operator.matmul, evaluated_ops) simp_op += diagram_coeficient * (sym_proj @ diagram_op @ sym_proj) # verify that the exact and simplified products of multi-body operators are equal check_equal(simp_op, exact_op) ########################################################################################## # verify the diagonsis of multi-body excitations ########################################################################################## # build random SU(n)-symmetric interaction Hamiltonian sun_coefs = random_tensor(2) swap = sum((lambda op: np.kron(op, op.T))(unit_tensor((mu, nu), spin_dim)) for mu in range(spin_dim) for nu in range(spin_dim)) sun_interactions = sum(sun_coefs[pp, qq] * _embed_operator(swap, [pp, qq]) for pp in range(spin_num) for qq in range(pp)) # build objects that appear in the multi-body eigenvalue problem sym_energy = sun_coefs.sum() / 2 sun_coef_vec = sum(sun_coefs) def coef_mod_val(choice): return sum(sun_coef_vec[pp] - sum(sun_coefs[pp, qq] for qq in choice) for pp in choice) def coef_mod_mat(shape):
if (A[i][j] != B[i][j]): return 0 return 1 I32 = -1 * np.identity(32) sigma1 = [[0, 1], [1, 0]] sigma2 = [[0, 0 - 1.j], [0 + 1.j, 0]] sigma3 = [[1, 0], [0, -1]] sigma4 = [[1, 0], [0, 1]] gamma = np.zeros((N, dim, dim)) #Based on value of N, it constructs N Majorana fermions of size 2^N/2 x 2^N/2 for i in range(0, N): if i == 0: temp = np.kron(sigma1, sigma1) elif i < int(N / 2): temp = np.kron(temp, sigma1) #print ("Shape is ", np.shape(gamma[i])) #print ("Now check Clifford Algebra for our Gamma matrices") #if (areSame(np.matmul(gamma1, gamma1), 1*I32)==1): # print("PASS") #else: # print("ERROR")
def mkron(a, b): return np.kron(a, b)
def quadrature_rule(avmap, N, NMC=10): """Get a quadrature rule on the space of simulation inputs. Parameters ---------- avmap : ActiveVariableMap a domains.ActiveVariableMap N : int the number of quadrature nodes in the active variables NMC : int, optional the number of samples in the simple Monte Carlo over the inactive variables (default 10) Returns ------- Xp : ndarray (N*NMC)-by-m matrix containing the quadrature nodes on the simulation input space Xw : ndarray (N*NMC)-by-1 matrix containing the quadrature weights on the simulation input space ind : ndarray array of indices identifies which rows of `Xp` correspond to the same fixed value of the active variables See Also -------- integrals.av_quadrature_rule Notes ----- This quadrature rule uses an integration rule on the active variables and simple Monte Carlo on the inactive variables. If the simulation inputs are bounded, then the quadrature nodes on the active variables is constructed with a Delaunay triangulation of a maximin design. The weights are computed by sampling the original variables, mapping them to the active variables, and determining which triangle the active variables fall in. These samples are used to estimate quadrature weights. Note that when the dimension of the active subspace is one-dimensional, this reduces to operations on an interval. If the simulation inputs are unbounded, the quadrature rule on the active variables is given by a tensor product Gauss-Hermite quadrature rule. """ if not isinstance(avmap, ActiveVariableMap): raise TypeError('avmap should be an ActiveVariableMap.') if not isinstance(N, int): raise TypeError('N should be an integer.') if not isinstance(NMC, int): raise TypeError('NMC should be an integer.') # get quadrature rule on active variables Yp, Yw = av_quadrature_rule(avmap, N) # get points on x space with MC Xp, ind = avmap.inverse(Yp, NMC) Xw = np.kron(Yw, np.ones((NMC,1)))/float(NMC) return Xp, Xw, ind
def align(self): L = self.E1.shape[0] K = self.N1.shape[1] T1 = np.zeros_like(self.A1) T2 = np.zeros_like(self.A2) # Normalize edge feature vectors for i in range(L): T1 += self.E1[i]**2 T2 += self.E2[i]**2 for i in range(T1.shape[0]): for j in range(T1.shape[1]): if T1[i, j] > 0: T1[i, j] = 1. / T1[i, j] for i in range(T2.shape[0]): for j in range(T2.shape[1]): if T2[i, j] > 0: T2[i, j] = 1. / T2[i, j] for i in range(L): self.E1[i] = self.E1[i] * T1 self.E2[i] = self.E2[i] * T2 # Normalize node feature vectors self.N1 = normalize(self.N1) self.N2 = normalize(self.N2) # Compute node feature cosine cross-similarity n1 = self.A1.shape[0] n2 = self.A2.shape[0] N = np.zeros(n1 * n2) for k in range(K): N += np.kron(self.N1[:, k], self.N2[:, k]) # Compute the Kronecker degree vector d = np.zeros_like(N) for i in range(L): for k in range(K): d += np.kron(np.dot(self.E1[i] * self.A1, self.N1[:, k]), np.dot(self.E2[i] * self.A2, self.N2[:, k])) D = N * d DD = 1. / (np.sqrt(D) + 1e-12) DD[DD == inf] = 0 # fixed-point solution q = DD * N h = self.H.flatten('F') s = h for i in range(self.maxiter): print("iterations ", i + 1) prev = s M = (q * s).reshape((n2, n1), order='F') S = np.zeros((n2, n1)) for l in range(L): S += np.dot(np.dot(self.E2[l] * self.A2, M), self.E1[l] * self.A1) s = (1 - self.alpha) * h + self.alpha * q * S.flatten('F') diff = np.sqrt(np.sum((s - prev)**2)) print(diff) if diff < self.tol: break self.alignment_matrix = s.reshape((n2, n1)).T return self.alignment_matrix
def form_compressed_hamiltonian_diag(vecs, Hi, Hij): # {{{ dim = 1 # dimension of subspace dims = [ ] # list of mode dimensions (size of hilbert space on each fragment) for vi, v in enumerate(vecs): dim = dim * v.shape[1] dims.extend([v.shape[1]]) H = np.zeros((dim, dim)) Htest = np.zeros((dim, dim)) n_dims = len(dims) H1 = cp.deepcopy(Hi) H2 = cp.deepcopy(Hij) for vi, v in enumerate(vecs): H1[vi] = np.dot(v.transpose(), np.dot(Hi[vi], v)) for vi, v in enumerate(vecs): for wi, w in enumerate(vecs): if wi > vi: vw = np.kron(v, w) H2[(vi, wi)] = np.dot(vw.transpose(), np.dot(Hij[(vi, wi)], vw)) dimsdims = dims dimsdims = np.append(dims, dims) #Htest = Htest.reshape(dimsdims) # Add up all the one-body contributions, making sure that the results is properly dimensioned for the # target subspace dim_i1 = 1 # dimension of space to the left dim_i2 = dim # dimension of space to the right for vi, v in enumerate(vecs): i1 = np.eye(dim_i1) dim_i2 = dim_i2 / v.shape[1] i2 = np.eye(dim_i2) #print "dim_i1 : dim_i2", dim_i1, dim_i2, dim H += np.kron(i1, np.kron(H1[vi], i2)) #nv = v.shape[1] #test = np.ones(len(dimsdims)).astype(int) #test[vi] = nv #test[vi+len(dims)] = nv #h = cp.deepcopy(H1[vi]) #h = h.reshape(test) #Htest = np.einsum('ijkljk->ijklmn',Htest,h) dim_i1 = dim_i1 * v.shape[1] # print H.reshape(dimsdims)[:,:,:,:,:,:] # print "a" # print "a" # print "a" # print H.reshape(dimsdims) # Htest = Htest.reshape(dim,dim) # exit(-1) # printm(Htest) # print # printm(H) # Add up all the two-body contributions, making sure that the results is properly dimensioned for the # target subspace dim_i1 = 1 # dimension of space to the left dim_i2 = 1 # dimension of space in the middle dim_i2 = dim # dimension of space to the right H = H.reshape(dimsdims) #print H.shape #print H[tuple([slice(0,3)])*len(H.shape)].shape ##print H[tuple([slice(0,3)])*len(H.shape)] - H #print np.diagonal(np.diagonal(H)).shape #print H[np.ones(len(H.shape)).astype(int)].shape #sliceij = [] #for d in dimsdims: # sliceij.extend([slice(0,d)]) #print sliceij for vi, v in enumerate(vecs): for wi, w in enumerate(vecs): if wi > vi: nv = v.shape[1] nw = w.shape[1] dim_env = dim / nv / nw #print ": ", nv, nw, dim_env, dim i1 = np.eye(dim_env) h = np.kron(H2[(vi, wi)], i1) #print ": ", H2[(vi,wi)].shape, i1.shape, h.shape, H.shape #print H2[(vi,wi)].shape, " x ", i1.shape, " = ", h.shape tens_dims = [] tens_inds = [] tens_inds.extend([vi]) tens_inds.extend([wi]) tens_dims.extend([nv]) tens_dims.extend([nw]) for ti, t in enumerate(vecs): if (ti != vi) and (ti != wi): tens_dims.extend([t.shape[1]]) tens_inds.extend([ti]) tens_dims = np.append(tens_dims, tens_dims) #tens_inds = np.append(tens_inds, tens_inds) sort_ind = np.argsort(tens_inds) #print "sort: ", sort_ind, np.array(tens_inds)[sort_ind] #print ":",vi,wi, tens_inds, tens_dims #swap indices since we have done kronecker product as H2xI #tens_dims[vi], tens_dims[] = tens_dims[0], tens_dims[vi] #tens_dims[vi+n_dims], tens_dims[0+n_dims] = tens_dims[0+n_dims], tens_dims[vi+n_dims] swap = np.append(sort_ind, sort_ind + n_dims) #todo and check #h.shape = (tens_dims) #H += h.transpose(swap) H += h.reshape(tens_dims).transpose(swap) #print "swap ", swap #h = h.reshape(tens_dims) #h = h.transpose(swap) #print h.shape #print h.shape, dimsdims #sl = cp.deepcopy(sliceij) #sl #print H[sl].shape #H[] = Hij[(vi,wi)] #dim_i2 = 1 #for i in range(vi,wi): # dim_i2 = dim_i2 * vecs[i].shape[1] #dim_i2 = dim_i2/v.shape[1] #i2 = np.eye(dim_i2) #print "dim_i1 : dim_i2", dim_i1, dim_i2, dim #H += np.kron(i1,np.kron(H1[vi],i2)) #dim_i1 = dim_i1 * v.shape[1] H = H.reshape(dim, dim) print " Size of Hamitonian block: ", H.shape #printm(H) return H
def newton_solver(source_demands, sink_demands, proportions): n, m = source_demands.shape[0], sink_demands.shape[0] # Source demands mapped to sink demands via proportions. X = np.kron(np.eye(m), np.reshape(source_demands, [1, -1])) y_vec = np.zeros((1, n)) y_vec[0][0] = 1 y_vec = np.tile(y_vec, reps=(1, m)) rows = [] for _ in range(n): rows.append(y_vec) y_vec = np.roll(y_vec, shift=1, axis=-1) # Outgoing flows for each source Y = np.vstack(rows) A = np.vstack([X, Y]) sink_col = np.reshape(sink_demands, [-1, 1]) source_col = np.reshape(np.ones_like(source_demands), [-1, 1]) b = np.vstack([sink_col, source_col]) v, _, _, _ = np.linalg.lstsq(A, b, rcond=None) v_prev = v + 10 p = np.reshape(proportions, [-1, 1]) d = m + n + m * n split = m * n mat = np.zeros(shape=(d, d)) I = np.eye(split) zero = np.zeros(shape=(m + n, m + n)) lhs = np.vstack([I, A]) rhs = np.vstack([A.T, zero]) mat = np.hstack([lhs, rhs]) print(A) pad = np.zeros(shape=(d - m * n, 1)) max_iter = 1000 step_size = 1 beta = 0.9 for i in range(max_iter): target = np.vstack([p - v, pad]) sol, _, _, _ = np.linalg.lstsq(mat, target, rcond=None) delta_v = sol[:m * n] v_prev = v v = v_prev + step_size * delta_v step_size *= beta i += 1 if np.linalg.norm(v - v_prev) < SMALL_NUMBER: print('Converged in {0} steps.'.format(i)) break return A.dot(v), v, p