コード例 #1
0
    def __init__(self, vx_, vy_, vz_):
        self.vx_ = vx_
        self.vy_ = vy_
        self.vz_ = vz_

        self.nvx = np.size(vx_)
        self.nvy = np.size(vy_)
        self.nvz = np.size(vz_)

        self.hvx = vx_[1] - vx_[0]
        self.hvy = vy_[1] - vy_[0]
        self.hvz = vz_[1] - vz_[0]
        self.hv3 = self.hvx * self.hvy * self.hvz

        self.vx, self.vy, self.vz = np.meshgrid(vx_, vy_, vz_, indexing='ij')

        self.vx_tt = tt_from_factors(vx_, np.ones(self.nvy), np.ones(self.nvz))
        self.vy_tt = tt_from_factors(np.ones(self.nvx), vy_, np.ones(self.nvz))
        self.vz_tt = tt_from_factors(np.ones(self.nvx), np.ones(self.nvy), vz_)

        self.v2 = (self.vx_tt * self.vx_tt + self.vy_tt * self.vy_tt +
                   self.vz_tt * self.vz_tt).round(1e-7, rmax=2)

        self.zero = 0. * tt.ones((self.nvx, self.nvy, self.nvz))
        self.ones = tt.ones((self.nvx, self.nvy, self.nvz))
コード例 #2
0
def vector(dx, dt, tau, I0, r02, k_sc, k_abs):
    nx = 2 ** dx # number of points in space
    nt = 2 ** dt # number of points in time
    
    bx = 1 # [0, b] - interval
    hx = bx / (nx - 1) # step 
    bt = 1 # [0, b] - interval
    ht = bt / (nt - 1) # step 
    
    x = hx * tt.xfun(2, dx) # coordinates generation
    ex = tt.ones(2, dx)
    t = ht * tt.xfun(2, dt) # coordinates generation
    et = tt.ones(2, dt)

    X = tt.mkron(x, ex, ex, et)
    Y = tt.mkron(ex, x, ex, et)
    Z = tt.mkron(ex, ex, x, et)
    T = tt.mkron(ex, ex, ex, t)
    
    Qs = tt.multifuncrs([X, Y, Z, T], lambda arg: I0 * (arg[:, 3]/tau *np.exp(-arg[:, 3]/tau)) * 
                        (np.exp( -(arg[:,1]**2 - arg[:,2]**2) / r02*np.exp(k_sc*arg[:,0]) ) * 
                         np.exp(-(k_sc + k_abs) * arg[:, 0]))  , 1e-6, verb = True)
    
    Qs = Qs.round(1e-6)
    
    return Qs
コード例 #3
0
ファイル: heat_discr.py プロジェクト: nalsur-veallam/Python
def vector(dx, dt, tau, I0, r02, k_sc, k_abs, rho, Cv, T0):
    nx = 2 ** dx # number of points in space
    nt = 2 ** dt # number of points in time
    
    bx = 1 # [0, b] - interval
    hx = bx / (nx - 1) # step 
    bt = 1 # [0, b] - interval
    ht = bt / (nt - 1) # step 
    
    
    x = hx * tt.xfun(2, dx) # coordinates generation
    ex = tt.ones(2, dx)
    t = ht * tt.xfun(2, dt) # coordinates generation
    et = tt.ones(2, dt)

    t0 = (T0 - 1)*tt.delta(2, dx, center = 0) # initial conditions for spatial
    t0 = tt.mkron(ex, ex, ex, et) + tt.mkron(t0, t0, t0, et)
    
    X = tt.mkron(x, ex, ex, et)
    Y = tt.mkron(ex, x, ex, et)
    Z = tt.mkron(ex, ex, x, et)
    T = tt.mkron(ex, ex, ex, t)
    
    Qs = tt.multifuncrs([X, Y, Z, T], lambda arg: I0 * (arg[:, 3]/tau *np.exp(-arg[:, 3]/tau)) * 
                        (np.exp( -(arg[:,1]**2 - arg[:,2]**2) / r02*np.exp(k_sc*arg[:,0]) ) * 
                         np.exp(-(k_sc + k_abs) * arg[:, 0]))  , 1e-14, verb = True)
    Qs = Qs + t0
    Qs = Qs.round(1e-14)
    
    return 1/(rho*Cv) * Qs
コード例 #4
0
def plot_patch(mesh_container, x, d, vmin=0, vmax=1, contours=True):
    px = zkronv(tt.xfun(2, d), tt.ones(2, d))
    py = zkronv(tt.ones(2, d), tt.xfun(2, d))
    px = px.full().flatten('F').astype(np.int)
    py = py.full().flatten('F').astype(np.int)

    pts = np.array([mesh_container._pts(ex, ey) for ex, ey in zip(px, py)])
    tri = Delaunay(pts)
    plt.tripcolor(pts[:, 0],
                  pts[:, 1],
                  tri.simplices.copy(),
                  x,
                  shading='gouraud',
                  vmin=vmin,
                  vmax=vmax)
    if contours:
        plt.tricontour(pts[:, 0],
                       pts[:, 1],
                       tri.simplices.copy(),
                       x,
                       np.linspace(vmin, vmax, 11),
                       colors='k')
    d = mesh_container.d
    p1 = mesh_container._pts(0, 0)
    p2 = mesh_container._pts(2**d - 1, 0)
    p3 = mesh_container._pts(2**d - 1, 2**d - 1)
    p4 = mesh_container._pts(0, 2**d - 1)
    plt.plot([p1[0], p2[0], p3[0], p4[0]], [p1[1], p2[1], p3[1], p4[1]], 'm')
