示例#1
0
def t0():
    # Incoming quark mom
    p1 = 0
    p2 = 0
    p3 = Symbol('p', real=True)
    p0 = p3
    p  = tensor1d([p0,p1,p2,p3],'mu')

    # Transverse (w.r.t p) component k_t of daughter momenta (spacelike)
    kt1 = 0
    kt2 = Symbol('kt', real=True)
    kt3 = 0
    kt0 = 0
    kt  = tensor1d([kt0,kt1,kt2,kt3],'mu')

    # Auxiliary light-like vector transverse to k_t
    n1  = Symbol('n', real=True)
    n2  = 0
    n3  = 0
    n0  = n1
    n   = tensor1d([n0,n1,n2,n3],'mu')

    # Longitudinal momentum fraction
    z   = tensor([Symbol('z', real=True)], None)
    omz = tensor([1.0 - Symbol('z', real=True)], None)
    
    # Outgoing quark momentum
    pa  =   z*p + kt - tensor([(kt2**2)], None)/  z* n/(2.0*n1*p3)

    # Outgoing gluon momentum
    pb  = omz*p - kt - tensor([(kt2**2)], None)/omz* n/(2.0*n1*p3)
    
    # Outgoing gluon reference mom
    g1 = Symbol('g1', real=True)
    g2 = Symbol('g2', real=True)
    g3 = Symbol('g3', real=True)
    g0 = sqrt(g1**2+g2**2+g3**2)

    m2 = (uminusbar(pb._array[0]._array[0],
                    pb._array[1]._array[0],
                    pb._array[2]._array[0],
                    pb._array[3]._array[0],'a')*
          Gamma('mu','a','b')*
          uplus(p0,p1,p2,p3,'b')*mink_metric('mu','nu')*
          conjugate_tensor1d(epsilonplus(pa._array[0]._array[0],
                                         pa._array[1]._array[0],
                                         pa._array[2]._array[0],
                                         pa._array[3]._array[0], 'nu', g0,g1,g2,g3)))

    M2 = m2._array[0]*cgt(m2._array[0])

    m2 = m2._array[0].simplify()

    from sympy import Q, refine, Abs
    from sympy.assumptions.refine import refine_abs
    
    from IPython import embed
    m2 =refine_abs(m2, Q.real(z._array[0]))
    embed()
示例#2
0
    def totensor(self):
        sz = self.tsize
        order = numpy.concatenate((self.rindices, self.cindices))
        order = order.tolist()
        data = self.data.reshape(tools.getelts(sz, order))

        data = tensor.tensor(data).ipermute(order).data

        return tensor.tensor(data, sz)
示例#3
0
    def totensor(self):
        sz = self.tsize;
        order = numpy.concatenate((self.rindices, self.cindices));
        order = order.tolist();
        data = self.data.reshape(tools.getelts(sz,order));

        data = tensor.tensor(data).ipermute(order).data;

        return tensor.tensor(data, sz);
示例#4
0
def boardcast(data1,data2):
    data1=ts.tensor(data1)
    data2=ts.tensor(data2)
    try:
        return expand(data1,data2.size()),data2
    except:
        try:
            return data1,expand(data2,data1.size())
        except:
            raise ValueError('can not boardcast with size %s and %s'%(data1.size(),data2.size()))
示例#5
0
 def convolve(self, h, idx):
     obj = t.tensor(self)
     if isinstance(h, t.tensor): h = h.arr
     N = obj.len(idx)
     obj.transpose([obj.index(idx), 0])
     z = zeros(obj.arr.shape) 
     obj.arr = append(obj.arr, z, axis=0)
     obj.transpose([obj.index(idx), -1],opt=True)
     X = fft.rfft(obj.arr)
     H = fft.rfft(append(h, zeros(2*N - h.size)))
     return t.tensor(fft.irfft(X*H)[0:N], obj.idx, obj.ud)
示例#6
0
    def __init__(self,i,n):
        # our inde scheme starts at 0, so subtract 1 from n
        # when naming the momenta
        k = n-1
        il = lorentz_key(i) if (i<0) else i
        p_str = "p{0}[{1}]"
        array = [tensor([c_variable(p_str.format(k,vect_gauge_dict[0]))], None), 
                 tensor([c_variable(p_str.format(k,vect_gauge_dict[1]))], None), 
                 tensor([c_variable(p_str.format(k,vect_gauge_dict[2]))], None), 
                 tensor([c_variable(p_str.format(k,vect_gauge_dict[3]))], None)]

        super(P,self).__init__(array,il)
