def build_plane(self, ind, kern_params, x0, x1): ''' ind: plane number ''' if 'sm' in self.kern: l, alpha, w, sigma = self.unpack(kern_params) pp = list(zip(l[ind], w[ind])) else: l, alpha, sigma = self.unpack(kern_params) pp = [l[ind]] fplus, fdiff = self.build_F(x0, x1, pp, self.fplus, self.fdiff, split=False) Aplus = self.Id * self.Es[ind] # selects appropriate diagonal elements Adiff = self.A * self.Es[ ind] # selects appropriate off-diagonal elements cplus = np.kron(Aplus, fplus) cdiff = alpha[ind] * np.kron(Adiff, fdiff) kxx = cplus + cdiff return sigma[ind] * kxx
def gen_marg_poiss(y_train, params, n_latents, n_neurons, coeffs, a1, N, D): len_sc, W = unpack_params(params) Da2W = (D * coeffs.T[2]) * W quad = 2 * Da2W @ W.T #cdiag = gpf.mkcovs.mkcovdiag_ASD_wellcond(init_len_sc+0, np.ones(np.size(init_len_sc)), nxcirc, wwnrm = wwnrm,addition = 1e-7).T C = [make_cov(N, i) + 1e-7 * np.eye(N) for i in len_sc] #all_cdiag = np.reshape(cdiag.T,np.size(init_len_sc)*N_four,-1) Cinv = [np.linalg.inv(C[i]) for i in np.arange(n_latents)] if n_latents is 1: sigma_inv = 2 * D * a2W.T @ W + Cinv[0] else: sigma_inv = np.kron(quad, np.eye(N)) + block_diag(Cinv, n_latents) #sigma_inv = 2*D*a2W.T@W + block_diag(Cinv, n_latents) Wkron = np.kron(W, np.eye(N)) second = Wkron @ (y_train - D * a1.T) mutot = np.squeeze(np.linalg.solve(sigma_inv, second)) #sigma = np.linalg.inv(sigma_inv) #mutot = np.squeeze([email protected]@(y_train- D*a1.T)) logl = np.squeeze((1 / 2) * mutot.T @ (sigma_inv) @ mutot) logdetC = 0 for i in np.arange(n_latents): logdetC = logdetC - (1 / 2) * np.linalg.slogdet(C[i])[1] neglogpost = logdetC + -(1 / 2) * np.linalg.slogdet(sigma_inv)[1] return -(neglogpost + logl)
def divergence(self, symbol, discretised_symbol, boundary_conditions): """Matrix-vector multiplication to implement the divergence operator. See :meth:`pybamm.SpatialMethod.divergence` """ domain = symbol.domain submesh_list = self.mesh.combine_submeshes(*domain) divergence_matrix = self.divergence_matrix(domain) # check for particle domain if submesh_list[0].coord_sys == "spherical polar": second_dim = len(submesh_list) edges = submesh_list[0].edges # create np.array of repeated submesh[0].nodes r_numpy = np.kron(np.ones(second_dim), submesh_list[0].nodes) r_edges_numpy = np.kron(np.ones(second_dim), edges) r = pybamm.Vector(r_numpy) r_edges = pybamm.Vector(r_edges_numpy) out = (1 / (r ** 2)) * ( divergence_matrix @ ((r_edges ** 2) * discretised_symbol) ) else: out = divergence_matrix @ discretised_symbol return out
def generate(si, theta, seed=0): np.random.seed(seed) n, p, r = len(si), 6, 5 X = np.random.normal(0, 1, n * p).reshape(n, p) X_kar = np.kron(np.eye(r), X) beta_star = np.random.uniform(0, 1, p * r).reshape(p * r, 1) A = np.random.uniform(0, 1, 25).reshape(5, 5) Gamma = PCA().fit(A).components_ Gamma1 = Gamma[:, :2] Gamma0 = Gamma[:, 2:] out1, out0 = list(), list() for i in range(2): out1.append([(-.9)**abs(i - j) for j in range(2)]) for i in range(3): out0.append([(-.5)**abs(i - j) for j in range(3)]) Omega1 = np.array(out1) Omega0 = np.array(out0) Sigma = np.matmul(np.matmul(Gamma1, Omega1), Gamma1.T) + np.matmul( np.matmul(Gamma0, Omega0), Gamma0.T) if (theta[0] == 0) & (theta[1] == 0): h = np.eye(len(si)) else: h = np.array(rho(si, theta)) Sigma_kr = np.kron(Sigma, h) Err_kr = np.random.multivariate_normal(np.repeat(0, n * r), Sigma_kr).reshape(n * r, 1) Y_kr = np.matmul(X_kar, beta_star) + np.array(Err_kr) Y = Y_kr.reshape(n, r) return (X, Y)
def C_mat(x): input_len, input_dim = x.shape if input_len > 2: vel_matrix = np.zeros((input_len - 1, input_len - 2)) vel_matrix[0, 0] = 1 vel_matrix[-1, -1] = -1 for i in range(1, input_len - 2): vel_matrix[i, i - 1] = -1 vel_matrix[i, i] = 1 e = np.array( list([-x[0, :]]) + [[0, 0, 0]] * (input_len - 3) + list([x[-1, :]])) k = np.kron(vel_matrix, np.eye(input_dim)) A = np.dot(k.T, k) b = np.dot(k.T, e.ravel()) c = np.dot(e.ravel().T, e.ravel()) / 2 A_term = np.dot(np.dot(x[1:-1].ravel().T, A), x[1:-1].ravel()) b_term = np.dot(x[1:-1].ravel().T, b) cost_prev = float(1 / 2.0) * A_term + b_term + c # * 1000 else: if input_len > 1: vel_matrix = -np.ones(input_len - 1) e = np.array(list([x[-1, :]])) k = np.kron(vel_matrix, np.eye(input_dim)) A = np.dot(k.T, k) b = np.dot(k.T, e.ravel()) c = np.dot(e.ravel().T, e.ravel()) / 2 A_term = np.dot(np.dot(x[0].ravel().T, A), x[0].ravel()) b_term = np.dot(x[0].ravel().T, b) else: vel_matrix = np.zeros(1) e = -x[:input_len + 1] * 0 k = np.kron(vel_matrix, np.eye(input_dim)) A = np.dot(k.T, k) b = np.dot(k.T, e.ravel()) c = np.dot(e.ravel().T, e.ravel()) / 2 A_term = np.dot(np.dot(x.ravel().T, A), x.ravel()) b_term = np.dot(x.ravel().T, b) cost_prev = float(1 / 2.0) * A_term + b_term + c # * 1000 return cost_prev
def channel_trace(num_q, num_anc): # kraus ops: Id x <x| kraus_ops = list() for x in range(2**num_anc): xbra = np.eye(1, 2**num_anc, x) kraus_ops.append(np.kron(np.identity(2**num_q), xbra)) return Kraus(kraus_ops)
def main(): args = parse_args() # Hyperparameters seed = 2151 # fixed for reproducibility rank = 1 learning_rate = 1e-3 theta_scale = 0.1 c_scale = v_scale = 5 p_scale = q_scale = r_scale = 1 n_iter = 100 if args.figure == "periodic": nonlinearity = FourierBasis(rank=rank, N=1) elif args.figure == "random_walk": nonlinearity = RandomWalk() else: raise ValueError("Unknown figure request: {args.figure}") np.random.seed(seed) Y = load_data(args.input, sample=True) d, T = Y.shape n_pred = int(0.2 * T) y = {k + 1: Y[:, k, None] for k in range(T)} y_train = {k: y[k] for k in range(1, T - n_pred + 1)} T = len(y_train) y_full = y C0 = c_scale * np.random.randn(d, rank) theta0 = theta_scale * np.random.rand(nonlinearity.n_params, 1) V0 = np.kron(v_scale, np.eye(rank)) mu0 = np.zeros([rank, 1]) P0 = p_scale * np.eye(rank) Q0 = q_scale * np.eye(rank) R0 = r_scale * np.eye(d) Qs = {k: Q0 for k in range(T + 1)} Rs = {k: R0 for k in range(T + 1)} psmf = PSMF(theta0, C0, V0, mu0, P0, Qs, Rs, nonlinearity) psmf.run( y_full, y_train, T, n_iter, n_pred, adam_gam=learning_rate, live_plot=args.live_plot, verbose=args.verbose, ) output_files = { "bases": args.output_bases, "cost_y": args.output_cost, "fit": args.output_fit, } psmf.figures_save( y, n_pred, T, output_files=output_files, fit_figsize=(8, 2) )
def main(): args = parse_args() seed = args.seed or np.random.randint(10000) print("Using seed: %r" % seed) np.random.seed(seed) d = 20 r = 6 T = 500 n_pred = 250 n_iter = 500 var = 0.1 data = generate_normal_data(nonlinearity, d=d, T=T, n_pred=n_pred, r=r, var=var) C0 = 0.1 * np.random.randn(d, r) theta0 = 0.1 * np.random.rand(r, 1) v0 = 0.1 V0 = np.kron(v0, np.eye(r)) mu0 = np.zeros([r, 1]) P0 = np.zeros([r, r]) Qs = {k: 0 * np.identity(r) for k in range(T + 1)} Rs = {k: np.identity(d) for k in range(T + 1)} psmf = PSMFIterSynthetic(theta0, C0, V0, mu0, P0, Qs, Rs, nonlinearity) psmf.run( data["y_train"], data["y_obs"], data["theta_true"], data["C_true"], data["x_true"], T, n_iter, n_pred, adam_gam=1e-3, live_plot=args.live_plot, verbose=args.verbose, ) output_files = dict( fit=args.output_fit, bases=args.output_bases, cost_y=args.output_cost_y, cost_theta=args.output_cost_theta, ) psmf.figures_save( data["y_obs"], n_pred, T, x_true=data["x_true"], output_files=output_files, ) psmf.figures_close()
def gen_marg_bino(y_train, params, n_latents, n_neurons, coeffs, N, D, count): len_sc, W = unpack_params(params) summedy = np.sum(y_train, axis=0) summedy = np.reshape(summedy, [np.size(summedy), -1]) a1 = np.array([np.repeat(coeffs.T[1], N)]) countvec = np.array([np.repeat(count, N)]) na2W = (count * coeffs.T[2]) * W quad = 2 * na2W @ W.T #a2W = (np.kron(a2W, np.eye(N)).T) #W = (np.kron(loadings, np.eye(N)).T) #cdiag = gpf.mkcovs.mkcovdiag_ASD_wellcond(init_len_sc+0, np.ones(np.size(init_len_sc)), nxcirc, wwnrm = wwnrm,addition = 1e-7).T C = [make_cov(N, i) + 1e-7 * np.eye(N) for i in len_sc] #all_cdiag = np.reshape(cdiag.T,np.size(init_len_sc)*N_four,-1) Cinv = [np.linalg.inv(C[i]) for i in np.arange(n_latents)] if n_latents is 1: sigma_inv = Cinv[0] else: sigma_inv = np.kron(quad, np.eye(N)) + block_diag(Cinv, n_latents) #sigma = np.linalg.inv(sigma_inv) Wkron = np.kron(W, np.eye(N)) second = Wkron @ (summedy - countvec.T - (countvec * a1).T) mutot = np.squeeze(np.linalg.solve(sigma_inv, second)) logl = np.squeeze((1 / 2) * mutot.T @ (sigma_inv) @ mutot) logdetC = 0 for i in np.arange(n_latents): logdetC = logdetC - (1 / 2) * np.linalg.slogdet(C[i])[1] neglogpost = logdetC + -(1 / 2) * np.linalg.slogdet(sigma_inv)[1] return -(neglogpost + logl)
def realStandardToNat(cls, M, covs): # This is for the general case I think # Avoid this because it is unnecessarily expensive cov_invs = [np.linalg.inv(cov) for cov in covs] n1 = reduce(lambda x, y: np.kron(x, y), cov_invs).reshape(M.shape + M.shape) N = len(M.shape) ind1 = string.ascii_letters[:N] ind2 = string.ascii_letters[N:N * 2] contract = ind2 + ',' + ind1 + ind2 + '->' + ind1 n2 = np.einsum(contract, M, n1) return -0.5 * n1, n2
def log_likelihoodRavel(cls, x, params=None, nat_params=None): assert (params is None) ^ (nat_params is None) M, covs = params if params is not None else cls.natToStandard( *nat_params) assert x.shape[1:] == M.shape fullMu = M.ravel() ans = 0.0 for _x in x: fullCov = reduce(lambda x, y: np.kron(x, y), covs) ans += Normal.log_likelihood(_x.ravel(), params=(fullMu, fullCov)) return ans
def _compute_inverse_coefficient_innovation(self, k, mu_bar, P_bar): Rbar = self._R[k - 1] + np.kron(mu_bar.T @ self._V[k - 1] @ mu_bar, np.eye(self._d)) if np.all(Rbar == np.diag(np.diagonal(Rbar))) and Rbar.sum() > 0: Ri = np.diag(1 / np.diag(Rbar)) RiC = Ri @ self._C[k - 1] Pi = np.linalg.inv(P_bar) PiCRiC = Pi + self._C[k - 1].T @ RiC Skinv = Ri - RiC @ np.linalg.inv(PiCRiC) @ RiC.T else: Sk = self._C[k - 1] @ P_bar @ self._C[k - 1].T + Rbar Skinv = np.linalg.inv(Sk) return Skinv
def gen_marg_negbino(y_train, params, n_latents, n_neurons, coeffs, a1y, a0y, a1, summedy, N, consts, scale): len_sc, loadings = unpack_params(params) D = np.shape(y_train)[0] #number of trials a2W = coeffs.T[2] * loadings a2W = (np.kron(a2W, np.eye(N)).T) W = (np.kron(loadings, np.eye(N)).T) #cdiag = gpf.mkcovs.mkcovdiag_ASD_wellcond(init_len_sc+0, np.ones(np.size(init_len_sc)), nxcirc, wwnrm = wwnrm,addition = 1e-7).T C = [make_cov(N, i) + 1e-8 * np.eye(N) for i in len_sc] #all_cdiag = np.reshape(cdiag.T,np.size(init_len_sc)*N_four,-1) Cinv = [np.linalg.inv(C[i]) for i in np.arange(n_latents)] if n_latents is 1: sigma_inv = 2 * D * scale * a2W.T @ W + 2 * a2W.T @ np.multiply( summedy, np.eye(N * n_neurons)) @ W + Cinv[0] else: sigma_inv = 2 * D * scale * a2W.T @ W + 2 * a2W.T @ np.multiply( summedy, np.eye(N * n_neurons)) @ W + block_diag(Cinv, n_latents) #sigma = np.linalg.inv(sigma_inv) second = W.T @ (np.squeeze(summedy) - np.squeeze(D * a1.T * scale) - np.squeeze(a1y)) mutot = np.squeeze(np.linalg.solve(sigma_inv, second)) logl = np.squeeze((1 / 2) * mutot.T @ (sigma_inv) @ mutot) logdetC = 0 for i in np.arange(n_latents): logdetC = logdetC - (1 / 2) * np.linalg.slogdet(C[i])[1] neglogpost = logdetC + -(1 / 2) * np.linalg.slogdet(sigma_inv)[1] return -(neglogpost + logl + consts)
def learn(self, data): noise = np.zeros((self.dm_state, self.dm_state, self.nb_steps)) for t in range(self.nb_steps): input = np.hstack((data['x'][:, t, :].T, data['u'][:, t, :].T)) target = data['xn'][:, t, :].T model = LinearGaussianWithMatrixNormalWishart(self.prior, affine=True) model = model.meanfield_update(y=target, x=input) self.mu[..., t] = np.reshape(model.posterior.matnorm.M, self.mu[..., t].shape, order='F') self.sigma[..., t] = np.linalg.inv(np.kron(model.posterior.matnorm.K, model.posterior.wishart.mode())) noise[..., t] = np.linalg.inv(model.posterior.wishart.mode()) return noise
def _make_A(self, eps_vec, delta_matrix, phi_matrix): """ Builds the multi-frequency electromagnetic operator A in Ax = b """ M = 2*self.Nsb + 1 N = self.Nx * self.Ny W = self.omega + npa.arange(-self.Nsb,self.Nsb+1)*self.omega_mod C = sp.kron(sp.eye(M), - 1 / MU_0 * self.Dxf.dot(self.Dxb) - 1 / MU_0 * self.Dyf.dot(self.Dyb)) entries_c, indices_c = get_entries_indices(C) # diagonal entries representing static refractive index # this part is just a block diagonal version of the single frequency fdfd_ez entries_diag = - EPSILON_0 * npa.kron(W**2, eps_vec) indices_diag = npa.vstack((npa.arange(M*N), npa.arange(M*N))) entries_a = npa.hstack((entries_diag, entries_c)) indices_a = npa.hstack((indices_diag, indices_c)) # off-diagonal entries representing dynamic modulation # this part couples different frequencies due to modulation # for a derivation of these entries, see Y. Shi, W. Shin, and S. Fan. Optica 3(11), 2016. Nfreq = npa.shape(delta_matrix)[0] for k in npa.arange(Nfreq): # super-diagonal entries (note the +1j phase) mod_p = - 0.5 * EPSILON_0 * delta_matrix[k,:] * npa.exp(1j*phi_matrix[k,:]) entries_p = npa.kron(W[:-k-1]**2, mod_p) indices_p = npa.vstack((npa.arange((M-k-1)*N), npa.arange((k+1)*N, M*N))) entries_a = npa.hstack((entries_p, entries_a)) indices_a = npa.hstack((indices_p,indices_a)) # sub-diagonal entries (note the -1j phase) mod_m = - 0.5 * EPSILON_0 * delta_matrix[k,:] * npa.exp(-1j*phi_matrix[k,:]) entries_m = npa.kron(W[k+1:]**2, mod_m) indices_m = npa.vstack((npa.arange((k+1)*N, M*N), npa.arange((M-k-1)*N))) entries_a = npa.hstack((entries_m, entries_a)) indices_a = npa.hstack((indices_m,indices_a)) return entries_a, indices_a
def compute_iKy(self, params, yknt, xt): k, n, t = yknt.shape Idt = np.eye(self.d * t) It = np.eye(t) kern_params, C, r, mu = self.unpack_params(params) KXX = self.kernel.build_Kxx(xt, xt, kern_params) KXX = KXX + np.eye(KXX.shape[0]) * self.fudge L = np.linalg.cholesky(KXX) iR12 = 1 / (np.sqrt(r)) A = L.T @ (np.kron(C.T @ np.diag(iR12), It)) # NT by NT B = Idt + L.T @ (np.kron(C.T @ np.diag(1 / r) @ C, It)) @ L M = np.linalg.cholesky(B) R_yk_nt = (yknt * iR12[None, :, None]).reshape([k, -1]) Ay = (A @ R_yk_nt.T).T # k by ... x = solve_triangular(M, Ay.T, lower=True) iBARy = solve_triangular(M.T, x, lower=False).T AiBARy = (A.T @ iBARy.T).T Idt_AiBARy = R_yk_nt - AiBARy # k by nt x = (Idt_AiBARy.reshape([k, n, t]) * iR12[None, :, None]).reshape( [k, -1]) return x, M, KXX
def l1_minimisation( G, h): # l1 norm minimization of x, given inequality constraint Gx <= h N = G.shape[-1] solvers.options['show_progress'] = False c = matrix(np.hstack([np.zeros(N), np.ones(N)])) #original constraint tmp_1 = np.hstack([G, np.zeros(G.shape)]) #constraint on absolute value tmp_2 = np.kron(np.array([[1, -1], [-1, -1]]), np.eye(N)) #ensure positivity of t tmp_3 = np.hstack([np.zeros(N), -np.ones(N)]) b = matrix(np.vstack([h.reshape(-1, 1), np.zeros((2 * N, 1)), 0])) A = matrix(np.vstack([tmp_1, tmp_2, tmp_3])) sol = solvers.lp(c, A, b) return sol['x'][:N]
def integral(self, child, discretised_child): """Vector-vector dot product to implement the integral operator. """ # Calculate integration vector integration_vector = self.definite_integral_matrix(child.domain) # Check for spherical domains submesh_list = self.mesh.combine_submeshes(*child.domain) if submesh_list[0].coord_sys == "spherical polar": second_dim = len(submesh_list) r_numpy = np.kron(np.ones(second_dim), submesh_list[0].nodes) r = pybamm.Vector(r_numpy) out = 4 * np.pi ** 2 * integration_vector @ (discretised_child * r) else: out = integration_vector @ discretised_child return out
def _ntied_transmat_prior(self, transmat_val): # TODO: document choices transmat = np.empty((0, self.n_components)) for r in range(self.n_unique): row = np.empty((self.n_chain, 0)) for c in range(self.n_unique): if r == c: subm = np.array(sp.diags([transmat_val[r, c], 1.0], [0, 1], shape=(self.n_chain, self.n_chain)).todense()) else: lower_left = np.zeros((self.n_chain, self.n_chain)) lower_left[self.n_tied, 0] = 1.0 subm = np.kron(transmat_val[r, c], lower_left) row = np.hstack((row, subm)) transmat = np.vstack((transmat, row)) return transmat
def expand(U, wires, num_wires): r"""Expand a multi-qubit operator into a full system operator. Args: U (array): :math:`2^n \times 2^n` matrix where n = len(wires). wires (Sequence[int]): Target subsystems (order matters! the left-most Hilbert space is at index 0). Returns: array: :math:`2^N\times 2^N` matrix. The full system operator. """ if num_wires == 1: # total number of wires is 1, simply return the matrix return U N = num_wires wires = np.asarray(wires) if np.any(wires < 0) or np.any( wires >= N) or len(set(wires)) != len(wires): raise ValueError( "Invalid target subsystems provided in 'wires' argument.") if U.shape != (2**len(wires), 2**len(wires)): raise ValueError( "Matrix parameter must be of size (2**len(wires), 2**len(wires))") # generate N qubit basis states via the cartesian product tuples = np.array(list(itertools.product([0, 1], repeat=N))) # wires not acted on by the operator inactive_wires = list(set(range(N)) - set(wires)) # expand U to act on the entire system U = np.kron(U, np.identity(2**len(inactive_wires))) # move active wires to beginning of the list of wires rearranged_wires = np.array(list(wires) + inactive_wires) # convert to computational basis # i.e., converting the list of basis state bit strings into # a list of decimal numbers that correspond to the computational # basis state. For example, [0, 1, 0, 1, 1] = 2^3+2^1+2^0 = 11. perm = np.ravel_multi_index(tuples[:, rearranged_wires].T, [2] * N) # permute U to take into account rearranged wires return U[:, perm][perm]
def shannon_rate(L, T): Ad = scipy.linalg.expm(A*T) y0 = np.zeros([A.shape[0]**2,1])[:,0] out = scipy.integrate.odeint(gramian_ode, y0, [0,T], args=(A,C)) Wo = out[1,:].reshape([A.shape[0], A.shape[0]]) lyap_tmp = - np.kron(Ad,Ad) + np.identity(n*n) Sigma = np.dot(L,L.transpose()) Sigma_norm = Sigma/(np.trace(Sigma)) Sigma_norm_B = np.dot(np.dot(B,Sigma_norm),B.transpose()) Sigma_norm_vec = np.reshape(Sigma_norm_B,(n*n,1)) Wcd_vec = np.dot(np.linalg.inv(lyap_tmp),Sigma_norm_vec) Wcd = np.reshape(Wcd_vec,(n,n)) Wnum = np.dot(Wo,Wcd) Wden = np.dot(Wo,Wcd-Sigma_norm_B) num = np.linalg.det(Wnum+sigma2*I) den = np.linalg.det(Wden+sigma2*I) return -np.log2(num/den)/(2.*T)
def get_fdbk_controller( x,t): k = np.where(param.get('T') == t)[0][0] my_1 = util.get_my_1() eta = dynamics.get_eta( x,t) dvdota_dvb = dynamics.get_dvdota_dvb(x,t) xtilde_dot = dynamics.get_xtildedot( x,t) dvdota_dxtilde = dynamics.get_dvdota_dxtilde( x,t) A = np.matmul( np.transpose( my_1), \ np.matmul( dvdota_dxtilde, xtilde_dot)) - \ util.list_to_vec( param.get('ad')[k,:]) B = np.matmul( np.transpose( my_1), dvdota_dvb) K = param.get('k_fdbk')*np.kron( np.eye(param.get('nd')), \ np.ones((1,param.get('gamma')))) u = np.matmul(np.linalg.pinv(B), - A - np.matmul(K,eta)) u = np.clip( u, -param.get('control_max'), param.get('control_max')) return u
def predx(self, yknt, params, xt): k, n, t = yknt.shape kern_params, C, R, mu = self.unpack_params(params) yknt = yknt - mu[None, :, None] iKy, M, _ = self.compute_iKy(params, yknt, xt) KXx = self.kernel.build_Kxx(self.xt, xt, kern_params) Kxx = self.kernel.build_Kxx(xt, xt, kern_params) iKyknt = iKy.reshape([k, n, t]) Cv = C.T @ iKyknt Cv = Cv.reshape([k, -1]) tmp = np.kron(C, np.eye(t)).reshape([n, t, self.d * t]).transpose([2, 0, 1]) iKC, _, _ = self.compute_iKy(params, tmp, xt) tmp = (C.T @ iKC.reshape([-1, n, t])).reshape([-1, self.d * t]) cov = Kxx - KXx.T @ tmp @ KXx dc = np.diag(cov) posterior_mean = (KXx.T @ Cv.T).T t = xt.shape[0] return posterior_mean.reshape([k, -1, t]), (np.sqrt(dc + 1e-5) * 2).reshape([self.d, -1])
def pred(self, xt, x1, ykdt, params): kern_params, wnoise, mean_params = self.unpack_params(params, fudge=self.fudge) k, d, t = ykdt.shape if self.mean: mu = self.mean(self.xt, params)[None] # D x T ### TO BE CHANGED yc = (ykdt - mu).reshape([self.k, -1]) else: yc = ykdt.reshape([k, -1]) KXX = self.build_Kxx(xt, xt, params, prior=True) # select points to condition on val_inds = np.argwhere(np.isnan(yc[0]) == False).squeeze() nval_inds = np.argwhere(np.isnan(yc[0]) == True).squeeze() KXX = KXX[:, val_inds] KXX = KXX[val_inds] yc = yc[:, val_inds] L = np.linalg.cholesky(KXX) iL = inv(L) Kinv = iL.T @ iL KXx = self.build_Kxx(xt, x1, params, prior=False) t0 = xt.shape[0] t1 = x1.shape[0] KXx = KXx.reshape([t0, d, t1, d]).reshape([t0 * d, -1]) noise = np.kron(np.diag(wnoise), np.eye(t0)) noise[nval_inds, nval_inds] = 0 KXx[:t0 * d, :t0 * d] += noise KXx = KXx.reshape([t0, d, t1, d]).reshape([d * t0, -1]) KXx = KXx[val_inds] Kxx = self.build_Kxx(x1, x1, params, prior=True) mu_pred = KXx.T.dot(Kinv).dot(yc.T).T cov_pred = Kxx - KXx.T.dot(Kinv).dot(KXx) mu_pred = mu_pred.reshape([k, d, -1]) return mu_pred, np.sqrt( np.diag(cov_pred).reshape([d, -1]) + self.fudge)
def _ntied_transmat(self, transmat_val): # TODO: document choices # +-----------------+ # |a|1|0|0|0|0|0|0|0| # +-----------------+ # |0|a|1|0|0|0|0|0|0| # +-----------------+ # +---+---+---+ |0|0|a|b|0|0|c|0|0| # | a | b | c | +-----------------+ # +-----------+ |0|0|0|e|1|0|0|0|0| # | d | e | f | +----> +-----------------+ # +-----------+ |0|0|0|0|e|1|0|0|0| # | g | h | i | +-----------------+ # +---+---+---+ |d|0|0|0|0|e|f|0|0| # +-----------------+ # |0|0|0|0|0|0|i|1|0| # +-----------------+ # |0|0|0|0|0|0|0|i|1| # +-----------------+ # |g|0|0|h|0|0|0|0|i| # +-----------------+ # for a model with n_unique = 3 and n_tied = 2 transmat = np.empty((0, self.n_components)) for r in range(self.n_unique): row = np.empty((self.n_chain, 0)) for c in range(self.n_unique): if r == c: subm = np.array(sp.diags([transmat_val[r, c], 1 - transmat_val[r, c]], [0, 1], shape=(self.n_chain, self.n_chain)).todense()) else: lower_left = np.zeros((self.n_chain, self.n_chain)) lower_left[self.n_tied, 0] = 1.0 subm = np.kron(transmat_val[r, c], lower_left) row = np.hstack((row, subm)) transmat = np.vstack((transmat, row)) return transmat
def _ntied_transmat(self, transmat_val): # TODO: document choices # +-----------------+ # |a|1|0|0|0|0|0|0|0| # +-----------------+ # |0|a|1|0|0|0|0|0|0| # +-----------------+ # +---+---+---+ |0|0|a|b|0|0|c|0|0| # | a | b | c | +-----------------+ # +-----------+ |0|0|0|e|1|0|0|0|0| # | d | e | f | +----> +-----------------+ # +-----------+ |0|0|0|0|e|1|0|0|0| # | g | h | i | +-----------------+ # +---+---+---+ |d|0|0|0|0|e|f|0|0| # +-----------------+ # |0|0|0|0|0|0|i|1|0| # +-----------------+ # |0|0|0|0|0|0|0|i|1| # +-----------------+ # |g|0|0|h|0|0|0|0|i| # +-----------------+ # for a model with n_unique = 3 and n_tied = 2 transmat = np.empty((0, self.n_components)) for r in range(self.n_unique): row = np.empty((self.n_chain, 0)) for c in range(self.n_unique): if r == c: subm = np.array( sp.diags([transmat_val[r, c], 1 - transmat_val[r, c]], [0, 1], shape=(self.n_chain, self.n_chain)).todense()) else: lower_left = np.zeros((self.n_chain, self.n_chain)) lower_left[self.n_tied, 0] = 1.0 subm = np.kron(transmat_val[r, c], lower_left) row = np.hstack((row, subm)) transmat = np.vstack((transmat, row)) return transmat
def lds_to_dense_infoparams(params): m0, S0, As, Bs, Qs, Cs, Ds, Rs, us, ys = params mu_init = m0 sigma_init = S0 A, B, sigma_states = As, Bs, Qs C, D, sigma_obs = Cs, Ds, Rs data = ys inputs = us # Copied from PYLDS tests/test_dense.py T, n = data.shape[0], D.shape[0] # mu_init, sigma_init = model.mu_init, model.sigma_init # A, B, sigma_states = model.A, model.B, model.sigma_states # C, D, sigma_obs = model.C, model.D, model.sigma_obs ss_inv = np.linalg.inv(sigma_states) h = np.zeros((T,n)) h[0] += np.linalg.solve(sigma_init, mu_init) # Dynamics h[1:] += inputs[:-1].dot(B.T).dot(ss_inv) h[:-1] += -inputs[:-1].dot(B.T).dot(np.linalg.solve(sigma_states, A)) # Emissions h += C.T.dot(np.linalg.solve(sigma_obs, data.T)).T h += -inputs.dot(D.T).dot(np.linalg.solve(sigma_obs, C)) J = np.kron(np.eye(T),C.T.dot(np.linalg.solve(sigma_obs,C))) J[:n,:n] += np.linalg.inv(sigma_init) pairblock = bmat([[A.T.dot(ss_inv).dot(A), -A.T.dot(ss_inv)], [-ss_inv.dot(A), ss_inv]]) for t in range(0,n*(T-1),n): J[t:t+2*n,t:t+2*n] += pairblock return J.reshape(T*n,T*n), h.reshape(T*n)
def test_multiple_expectation_different_wires(self): "Tests that qnodes return multiple expectation values." self.logTestName() a, b, c = 0.5, 0.54, 0.3 @qml.qnode(self.dev2) def circuit(x, y, z): qml.RX(x, [0]) qml.RZ(y, [0]) qml.CNOT([0, 1]) qml.RY(y, [0]) qml.RX(z, [0]) return qml.expval.PauliY(0), qml.expval.PauliZ(1) res = circuit(a, b, c) out_state = np.kron(Rotx(c), I) @ np.kron(Roty(b), I) @ CNOT \ @ np.kron(Rotz(b), I) @ np.kron(Rotx(a), I) @ np.array([1, 0, 0, 0]) ex0 = np.vdot(out_state, np.kron(Y, I) @ out_state) ex1 = np.vdot(out_state, np.kron(I, Z) @ out_state) ex = np.array([ex0, ex1]) self.assertAllAlmostEqual(ex, res, delta=self.tol)
def get_p_i(i): pi = np.zeros((1, 2 * param.get('ni'))) pi[0, 2 * i] = 1 return np.kron(pi, np.eye(param.get('nd')))
def get_v_b(): # get matrix to extract stacked velocities of all control agents pi = np.zeros((param.get('nb'), 2 * param.get('ni'))) for i in range(param.get('nb')): pi[i, 2 * (i + param.get('ni')) + 1] = 1 return np.kron(pi, np.eye(param.get('nd')))
def get_v_a(): # get matrix to extract stacked velocities of all free agents pi = np.zeros((param.get('na'), 2 * param.get('ni'))) for i in range(param.get('na')): pi[i, 2 * i + 1] = 1 return np.kron(pi, np.eye(param.get('nd')))