コード例 #5
0
ファイル: vector.py プロジェクト: TripleEss/qttpdesolver
 def ones(d, mode=MODE_NP, tau=None, name=DEF_VECTOR_NAME):
     res = Vector(None, d, mode, tau, False, name=name)
     if mode == MODE_NP or mode == MODE_SP:
         res.x = np.ones(res.n)
     if mode == MODE_TT:
         res.x = tt.ones(2, d)
     return res
コード例 #6
0
def inessential_players(game, eps=1e-10):
    """
    Return all inessential players, sorted. An inessential player n adds v(n) to every coalition

    :param game:
    :param eps:
    :return: a vector of integers between 0 and N-1

    """

    N = game.d
    norm = tt.vector.norm(game)
    players = []
    t = tt.vector.from_list([
        np.concatenate([core[:, [0, 1], :], core[:, [1], :] - core[:, [0], :]],
                       axis=1) for core in tt.vector.to_list(game)
    ])
    for n in range(N):
        idx = [slice(0, 2)] * N
        idx[n] = [2]
        tidx = t[idx]
        if tt.vector.norm(tidx - tr.core.set_choose(game, n) *
                          tt.ones(tidx.n)) / norm < eps:
            players.append(n)
    return np.array(players)
コード例 #7
0
def sum_and_compress(tts,
                     rounding=1e-8,
                     rmax=np.iinfo(np.int32).max,
                     verbose=False):
    """
    Sum a sequence of tensors in the TT format (of the same size), by computing a pyramid-like merging with a two-at-a-time summing step followed by truncation (TT-round)

    :param tts: A generator (or list) of TT-tensors, all with the same shape
    :param rounding: Intermediate tensors will be rounded to this value when climbing up the hierarchy
    :return: The summed TT-tensor

    """

    d = dict()
    result = None
    for i, elem in enumerate(tts):
        if result is None:
            result = 0 * tt.ones(elem.n)
        if verbose and i % 100 == 0:
            print("sum_and_compress: {}-th element".format(i))
        climb = 0  # For going up the tree
        add = elem
        while climb in d:
            if verbose:
                print("Hierarchy level:", climb, "- We sum", add.r, "and",
                      d[climb].r)
            add = tr.core.round(d[climb] + add, eps=rounding, rmax=rmax)
            d.pop(climb)
            climb += 1
        d[climb] = add
    for key in d:
        result += d[key]
    return tr.core.round(result, eps=rounding, rmax=rmax)
コード例 #8
0
def banzhaf_power_indices(st,
                          threshold=0.5,
                          eps=1e-6,
                          verbose=False,
                          **kwargs):
    """
    Compute all N Banzhaf values for a 2^N tensor: for each n-th variable, it is the proportion of all swing votes in which it is the key vote (i.e. tuples whose closed value exceeds a given threshold). The value of a coalition is its closed value

    :param st: a Sobol TT
    :param threshold: real between 0 and 1 that defines the majority (default: 0.5)
    :param eps: default is 1e-6
    :return: a vector with the N Banzhaf values

    """

    N = st.d
    threshold *= tr.core.sum(st)
    cst = tr.core.to_lower(st)
    cst_masked = tt.multifuncrs2([cst],
                                 lambda x: x >= threshold,
                                 eps=eps,
                                 verb=verbose,
                                 **kwargs)

    result = np.empty(N)
    for i in range(N):
        idx1 = [slice(None)] * N
        idx1[i] = 1
        idx2 = [slice(None)] * N
        idx2[i] = 0
        result[i] = tr.core.sum(
            cst_masked[idx1] *
            (tt.ones(cst_masked[idx2].n) - cst_masked[idx2]))
    return result / np.sum(result)
コード例 #9
0
ファイル: riemannian_test.py プロジェクト: vseledkin/ttpy
 def random_tanget_space_point(X):
     coresX = tt.tensor.to_list(X)
     point = 0 * tt.ones(X.n)
     for dim in range(X.d):
         curr = deepcopy(coresX)
         curr[dim] = np.random.rand(curr[dim].shape[0], curr[dim].shape[1], curr[dim].shape[2])
         point += tt.tensor.from_list(curr)
     return point
コード例 #10
0
ファイル: riemannian_test.py プロジェクト: zhanglang1860/ttpy
 def random_tanget_space_point(X):
     coresX = tt.tensor.to_list(X)
     point = 0 * tt.ones(X.n)
     for dim in range(X.d):
         curr = deepcopy(coresX)
         curr[dim] = np.random.rand(curr[dim].shape[0],
                                    curr[dim].shape[1],
                                    curr[dim].shape[2])
         point += tt.tensor.from_list(curr)
     return point
コード例 #11
0
ファイル: generate_mesh.py プロジェクト: RerRayne/qtt-laplace
def add_to_final_mass_matrix(f, Ml, eps, d):
    rhs = tt.ones(4, d)

    # Впечатываем куда надо диагональные элементы
    if f is None:
        f = tt.matvec(Ml, rhs)
    else:
        f += tt.matvec(Ml, rhs)

    return f.round(eps)