示例#7
0
    def __init__(self, i, n):
        # our inde scheme starts at 0, so subtract 1 from n
        # when naming the momenta
        k = n - 1
        il = lorentz_key(i) if (i < 0) else i
        p_str = "p{0}[{1}]"
        array = [
            tensor([c_variable(p_str.format(k, vect_gauge_dict[0]))], None),
            tensor([c_variable(p_str.format(k, vect_gauge_dict[1]))], None),
            tensor([c_variable(p_str.format(k, vect_gauge_dict[2]))], None),
            tensor([c_variable(p_str.format(k, vect_gauge_dict[3]))], None)
        ]

        super(P, self).__init__(array, il)
示例#8
0
    def __init__(self, i, n):
        # our inde scheme starts at 0, so subtract 1 from n
        # when naming the momenta
        k = n - 1
        il = lorentz_key(i) if (i < 0) else i
        p_str = "p{0}{1}"
        array = [
            tensor([parse_expr(p_str.format(k, 0))], None),
            tensor([parse_expr(p_str.format(k, 1))], None),
            tensor([parse_expr(p_str.format(k, 2))], None),
            tensor([parse_expr(p_str.format(k, 3))], None)
        ]

        super(P, self).__init__(array, il)
示例#9
0
    def compute_materialtangent(self):
        # =============================================================================================
        #%% Compute error on material tangent operator by finite (central) difference of stress
        # =============================================================================================
        d = self.FE_model.dim
        DC = 1.e-5
        TOLMAX = 1.e-3
        PRECISION = 1.e-16
        printerror = False
        e = 1  # element
        KerrMax = 1e-30
        for e in range(self.FE_model.nElements()):
            Ed = self.E[e].reshape(d, d)  # Lagrange deformation
            Cd = 2 * Ed + tensor.I(d)  # right Cauchy-Green tensor
            Sp = tensor.tensor(d)  # S(C+DC/2) Piola Kirchhoff II tensor "plus"
            # S(C-DC/2) Piola Kirchhoff II tensor "minus"
            Sm = tensor.tensor(d)
            S = self.FE_model.material.stress(Cd)
            # Lagrangian tangent operator 2*dS/dC
            M = self.FE_model.material.stiffness(Cd)

            for k in range(d):
                for l in range(d):
                    Cd[k, l] += DC / 2.
                    Sp = self.FE_model.material.stress(Cd)

                    Cd[k, l] -= DC
                    Sm = self.FE_model.material.stress(Cd)

                    Cd[k, l] += DC / 2.  # come back to before perturbation
                    for i in range(d):
                        for j in range(d):
                            Knum = (Sp[i, j] - Sm[i, j] + Sp[j, i] -
                                    Sm[j, i]) / DC  # 2*(Sp-Sm + Sp-Sm)/2/DC
                            # K_ijkl = ( S_ij(C_kl+DC/2) - S_ji(C_kl-DC/2) ) SYM
                            if (np.fabs(M[i, j, k, l]) > 1.0):
                                Ktest = np.fabs(M[i, j, k, l])
                            else:
                                Ktest = 1.0
                            Kerr = np.fabs(M[i, j, k, l] - Knum) / Ktest
                            if (Kerr > KerrMax):
                                KerrMax = Kerr
                            if (printerror) and (Kerr > TOLMAX) and (np.fabs(Knum) > PRECISION):
                                print('%d %d %d %d %13.6e %13.6e %13.6e' %
                                      (i, j, k, l, M[i, j, k, l], Knum, Kerr))
        # print('Maximal error = %13.6e' % KerrMax)
        if KerrMax > TOLMAX:
            msg = "Material tangent not valided: KerrMax = %.2e" % KerrMax
            raise Exception(msg)
示例#10
0
 def stress(self, C):
     """
     Compute 2nd Piola-Kirchhoff stress
     PK2 = 2*dphi/dC
         = lambda * tr(E) * I + 2 * mu * E
     """
     dim = len(C)
     PK2 = tensor.tensor(dim)
     lamda = self.get1LAME()
     mu = self.get2LAME()
     E = tensor.tensor(dim)
     E = 0.5 * (C - tensor.I(dim))
     II = tensor.I(dim)
     PK2 = lamda * tensor.trace(E) * II + 2 * mu * E
     return PK2
