def test_sparse(self): N = 16 P = 2**N Xs = np.array(np.unravel_index(np.arange(P), [ 2, ] * N)).T ys = 1. / (np.sum(Xs, axis=1) + 1) # Hilbert tensor for i in range(1, 5): eps = 10**(-i) t = tr.core.sparse_tt_svd(Xs, ys, shape=[ 2, ] * N, rmax=5, verbose=False, eps=eps) reco = t.full() gt = np.zeros([ 2, ] * N) gt[list(Xs.T)] = ys error = np.linalg.norm(reco - gt) / np.linalg.norm(gt) self.assertLessEqual(error, eps) t = tt.vector(gt, eps=eps) reco = t.full() error_tt = np.linalg.norm(reco - gt) / np.linalg.norm(gt) self.assertLessEqual((error - error_tt) / error_tt, 1.5)
def project_TT(T, rank): ''' Vectorizing tensor :param T: Input tensor T :param rank: Number of rank you want to preserve :return: Vectorized tensor ''' T = tt.vector(T).round(1e-10, rmax=rank) return T.full()
def test_qtt_vector(self): d = 10 eps = 1e-14 a = np.arange(2**d) v = tt.reshape(tt.vector(a), [2]*d, eps=eps) r = v.r self.assertEqual(r.dtype, np.int32, 'Vector ranks are not integers, expected int32') self.assertTrue((r[1:-1] == 2).all(), 'This vector ranks should be exactly 2') b = v.full().reshape(-1, order='F') self.assertTrue(np.linalg.norm(a - b) < 10 * 2**d * eps, 'The approximation error is too large')
def test_random_sampling(self): N = 3 I = 8 P = 100 # A joint PDF # Rs = [1, ] + [10, ]*(N-1) + [1, ] # pdf = tt.vector.from_list([np.random_sampling.rand(Rs[n], I, Rs[n+1]) for n in range(N)]) # Rs = np.ones(N+1) # pdf = tt.vector.from_list([np.exp(-np.linspace(-7.5, 7.5, I)**2)[np.newaxis, :, np.newaxis]]*N) pdf = np.zeros((I,) * N) for i in range(I): pdf[i, :, i] = 1 pdf = tt.vector(pdf, eps=0) Xs = tr.core.random_sampling(pdf, P) self.assertAlmostEqual(np.linalg.norm(Xs[:, 0] - Xs[:, 2]), 0)
def conv2mode(self, mode=None, tau=None): if mode is not None: self.mode = mode if tau is not None: self.tau = tau if self.x is None: return elif isinstance(self.x, np.ndarray): if len(self.x.shape) != 1: raise ValueError('Incorrect shape.') self.d = _n2d(self.x.shape[0]) if self.mode == MODE_TT: self.x = tt.vector(self.x.reshape([2] * self.d, order='F'), eps=self.tau) elif isinstance(self.x, tt.vector): self.d = self.x.d if self.mode == MODE_NP or self.mode == MODE_SP: self.x = self.x.full().flatten('F') else: raise ValueError('Incorrect vector.')
def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000): """ Dynamical tensor-train approximation based on projector splitting This function performs one step of dynamical tensor-train approximation for the equation .. math :: \\frac{dy}{dt} = A y, \\quad y(0) = y_0 and outputs approximation for :math:`y(\\tau)` :References: 1. Christian Lubich, Ivan Oseledets, and Bart Vandereycken. Time integration of tensor trains. arXiv preprint 1407.2042, 2014. http://arxiv.org/abs/1407.2042 2. Christian Lubich and Ivan V. Oseledets. A projector-splitting integrator for dynamical low-rank approximation. BIT, 54(1):171-188, 2014. http://dx.doi.org/10.1007/s10543-013-0454-0 :param A: Matrix in the TT-format :type A: matrix :param y0: Initial condition in the TT-format, :type y0: tensor :param tau: Timestep :type tau: float :param scheme: The integration scheme, possible values: 'symm' -- second order, 'first' -- first order :type scheme: str :param space: Maximal dimension of the Krylov space for the local EXPOKIT solver. :type space: int :rtype: tensor :Example: >>> import tt >>> import tt.ksl >>> import numpy as np >>> d = 8 >>> a = tt.qlaplace_dd([d, d, d]) >>> y0, ev = tt.eigb.eigb(a, tt.rand(2 , 24, 2), 1e-6, verb=0) Solving a block eigenvalue problem Looking for 1 eigenvalues with accuracy 1E-06 swp: 1 er = 1.1408 rmax:2 swp: 2 er = 190.01 rmax:2 swp: 3 er = 2.72582E-08 rmax:2 Total number of matvecs: 0 >>> y1 = tt.ksl.ksl(a, y0, 1e-2) Solving a real-valued dynamical problem with tau=1E-02 >>> print tt.dot(y1, y0) / (y1.norm() * y0.norm()) - 1 #Eigenvectors should not change 0.0 """ ry = y0.r.copy() if scheme is 'symm': tp = 2 else: tp = 1 # Check for dtype y = tt.vector() if np.iscomplex(A.tt.core).any() or np.iscomplex(y0.core).any(): dyn_tt.dyn_tt.ztt_ksl( y0.d, A.n, A.m, A.tt.r, A.tt.core + 0j, y0.core + 0j, ry, tau, rmax, 0, 10, verb, tp, space) y.core = dyn_tt.dyn_tt.zresult_core.copy() else: A.tt.core = np.real(A.tt.core) y0.core = np.real(y0.core) dyn_tt.dyn_tt.tt_ksl( y0.d, A.n, A.m, A.tt.r, A.tt.core, y0.core, ry, tau, rmax, 0, 10, verb) y.core = dyn_tt.dyn_tt.result_core.copy() dyn_tt.dyn_tt.deallocate_result() y.d = y0.d y.n = A.n.copy() y.r = ry y.get_ps() return y
np.fill_diagonal(L[-n:, i:], v) L = L #L[0,:] = 0 #L[-1,:] = 0 #L[0,0] = 1 #L[-1,-1] = 1 #creating Identity matrix for kronecker product Identity = np.identity(n + 1) #------------------converting to TT-format------------------ #convert right-hand side b to TT-format b1_tt = tt.vector(b1) b2_tt = tt.vector(b2) #convert Identity matrix to TT-format Identity_tt = tt.matrix(Identity) #convert laplacian matrix to TT-format L_tt = tt.matrix(L) #------------------building 3d laplacian matrix in TT-format with TT-kronecker product------------------ L_tt1 = tt.kron(tt.kron(L_tt, Identity_tt), Identity_tt) L_tt2 = tt.kron(tt.kron(Identity_tt, L_tt), Identity_tt) L_tt3 = tt.kron(tt.kron(Identity_tt, Identity_tt), L_tt) L_tt = L_tt1 + L_tt2 + L_tt3
import numpy as np import tt a = tt.rand([3, 5, 7, 11], 4, [1, 4, 6, 5, 1]) b = tt.rand([3, 5, 7, 11], 4, [1, 2, 4, 3, 1]) c = tt.multifuncrs2([a, b], lambda x: np.sum(x, axis=1), eps=1E-6) print("Relative error norm:", (c - (a + b)).norm() / (a + b).norm()) # %% a # %% a.full().shape # %% c # %% a = tt.vector(np.array([[[-1,2],[-5,4]],[[-1,2],[-5,4]]])) def iamafunc(x): print("in",x) y=np.maximum(x,0) print("out",y) return y c = tt.multifuncrs2([a], np.vectorize(iamafunc), eps=1E-6) # %% c.full().shape # %% def testf(x): #print("A",x) #print("0",x[:,0]) #print("1",x[:,1]) #print(x) y1=x[:,0]
# You should have received a copy of the GNU Lesser General Public License # along with ttrecipes. If not, see <http://www.gnu.org/licenses/>. # ----------------------------------------------------------------------------- from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import numpy as np import tt import ttrecipes as tr import ttrecipes.tikz np.random.seed(1) X = np.random.randn(3, 4, 3, 4) t = tt.vector(X, eps=0.0) output_file = 'tikz_example.tex' selected = [1, 3, 0, 1] tr.tikz.draw(t=t, output_file=output_file, rank_labels=True, core_sep=5.5, colormap='autumn', figure_decorator=False, letter='T', selected=selected)
def tt_from_dense(X, max_r, nIter=1): for i in range(nIter): ttX = tt.vector(X, rmax=max_r) return ttX