コード例 #12
0
def gen_mask(xbc, ybc, d):
    """
    Generate boundary mask
    :param xbc:
    :param ybc:
    :param d:
    :return: mask
    """
    xmask = tt.ones(2, d)  # O(d)
    ymask = tt.ones(2, d)  # O(d)
    if xbc[0] == 'D':
        xmask = xmask - tt.unit(2, d, j=0)  # O(d)
    if xbc[1] == 'D':
        xmask = xmask - tt.unit(2, d, j=2**d - 1)  # O(d)
    if ybc[0] == 'D':
        ymask = ymask - tt.unit(2, d, j=0)  # O(d)
    if ybc[1] == 'D':
        ymask = ymask - tt.unit(2, d, j=2**d - 1)  # O(d)
    mask = zkronv(xmask, ymask)  # O(d),because TT-ranks=1
    return tt.diag(mask)  # O(d)
コード例 #13
0
 def ones(d, mode=MODE_NP, tau=None, name=DEF_MATRIX_NAME):
     ''' 
     Matrix of all ones.
     '''
     res = Matrix(None, d, mode, tau, False, name=name)
     if mode == MODE_NP:
         res.x = np.ones((res.n, res.n))
     if mode == MODE_TT:
         res.x = tt.eye(2, d)
         res.x.tt = tt.ones(4, d)
     if mode == MODE_SP:
         raise NotImplementedError()
     return res
コード例 #14
0
 def volterra(d, mode=MODE_NP, tau=None, h=1., name=DEF_MATRIX_NAME):
     '''
     Volterra integral 1D matrix
     [i, j] = h if i>=j and = 0 otherwise.
     '''
     res = Matrix(None, d, mode, tau, False, name)
     if mode == MODE_NP:
         res.x = h * toeplitz(c=np.ones(res.n), r=np.zeros(res.n))
     if mode == MODE_TT:
         res.x = h * (tt.Toeplitz(tt.ones(2, d), kind='U') + tt.eye(2, d))
         res = res.round()
     if mode == MODE_SP:
         raise NotImplementedError()
     return res
コード例 #15
0
def check_constant_sum(game, eps=1e-10):
    """
    Check if v(S) + v(N\S) == v(N) for all S contained in N

    :param game:
    :param eps:
    :return: True or False

    """

    N = game.d
    vN = game[[1] * N]
    residual = vN * tt.ones([2] * N) - (game + tr.core.complement(game))
    return np.abs(tt.vector.norm(residual) / tt.vector.norm(game)) < eps
コード例 #16
0
ファイル: zoperations.py プロジェクト: RerRayne/qtt-laplace
def zmeshgrid(d):
    """

    :param d:
    :return:
    """
    # assert d > 2

    lin = tt.xfun(2, d)
    one = tt.ones(2, d)

    xx = zkronv(lin, one)
    yy = zkronv(one, lin)

    return xx, yy
コード例 #17
0
ファイル: solver_tt.py プロジェクト: KornevEK/Boltzmann-T
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
コード例 #18
0
ファイル: Task2.py プロジェクト: zaub3rfuchs/SPMI
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

#------------------solving higher order linear system in TT-format------------------

#defining initial guess vector
x = tt.ones(11, d)

#solving the higher order linear system with AMEN
print("")
print("Solving Problem 1 with AMEN")
print("")
u1 = amen_solve(L_tt, b1_tt, x, 1e-6)

time.sleep(0.01)
print("")
print("Solving Problem 2 with AMEN")
print("")
u2 = amen_solve(L_tt, b2_tt, x, 1e-6)

#------------------calculating RMS-Error for the Solution------------------
コード例 #19
0
ファイル: hh_hermite.py プロジェクト: jaidevd/ttpy
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)

#Henon-Heiles correction
コード例 #20
0
ファイル: vsintest.py プロジェクト: churli/TT
functions = [vsum, vsin]

header = ["d","n","sizeFull"]
for f in functions:
    header.append("%s_ttSize" %(f.func_name))
    header.append("%s_tensorCrossApproxTime" %(f.func_name))
    
results = [] # Each dim: [d,n,sizefull,f1_ttSize,f1_sizeRatio,...]

for d in D:
    print("### DIMENSION %d ###" %(d))
    localResults = [d,n,"%d^%d"%(n,d)]

    for f in functions:
        t0 = timing.log("Cross-aproximating tensor to TT")
        tones = tt.ones(n,d)
        tensin = cross(f, tones, nswp=10)
        tFoo, tDiffCross = timing.log("Tensor compressed", t0)
        size = numparams(tensin)
        print("n = %d, d = %d, numparams = %d, tDiffCross = %s" %(n,d,size,tDiffCross))
        localResults.append(size)
        localResults.append(tDiffCross)
        
    results.append(localResults)

f = open("results_cross.csv", 'w')
f.write(";".join(header)+"\n")
for line in results:
    sLine = [str(x) for x in line]
    f.write(";".join(sLine)+"\n")
f.close()
コード例 #21
0
ファイル: test_common.py プロジェクト: Piyush3dB/ttpy
#   test_common.py
#   See LICENSE for details
"""Test common matrix operation with QTT-toolbox like matmat-operation and matvec-operation.
"""

from __future__ import print_function, absolute_import, division
import numpy as np
import sys

sys.path.append('../')

import tt