示例#11
0
 def m_1Inner(b):
     b = b[1].clean()
     answer = tensor()
     if b.degree() != 0:
         for i in range(b.degree()):
             answer += b.coefficient * pureTensor([b[0:i],b[i],b[i+1:]])
     return answer
示例#12
0
def ctor(verbose):

    dat = numpy.arange(24).reshape([2, 3, 4])

    t = tensor.tensor(dat)
    print t
    if (verbose):
        obj = tenmat.tenmat(t, [1, 0])
        print obj
        print obj.copy()

    dat = dat.reshape([4, 6])
    t = tensor.tensor(dat)
    if (verbose):
        obj = tenmat.tenmat(t, [0], [1], [4, 6])
        print obj
示例#13
0
 def getStrainEulerAlmansi(self, n):
     """ Return average of EA strain at all integration points of element n"""
     avg = tensor.tensor(self.dim)
     for tens in self.elems[n].E_EA:
         avg += tens
     avg /= self.elems[n].getNIntPts()
     return avg
示例#14
0
 def mov_ave(self, wid, dx, idx, fs):
     f =  fft.rfftfreq(self.len(idx), float(fs))
     L = int(float(wid) / float(dx))
     H = ((sin(pi *  f * L / fs) / sin(pi * f / fs)) * exp(-1j * pi * f * (L-1) / fs)) / L
     H[0] = 1.
     X = self.rfft(idx).arr * H
     return t.tensor(fft.irfft(X), self.idx, self.ud)
示例#15
0
def ctor(verbose):
    
    dat = numpy.arange(24).reshape([2,3,4]);
    
    t = tensor.tensor(dat);
    print t;
    if (verbose):
        obj = tenmat.tenmat(t, [1,0]);
        print obj;
        print obj.copy();
        
    dat = dat.reshape([4,6]);
    t = tensor.tensor(dat);
    if (verbose):
        obj = tenmat.tenmat(t, [0], [1], [4,6]);
        print obj;
示例#16
0
 def tensorProduct(self,other):
     """Add other as a component(s) on the right of self. e.g. (a|b).tensorProduct(c) = a|b|c"""
     if type(other) in [relation.relation,doublyDefined.doublyDefined,coefficient.coefficient, str, float, int, monomial.monomial]:
         return self.tensorProduct(pureTensor(other))
     if not isinstance(other,pureTensor):
         return reduce(lambda x,y: x+y, [self.tensorProduct(z) for z in other], tensor.tensor())
     return pureTensor(self.monomials + other.monomials, self.coefficient * other.coefficient)
示例#17
0
 def i_3Inner(pT):
     answer = tensor()
     doublyDefined = pT[1]
     for generator, rel in doublyDefined.leftHandRepresentation:
         rightHandSide = generator * i_2(pureTensor([1,rel,1]),alg)
         answer = answer + pureTensor(1).tensorProduct(rightHandSide)
     return answer
示例#18
0
def generateNeighborInteractions(interaction_vector):
    """
      Generate the interaction between two sites
      interaction_vector (list): A list of length (num_qubits) with 1 on index i if the 
                                 site is a constituent of the interaction. For example, 
                                 for interaction between site 1 and 2 in a 4 qubit system, 
                                 the vector would be,[1, 1, 0, 0] and for stie 1 and 3, [1, 0, 1, 0]
    """
    pauli_z = tensor(2, {(0, 0): 1, (1, 1): -1})
    id = tensor(2, {(0, 0): 1, (1, 1): 1})

    _tensor = pauli_z if interaction_vector[0] == 1 else id
    for site_i in interaction_vector[1:]:
        field = pauli_z if site_i == 1 else id
        _tensor = _tensor.tensor_prod(field)
    return _tensor
示例#19
0
 def i_2Inner(pT):
     answer = tensor()
     rel = pT[1]
     for term in rel.leadingMonomial:
         answer = answer + term.coefficient * pureTensor((1,term[0],term[1],1))
     for term in rel.lowerOrderTerms:
         answer = answer - term.coefficient * pureTensor((1,term[0],term[1],1))
     return answer
示例#20
0
 def k_4Inner(pT):
     answer= tensor()
     doublyDefined = pT[1]
     for generator, rel in doublyDefined.leftHandRepresentation:
         answer = answer + pureTensor((generator,rel,1)).clean()
     for rel, generator in doublyDefined.rightHandRepresentation:
         answer = answer - pureTensor((1,rel,generator)).clean()
     return answer
