def __call__(self,observation): lst = [ tt.tensor(np.exp(-0.5*(observation[i]-np.arange(self.N[i]))**2/self.sigmas[i]**2)/(self.sigmas[i]*np.sqrt(2*np.pi))) if self.observation_vector[i] else tt.ones([self.N[i]]) for i in range(len(self.N))] lst = [ tt.tensor(np.exp(-0.5*(observation[i]-np.arange(self.N[i]))**2/self.sigmas[i]**2)) if self.observation_vector[i] else tt.ones([self.N[i]]) for i in range(len(self.N))] tens = tt.mkron(lst) return tens
def ObservationOperator(y, P, t): sigma = 1 / 2 PO = tt.kron( tt.tensor(np.exp(-0.5 * (y[0] - np.arange(N[0]))**2 / sigma**2)), tt.tensor(np.exp(-0.5 * (y[1] - np.arange(N[1]))**2 / sigma**2))) * (1 / (sigma**2 * 2 * np.pi)) # PO = PO * (1/tt.sum(PO)) return PO
def ObservationOperator(y, P, t): sigma = 0.3 PO = tt.tensor(np.exp(-0.5 * (y[0] - np.arange(N[0]))**2 / sigma**2)) PO = tt.kron( PO, tt.tensor(np.exp(-0.5 * (y[1] - np.arange(N[1]))**2 / sigma**2))) PO = tt.kron( PO, tt.tensor(np.exp(-0.5 * (y[2] - np.arange(N[2]))**2 / sigma**2))) PO = tt.kron( PO, tt.tensor(np.exp(-0.5 * (y[3] - np.arange(N[3]))**2 / sigma**2))) # PO = PO * (1/tt.sum(PO)) return PO
def goal_function(thetuta): L1 = np.array([lagrange(thetuta[0], i, pts1) for i in range(pts1.size)]) L2 = np.array([lagrange(thetuta[1], i, pts2) for i in range(pts2.size)]) L3 = np.array([lagrange(thetuta[2], i, pts3) for i in range(pts3.size)]) L4 = np.array([lagrange(thetuta[3], i, pts4) for i in range(pts4.size)]) L5 = np.array([lagrange(thetuta[4], i, pts5) for i in range(pts5.size)]) val = tt.dot( Post, tt.mkron(tt.tensor(L1.flatten()), tt.tensor(L2.flatten()), tt.tensor(L3.flatten()), tt.tensor(L4.flatten()), tt.tensor(L5.flatten()))) return -val
def gen_projected_gaussian_guess(H, r, eps=1e-10): """ Generate full N(0,1) vector and then project it to a random unitary TT of given rank Parameters: ----------- H: tt.matrix Matrix used to infer dimension of a guess vector r: int TT rank of the guess """ # generate tensor with haar distributed cores x = tt.rand(H.n, r=r) x = x.round(eps) x_cores = gen_haar_cores_like(x, left_to_right=True) x = x.from_list(x_cores) # project full dimensional gaussian vector to x dimensions = x.n Z = np.random.randn(*(dimensions)) Z = tt.tensor(Z) PZ = tt_project(x, Z) PZ = PZ.round(eps, rmax=r) return PZ * (1.0 / PZ.norm())
def __call__(self,observation): noise_model = lambda x,y,s : 1/(y*s*np.sqrt(2*np.pi)) * np.exp(-(np.log(y)-np.log(x+1))**2/(2*s**2)) lst = [ tt.tensor(noise_model(np.arange(self.N[i]),observation[i],self.sigmas[i])) if self.observation_vector[i] else tt.ones([self.N[i]]) for i in range(len(self.N))] tens = tt.mkron(lst) return tens
def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1): """ Approximate computation of minimal eigenvalues in tensor train format This function uses alternating least-squares algorithm for the computation of several minimal eigenvalues. If you want maximal eigenvalues, just send -A to the function. :Reference: S. V. Dolgov, B. N. Khoromskij, I. V. Oseledets, and D. V. Savostyanov. Computation of extreme eigenvalues in higher dimensions using block tensor train format. Computer Phys. Comm., 185(4):1207-1216, 2014. http://dx.doi.org/10.1016/j.cpc.2013.12.017 :param A: Matrix in the TT-format :type A: matrix :param y0: Initial guess in the block TT-format, r(d+1) is the number of eigenvalues sought :type y0: tensor :param eps: Accuracy required :type eps: float :param rmax: Maximal rank :type rmax: int :param kickrank: Addition rank, the larger the more robus the method, :type kickrank: int :rtype: A tuple (ev, tensor), where ev is a list of eigenvalues, tensor is an approximation to eigenvectors. :Example: >>> import tt >>> import tt.eigb >>> d = 8; f = 3 >>> r = [8] * (d * f + 1); r[d * f] = 8; r[0] = 1 >>> x = tt.rand(n, d * f, r) >>> a = tt.qlaplace_dd([8, 8, 8]) >>> sol, ev = tt.eigb.eigb(a, x, 1e-6, verb=0) Solving a block eigenvalue problem Looking for 8 eigenvalues with accuracy 1E-06 swp: 1 er = 35.93 rmax:19 swp: 2 er = 4.51015E-04 rmax:18 swp: 3 er = 1.87584E-12 rmax:17 Total number of matvecs: 0 >>> print ev [ 0.00044828 0.00089654 0.00089654 0.00089654 0.0013448 0.0013448 0.0013448 0.00164356] """ ry = y0.r.copy() lam = tt_eigb.tt_block_eig.tt_eigb(y0.d, A.n, A.m, A.tt.r, A.tt.core, y0.core, ry, eps, rmax, ry[y0.d], 0, nswp, max_full_size, verb) y = tensor() y.d = y0.d y.n = A.n.copy() y.r = ry y.core = tt_eigb.tt_block_eig.result_core.copy() tt_eigb.tt_block_eig.deallocate_result() y.get_ps() return y, lam
def amr_solve(A,f,x0,eps,rmax=150,kickrank=5,nswp=20,verb=1,prec='n',nrestart=40,niters=2): """ Approximate linear system solution X = AMR_SOLVE(A,F,X0,EPS), using AMR/DMRG algorithm """ rx0 = x0.r.copy() amr_f90.tt_adapt_als.tt_amr_solve(f.d,A.n,A.m,f.r,A.tt.r,A.tt.core,f.core,x0.core,rx0,eps,kickrank,nswp,verb,prec,nrestart,niters) x = tensor() x.d = f.d x.n = f.n.copy() x.r = rx0 x.core = amr_f90.tt_adapt_als.result_core.copy() amr_f90.tt_adapt_als.deallocate_result() x.get_ps() return x
def mvk4(A,x,y0,eps,rmax=150,kickrank=5,nswp=20,verb=1): """ Approximate matrix-by-vector multiplication Y = MVK4(A,X,Y0,EPS) Multiply a TT-matrix A with a TT-vector x with accuracy eps using the AMR/DMRG algorithm """ ry = y0.r.copy() amr_f90.tt_adapt_als.tt_mvk4(x.d,A.n,A.m,x.r,A.tt.r,A.tt.core, x.core, y0.core, ry, eps, rmax, kickrank, nswp, verb) y = tensor() y.d = x.d y.n = A.n.copy() y.r = ry y.core = amr_f90.tt_adapt_als.result_core.copy() amr_f90.tt_adapt_als.deallocate_result() y.get_ps() return y
def eigb(A,y0,eps,rmax=150,kickrank=5,nswp=20,verb=1): """ Approximate matrix-by-vector multiplication Y = EIGB(A,X,Y0,EPS) Find several eigenvalues of the TT-matrix """ ry = y0.r.copy() #lam = np.zeros(ry[y0.d]) lam = tt_eigb.tt_block_eig.tt_eigb(y0.d,A.n,A.m,A.tt.r,A.tt.core, y0.core, ry, eps, rmax,ry[y0.d], kickrank, nswp, verb) y = tensor() y.d = y0.d y.n = A.n.copy() y.r = ry y.core = tt_eigb.tt_block_eig.result_core.copy() tt_eigb.tt_block_eig.deallocate_result() y.get_ps() return y,lam
def gen_rounded_gaussian_guess(H, r, eps=1e-10): """ Generate full N(0,1) vector and then compress it to a TT with given rank and eps Parameters: ----------- H: tt.matrix Matrix used to infer dimension of a guess vector r: int TT rank of the guess """ psi_full = np.random.randn(*H.n) psi = tt.tensor(psi_full, eps, rmax=r) psi = psi * (1.0 / psi.norm()) return psi
def project_gaussian_to_x(X): """ Generates projection of a the gaussian vector in tangent space to a given TT vector X Parameters: ----------- X: tt.vector Vector to project to """ x = X.round(eps=1e-14) # removes excessive ranks d = x.d r = x.r dimensions = x.n Z = np.random.randn(*(dimensions)) Z = tt.tensor(Z) PZ = tt_project(x, Z) return PZ
def findif(d, mode=MODE_NP, tau=None, h=1., name=DEF_MATRIX_NAME): ''' Finite difference 1D matrix [i, j] = 1/h if i=j, [i, j] =-1/h if i=j+1 and = 0 otherwise. ''' res = Matrix(None, d, mode, tau, False, name) if mode == MODE_NP or mode == MODE_SP: res.x = sp_diag([np.ones(res.n), -np.ones(res.n - 1)], [0, -1], format='csr') res.x *= 1. / h if mode == MODE_NP: res.x = res.x.toarray() if mode == MODE_TT: e1 = tt.tensor(np.array([0., 1.])) e2 = tt.mkron([e1] * d) res.x = tt.Toeplitz(-e2, kind='U') + tt.eye(2, d) res.x *= (1. / h) res = res.round() return res
def amen_solve(A, f, x0, eps, kickrank=4, nswp=20, local_prec='n', local_iters=2, local_restart=40, trunc_norm=1, max_full_size=50, verb=1): """ Approximate linear system solution X = amen_solve(A,F,X0,EPS), using AMR/DMRG algorithm. :param A: Coefficients matrix, QTT-decomposed. :type A: matrix :param f: Right-hand side, TT-decomposed. :type f: tensor :param x0: TT-tensor of initial guess. :type x0: tensor :param eps: Accuracy. :type eps: float """ m = A.m.copy() rx0 = x0.r.copy() psx0 = x0.ps.copy() if A.is_complex or f.is_complex: amen_f90.amen_f90.ztt_amen_wrapper(f.d, A.n, m, \ A.tt.r, A.tt.ps, A.tt.core, \ f.r, f.ps, f.core, \ rx0, psx0, x0.core, \ eps, kickrank, nswp, local_iters, local_restart, trunc_norm, max_full_size, verb, local_prec) else: if x0.is_complex: x0 = x0.real() rx0 = x0.r.copy() psx0 = x0.ps.copy() amen_f90.amen_f90.dtt_amen_wrapper(f.d, A.n, m, \ A.tt.r, A.tt.ps, A.tt.core, \ f.r, f.ps, f.core, \ rx0, psx0, x0.core, \ eps, kickrank, nswp, local_iters, local_restart, trunc_norm, max_full_size, verb, local_prec) x = tt.tensor() x.d = f.d x.n = m.copy() x.r = rx0 if A.is_complex or f.is_complex: x.core = amen_f90.amen_f90.zcore.copy() else: x.core = amen_f90.amen_f90.core.copy() amen_f90.amen_f90.deallocate_result() x.get_ps() return x
def kls(A,y0,tau,rmax=150,kickrank=5,verb=1,nswp=10): """ Dynamical TT-approximation """ ry = y0.r.copy() #lam = np.zeros(ry[y0.d]) #for i in xrange(10): #Check for dtype y = tensor() if np.iscomplex(A.tt.core).any() or np.iscomplex(y0.core).any(): dyn_tt.dyn_tt.ztt_kls(y0.d,A.n,A.m,A.tt.r,A.tt.core +0j, y0.core+0j, ry, tau, rmax, kickrank, nswp, verb) 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_kls(y0.d,A.n,A.m,A.tt.r,A.tt.core, y0.core, ry, tau, rmax, kickrank, nswp, 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
def ksl(A,y0,tau,rmax=150,kickrank=5,verb=1,nswp=10, scheme = 'symm', space = 8): """ Dynamical TT-approximation """ ry = y0.r.copy() if scheme is 'symm': tp = 2 else: tp = 1 #Check for dtype y = tensor() 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, kickrank, nswp, 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, kickrank, nswp, 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
#Calculate the kinetic energy (Laplace) operator lp2 = None eps = 1e-8 for i in xrange(f): w = lp for j in xrange(i): w = tt.kron(e,w) for j in xrange(i+1,f): w = tt.kron(w,e) lp2 = lp2 + w lp2 = lp2.round(eps) #Now we will compute Henon-Heiles stuff xx = [] t = tt.tensor(x) ee = tt.ones([N]) for i in xrange(f): t0 = t for j in xrange(i): t0 = tt.kron(ee,t0) for j in xrange(i+1,f): t0 = tt.kron(t0,ee) xx.append(t0) #Harmonic potential harm = None for i in xrange(f): harm = harm + (xx[i]*xx[i]) harm = harm.round(eps)
x * s * np.sqrt(2 * np.pi)) def ObservationOperator(y, P, t): sigma = 1 / 2 PO = tt.kron( tt.tensor(np.exp(-0.5 * (y[0] - np.arange(N[0]))**2 / sigma**2)), tt.tensor(np.exp(-0.5 * (y[1] - np.arange(N[1]))**2 / sigma**2))) * (1 / (sigma**2 * 2 * np.pi)) # PO = PO * (1/tt.sum(PO)) return PO #%% Prior # IC P0 = tt.tensor(x0) # Prior mu = rates var = rates / np.array([1000, 350, 25, 600]) alpha_prior = mu**2 / var beta_prior = mu / var # Pt = tt.kron( tt.kron( tt.tensor( gamma_pdf(pts1,alpha_prior[0],beta_prior[0]) ) , tt.tensor( gamma_pdf(pts2,alpha_prior[1],beta_prior[1]) ) ),tt.kron( tt.tensor( gamma_pdf(pts3,alpha_prior[2],beta_prior[2]) ) , tt.tensor( gamma_pdf(pts4,alpha_prior[3],beta_prior[3]) ) ) ) params = [] Ns = 500000 param_now = np.random.gamma(alpha_prior, 1 / beta_prior) # Pprev = eval_post(Atts,param_now,P0,time_observation,observations_noise,ObservationOperator,eps=1e-5,method = 'crank–nicolson',dtmax=2,Nmax = 64) Pprev = eval_post_full(mdl, param_now,
def TensorTrain(data, rank=6): return tensor.to_list(tensor(data, rmax=rank)) # n = 10 # R = 5 # u1 = np.random.random([n, R]) # u2 = np.random.random([n, R]) # u3 = np.random.random([n, R]) # v = np.random.random([n, 1]) # g = np.zeros([R, R, R]) # np.fill_diagonal(g, 1.) # a = ktensor([u1,u2,u3]) # a = a.toarray() # vec1 = np.einsum('ijk,jb,kc',a, v, v) # modes= [1,2] # for r in range(1,6): # tensor = BaseTensor(a,rank=r) # vec = tensor.dot([v,v],modes) # print('canon',r, np.linalg.norm(vec-vec1)/np.linalg.norm(vec1)) # for r in range(1,6): # ttensor = TuckerTensor(a,(r,r,r)) # vec = ttensor.dot([v,v],modes) # print('tucker',r, np.linalg.norm(vec-vec1)/np.linalg.norm(vec1)) # n = 100 # a = np.random.random((n,n,n)) # v = np.random.random([n, 1]) # #a = np.einsum('ijk,ai,bj,ck', g, u1, u2, u3) # vec1 = np.einsum('ijk,jb,kc',a, v, v) # # a = np.einsum('ijk,ai,bj,ck', g, u1, u2, u3) # # print(a.shape) # # vec1 = np.einsum('ijk,bj,ck',a, v, v) # # t = ktensor(dtensor(a)) # for r in range(1,10): # tensor = BaseTensor(a,[0],[1,2],rank=r) # vec = tensor.dot([v,v]) # print('canon',r, np.linalg.norm(vec-vec1)/np.linalg.norm(vec1)) # for r in range(1,10): # ttensor = TuckerTensor(a,[0],[1,2],(r,r,r)) # vec = ttensor.dot([v,v]) # print('tucker',r, np.linalg.norm(vec-vec1)/np.linalg.norm(vec1)) # n=100 # random_tensor = np.random.random((n,n,n)) # random_vector = np.random.random(n) # # random_vector = np.ones(n) # random_vector = np.random.random([n, 1]) # vec1 = np.einsum('ijk,bj,ck',random_tensor, random_vector, random_vector) # # dt = dtensor(random_tensor) # # vec1 = dt.ttv((random_vector,random_vector),[1,2]) # tensor = BaseTensor(random_tensor,[0],[1,2],100) # vec = tensor.dot([random_vector,random_vector]) # print(np.linalg.norm(vec-vec1)/np.linalg.norm(vec1)) # ttensor = TuckerTensor(random_tensor,[0],[1,2],(100,100,100)) # vec = ttensor.dot([random_vector,random_vector]) # print(np.linalg.norm(vec-vec1)/np.linalg.norm(vec1)) # t = time.time() # for i in range(100): # random_vector = np.random.random(n) # vec = tensor.dot([random_vector,random_vector]) # vec2 = ttensor.dot([random_vector,random_vector]) # print(np.linalg.norm(vec2-vec)) # print(time.time()-t) # dt = dtensor(random_tensor) # t = time.time() # for i in range(100): # random_vector = np.random.random(n) # vvec1 = dt.ttv((random_vector,random_vector),[1,2]) # print(time.time()-t)
lp2 = None eps = 1e-8 for i in xrange(f): w = lp for j in xrange(i): w = tt.kron(e,w) for j in xrange(i+1,f): w = tt.kron(w,e) lp2 = lp2 + w lp2 = lp2.round(eps) #Now we will compute Henon-Heiles stuff xx = [] t = tt.tensor(x) ee = tt.ones([N]) for i in xrange(f): t0 = t for j in xrange(i): t0 = tt.kron(ee,t0) for j in xrange(i+1,f): t0 = tt.kron(t0,ee) xx.append(t0) #Harmonic potential harm = None for i in xrange(f): harm = harm + (xx[i]*xx[i]) harm = harm.round(eps)
s4 = 0.05 observations = states + np.hstack( (np.random.normal(0, 1, (states.shape[0], 3)), np.random.normal(0, 0.000001, [states.shape[0], 1]))) observations = np.hstack( (np.random.lognormal(np.log(states[:, 0] + 1), s1).reshape([-1, 1]), np.random.lognormal(np.log(states[:, 1] + 1), s2).reshape([-1, 1]), np.random.lognormal(np.log(states[:, 2] + 1), s3).reshape([-1, 1]), np.random.lognormal(np.log(states[:, 3] + 1), s4).reshape([-1, 1]))) noise_model = lambda x, y, s: 1 / (y * s * np.sqrt(2 * np.pi)) * np.exp(-( np.log(y) - np.log(x + 1))**2 / (2 * s**2)) #%% Forward pass tme_total = datetime.datetime.now() P = tt.tensor(x0) if qtt: A_qtt = ttm2qttm(A_tt) fwd_int = ttInt(A_qtt, epsilon=1e-6, N_max=8, dt_max=1.0, method='cheby') P = tt2qtt(P) else: fwd_int = ttInt(A_tt, epsilon=1e-6, N_max=8, dt_max=1.0, method='cheby') P_fwd = [P.copy()] ranks_fwd = [[0, max(P.r)]] time = 0 for i in range(1, No): y = observations[i, :]
import numpy as np from math import pi,sqrt import tt from tt.ksl import ksl import time from scipy.linalg import expm d = 6 f = 1 A = tt.qlaplace_dd([d]*f) n = [2]*(d*f) n0 = 2**d x = np.arange(1,n0+1)*1.0/(n0+1) x = np.exp(-10*(x-0.5)**2) x = tt.tensor(x.reshape([2]*d,order='F'),1e-8) #x = tt.ones(2,d) tau = 1 tau1 = 1 y = x.copy() ns_fin = 8 tau0 = 1.0 tau_ref = tau0/2**ns_fin for i in xrange(2**ns_fin): y=ksl(-1.0*A,y,tau_ref) yref = y.copy() tau = 5e-2 res = "" ns = 2 while ( ns <= ns_fin ): tau = tau0/(2**ns) y = x.copy() for i in xrange(2**ns):
plt.figure() plt.title('Means') plt.plot(time_sample, np.mean(sample[:, 0, :], 1), 'b') plt.plot(time_sample, np.mean(sample[:, 1, :], 1), 'orange') plt.plot(time_sample, np.mean(sample[:, 2, :], 1), 'r') plt.plot(time_sample, np.mean(sample[:, 3, :], 1), 'g') plt.legend(['Susceptible', 'Exposed', 'Infected', 'Recovered']) plt.ylabel(r'#individuals') plt.xlabel(r'$t$ [d]') #%% Integrate ODE A_tt = mdl.construct_generator_tt() # A_tt = tt.reshape(A_tt,np.array(2*[[15]*8]).transpose()) P = tt.kron(tt.kron(tt.tensor(p1), tt.tensor(p2)), tt.kron(tt.tensor(p3), tt.tensor(p4))) P = P * (1 / tt.sum(P)) P0 = P # P = tt.reshape(P,[15]*8) x_S = tt.kron(tt.tensor(np.arange(N[0])), tt.ones(N[1:])) x_E = tt.kron(tt.ones([N[0]]), tt.kron(tt.tensor(np.arange(N[1])), tt.ones(N[2:]))) x_I = tt.kron(tt.ones(N[:2]), tt.kron(tt.tensor(np.arange(N[2])), tt.ones([N[3]]))) x_R = tt.kron(tt.ones(N[:3]), tt.tensor(np.arange(N[3]))) epsilon = 1e-10 rmax = 30
def f_init(x, y, z, vx, vy, vz): if (x <= 0.): return tt.tensor(Boltzmann_cyl.f_maxwell(vx, vy, vz, T_l, n_l, u_l, 0., 0., gas_params.Rg)) else: return tt.tensor(Boltzmann_cyl.f_maxwell(vx, vy, vz, T_r, n_r, u_r, 0., 0., gas_params.Rg))
vmax = 22 * v_s hv = 2. * vmax / nv vx_ = np.linspace(-vmax+hv/2, vmax-hv/2, nv) # coordinates of velocity nodes vx, vy, vz = np.meshgrid(vx_, vx_, vx_, indexing='ij') def f_init(x, y, z, vx, vy, vz): if (x <= 0.): return tt.tensor(Boltzmann_cyl.f_maxwell(vx, vy, vz, T_l, n_l, u_l, 0., 0., gas_params.Rg)) else: return tt.tensor(Boltzmann_cyl.f_maxwell(vx, vy, vz, T_r, n_r, u_r, 0., 0., gas_params.Rg)) f_in = tt.tensor(Boltzmann_cyl.f_maxwell(vx, vy, vz, T_l, n_l, u_l, 0., 0., gas_params.Rg)) f_out = tt.tensor(Boltzmann_cyl.f_maxwell(vx, vy, vz, T_r, n_r, u_r, 0., 0., gas_params.Rg)) #print(f_bound) fmax = tt.tensor(Boltzmann_cyl.f_maxwell(vx, vy, vz, T_w, 1., 0., 0., 0., gas_params.Rg)) #print(fmax) problem = Boltzmann_cyl.Problem(bc_type_list = ['sym-z', 'in', 'out', 'wall', 'sym-y'], bc_data = [[], [f_in], [f_out], [fmax], []], f_init = f_init) CFL = 50.
def amen_solve(A, f, x0, eps, kickrank=4, nswp=20, local_prec='n', local_iters=2, local_restart=40, trunc_norm=1, max_full_size=50, verb=1): """ Approximate linear system solution in the tensor-train (TT) format using Alternating minimal energy (AMEN approach) :References: Sergey Dolgov, Dmitry. Savostyanov Paper 1: http://arxiv.org/abs/1301.6068 Paper 2: http://arxiv.org/abs/1304.1222 :param A: Matrix in the TT-format :type A: matrix :param f: Right-hand side in the TT-format :type f: tensor :param x0: TT-tensor of initial guess. :type x0: tensor :param eps: Accuracy. :type eps: float :Example: >>> import tt >>> import tt.amen #Needed, not imported automatically >>> a = tt.qlaplace_dd([8, 8, 8]) #3D-Laplacian >>> rhs = tt.ones(2, 3 * 8) #Right-hand side of all ones >>> x = tt.amen.amen_solve(a, rhs, rhs, 1e-8) amen_solve: swp=1, max_dx= 9.766E-01, max_res= 3.269E+00, max_rank=5 amen_solve: swp=2, max_dx= 4.293E-01, max_res= 8.335E+00, max_rank=9 amen_solve: swp=3, max_dx= 1.135E-01, max_res= 5.341E+00, max_rank=13 amen_solve: swp=4, max_dx= 9.032E-03, max_res= 5.908E-01, max_rank=17 amen_solve: swp=5, max_dx= 9.500E-04, max_res= 7.636E-02, max_rank=21 amen_solve: swp=6, max_dx= 4.002E-05, max_res= 5.573E-03, max_rank=25 amen_solve: swp=7, max_dx= 4.949E-06, max_res= 8.418E-04, max_rank=29 amen_solve: swp=8, max_dx= 9.618E-07, max_res= 2.599E-04, max_rank=33 amen_solve: swp=9, max_dx= 2.792E-07, max_res= 6.336E-05, max_rank=37 amen_solve: swp=10, max_dx= 4.730E-08, max_res= 1.663E-05, max_rank=41 amen_solve: swp=11, max_dx= 1.508E-08, max_res= 5.463E-06, max_rank=45 amen_solve: swp=12, max_dx= 3.771E-09, max_res= 1.847E-06, max_rank=49 amen_solve: swp=13, max_dx= 7.797E-10, max_res= 6.203E-07, max_rank=53 amen_solve: swp=14, max_dx= 1.747E-10, max_res= 2.058E-07, max_rank=57 amen_solve: swp=15, max_dx= 8.150E-11, max_res= 8.555E-08, max_rank=61 amen_solve: swp=16, max_dx= 2.399E-11, max_res= 4.215E-08, max_rank=65 amen_solve: swp=17, max_dx= 7.871E-12, max_res= 1.341E-08, max_rank=69 amen_solve: swp=18, max_dx= 3.053E-12, max_res= 6.982E-09, max_rank=73 >>> print (tt.matvec(a, x) - rhs).norm() / rhs.norm() 5.5152374305127345e-09 """ m = A.m.copy() rx0 = x0.r.copy() psx0 = x0.ps.copy() if A.is_complex or f.is_complex: amen_f90.amen_f90.ztt_amen_wrapper(f.d, A.n, m, \ A.tt.r, A.tt.ps, A.tt.core, \ f.r, f.ps, f.core, \ rx0, psx0, x0.core, \ eps, kickrank, nswp, local_iters, local_restart, trunc_norm, max_full_size, verb, local_prec) else: if x0.is_complex: x0 = x0.real() rx0 = x0.r.copy() psx0 = x0.ps.copy() amen_f90.amen_f90.dtt_amen_wrapper(f.d, A.n, m, \ A.tt.r, A.tt.ps, A.tt.core, \ f.r, f.ps, f.core, \ rx0, psx0, x0.core, \ eps, kickrank, nswp, local_iters, local_restart, trunc_norm, max_full_size, verb, local_prec) x = tt.tensor() x.d = f.d x.n = m.copy() x.r = rx0 if A.is_complex or f.is_complex: x.core = amen_f90.amen_f90.zcore.copy() else: x.core = amen_f90.amen_f90.core.copy() amen_f90.amen_f90.deallocate_result() x.get_ps() return x
def __init__(self, gas_params, problem, mesh, v, config): self.gas_params = gas_params self.problem = problem self.mesh = mesh self.v = v self.config = config self.path = './' + 'job_tt_' + config.solver + '_' + datetime.now( ).strftime("%Y.%m.%d_%H:%M:%S") + '/' os.mkdir(self.path) self.vn = [ None ] * mesh.nf # list of tensors of normal velocities at each mesh face self.vn_tmp = np.zeros((v.nvx, v.nvy, v.nvz)) self.vnm = [None] * mesh.nf # negative part of vn: 0.5 * (vn - |vn|) self.vnp = [None] * mesh.nf # positive part of vn: 0.5 * (vn + |vn|) self.vn_abs = [None] * mesh.nf # approximations of |vn| for jf in range(mesh.nf): self.vn_tmp = mesh.face_normals[jf, 0] * v.vx + mesh.face_normals[ jf, 1] * v.vy + mesh.face_normals[jf, 2] * v.vz self.vn[ jf] = mesh.face_normals[jf, 0] * v.vx_tt + mesh.face_normals[ jf, 1] * v.vy_tt + mesh.face_normals[jf, 2] * v.vz_tt self.vnp[jf] = tt.tensor(np.where(self.vn_tmp > 0, self.vn_tmp, 0.), eps=config.tol) self.vnm[jf] = tt.tensor(np.where(self.vn_tmp < 0, self.vn_tmp, 0.), eps=config.tol) self.vn_abs[jf] = tt.tensor(np.abs(self.vn_tmp), rmax=4) self.h = np.min(mesh.cell_diam) self.tau = self.h * config.CFL / (np.max(np.abs(v.vx_)) * (3.**0.5)) self.diag = [ None ] * mesh.nc # part of diagonal coefficient in implicit scheme self.diag_r1 = [None] * mesh.nc # precompute diag # simple approximation for v_abs self.vn_abs_r1 = tt.tensor((v.vx**2 + v.vy**2 + v.vz**2)**0.5, rmax=1) for ic in range(mesh.nc): diag_temp = np.zeros((v.nvx, v.nvy, v.nvz)) diag_sc = 0. for j in range(6): jf = mesh.cell_face_list[ic, j] vn_full = (mesh.face_normals[jf, 0] * v.vx + mesh.face_normals[jf, 1] * v.vy \ + mesh.face_normals[jf, 2] * v.vz) * mesh.cell_face_normal_direction[ic, j] vnp_full = np.where(vn_full > 0, vn_full, 0.) vn_abs_full = np.abs(vn_full) diag_temp += (mesh.face_areas[jf] / mesh.cell_volumes[ic]) * vnp_full diag_sc += 0.5 * (mesh.face_areas[jf] / mesh.cell_volumes[ic]) self.diag_r1[ic] = diag_sc * self.vn_abs_r1 diag_tt_full = tt.tensor(diag_temp, 1e-7, rmax=1).full() if (np.amax(diag_temp - diag_tt_full) > 0.): ind_max = np.unravel_index(np.argmax(diag_temp - diag_tt_full), diag_temp.shape) diag_tt_full = (diag_temp[ind_max] / diag_tt_full[ind_max]) * diag_tt_full self.diag[ic] = tt.tensor(diag_tt_full) # set initial condition self.f = [None] * mesh.nc # RENAME f! if (config.init_type == 'default'): for i in range(mesh.nc): x = mesh.cell_center_coo[i, 0] y = mesh.cell_center_coo[i, 1] z = mesh.cell_center_coo[i, 2] self.f[i] = problem.f_init(x, y, z, v) elif (config.init_type == 'restart'): # restart from distribution function self.f = self.load_restart() elif (config.init_type == 'macro_restart'): # restart form macroparameters array init_data = np.loadtxt(config.init_filename) for ic in range(mesh.nc): self.f[ic] = f_maxwell_tt(v, init_data[ic, 0], init_data[ic, 1], init_data[ic, 2], init_data[ic, 3], init_data[ic, 5], gas_params.Rg) self.f_plus = [None] * mesh.nf # Reconstructed values on the right self.f_minus = [None] * mesh.nf # reconstructed values on the left self.flux = [None] * mesh.nf # Flux values self.rhs = [None] * mesh.nc self.df = [None] * mesh.nc # Arrays for macroparameters self.n = np.zeros(mesh.nc) self.rho = np.zeros(mesh.nc) self.ux = np.zeros(mesh.nc) self.uy = np.zeros(mesh.nc) self.uz = np.zeros(mesh.nc) self.p = np.zeros(mesh.nc) self.T = np.zeros(mesh.nc) self.nu = np.zeros(mesh.nc) self.rank = np.zeros(mesh.nc) self.data = np.zeros((mesh.nc, 7)) self.frob_norm_iter = np.array([]) self.create_res()
def solver_tt(gas_params, problem, mesh, nt, nv, vx_, vx, vy, vz, \ CFL, tol, filename, init = '0'): """Solve Boltzmann equation with model collision integral gas_params -- object of class GasParams, contains gas parameters and viscosity law problem -- object of class Problem, contains list of boundary conditions, data for b.c., and function for initial condition mesh - object of class Mesh nt -- number of time steps vmax -- maximum velocity in each direction in velocity mesh nv -- number of nodes in velocity mesh CFL -- courant number filename -- name of output file for f init - name of restart file """ # Function for LU-SGS mydivide = lambda x: x[:, 0] / x[:, 1] zero_tt = 0. * tt.ones((nv, nv, nv)) ones_tt = tt.ones((nv, nv, nv)) # # Initialize main arrays and lists # vn = [None ] * mesh.nf # list of tensors of normal velocities at each mesh face vn_tmp = np.zeros((nv, nv, nv)) vnm = [None] * mesh.nf # negative part of vn: 0.5 * (vn - |vn|) vnp = [None] * mesh.nf # positive part of vn: 0.5 * (vn + |vn|) vn_abs = [None] * mesh.nf # approximations of |vn| vx_tt = tt.tensor(vx).round(tol) vy_tt = tt.tensor(vy).round(tol) vz_tt = tt.tensor(vz).round(tol) vn_error = 0. for jf in range(mesh.nf): vn_tmp = mesh.face_normals[jf, 0] * vx + mesh.face_normals[ jf, 1] * vy + mesh.face_normals[jf, 2] * vz vn[jf] = mesh.face_normals[jf, 0] * vx_tt + mesh.face_normals[ jf, 1] * vy_tt + mesh.face_normals[jf, 2] * vz_tt vnp[jf] = tt.tensor(np.where(vn_tmp > 0, vn_tmp, 0.), eps=tol) vnm[jf] = tt.tensor(np.where(vn_tmp < 0, vn_tmp, 0.), eps=tol) vn_abs[jf] = tt.tensor(np.abs(vn_tmp), rmax=4) vn_error = max( vn_error, np.linalg.norm(vn_abs[jf].full() - np.abs(vn_tmp)) / np.linalg.norm(np.abs(vn_tmp))) print('max||vn_abs_tt - vn_abs||_F/max||vn_abs||_F = ', vn_error) h = np.min(mesh.cell_diam) tau = h * CFL / (np.max(vx_) * (3.**0.5)) v2 = (vx_tt * vx_tt + vy_tt * vy_tt + vz_tt * vz_tt).round(tol) diag = [None] * mesh.nc # part of diagonal coefficient in implicit scheme # precompute diag diag_full = np.zeros( (mesh.nc, nv, nv, nv)) # part of diagonal coefficient in implicit scheme # precompute diag for ic in range(mesh.nc): for j in range(6): jf = mesh.cell_face_list[ic, j] vn_tmp = mesh.face_normals[jf, 0] * vx + mesh.face_normals[ jf, 1] * vy + mesh.face_normals[jf, 2] * vz vnp_full = np.where( mesh.cell_face_normal_direction[ic, j] * vn_tmp[:, :, :] > 0, mesh.cell_face_normal_direction[ic, j] * vn_tmp[:, :, :], 0.) diag_full[ic, :, :, :] += (mesh.face_areas[jf] / mesh.cell_volumes[ic]) * vnp_full for ic in range(mesh.nc): diag_temp = np.zeros((nv, nv, nv)) for j in range(6): jf = mesh.cell_face_list[ic, j] vn_full = (mesh.face_normals[jf, 0] * vx + mesh.face_normals[jf, 1] * vy \ + mesh.face_normals[jf, 2] * vz) * mesh.cell_face_normal_direction[ic, j] vnp_full = np.where(vn_full > 0, vn_full, 0.) vn_abs_full = np.abs(vn_full) diag_temp += (mesh.face_areas[jf] / mesh.cell_volumes[ic]) * vnp_full # diag_temp += 0.5 * (mesh.face_areas[jf] / mesh.cell_volumes[ic]) * vn_abs_full diag[ic] = tt.tensor(diag_temp) # Compute mean rank of diag diag_rank = 0. for ic in range(mesh.nc): diag_rank += 0.5 * (diag[ic].r[1] + diag[ic].r[2]) diag_rank = diag_rank / ic print('diag_rank = ', diag_rank) # diag_scal = np.zeros(mesh.nc) for ic in range(mesh.nc): for j in range(6): jf = mesh.cell_face_list[ic, j] diag_scal[ic] += 0.5 * (mesh.face_areas[jf] / mesh.cell_volumes[ic]) diag_scal *= np.max(np.abs(vx_)) * 3**0.5 # set initial condition f = [None] * mesh.nc if (init == '0'): for i in range(mesh.nc): x = mesh.cell_center_coo[i, 0] y = mesh.cell_center_coo[i, 1] z = mesh.cell_center_coo[i, 2] f[i] = problem.f_init(x, y, z, vx, vy, vz) else: # restart from distribution function # f = load_tt(init, mesh.nc, nv) # restart form macroparameters array init_data = np.loadtxt(init) for ic in range(mesh.nc): f[ic] = tt.tensor(f_maxwell(vx, vy, vz, init_data[ic, 5], \ init_data[ic, 0], init_data[ic, 1], init_data[ic, 2], init_data[ic, 3], gas_params.Rg), tol) # TODO: may be join f_plus and f_minus in one array f_plus = [None] * mesh.nf # Reconstructed values on the right f_minus = [None] * mesh.nf # reconstructed values on the left flux = [None] * mesh.nf # Flux values rhs = [None] * mesh.nc df = [None] * mesh.nc # Arrays for macroparameters n = np.zeros(mesh.nc) rho = np.zeros(mesh.nc) ux = np.zeros(mesh.nc) uy = np.zeros(mesh.nc) uz = np.zeros(mesh.nc) p = np.zeros(mesh.nc) T = np.zeros(mesh.nc) nu = np.zeros(mesh.nc) rank = np.zeros(mesh.nc) data = np.zeros((mesh.nc, 7)) # Dummy tensor with [1, 1, 1, 1] ranks F = tt.rand([nv, nv, nv], 3, [1, 1, 1, 1]) frob_norm_iter = np.array([]) it = 0 while (it < nt): it += 1 # reconstruction for inner faces # 1st order for ic in range(mesh.nc): for j in range(6): jf = mesh.cell_face_list[ic, j] if (mesh.cell_face_normal_direction[ic, j] == 1): f_minus[jf] = f[ic].copy() else: f_plus[jf] = f[ic].copy() # boundary condition # loop over all boundary faces for j in range(mesh.nbf): jf = mesh.bound_face_info[j, 0] # global face index bc_num = mesh.bound_face_info[j, 1] bc_type = problem.bc_type_list[bc_num] bc_data = problem.bc_data[bc_num] if (mesh.bound_face_info[j, 2] == 1): f_plus[jf] = set_bc_tt(gas_params, bc_type, bc_data, f_minus[jf], vx, vy, vz, vn[jf], vnp[jf], vnm[jf], tol) else: f_minus[jf] = set_bc_tt(gas_params, bc_type, bc_data, f_plus[jf], vx, vy, vz, -vn[jf], -vnm[jf], -vnp[jf], tol) # riemann solver - compute fluxes for jf in range(mesh.nf): flux[jf] = 0.5 * mesh.face_areas[jf] *\ ((f_plus[jf] + f_minus[jf]) * vn[jf] - (f_plus[jf] - f_minus[jf]) * vn_abs[jf]) flux[jf] = flux[jf].round(tol) # computation of the right-hand side for ic in range(mesh.nc): rhs[ic] = zero_tt.copy() # sum up fluxes from all faces of this cell for j in range(6): jf = mesh.cell_face_list[ic, j] rhs[ic] += -(mesh.cell_face_normal_direction[ic, j]) * ( 1. / mesh.cell_volumes[ic]) * flux[jf] rhs[ic] = rhs[ic].round(tol) # Compute macroparameters and collision integral J, n[ic], ux[ic], uy[ic], uz[ic], T[ic], nu[ic], rho[ic], p[ ic] = comp_macro_param_and_j_tt(f[ic], vx_, vx, vy, vz, vx_tt, vy_tt, vz_tt, v2, gas_params, tol, F, ones_tt) rhs[ic] += J rhs[ic] = rhs[ic].round(tol) frob_norm_iter = np.append( frob_norm_iter, np.sqrt(sum([(rhs[ic].norm())**2 for ic in range(mesh.nc)]))) # # update values, expclicit scheme # for ic in range(mesh.nc): f[ic] = (f[ic] + tau * rhs[ic]).round(tol) # save rhs norm and tec tile if ((it % 100) == 0): fig, ax = plt.subplots(figsize=(20, 10)) line, = ax.semilogy(frob_norm_iter / frob_norm_iter[0]) ax.set(title='$Steps =$' + str(it)) plt.savefig('norm_iter.png') plt.close() data[:, 0] = n[:] data[:, 1] = ux[:] data[:, 2] = uy[:] data[:, 3] = uz[:] data[:, 4] = p[:] data[:, 5] = T[:] data[:, 6] = rank[:] write_tecplot(mesh, data, 'tec_tt.dat', ('n', 'ux', 'uy', 'uz', 'p', 'T', 'rank')) save_tt(filename, f, mesh.nc, nv) Return = namedtuple( 'Return', ['f', 'n', 'ux', 'uy', 'uz', 'T', 'p', 'rank', 'frob_norm_iter']) S = Return(f, n, ux, uy, uz, T, p, rank, frob_norm_iter) return S
def solve(self, initial_tt, T, intervals=None, return_all=False, nswp=40, qtt=False, verb=False, rounding=True): if intervals == None: pass else: x_tt = initial_tt dT = T / intervals Nt = self.N_max S, P, ev, basis = self.get_SP(dT, Nt) if qtt: nqtt = int(np.log2(Nt)) S = ttm2qttm(tt.matrix(S)) P = ttm2qttm(tt.matrix(P)) I_tt = tt.eye(self.A_tt.n) B_tt = tt.kron(I_tt, tt.matrix(S)) - tt.kron( I_tt, P) @ tt.kron(self.A_tt, ttm2qttm(tt.eye([Nt]))) else: nqtt = 1 I_tt = tt.eye(self.A_tt.n) B_tt = tt.kron(I_tt, tt.matrix(S)) - tt.kron( I_tt, tt.matrix(P)) @ tt.kron(self.A_tt, tt.matrix(np.eye(Nt))) # print(dT,T,intervals) returns = [] for i in range(intervals): # print(i) if qtt: f_tt = tt.kron(x_tt, tt2qtt(tt.tensor(ev))) else: f_tt = tt.kron(x_tt, tt.tensor(ev)) # print(B_tt.n,f_tt.n) try: # xs_tt = xs_tt.round(1e-10,5) # tme = datetime.datetime.now() xs_tt = tt.amen.amen_solve(B_tt, f_tt, self.xs_tt, self.epsilon, verb=1 if verb else 0, nswp=nswp, kickrank=8, max_full_size=50, local_prec='n') # tme = datetime.datetime.now() - tme # print(tme) self.xs_tt = xs_tt except: # tme = datetime.datetime.now() xs_tt = tt.amen.amen_solve(B_tt, f_tt, f_tt, self.epsilon, verb=1 if verb else 0, nswp=nswp, kickrank=8, max_full_size=50, local_prec='n') # tme = datetime.datetime.now() - tme # print(tme) self.xs_tt = xs_tt # print('SIZE',tt_size(xs_tt)/1e6) # print('PLMMM',tt.sum(xs_tt),xs_tt.r) if basis == None: if return_all: returns.append(xs_tt) x_tt = xs_tt[tuple([slice(None, None, None)] * len(self.A_tt.n) + [-1] * nqtt)] x_tt = x_tt.round(self.epsilon / 10) else: if return_all: if qtt: beval = basis(np.array([0])).flatten() temp1 = xs_tt * tt.kron(tt.ones(self.A_tt.n), tt2qtt(tt.tensor(beval))) for l in range(nqtt): temp1 = tt.sum(temp1, len(temp1.n) - 1) beval = basis(np.array([dT])).flatten() temp2 = xs_tt * tt.kron(tt.ones(self.A_tt.n), tt2qtt(tt.tensor(beval))) for l in range(nqtt): temp2 = tt.sum(temp2, len(temp2.n) - 1) returns.append( tt.kron(temp1, tt.tensor(np.array([1, 0]))) + tt.kron(temp2, tt.tensor(np.array([0, 1])))) else: beval = basis(np.array([0])).flatten() temp1 = xs_tt * tt.kron(tt.ones(self.A_tt.n), tt.tensor(beval)) temp1 = tt.sum(temp1, len(temp1.n) - 1) beval = basis(np.array([dT])).flatten() temp2 = xs_tt * tt.kron(tt.ones(self.A_tt.n), tt.tensor(beval)) temp2 = tt.sum(temp2, len(temp2.n) - 1) returns.append( tt.kron(temp1, tt.tensor(np.array([1, 0]))) + tt.kron(temp2, tt.tensor(np.array([0, 1])))) beval = basis(np.array([dT])).flatten() if qtt: x_tt = xs_tt * tt.kron(tt.ones(self.A_tt.n), tt2qtt(tt.tensor(beval))) for l in range(nqtt): x_tt = tt.sum(x_tt, len(x_tt.n) - 1) if rounding: x_tt = x_tt.round(self.epsilon / 10) else: x_tt = tt.sum( xs_tt * tt.kron(tt.ones(self.A_tt.n), tt.tensor(beval)), len(xs_tt.n) - 1) if rounding: x_tt = x_tt.round(self.epsilon / 10) # print('SIZE 2 ',tt_size(x_tt)/1e6) if not return_all: returns = x_tt return returns
L_qtt = np.reshape(L,qtt_matrix) Lbd_qtt = np.reshape(Lbd,qtt_matrix) Lf_qtt = np.reshape(Lf,qtt_matrix) f1_qtt = np.reshape(f1,qtt_tensor) g1_qtt = np.reshape(g1,qtt_tensor) f2_qtt = np.reshape(f2,qtt_tensor) g2_qtt = np.reshape(g2,qtt_tensor) Identity_qtt = np.reshape(Identity,qtt_matrix) Identity_bd_qtt=np.reshape(identity_bd,qtt_matrix) #------------------converting to TT-format------------------ # #converting rightside to TT-format # #problem 1 f1_qtt = tt.tensor(f1_qtt) g1_qtt = tt.tensor(g1_qtt ) # #problem 1 f2_qtt = tt.tensor(f2_qtt) g2_qtt = tt.tensor(g2_qtt) # #convert Identity matrix to TT-format Identity_qtt = tt.matrix(Identity_qtt) Identity_bd_qtt=tt.matrix(Identity_bd_qtt) # #convert laplacian matrix to TT-format L_qtt = tt.matrix(L_qtt) Lbd_qtt = tt.matrix(Lbd_qtt) Lf_qtt = tt.matrix(Lf_qtt)
l_s = delta * mu_s * v_s / p_s #print 'l_s = ', l_s #print 'v_s = ', v_s nv = 44 vmax = 22 * v_s hv = 2. * vmax / nv vx_ = np.linspace(-vmax + hv / 2, vmax - hv / 2, nv) # coordinates of velocity nodes vx, vy, vz = np.meshgrid(vx_, vx_, vx_, indexing='ij') f_init = lambda x, y, z, vx, vy, vz: tt.tensor( Boltzmann_cyl.f_maxwell(vx, vy, vz, T_l, n_l, u_l, 0., 0., gas_params.Rg)) f_bound = tt.tensor( Boltzmann_cyl.f_maxwell(vx, vy, vz, T_l, n_l, u_l, 0., 0., gas_params.Rg)) #print(f_bound) fmax = tt.tensor( Boltzmann_cyl.f_maxwell(vx, vy, vz, T_w, 1., 0., 0., 0., gas_params.Rg)) #print(fmax) problem = Boltzmann_cyl.Problem( bc_type_list=['sym-z', 'in', 'out', 'wall', 'sym-y'], bc_data=[[], [f_bound], [f_bound], [fmax], []], f_init=f_init) #print 'vmax =', vmax CFL = 5e+1
# Set up model mdl = CME(N, Pre, Post, rates * 0 + 1, Props) Atts = mdl.construct_generator_tt(as_list=True) Nl = 64 mult = 6 param_range = [[0, r * mult] for r in rates] # basis = [LegendreBasis(Nl,[p[0],p[1]]) for p in param_range] basis = [BSplineBasis(Nl, [p[0], p[1]], deg=2) for p in param_range] pts = [b.integration_points(4)[0] for b in basis] ws = [b.integration_points(4)[1] for b in basis] lint = pts[0].size WS = tt.mkron([tt.tensor(b.get_integral()) for b in basis]) A_tt = extend_cme(Atts, pts) A_tt = A_tt.round(1e-10, 20) mass_tt, mass_inv_tt = get_mass(basis) stiff_tt = get_stiff(A_tt, N, pts, ws, basis) M_tt = tt.kron(tt.eye(N), mass_inv_tt) @ stiff_tt #%% Get observation np.random.seed(34548) # reaction_time,reaction_jumps,reaction_indices = Gillespie(np.array(Initial),time_observation[-1],Pre,Post-Pre,rates) # observations = Observations_grid(time_observation, reaction_time, reaction_jumps) # observations_noise = observations+np.random.normal(0,sigma,observations.shape)
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 = tensor() 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
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 = tensor() 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
results = [] # Each dim: [d,n,sizefull,f1_ttSize,f1_sizeRatio,...] for d in D: print("### DIMENSION %d ###" %(d)) xVec = np.meshgrid(*tuple([vtheta for x in range(d)])) localResults = [d,n,n**d] for f in functions: t0 = timing.log("Creating full tensor of function %s with n=%d, d=%d" %(f.func_name,n,d)) tensor = f(np.asarray(xVec)) tFoo, tDiffCreation = timing.log("Full tensor created", t0) t0 = timing.log("Compressing tensor to TT") a = tt.tensor(tensor) tFoo, tDiffCompression = timing.log("Tensor compressed", t0) s_tensor = n**d print("Size of full tensor: %d params" %(s_tensor)) s_a = numparams(a) print("Size of tt representation: %d params" %(s_a)) s_ratio = float(s_a) / s_tensor print("Size ratio (tt/full): %f" %(s_ratio)) print("Dimensions of tensor: %s" %(a.n))
Props = [ lambda x: x[:,0], lambda x: x[:,0] , lambda x: x[:,0]*0+1 , lambda x: x[:,1] ] # construct the model and the CME operator N = [80,120] # state truncation mdl = CME(N, Pre,Post,rates,Props) mdl.construct_generator2(to_tf=False) A_tt = mdl.construct_generator_tt() Initial = [2,4] P0 = np.zeros(N) P0[Initial[0],Initial[1]] = 1.0 P0_tt = tt.tensor(P0) dT = 128 Nt = 8 time = np.arange(Nt+1) * dT # Reference solution print('Reference solution...') tme_ode45 = timeit.time.time() mdl.construct_generator2(to_tf=False) Gen = mdl.gen def func(t,y): return Gen.dot(y) # solve CME res = scipy.integrate.solve_ivp(func,[0,time[-1]],P0.flatten(),t_eval=time,max_step=dT/10000)
plt.plot( np.repeat(reaction_time, 2)[1:], np.repeat(reaction_jumps[:, 3], 2)[:-1]) plt.plot( np.repeat(reaction_time, 2)[1:], np.repeat(reaction_jumps[:, 4], 2)[:-1]) plt.plot( np.repeat(reaction_time, 2)[1:], np.repeat(reaction_jumps[:, 5], 2)[:-1]) # import sys # sys.exit() evector = lambda n, i: np.eye(n)[:, i] P = tt.kron(tt.tensor(evector(N[0], s0[0])), tt.tensor(evector(N[1], s0[1]))) P = tt.kron(P, tt.tensor(evector(N[2], s0[2]))) P = tt.kron(P, tt.tensor(evector(N[3], s0[3]))) P = tt.kron(P, tt.tensor(evector(N[4], s0[4]))) P = tt.kron(P, tt.tensor(evector(N[5], s0[5]))) if qtt: A_qtt = ttm2qttm(Att) integrator = ttInt(A_qtt, epsilon=1e-7, N_max=8, dt_max=1.0, method='cheby') P = tt2qtt(P) else: integrator = ttInt(Att,
def amen_solve(A, f, x0, eps, kickrank=4, nswp=20, local_prec='n', local_iters=2, local_restart=40, trunc_norm=1, max_full_size=50, verb=1): """ Approximate linear system solution in the tensor-train (TT) format using Alternating minimal energy (AMEN approach) :References: Sergey Dolgov, Dmitry. Savostyanov Paper 1: http://arxiv.org/abs/1301.6068 Paper 2: http://arxiv.org/abs/1304.1222 :param A: Matrix in the TT-format :type A: matrix :param f: Right-hand side in the TT-format :type f: tensor :param x0: TT-tensor of initial guess. :type x0: tensor :param eps: Accuracy. :type eps: float :Example: >>> import tt >>> import tt.amen #Needed, not imported automatically >>> a = tt.qlaplace_dd([8, 8, 8]) #3D-Laplacian >>> rhs = tt.ones(2, 3 * 8) #Right-hand side of all ones >>> x = tt.amen.amen_solve(a, rhs, rhs, 1e-8) amen_solve: swp=1, max_dx= 9.766E-01, max_res= 3.269E+00, max_rank=5 amen_solve: swp=2, max_dx= 4.293E-01, max_res= 8.335E+00, max_rank=9 amen_solve: swp=3, max_dx= 1.135E-01, max_res= 5.341E+00, max_rank=13 amen_solve: swp=4, max_dx= 9.032E-03, max_res= 5.908E-01, max_rank=17 amen_solve: swp=5, max_dx= 9.500E-04, max_res= 7.636E-02, max_rank=21 amen_solve: swp=6, max_dx= 4.002E-05, max_res= 5.573E-03, max_rank=25 amen_solve: swp=7, max_dx= 4.949E-06, max_res= 8.418E-04, max_rank=29 amen_solve: swp=8, max_dx= 9.618E-07, max_res= 2.599E-04, max_rank=33 amen_solve: swp=9, max_dx= 2.792E-07, max_res= 6.336E-05, max_rank=37 amen_solve: swp=10, max_dx= 4.730E-08, max_res= 1.663E-05, max_rank=41 amen_solve: swp=11, max_dx= 1.508E-08, max_res= 5.463E-06, max_rank=45 amen_solve: swp=12, max_dx= 3.771E-09, max_res= 1.847E-06, max_rank=49 amen_solve: swp=13, max_dx= 7.797E-10, max_res= 6.203E-07, max_rank=53 amen_solve: swp=14, max_dx= 1.747E-10, max_res= 2.058E-07, max_rank=57 amen_solve: swp=15, max_dx= 8.150E-11, max_res= 8.555E-08, max_rank=61 amen_solve: swp=16, max_dx= 2.399E-11, max_res= 4.215E-08, max_rank=65 amen_solve: swp=17, max_dx= 7.871E-12, max_res= 1.341E-08, max_rank=69 amen_solve: swp=18, max_dx= 3.053E-12, max_res= 6.982E-09, max_rank=73 >>> print (tt.matvec(a, x) - rhs).norm() / rhs.norm() 5.5152374305127345e-09 """ m = A.m.copy() rx0 = x0.r.copy() psx0 = x0.ps.copy() if A.is_complex or f.is_complex: amen_f90.amen_f90.ztt_amen_wrapper(f.d, A.n, m, A.tt.r, A.tt.ps, A.tt.core, f.r, f.ps, f.core, rx0, psx0, x0.core, eps, kickrank, nswp, local_iters, local_restart, trunc_norm, max_full_size, verb, local_prec) else: if x0.is_complex: x0 = x0.real() rx0 = x0.r.copy() psx0 = x0.ps.copy() amen_f90.amen_f90.dtt_amen_wrapper(f.d, A.n, m, A.tt.r, A.tt.ps, A.tt.core, f.r, f.ps, f.core, rx0, psx0, x0.core, eps, kickrank, nswp, local_iters, local_restart, trunc_norm, max_full_size, verb, local_prec) x = tt.tensor() x.d = f.d x.n = m.copy() x.r = rx0 if A.is_complex or f.is_complex: x.core = amen_f90.amen_f90.zcore.copy() else: x.core = amen_f90.amen_f90.core.copy() amen_f90.amen_f90.deallocate_result() x.get_ps() return x
plt.scatter(time_observation, observations_noise[:, 3], c='k', marker='x', s=20) plt.xlabel('t [s]') plt.ylabel('#individuals') plt.legend(['G', 'M', 'P', 'G*', 'observations']) tikzplotlib.save('./../results/3stage_45_sample.tex') plt.pause(0.05) gamma_pdf = lambda x, a, b: x**(a - 1) * np.exp(-b * x) #%% Loops # IC P = tt.kron(tt.tensor(x0), tt.ones([Nl] * 5)) # Prior # alpha_prior, beta_prior = gamma_params(rates,rates / np.array([1000,250,25,900])) mu = rates[:-1] * np.array([1.5, 1.5, 1.5, 1.0, 1.0]) var = rates[:-1] * np.array([4 / 3, 5, 0.25, 0.04, 0.2]) alpha_prior = mu**2 / var beta_prior = mu / var Pt = tt.tensor(gamma_pdf(pts1, alpha_prior[0], beta_prior[0])) Pt = tt.kron(Pt, tt.tensor(gamma_pdf(pts2, alpha_prior[1], beta_prior[1]))) Pt = tt.kron(Pt, tt.tensor(gamma_pdf(pts3, alpha_prior[2], beta_prior[2]))) Pt = tt.kron(Pt, tt.tensor(gamma_pdf(pts4, alpha_prior[3], beta_prior[3]))) Pt = tt.kron(Pt, tt.tensor(gamma_pdf(pts5, alpha_prior[4], beta_prior[4]))) # Pt = tt.tensor(np.ones([Nl,Nl])) WS = tt.kron( tt.kron(tt.kron(tt.tensor(ws1), tt.tensor(ws2)),
def tt_meshgrid(xs): lst = [] for i in range(len(xs)): lst.append(tt.mkron([tt.tensor(xs[i]) if i==k else tt.ones([xs[k].size]) for k in range(len(xs)) ])) return lst
def mode_prod(t, Ms): cores = t.to_list(t) for i in range(len(cores)): cores[i] = np.einsum('ijk,jl->ilk', cores[i], Ms[i]) return tt.tensor().from_list(cores)
A = None for i in xrange(d-1): A = A + 0.5 * (ssp[i] * ssm[i+1] + ssm[i] * ssp[i+1]) + (ssz[i] * ssz[i+1]) A = A.round(1e-8) return A if __name__ == '__main__': d = 5 A = gen_heisen(d) n = A.n d = A.tt.d #In this case we will start from the rank-1 tensor "all spins up" #It is not good, since it leads to an eigenvector #Random start also seems to be quite useless #Maybe first d/2 is up other d/2 are down? v0 = np.array([1,0],dtype=np.float); v0 = tt.tensor(v0,1e-12) v1 = np.array([0,1],dtype=np.float); v1 = tt.tensor(v1,1e-12) e1 = None for j in xrange(d): if j % 2: e0 = v0#np.random.rand(2) else: e0 = v1#e0 = tt.tensor(e0,1e-12) e1 = tt.kron(e1,e0) r = [1]*(d+1) r[0] = 1 r[d] = 1 x0 = tt.rand(n,d,r) tau = 1e-2 tf = 100 t = 0