x = tt.xfun(2, 3)
e = tt.ones(2, 2)
X = tt.matrix(x, n=[2] * 3, m=[1] * 3) # [0, 1, 2, 3, 4, 5, 6, 7]^T
E = tt.matrix(e, n=[1] * 2, m=[2] * 2) # [1, 1, 1, 1]
#[[ 0.  0.  0.  0.]
# [ 1.  1.  1.  1.]
# [ 2.  2.  2.  2.]
# [ 3.  3.  3.  3.]
# [ 4.  4.  4.  4.]
# [ 5.  5.  5.  5.]
# [ 6.  6.  6.  6.]
# [ 7.  7.  7.  7.]]
print((X * E).full())
assert np.all((X * E) * np.arange(4) == np.arange(8) * 6.)

A = tt.matrix(tt.xfun(2, 3), n=[1] * 3, m=[2] * 3)
u = np.arange(8)
コード例 #22
0
    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
コード例 #23
0
ファイル: amen_mv.py プロジェクト: oseledets/ttpy
        y = _reshape(y, (ry1 * n * ry2, b))

    return y


if __name__ == '__main__':

    d = 12
    n = 15
    m = 15
    ra = 30
    rb = 10
    eps = 1e-6

    a = 0 * _tt.rand(n * m, d, r=ra)
    a = a + _tt.ones(n * m, d)
    #a = a.round(1e-12)
    a = _tt.vector.to_list(a)
    for i in xrange(d):
        sa = a[i].shape
        a[i] = _reshape(a[i], (sa[0], m, n, sa[-1]))
    A = _tt.matrix.from_list(a)

    b = _tt.rand(n, d, r=rb)

    c = amen_mv(A, b, eps, y=None, z=None, nswp=20, kickrank=4,
                kickrank2=0, verb=True, init_qr=True, renorm='gram', fkick=False)
    d = _tt.matvec(A, b).round(eps)

    print((c[0] - d).norm() / d.norm())
コード例 #24
0
# import sys
# sys.exit()
Pts = []
Pjs_fwd = []
print('Starting...')
tme_total = datetime.datetime.now()
tensor_size = 0
for i in range(1, No):

    y = observations_noise[i, :]

    PO = obs_operator(y)

    # PO = tt.kron(PO,Puniform.tt)
    PO = tt.kron(PO, tt.ones([Nl] * 4))
    # PO = tt.ones(N+5*[Nl])
    if qtt: PO = tt2qtt(PO)

    print('new observation ', i, '/', No, ' at time ', time_observation[i],
          ' ', y)

    tme = datetime.datetime.now()
    P = fwd_int.solve(P, dT, intervals=Nbs, qtt=qtt, verb=False, rounding=True)
    tme = datetime.datetime.now() - tme

    print('\tmax rank ', max(P.r))
    Ppred = P
    Ppost = PO * Ppred
    Ppost = Ppost.round(1e-10)
    print('\tmax rank (after observation) ', max(Ppost.r))
コード例 #25
0
    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
コード例 #26
0
ファイル: test_amen.py プロジェクト: oseledets/ttpy
from __future__ import print_function, absolute_import, division
import sys
sys.path.append('../')
import tt
from tt.amen import amen_solve
""" This program test two subroutines: matrix-by-vector multiplication
    and linear system solution via AMR scheme"""

d = 12
A = tt.qlaplace_dd([d])
x = tt.ones(2,d)
y = amen_solve(A,x,x,1e-6)


コード例 #27
0
ファイル: heat_discr.py プロジェクト: nalsur-veallam/Python
def initial_cond(T0, dx):
    t0 = T0*tt.ones(2, 3*dx)
    
    t0 = t0.round(1e-14)

    return t0