示例#21
0
def totensorTests(verbose):
    
    dat = numpy.arange(24).reshape([2,3,4]);
    t = tensor.tensor(dat);
    obj = tenmat.tenmat(t,[2,1]);
    if(verbose):
        print obj;
        print obj.totensor();
示例#22
0
def totensorTests(verbose):

    dat = numpy.arange(24).reshape([2, 3, 4])
    t = tensor.tensor(dat)
    obj = tenmat.tenmat(t, [2, 1])
    if (verbose):
        print obj
        print obj.totensor()
示例#23
0
 def getStrainGreenLagrange(self, n):
     """
     Return average of GL strain at all integration points of element n
     """
     avg = tensor.tensor(self.dim)
     for tens in self.elems[n].E_GL:
         avg += tens
     avg /= self.elems[n].getNIntPts()
     return avg
示例#24
0
 def getStrainHencky(self, n):
     """
     Return average of hencky strain at all integration points of element n
     """
     avg = tensor.tensor(self.dim)
     for tens in self.elems[n].hencky:
         avg += tens
     avg /= self.elems[n].getNIntPts()
     return avg
示例#25
0
 def getStressPK1(self, n):
     """
     Return average of PK1 stress at all integration points of element n
     """
     avg = tensor.tensor(self.dim)
     for tens in self.elems[n].PK1:
         avg += tens
     avg /= self.elems[n].getNIntPts()
     return avg
示例#26
0
 def getDeformationGradient(self, n):
     """
     Return average of deformation gradient at all integration points of element n
     """
     avg = tensor.tensor(self.dim)
     for tens in self.elems[n].F:
         avg += tens
     avg /= self.elems[n].getNIntPts()
     return avg
示例#27
0
 def listOfPolysToTensors(ps):
     ps = iter(ps)
     pureTensors = [pureTensor.pureTensor(mono) for mono in next(ps)]
     for poly in ps:
         newPureTensors = []
         for mono in poly:
             newPureTensors.extend([x.tensorProduct(mono) for x in pureTensors])
         pureTensors = newPureTensors
     return tensor.tensor(pureTensors)
示例#28
0
 def getStressCauchy(self, n):
     """
     Return average of cauchy stress at all integration points of element n
     """
     avg = tensor.tensor(self.dim)
     for tens in self.elems[n].sigma:
         avg += tens
     avg /= self.elems[n].getNIntPts()
     return avg
示例#29
0
def ctorTests(verbose):
    arr = numpy.arange(24).reshape([2,3,4]);
    A = numpy.array([[1,2],[3,4],[5,6]]);
    B = numpy.array([[1,2,3],[4,5,6]]);
    C = numpy.array([[1,2,3,4]]);
    
    obj = ttensor.ttensor(tensor.tensor(arr), [A, B, C]);
    print obj;
    print obj.shape;
示例#30
0
 def mtimes(self, B):
     tsize = numpy.hstack((self.tsize[self.rindices], B.tsize[B.cindices]))
     data = tensor.tensor([])
     C = tenmat2(data)
     C.rindices = numpy.array(range(0, len(self.rindices)))
     C.cindices = numpy.array(range(0, len(B.cindices))) + len(self.rindices)
     C.data = numpy.dot(self.data, B.data)
     C.tsize = tsize
     return C
示例#31
0
def ctorTests(verbose):
    arr = numpy.arange(24).reshape([2, 3, 4])
    A = numpy.array([[1, 2], [3, 4], [5, 6]])
    B = numpy.array([[1, 2, 3], [4, 5, 6]])
    C = numpy.array([[1, 2, 3, 4]])

    obj = ttensor.ttensor(tensor.tensor(arr), [A, B, C])
    print obj
    print obj.shape
示例#32
0
 def totensor(self):
     """returns a new tensor object that contains the same values"""
     temp = numpy.ndarray(self.shape);
     temp.fill(0);
     
     for i in range(0, len(self.vals)):
         temp.put(tools.sub2ind(self.shape, self.subs[i])[0], self.vals[i][0]);
     
     return tensor.tensor(temp, self.shape);
示例#33
0
def tosptensor(verbose):
    
    dat = numpy.array([1,2,3,4,5,6,7,8,9,10,0,0,13,14,15,16,17,18]);
    siz = numpy.array([3,3,2]);
    
    obj = tensor.tensor(dat, siz);
    if(verbose == 1):
        print obj;
        print (obj.tosptensor());
示例#34
0
 def totensor(self):
     """returns a new tensor object that contains the same values"""
     temp = numpy.ndarray(self.shape);
     temp.fill(0);
     
     for i in range(0, len(self.vals)):
         temp.put(tools.sub2ind(self.shape, self.subs[i])[0], self.vals[i][0]);
     
     return tensor.tensor(temp, self.shape);
示例#35
0
 def append(self, obj, idx):
     ## \brief Append a tensor to other tensor.
     self.same_trans(obj)    
     self.transpose([idx,0])
     obj.transpose([idx,0])
     if self.idx != obj.idx:
         raise ValueError, "Index is not much."
     ret = t.tensor(append(self.arr, obj.arr, axis=0), self.idx, self.ud)
     
     return ret
示例#36
0
 def form_factors_implementations(self, parameter_map):
     evaluated_form_factors = {}
     wrapped_parameter_map = {
         k: tensor([sym_var(Symbol(v, complex=True))], None)
         for k, v in parameter_map.items()
     }
     for k, v in self._form_factors.items():
         evaluated_form_factors[k] = eval(v, globals(),
                                          wrapped_parameter_map)
     return evaluated_form_factors
示例#37
0
def tosptensor(verbose):

    dat = numpy.array(
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 13, 14, 15, 16, 17, 18])
    siz = numpy.array([3, 3, 2])

    obj = tensor.tensor(dat, siz)
    if (verbose == 1):
        print obj
        print(obj.tosptensor())
示例#38
0
    def mov_grad(self, obj, wid, dx, idx, fs):
        x = obj
        y = self
        xy = x * y
        L = abs(int(float(wid)/float(dx))) 
        h = t.tensor(ones(L), idx, self.gud(idx))

        conv_x = x.convolve(h, idx)
        a = (L * xy.convolve(h, idx) - conv_x * y.convolve(h, idx)) / (L * (x**2).convolve(h, idx) - conv_x ** 2)
        return a
示例#39
0
def test2():
#    A = numpy.array([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]);
#    A = numpy.arange(12).reshape([4,3]) + 1;
    A = numpy.arange(1000).reshape([10,10,10])+1;
    (ans1, ans2) = DTA.DTA(tensor.tensor(A), [2,2,2]);
    print ans1;
    for i in range(0, len(ans2)):
        print "{0} th array\n {1}".format(i, ans2[i]);
        
    print ans1.totensor();
示例#40
0
def test2():
    #    A = numpy.array([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]);
    #    A = numpy.arange(12).reshape([4,3]) + 1;
    A = numpy.arange(1000).reshape([10, 10, 10]) + 1
    (ans1, ans2) = DTA.DTA(tensor.tensor(A), [2, 2, 2])
    print ans1
    for i in range(0, len(ans2)):
        print "{0} th array\n {1}".format(i, ans2[i])

    print ans1.totensor()
示例#41
0
    def ttv(self, v, dims):
        """ 
        Computes the product of this tensor with the column vector along
        specified dimensions.
        
        Parameters
        ----------
        v - column vector 
        d - dimensions to multiply the product

        Returns
        -------
        out : a sparse tensor if 50% or fewer nonzeros
        """

        (dims, vidx) = tools.tt_dimscheck(dims, self.ndims(), len(v))
        remdims = numpy.setdiff1d(range(self.ndims()), dims)
        newvals = self.vals
        subs = self.subs

        # Multiple each value by the appropriate elements of the appropriate vector
        for n in range(len(dims)):
            idx = subs[:, dims[n]]
            # extract indices for dimension n
            w = v[vidx[n]]
            # extract nth vector
            bigw = w[idx]
            # stretch out the vector
            newvals = numpy.multiply(newvals.flatten(), bigw)

        # Case 0: all dimensions specified - return the sum
        if len(remdims) == 0:
            c = numpy.sum(newvals)
            return c

        # Otherwise figure out the subscripts and accumulate the results
        newsubs = self.subs[:, remdims]
        newsiz = numpy.array(self.shape)[remdims]

        # Case 1: return a vector
        if len(remdims) == 1:
            c = tools.accum_np(newsubs, newvals, newsiz[0])
            #if numpy.count_nonzero(c) < 0.5*newsiz[0]:
            #    c = sptensor.sptensor(numpy.arange(newsiz[0]).reshape(newsiz[0],1), c.reshape(newsiz[0],1));
            #else:
            c = tensor.tensor(c, newsiz)
            return c

        # Case 2: result is a multi-way array
        c = sptensor.sptensor(newsubs, newvals.reshape(len(newvals), 1),
                              newsiz)
        # check to see if it's dense
        if c.nnz() > 0.5 * numpy.prod(c.shape):
            return c.totensor()
        return c