コード例 #28
0
ファイル: TTRegression.py プロジェクト: Bihaqo/exp-machines
    def fit_log_val(self, X_, y_, val_X_=None, val_y_=None):
        """Fit the model according to the given training data. Log validation loss on each epoch.
        Parameters
        ----------
        X_ : {array-like}, shape (n_samples, n_features)
            Training object-feature matrix, where n_samples in the number
            of samples and n_features is the number of features.
        y_ : array-like, shape (n_samples,)
             Target vector relative to X_.
        val_X_ : {array-like}, shape (n_val_samples, n_features)
                 Validation object-feature matrix.
        val_y_ : array-like, shape (n_val_samples,)
                 Target vector relative to val_X_.
        Returns
        -------
        self : object
            Returns self.
        """
        self.parse_params()

        self.logger = logging.Logging(self.verbose, self.watched_metrics, log_w_norm=True)
        if np.abs(self.reg) > 1e-10 and self.logger.disp():
            print('WARNING: reg parameter means different things for different solvers.\n'
                  'Riemannian-sgd assumes L2 regularization in terms of the tensor w:\n'
                  '\treg * <w, w> / 2\n'
                  'while sgd solver assumes regularization in terms of the cores elements:\n'
                  '\treg * <w.core, w.core> / 2\n')

        if self.persuit_init and self.coef0 is not None:
            if self.logger.disp():
                print('WARNING: persuit_init parameter is not compatible with '
                      'explicitly providing initial values.')

        # TODO: deal with sparse data.
        # Copy the dataset, since preprocessing changes user's data, which is messy.
        X = deepcopy(X_)
        y = deepcopy(y_)
        X, y, self.info = self.preprocess(X, y)
        if val_X_ is not None and val_y_ is not None:
            val_X = deepcopy(val_X_)
            val_y = deepcopy(val_y_)
            val_X, val_y, self.info = self.preprocess(val_X, val_y, self.info)
        else:
            val_X, val_y = None, None
        if self.coef0 is None:
            self.coef_, self.intercept_ = self.linear_init(X, y)
            # Convert coefficients of linear model into the TT-format.
            self.coef_ = self.tensorize_linear_init(self.coef_, self.intercept_)
            if self.rank < max(self.coef_.r):
                # Decrease rank if necessary.
                self.coef_ = self.coef_.round(eps=0, rmax=self.rank)
            # Once we incorporated the intercept in coef, we don't need to have it
            # separately.
            self.intercept_ = 0
            # Increase the rank up to the desired one.
            if self.persuit_init and self.solver != 'riemannian-sgd':
                self.persuit_init = False
                if self.logger.disp():
                    print('WARNING: persuit_init is supported only by the riemannian-sgd solver')
            if self.persuit_init:
                if self.solver == 'riemannian-sgd':
                    from optimizers.riemannian_sgd import increase_rank
                    self.coef_ = increase_rank(self.coef_, self.rank, X, y,
                                               self.tt_dot, self.loss, self.loss_grad,
                                               self.project, self.object_tensor,
                                               self.reg)
            else:
                n = self.coef_.n
                for _ in range(self.rank - max(self.coef_.r)):
                    self.coef_ = self.coef_ + 0 * tt.ones(n)
                self.coef_ = self.coef_.round(eps=0)
            assert(max(self.coef_.r) == self.rank)
        else:
            self.coef_ = self.coef0
            self.intercept_ = self.intercept0
            if self.intercept_ is None:
                self.intercept_ = 0

        if self.solver == 'riemannian-sgd':
            from optimizers.riemannian_sgd import riemannian_sgd
            w, b = riemannian_sgd(X, y, self.tt_dot, self.loss, self.loss_grad,
                                  self.project, w0=self.coef_,
                                  intercept0=self.intercept_,
                                  fit_intercept=self.fit_intercept,
                                  val_x=val_X, val_y=val_y,
                                  reg=self.reg, exp_reg=self.exp_reg,
                                  dropout=self.dropout,
                                  batch_size=self.batch_size,
                                  num_passes=self.max_iter,
                                  logger=self.logger, verbose_period=1,
                                  beta=0.5, rho=0.1)
            self.coef_, self.intercept_ = w, b
        elif self.solver == 'sgd':
            if self.dropout is not None:
                print('WARNING: dropout for "sgd" solver is not supported.')

            from optimizers.core_sgd import core_sgd
            w, b = core_sgd(X, y, self.tt_dot, self.loss, self.loss_grad,
                            self.gradient_wrt_cores, w0=self.coef_,
                            intercept0=self.intercept_,
                            fit_intercept=self.fit_intercept,
                            val_x=val_X, val_y=val_y, reg=self.reg,
                            batch_size=self.batch_size,
                            num_passes=self.max_iter,
                            logger=self.logger, verbose_period=1,
                            beta=0.5, rho=0.1)
            self.coef_, self.intercept_ = w, b
        else:
            raise ValueError("Only 'riemannian-sgd' and 'sgd' solvers are supported.")
        return self
コード例 #29
0
ファイル: tt_aux.py プロジェクト: ion-g-ion/paper-cme-tt
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
コード例 #30
0
 def create_generator():
     for i in range(P):
         yield i*tt.ones([1])
コード例 #31
0
def subset_tensor(x):
    tens = tt.ones(2 * np.ones(len(x)))
    tens.core[range(1, 2 * len(x), 2)] = x
    return tens
コード例 #32
0
ファイル: test_cross.py プロジェクト: Bihaqo/ttpy
import sys
sys.path.append('../')
import numpy as np
import tt

d = 30
n = 2 ** d
b = 1E3
h = b / (n + 1)
#x = np.arange(n)
#x = np.reshape(x, [2] * d, order = 'F')
#x = tt.tensor(x, 1e-12)
x = tt.xfun(2, d)
e = tt.ones(2, d)
x = x + e
x = x * h 


sf = lambda x : np.sin(x) / x #Should be rank 2

y = tt.multifuncrs([x], sf, 1e-6, ['y0', tt.ones(2, d)])
#y1 = tt.tensor(sf(x.full()), 1e-8)

print "pi / 2 ~ ", tt.dot(y, tt.ones(2, d)) * h
#print (y - y1).norm() / y.norm()
コード例 #33
0
    #------------------building 3d laplacian matrix in TT-format with TT-kronecker product------------------
    
    L_qtt = tt.kron(tt.kron(L_qtt,Identity_qtt),Identity_qtt)+tt.kron(tt.kron(Identity_qtt,L_qtt),Identity_qtt)+tt.kron(tt.kron(Identity_qtt,Identity_qtt),L_qtt)
  
    # #adding boundary matrix to laplacian matrix
    L_qtt = L_qtt+Lbd_qtt
    
    # #matrix-vector multiplication to maintain f and g and sum both to get the complete righside b
    b1_qtt = tt.matvec(Lf_qtt,f1_qtt) + tt.matvec(Lbd_qtt,g1_qtt)
    b2_qtt = tt.matvec(Lf_qtt,f2_qtt) + tt.matvec(Lbd_qtt,g2_qtt)
    

    #------------------solving higher order linear system in TT-format------------------
    
    #defining initial guess vector
    x_qtt= tt.ones(2,int(np.log2(n+1)*(d)))

    #solving the higher order linear system with AMEN
    print("")
    print("Solving Problem 1 with AMEN")
    print("")
    u1_qtt=amen_solve(L_qtt,b1_qtt,x_qtt,1e-10,nswp=100)
    
    time.sleep(0.01)
    print("")
    print("Solving Problem 2 with AMEN")
    print("")
    u2_qtt=amen_solve(L_qtt,b2_qtt,x_qtt,1e-10,nswp=100)
    u2_qtt=u2_qtt.round(1e-10,8)

    #------------------calculating RMS-Error for the Solution------------------