示例#42
0
 def k_2Inner(tens):
     assert isinstance(tens,pureTensor)
     answer= tensor()
     rel =tens.monomials[1]
     for i in rel.leadingMonomial:
         answer = answer + i.coefficient * pureTensor((i.submonomial(0,1),i.submonomial(1,2), 1))
         answer = answer + i.coefficient * pureTensor((1,i.submonomial(0,1),i.submonomial(1,2)))
     for i in rel.lowerOrderTerms:
         answer = answer - i.coefficient * pureTensor((i.submonomial(0,1),i.submonomial(1,2), 1))
         answer = answer - i.coefficient * pureTensor((1,i.submonomial(0,1),i.submonomial(1,2)))
     return answer
示例#43
0
def replacer_T(a, i, j):
    return sqrt(2.0) * tensor([
        T1(i, j),
        T2(i, j),
        T3(i, j),
        T4(i, j),
        T5(i, j),
        T6(i, j),
        T7(i, j),
        T8(i, j)
    ], a)
示例#44
0
def ctor(verbose):
    dat = numpy.arange(24);
    dat[10] = 100;
    dat[16] = -1;
    siz = numpy.array([4,3,2]);
    
    obj = tensor.tensor(dat, siz);
    if(verbose == 1):
        print obj;
        print obj.ndims();
    
    obj2 = tensor.tensor(dat.reshape([2,3,4]),siz);
    if(verbose == 1):
        print obj;
        print obj.shape;
    
    dat = numpy.array([1,2,3,4,5,6,7,8,9,10,0,0,13,14,15,16,17,18]);
    obj2 = tensor.tensor(dat);
    if(verbose == 1):
        print obj2;
        print obj2.shape;
示例#45
0
def T(a, i, j):
    """Fundamental representation matrices"""
    return tensor([
        T1(color_key(i, 'fu'), color_key(j, 'af')),
        T2(color_key(i, 'fu'), color_key(j, 'af')),
        T3(color_key(i, 'fu'), color_key(j, 'af')),
        T4(color_key(i, 'fu'), color_key(j, 'af')),
        T5(color_key(i, 'fu'), color_key(j, 'af')),
        T6(color_key(i, 'fu'), color_key(j, 'af')),
        T7(color_key(i, 'fu'), color_key(j, 'af')),
        T8(color_key(i, 'fu'), color_key(j, 'af'))
    ], color_key(a, 'ad'))
示例#46
0
def ttmTest(verbose):
    dat = numpy.arange(24).reshape([2,3,4]);
    siz = numpy.array([2,3,4]);
    obj = tensor.tensor(dat, siz);
    
    A = numpy.arange(18).reshape([6,3]);
    
    print obj.ttm(A,1);
    B = numpy.arange(12).reshape([3,4]);
    print obj.ttm([A,B],[1,2]);
    print "a";
    print obj.ttm([A.transpose(),B.transpose()],[1,2],'t');
示例#47
0
def ttmTest(verbose):
    dat = numpy.arange(24).reshape([2, 3, 4])
    siz = numpy.array([2, 3, 4])
    obj = tensor.tensor(dat, siz)

    A = numpy.arange(18).reshape([6, 3])

    print obj.ttm(A, 1)
    B = numpy.arange(12).reshape([3, 4])
    print obj.ttm([A, B], [1, 2])
    print "a"
    print obj.ttm([A.transpose(), B.transpose()], [1, 2], 't')
示例#48
0
 def m_2Inner(PT):
     assert isinstance(PT, pureTensor)
     assert len(PT) == 4
     PT = PT.clean()
     w = PT[1] * PT[2]
     answer = tensor()
     sequence = alg.makeReductionSequence(w)
     for reductionFunction, weight in sequence:
         answer += PT.coefficient * weight * PT[0] \
             * pureTensor([reductionFunction.leftMonomial,
                           reductionFunction.relation,
                           reductionFunction.rightMonomial]) * PT[3]
     return answer
示例#49
0
def mathlogicops(verbose):
    dat = numpy.arange(24).reshape([2, 3, 4])
    siz = numpy.array([2, 3, 4])
    obj = tensor.tensor(dat, siz)

    print obj + 100
    print obj - 100
    print obj + (obj + 10)
    print obj * 1.5
    print obj < 10
    print obj > 10l
    print obj == 10
    print obj == obj
示例#50
0
def ctor(verbose):
    dat = numpy.arange(24)
    dat[10] = 100
    dat[16] = -1
    siz = numpy.array([4, 3, 2])

    obj = tensor.tensor(dat, siz)
    if (verbose == 1):
        print obj
        print obj.ndims()

    obj2 = tensor.tensor(dat.reshape([2, 3, 4]), siz)
    if (verbose == 1):
        print obj
        print obj.shape

    dat = numpy.array(
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 13, 14, 15, 16, 17, 18])
    obj2 = tensor.tensor(dat)
    if (verbose == 1):
        print obj2
        print obj2.shape
示例#51
0
    def ttv(self, v, dims):
        """ 
        Computes the product of this tensor with the column vector along
        specified dimensions.
        
        Parameters
        ----------
        v - column vector 
        d - dimensions to multiply the product

        Returns
        -------
        out : a sparse tensor if 50% or fewer nonzeros
        """
        
        (dims, vidx) = tools.tt_dimscheck(dims, self.ndims(), len(v));
        remdims = numpy.setdiff1d(range(self.ndims()), dims);
        newvals = self.vals;
        subs = self.subs;
        
        # Multiple each value by the appropriate elements of the appropriate vector
        for n in range(len(dims)):
            idx = subs[:, dims[n]]; # extract indices for dimension n
            w = v[vidx[n]];         # extract nth vector
            bigw = w[idx];          # stretch out the vector
            newvals = numpy.multiply(newvals.flatten(), bigw);
            
        # Case 0: all dimensions specified - return the sum
        if len(remdims) == 0: 
            c = numpy.sum(newvals);
            return c;
        
        # Otherwise figure out the subscripts and accumulate the results
        newsubs = self.subs[:, remdims];
        newsiz = numpy.array(self.shape)[remdims];
        
        # Case 1: return a vector
        if len(remdims) == 1:
            c = tools.accum_np(newsubs, newvals, newsiz[0]);
            #if numpy.count_nonzero(c) < 0.5*newsiz[0]:
            #    c = sptensor.sptensor(numpy.arange(newsiz[0]).reshape(newsiz[0],1), c.reshape(newsiz[0],1));
            #else:
            c = tensor.tensor(c, newsiz);
            return c;
        
        # Case 2: result is a multi-way array
        c = sptensor.sptensor(newsubs, newvals.reshape(len(newvals), 1), newsiz);
        # check to see if it's dense
        if c.nnz() > 0.5*numpy.prod(c.shape):
            return c.totensor();
        return c;
示例#52
0
def mathlogicops(verbose):
    dat = numpy.arange(24).reshape([2,3,4]);
    siz = numpy.array([2,3,4]);
    obj = tensor.tensor(dat, siz);
    
    print obj + 100;
    print obj - 100;
    print obj + (obj + 10);
    print obj * 1.5;
    print obj < 10;
    print obj > 10l
    print obj == 10;
    print obj == obj;
    
示例#53
0
def permutetest(verbose):

    dat = numpy.arange(24).reshape([2, 3, 4])
    siz = numpy.array([2, 3, 4])

    obj = tensor.tensor(dat, siz)
    if (verbose == 1):
        print obj
        print "permute by {0}".format("[2,0,1]")
        print obj.permute([2, 0, 1])
        print "permute by {0}".format("[1,2,0]")
        print obj.permute([1, 2, 0])
        print "ipermuted by {0}".format("[1,2,0]")
        print obj.ipermute([1, 2, 0])
        print obj.permute([1, 2, 0]).ipermute([1, 2, 0])
示例#54
0
def permutetest(verbose):
    
    dat = numpy.arange(24).reshape([2,3,4]);
    siz = numpy.array([2,3,4]);
    
    obj = tensor.tensor(dat, siz);
    if(verbose == 1):
        print obj;
        print "permute by {0}".format("[2,0,1]");
        print obj.permute([2,0,1]);
        print "permute by {0}".format("[1,2,0]");
        print obj.permute([1,2,0]);
        print "ipermuted by {0}".format("[1,2,0]");
        print obj.ipermute([1,2,0]);
        print obj.permute([1,2,0]).ipermute([1,2,0]);