コード例 #34
0
def initial_cond(T0, dx, dt):
    return T0*tt.ones(2, 3*dx+dt)
コード例 #35
0
#!/usr/bin/env python2
#   test_common.py
#   See LICENSE for details
"""Test common matrix operation with QTT-toolbox like matmat-operation and matvec-operation.
"""

from __future__ import print_function, absolute_import, division
import numpy as np
import sys

sys.path.append('../')

import tt

x = tt.xfun(2, 3)
e = tt.ones(2, 2)
X = tt.matrix(x, n=[2] * 3, m=[1] * 3)  # [0, 1, 2, 3, 4, 5, 6, 7]^T
E = tt.matrix(e, n=[1] * 2, m=[2] * 2)  # [1, 1, 1, 1]
#[[ 0.  0.  0.  0.]
# [ 1.  1.  1.  1.]
# [ 2.  2.  2.  2.]
# [ 3.  3.  3.  3.]
# [ 4.  4.  4.  4.]
# [ 5.  5.  5.  5.]
# [ 6.  6.  6.  6.]
# [ 7.  7.  7.  7.]]
print((X * E).full())
assert np.all((X * E) * np.arange(4) == np.arange(8) * 6.)

A = tt.matrix(tt.xfun(2, 3), n=[1] * 3, m=[2] * 3)
u = np.arange(8)
コード例 #36
0
ファイル: riemannian_sgd.py プロジェクト: Bihaqo/exp-machines
def build_reg_tens(n, exp_reg):
    reg_tens = tt.ones(n)
    reg_tens.core[1::2] = exp_reg
    return reg_tens
コード例 #37
0
    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
コード例 #38
0
ファイル: all_subsets.py プロジェクト: Bihaqo/exp-machines
def subset_tensor(x):
    tens = tt.ones(2 * np.ones(len(x)))
    tens.core[range(1, 2*len(x), 2)] = x
    return tens
コード例 #39
0
ファイル: test_amen.py プロジェクト: shartser-leonid/general
#%%
from __future__ import print_function, absolute_import, division
import sys
sys.path.append('../')
import tt
from tt.amen import amen_solve
""" This program test two subroutines: matrix-by-vector multiplication
    and linear system solution via AMR scheme"""

d = 12
A = tt.qlaplace_dd([d])
x = tt.ones(2,d)
y = amen_solve(A,x,x,1e-6)

#%%

c = tt.multifuncrs2([a, b], lambda x: np.sum(x, axis=1), eps=1E-6)

y = amen_solve(A,x,x,1e-6)