示例#55
0
    def __init__(self,i,j,k,l):

        perms = list(permutations([0,1,2,3]))
        
        il = lorentz_key(i) if (i<0) else i
        jl = lorentz_key(j) if (j<0) else j
        kl = lorentz_key(k) if (k<0) else k
        ll = lorentz_key(l) if (l<0) else l
        tmp = new(il, 4,{jl:4,kl:4,ll:4})

        for perm in perms:
            tmp.__setitem__({il:perm[0], jl:perm[1], kl:perm[2], ll:perm[3]}, 
                            tensor([parity(list(perm))], None))
        
        super(Epsilon,self).__init__(tmp._array, tmp._toplevel_key)
示例#56
0
 def __add__(self,other ):
     if other == 0:
         return self
     new1 = self.clean()
     other = other.clean()
     if isinstance(other,pureTensor):
         if new1.isAddable(other):
             if self.isZero():
                 return other
             else:
                 newCoefficient = new1.coefficient + other.coefficient
                 return pureTensor(self.monomials,newCoefficient)
         else:
             return tensor.tensor((new1,other))
     else:
         return NotImplemented
示例#57
0
    def stress(self, C):
        """
        Compute 2nd Piola-Kirchhoff stress
        """

        dim = len(C)
        PK2 = tensor.tensor(dim)
        detC = tensor.det(C)
        detF = np.sqrt(detC)
        lnJ = np.log(detF)
        lamda = self.get1LAME()
        mu = self.get2LAME()
        invC = tensor.inv(C)
        I = tensor.I(dim)
        PK2 = mu * (I - invC) + lamda * lnJ * invC

        return PK2
示例#58
0
 def sum(self, idx):
     obj = t.tensor(self)
     for c in idx:
         obj.transpose([c,0])
         obj.arr = obj.arr.sum(axis=0)
         a = array([])
         if type(obj.arr) != type(a):
             return obj.arr
         obj.idx = obj.idx[1:]
         obj.ud = obj.ud[1:]
     #for c in idx:
     #    if c in obj.idx:
     #        N = obj.arr.shape[obj.idx.find(c)]
     #        ud = obj.ud[obj.idx.find(c)]
     #        o = t.tensor(ones(N), idx=c, ud={"u":"d", "d": "u"}[ud])
     #        
     #        obj = obj * o
     #        check = True
     return obj
示例#59
0
    def reduce(self,tens):
        if len(self) == 1: #If this is just an algebra
            return self[0].reduce(tens)
        newTens = tensor.tensor()
        for pure in tens:
            polys = []
            for index in range(len(pure)):
                currentAlgebra = self[index]
                polys.append(currentAlgebra.reduce(pure[index]))

            def listOfPolysToTensors(ps):
                ps = iter(ps)
                pureTensors = [pureTensor.pureTensor(mono) for mono in next(ps)]
                for poly in ps:
                    newPureTensors = []
                    for mono in poly:
                        newPureTensors.extend([x.tensorProduct(mono) for x in pureTensors])
                    pureTensors = newPureTensors
                return tensor.tensor(pureTensors)
            newTens = newTens + pure.coefficient * listOfPolysToTensors(polys)
        return newTens
示例#60
0
def test1():
    A = ttensor.ttensor(tensor.tenrands([2,3,4]),
                    [numpy.random.random([10,2]),
                    numpy.random.random([30,3]),
                    numpy.random.random([40,4])]).totensor();

    [a,b] = DTA.DTA(A, [1,2,3]);
    #print a;
    #print b;

    Core = numpy.arange(24).reshape([2,3,4]);
    #Core = numpy.array([[1,3,5],[2,4,6]] , [[7,9,11],[8,10,12]])
    u1 = numpy.array([[1,2],[3,4]]);
    u2 = numpy.array([[0,1,0],[1,0,1],[1,1,1]]);
    u3 = numpy.array([[1,1,1,1],[1,2,3,4],[1,1,1,1]]);
    tt = ttensor.ttensor(tensor.tensor(Core), [u1,u2,u3]);
    
    print tt;
    [a,b] = DTA.DTA(tt.totensor(), [1,2,3]);
    print a;
    print a.totensor();
    print b;