# %%
y
# %%
A
# %%
x
# %%
z=tt.matvec(A,x)
# %%
z
コード例 #40
0
ファイル: tt_reshape.py プロジェクト: kharyuk/ttpy
def tt_reshape(tt_array, shape, eps=1e-14, rl=1, rr=1):
    ''' Reshape of the TT-tensor
       [TT1]=TT_RESHAPE(TT,SZ) reshapes TT-tensor or TT-matrix into another 
       with mode sizes SZ, accuracy 1e-14

       [TT1]=TT_RESHAPE(TT,SZ,EPS) reshapes TT-tensor/matrix into another with
       mode sizes SZ and accuracy EPS
       
       [TT1]=TT_RESHAPE(TT,SZ,EPS, RL) reshapes TT-tensor/matrix into another 
       with mode size SZ and left tail rank RL

       [TT1]=TT_RESHAPE(TT,SZ,EPS, RL, RR) reshapes TT-tensor/matrix into 
       another with mode size SZ and tail ranks RL*RR
       Reshapes TT-tensor/matrix into a new one, with dimensions specified by SZ.

       If the input is TT-matrix, SZ must have the sizes for both modes, 
       so it is a matrix if sizes d2-by-2.
       If the input is TT-tensor, SZ may be either a column or a row vector.
    '''
    tt1 = deepcopy(tt_array)
    sz = deepcopy(shape)
    ismatrix = False
    if isinstance(tt1, tt.matrix):
        d1 = tt1.tt.d
        d2 = sz.shape[0]
        ismatrix = True
        # The size should be [n,m] in R^{d x 2}
        restn2_n = sz[:, 0]
        restn2_m = sz[:, 1]
        sz_n = copy(sz[:, 0])
        sz_m = copy(sz[:, 1])
        n1_n = tt1.n
        n1_m = tt1.m    
        sz = np.prod(sz, axis = 1) # We will split/convolve using the vector form anyway
        tt1 = tt1.tt
    else:
        d1 = tt1.d
        d2 = len(sz)


    # Recompute sz to include r0,rd,
    # and the items of tt1

    sz[0] = sz[0] * rl
    sz[d2-1] = sz[d2-1] * rr
    tt1.n[0] = tt1.n[0] * tt1.r[0]
    tt1.n[d1-1] = tt1.n[d1-1] * tt1.r[d1]
    if ismatrix: # in matrix: 1st tail rank goes to the n-mode, last to the m-mode
        restn2_n[0] = restn2_n[0] * rl
        restn2_m[d2-1] = restn2_m[d2-1] * rr
        n1_n[0] = n1_n[0] * tt1.r[0]
        n1_m[d1-1] = n1_m[d1-1] * tt1.r[d1]

    tt1.r[0] = 1
    tt1.r[d1] = 1

    n1 = tt1.n

    assert np.prod(n1) == np.prod(sz), 'Reshape: incorrect sizes'

    needQRs = False
    if d2 > d1:
        needQRs = True

    if d2 <= d1:
        i2 = 0
        n2 = sz
        for i1 in xrange(d1):
            if n2[i2] == 1:
                i2 = i2 + 1
                if i2 > d2:
                    break
            if n2[i2] % n1[i1] == 0:
                n2[i2] = n2[i2] / n1[i1]
            else:
                needQRs = True
                break

    r1 = tt1.r
    tt1 = tt1.to_list(tt1)

    if needQRs: # We have to split some cores -> perform QRs
        for i in xrange(d1-1, 0, -1):
            cr = tt1[i]
            cr = np.reshape(cr, (r1[i], n1[i]*r1[i+1]), order = 'F')
            [cr, rv] = np.linalg.qr(cr.T) # Size n*r2, r1new - r1nwe,r1
            cr0 = tt1[i-1]
            cr0 = np.reshape(cr0, (r1[i-1]*n1[i-1], r1[i]), order = 'F')
            cr0 = np.dot(cr0, rv.T) # r0*n0, r1new
            r1[i] = cr.shape[1]        
            cr0 = np.reshape(cr0, (r1[i-1], n1[i-1], r1[i]), order = 'F')
            cr = np.reshape(cr.T, (r1[i], n1[i], r1[i+1]), order = 'F')
            tt1[i] = cr
            tt1[i-1] = cr0  

    r2 = np.ones(d2 + 1)
        
    i1 = 0 # Working index in tt1
    i2 = 0 # Working index in tt2
    core2 = np.zeros((0))
    curcr2 = 1
    restn2 = sz
    n2 = np.ones(d2)
    if ismatrix:
        n2_n = np.ones(d2)
        n2_m = np.ones(d2)

    while i1 < d1:
        curcr1 = tt1[i1]    
        if gcd(restn2[i2], n1[i1]) == n1[i1]:
            # The whole core1 fits to core2. Convolve it
            if (i1 < d1-1) and (needQRs): # QR to the next core - for safety
                curcr1 = np.reshape(curcr1, (r1[i1]*n1[i1], r1[i1+1]), order = 'F')
                [curcr1, rv] = np.linalg.qr(curcr1)
                curcr12 = tt1[i1+1]
                curcr12 = np.reshape(curcr12, (r1[i1+1], n1[i1+1]*r1[i1+2]), order = 'F')
                curcr12 = np.dot(rv, curcr12)
                r1[i1+1] = curcr12.shape[0]
                tt1[i1+1] = np.reshape(curcr12, (r1[i1+1], n1[i1+1], r1[i1+2]), order = 'F')
            # Actually merge is here
            curcr1 = np.reshape(curcr1, (r1[i1], n1[i1]*r1[i1+1]), order = 'F')
            curcr2 = np.dot(curcr2, curcr1) # size r21*nold, dn*r22        
            if ismatrix: # Permute if we are working with tt_matrix
                curcr2 = np.reshape(curcr2, (r2[i2], n2_n[i2], n2_m[i2], n1_n[i1], n1_m[i1], r1[i1+1]), order = 'F')
                curcr2 = np.transpose(curcr2, [0, 1, 3, 2, 4, 5])
                # Update the "matrix" sizes            
                n2_n[i2] = n2_n[i2]*n1_n[i1]
                n2_m[i2] = n2_m[i2]*n1_m[i1]
                restn2_n[i2] = restn2_n[i2] / n1_n[i1]
                restn2_m[i2] = restn2_m[i2] / n1_m[i1]
            r2[i2+1] = r1[i1+1]
            # Update the sizes of tt2
            n2[i2] = n2[i2]*n1[i1]
            restn2[i2] = restn2[i2] / n1[i1]
            curcr2 = np.reshape(curcr2, (r2[i2]*n2[i2], r2[i2+1]), order = 'F')
            i1 = i1+1 # current core1 is over
        else:
            if (gcd(restn2[i2], n1[i1]) !=1 ) or (restn2[i2] == 1):
                # There exists a nontrivial divisor, or a singleton requested
                # Split it and convolve
                n12 = gcd(restn2[i2], n1[i1])
                if ismatrix: # Permute before the truncation
                    # Matrix sizes we are able to split
                    n12_n = gcd(restn2_n[i2], n1_n[i1])
                    n12_m = gcd(restn2_m[i2], n1_m[i1])
                    curcr1 = np.reshape(curcr1, (r1[i1], n12_n, n1_n[i1] / n12_n, n12_m, n1_m[i1] / n12_m, r1[i1+1]), order = 'F')
                    curcr1 = np.transpose(curcr1, [0, 1, 3, 2, 4, 5])
                    # Update the matrix sizes of tt2 and tt1
                    n2_n[i2] = n2_n[i2]*n12_n
                    n2_m[i2] = n2_m[i2]*n12_m
                    restn2_n[i2] = restn2_n[i2] / n12_n
                    restn2_m[i2] = restn2_m[i2] / n12_m
                    n1_n[i1] = n1_n[i1] / n12_n
                    n1_m[i1] = n1_m[i1] / n12_m
                
                curcr1 = np.reshape(curcr1, (r1[i1]*n12, (n1[i1]/n12)*r1[i1+1]), order = 'F')
                [u,s,v] = np.linalg.svd(curcr1, full_matrices = False)
                r = my_chop2(s, eps*np.linalg.norm(s)/(d2-1)**0.5)
                u = u[:, :r]
                v = v.T
                v = v[:, :r]*s[:r]
                u = np.reshape(u, (r1[i1], n12*r), order = 'F')
                # u is our admissible chunk, merge it to core2
                curcr2 = np.dot(curcr2, u) # size r21*nold, dn*r22
                r2[i2+1] = r
                # Update the sizes of tt2
                n2[i2] = n2[i2]*n12
                restn2[i2] = restn2[i2] / n12
                curcr2 = np.reshape(curcr2, (r2[i2]*n2[i2], r2[i2+1]), order = 'F')
                r1[i1] = r
                # and tt1
                n1[i1] = n1[i1] / n12
                # keep v in tt1 for next operations
                curcr1 = np.reshape(v.T, (r1[i1], n1[i1], r1[i1+1]), order = 'F')
                tt1[i1] = curcr1
            else:
                # Bad case. We have to merge cores of tt1 until a common divisor appears
                i1new = i1+1
                curcr1 = np.reshape(curcr1, (r1[i1]*n1[i1], r1[i1+1]), order = 'F')
                while (gcd(restn2[i2], n1[i1]) == 1) and (i1new < d1):
                    cr1new = tt1[i1new]
                    cr1new = np.reshape(cr1new, (r1[i1new], n1[i1new]*r1[i1new+1]), order = 'F')
                    curcr1 = np.dot(curcr1, cr1new) # size r1(i1)*n1(i1), n1new*r1new
                    if ismatrix: # Permutes and matrix size updates
                        curcr1 = np.reshape(curcr1, (r1[i1], n1_n[i1], n1_m[i1], n1_n[i1new], n1_m[i1new], r1[i1new+1]), order = 'F')
                        curcr1 = np.transpose(curcr1, [0, 1, 3, 2, 4, 5])
                        n1_n[i1] = n1_n[i1]*n1_n[i1new]
                        n1_m[i1] = n1_m[i1]*n1_m[i1new]
                    n1[i1] = n1[i1]*n1[i1new]
                    curcr1 = np.reshape(curcr1, (r1[i1]*n1[i1], r1[i1new+1]), order = 'F')
                    i1new = i1new+1
                # Inner cores merged => squeeze tt1 data
                n1 = np.concatenate((n1[:i1], n1[i1new:]))
                r1 = np.concatenate((r1[:i1], r1[i1new:]))
                tt1[i] = np.reshape(curcr1, (r1[i1], n1[i1], r1[i1new]), order = 'F')
                tt1 = tt1[:i1] + tt1[i1new:]
                d1 = len(n1)
        
        if (restn2[i2] == 1) and ((i1 >= d1) or ((i1 < d1) and (n1[i1] != 1))):
            # The core of tt2 is finished
            # The second condition prevents core2 from finishing until we 
            # squeeze all tailing singletons in tt1.
            curcr2 = curcr2.flatten(order = 'F')
            core2 = np.concatenate((core2, curcr2))
            i2 = i2+1
            # Start new core2
            curcr2 = 1

    # If we have been asked for singletons - just add them
    while (i2 < d2):
        core2 = np.concatenate((core2, np.ones(1)))
        r2[i2] = 1
        i2 = i2+1

    tt2 = tt.ones(2, 1) # dummy tensor
    tt2.d = d2
    tt2.n = n2
    tt2.r = r2
    tt2.core = core2
    tt2.ps = np.cumsum(np.concatenate((np.ones(1), r2[:-1] * n2 * r2[1:])))


    tt2.n[0] = tt2.n[0] / rl
    tt2.n[d2-1] = tt2.n[d2-1] / rr
    tt2.r[0] = rl
    tt2.r[d2] = rr

    if ismatrix:
        ttt = tt.eye(1,1) # dummy tt matrix
        ttt.n = sz_n
        ttt.m = sz_m
        ttt.tt = tt2
        return ttt
    else:
        return tt2
コード例 #41
0
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)),
コード例 #42
0
ファイル: test_cross.py プロジェクト: oseledets/ttpy
from __future__ import print_function, absolute_import, division
import sys
sys.path.append('../')
import numpy as np
import tt

d = 30
n = 2 ** d
b = 1E3
h = b / (n + 1)
#x = np.arange(n)
#x = np.reshape(x, [2] * d, order = 'F')
#x = tt.tensor(x, 1e-12)
x = tt.xfun(2, d)
e = tt.ones(2, d)
x = x + e
x = x * h


sf = lambda x : np.sin(x) / x #Should be rank 2

y = tt.multifuncrs([x], sf, 1e-6, y0=tt.ones(2, d))
#y1 = tt.tensor(sf(x.full()), 1e-8)

print("pi / 2 ~ ", tt.dot(y, tt.ones(2, d)) * h)
#print (y - y1).norm() / y.norm()