def compare(self, g1, g2, alpha, verbose=False):
     """Compute the kernel value (similarity) between two graphs. 
     
     Parameters
     ----------
     g1 : networkx.Graph
         First graph.
     g2 : networkx.Graph
         Second graph.
     alpha : interger < 1
         A rule of thumb for setting it is to take the largest power of 10
         which is samller than 1/d^2, being d the largest degree in the 
         dataset of graphs.    
         
     Returns
     -------        
     k : The similarity value between g1 and g2.
     """
     am1 = nx.adj_matrix(g1)
     am2 = nx.adj_matrix(g2)
     x = np.zeros((len(am1),len(am2)))
     A = self.smt_filter(x,am1,am2,alpha)
     b = np.ones(len(am1)*len(am2))
     tol = 1e-6
     maxit = 20
     pcg(A,b,x,tol,maxit)
     return np.sum(x)
Example #2
0
    def fea(self):
        """
        Performs a Finite Element Analysis given the updated global stiffness
        matrix [K] and the load vector {r}, both of which must be in the
        modified state, i.e., [K] and {r} must represent the unconstrained
        system of equations. Return the global displacement vector {d} as a
        NumPy array.

        EXAMPLES:
            >>> t.fea()

        See also: set_top_params

        """
        if not self.topydict:
            raise Exception('You must first load a TPD file!')
        if self.itercount >= MAX_ITERS:
            raise Exception('Maximum internal number of iterations exceeded!')

        Kfree = self._updateK(self.K.copy())

        if self.dofpn < 3 and self.nelz == 0:  # Direct solver
            Kfree = Kfree.to_csr()  # Need CSR for SuperLU factorisation
            lu = superlu.factorize(Kfree)
            lu.solve(self.rfree, self.dfree)
            if self.probtype == 'mech':
                lu.solve(self.rfreeout, self.dfreeout)  # mechanism synthesis
        else:  # Iterative solver for 3D problems
            Kfree = Kfree.to_sss()
            preK = precon.ssor(Kfree)  # Preconditioned Kfree
            (info, numitr, relerr) = itsolvers.pcg(Kfree, self.rfree,
                                                   self.dfree, 1e-8, 8000,
                                                   preK)
            if info < 0:
                logger.error('PySparse error: Type: {}, '
                             'at {} iterations'.format(info, numitr))
                raise Exception('Solution for FEA did not converge.')
            else:
                logger.debug('ToPy: Solution for FEA converged after '
                             '{} iterations'.format(numitr))
            if self.probtype == 'mech':  # mechanism synthesis
                (info, numitr, relerr) = itsolvers.pcg(Kfree, self.rfreeout,
                                                       self.dfreeout, 1e-8,
                                                       8000, preK)
                if info < 0:
                    logger.error('PySparse error: Type: {}, '
                                 'at {} iterations'.format(info, numitr))
                    raise Exception('Solution for FEA of adjoint load '
                                    'case did not converge.')

        # Update displacement vectors:
        self.d[self.freedof] = self.dfree
        if self.probtype == 'mech':  # 'adjoint' vectors
            self.dout[self.freedof] = self.dfreeout
        # Increment internal iteration counter
        self.itercount += 1
Example #3
0
    def fea(self):
        """
        Performs a Finite Element Analysis given the updated global stiffness
        matrix [K] and the load vector {r}, both of which must be in the
        modified state, i.e., [K] and {r} must represent the unconstrained
        system of equations. Return the global displacement vector {d} as a
        NumPy array.

        EXAMPLES:
            >>> t.fea()

        See also: set_top_params

        """
        if not self.topydict:
            raise ToPyError('You must first load a TPD file!')
        if self.itercount >= MAX_ITERS:
            raise ToPyError('Maximum internal number of iterations exceeded!')

        Kfree = self._updateK(self.K.copy())

        if self.dofpn < 3 and self.nelz == 0: #  Direct solver
            Kfree = Kfree.to_csr() #  Need CSR for SuperLU factorisation
            lu = superlu.factorize(Kfree)
            lu.solve(self.rfree, self.dfree)
            if self.probtype == 'mech':
                lu.solve(self.rfreeout, self.dfreeout)  # mechanism synthesis
        else: #  Iterative solver for 3D problems
            Kfree = Kfree.to_sss()
            preK = precon.ssor(Kfree) #  Preconditioned Kfree
            (info, numitr, relerr) = \
            itsolvers.pcg(Kfree, self.rfree, self.dfree, 1e-8, 8000, preK)
            if info < 0:
                print 'PySparse error: Type:', info,', at', numitr, \
'iterations.'
                raise ToPyError('Solution for FEA did not converge.')
            else:
                print 'ToPy: Solution for FEA converged after', numitr, \
'iterations.'
            if self.probtype == 'mech':  # mechanism synthesis
                (info, numitr, relerr) = \
                itsolvers.pcg(Kfree, self.rfreeout, self.dfreeout, 1e-8, \
                8000, preK)
                if info < 0:
                    print 'PySparse error: Type:', info,', at', numitr, \
'iterations.'
                    raise ToPyError('Solution for FEA of adjoint load case \
                    did not converge.')

        # Update displacement vectors:
        self.d[self.freedof] = self.dfree
        if self.probtype == 'mech':  # 'adjoint' vectors
            self.dout[self.freedof] = self.dfreeout
        # Increment internal iteration counter
        self.itercount += 1
Example #4
0
    def _solve_(self, L, x, b):
##      print 'L:',L
##      print 'x:',x
##      print 'b:',b
##      raw_input('end output')
    
        A = L._getMatrix().to_sss()

        Assor=precon.ssor(A)

        info, iter, relres = itsolvers.pcg(A, b, x, self.tolerance, self.iterations, Assor)
##        print info, iter, relres

        self._raiseWarning(info, iter, relres)
Example #5
0
print 'Time for constructing the matrix using poisson2d        : %8.2f sec' % (time.clock() - t1, )


A = L.to_csr()
S = L.to_sss()
print L.nnz
print S.nnz
print A.nnz
b = numpy.ones(n*n, 'd')

# ---------------------------------------------------------------------------------------

t1 = time.clock()

x = numpy.zeros(n*n, 'd')
info, iter, relres = itsolvers.pcg(S, b, x, tol, 2000)
print 'info=%d, iter=%d, relres=%e' % (info, iter, relres)

print 'Time for solving the system using SSS matrix: %8.2f sec' % (time.clock() - t1, )

print 'norm(x) = %g' % math.sqrt(numpy.dot(x, x))

r = numpy.zeros(n*n, 'd')
S.matvec(x, r)
r = b - r
print 'norm(b - A*x) = %g' % math.sqrt(numpy.dot(r, r))

print x[0:10]

# ---------------------------------------------------------------------------------------
 def _solveSystem(self,matrix,rhs,ans):
     info, iter, relres = its.pcg(matrix, rhs, ans, 1e-10, 100)
Example #7
0
L = poisson.poisson2d_sym_blk(N)
S = L.to_sss()

b = Numeric.ones(N*N, 'd')

print 'Solving 2D-Laplace equation using PCG and SSOR preconditioner with variable omega'
print
print 'omega    nit    time       resid' 
print '--------------------------------' 

for omega in [0.1*(i+1) for i in range(20)]:

    K_ssor = precon.ssor(S, omega, SSOR_STEPS)
    t1 = time.clock()

    x = Numeric.zeros(N*N, 'd')
    info, iter, relres = itsolvers.pcg(S, b, x, TOL, MAXIT, K_ssor)

    elapsed_time = time.clock() - t1

    r = Numeric.zeros(N*N, 'd')
    S.matvec(x, r)
    r = b - r
    res_nrm2 = math.sqrt(Numeric.dot(r, r))

    if info == 0:
        iter_str = str(iter)
    else:
        iter_str = '---'
    print '%5.1f  %5s  %6.2f  %10.3e' % (omega, iter_str, elapsed_time, res_nrm2)
Example #8
0
def analyze(vxg, loads, boundary, iter):
    """
    main analysis function
       - vxg: voxel grid (3d list)
       - loads: each consisting of
           * points [point set #1, point set #2 ...]
           * value [value #1, value #2, ...]
       - boundary
           * points
       - iter: whether to use iterative or direct solver
        (points are element numbers)
    output:
       - displacement vector
       - von Mises stress vector
    """
    global Ke, B, C

    nz = len(vxg)
    ny = len(vxg[0])
    nx = len(vxg[0][0])
    _log('voxelization')
    print('voxel grid: ' + str(nx) + ' x ' + str(ny) + ' x ' + str(nz))

    # compute stiffness matrix for individual elements
    DOF = 3
    ksize = DOF * (nx + 1) * (ny + 1) * (nz + 1)
    kall = spmatrix.ll_mat_sym(ksize, ksize)

    SOLID = 1.000
    VOID = 0.001
    for i in range(0, nz):
        for j in range(0, ny):
            for k in range(0, nx):
                xe = SOLID if vxg[i][j][k] == 1 else VOID
                nodes = _node_nums_3d(nx, ny, nz, k + 1, j + 1, i + 1)
                ind = []
                for n in nodes:
                    ind.extend([(n - 1) * DOF, (n - 1) * DOF + 1,
                                (n - 1) * DOF + 2])
                mask = np.ones(len(ind), dtype=int)
                kall.update_add_mask_sym(Ke * xe, ind, mask)

    _log('updated stiffness matrix for all elements')

    # formulate loading scenario
    rall = [0] * ksize
    indicesset = loads['points']
    values = loads['values']

    for i in range(0, len(indicesset)):
        indices = indicesset[i]
        value = values[i]
        for idx in indices:
            nodes = _node_nums_3d(nx, ny, nz, idx[0] + 1, idx[1] + 1,
                                  idx[2] + 1)
            for j in range(0, DOF):
                for k in range(0, len(nodes)):
                    rall[DOF * (nodes[k] - 1) + j] = value[j]

    # formulate boundary condition
    elemmask = [1] * (nx + 1) * (ny + 1) * (nz + 1)
    for idx in boundary:
        nodes = _node_nums_3d(nx, ny, nz, idx[0] + 1, idx[1] + 1, idx[2] + 1)
        for j in range(0, len(nodes)):
            elemmask[nodes[j] - 1] = 0

    freedofs = []
    fixeddofs = []
    for i in range(0, len(elemmask)):
        if elemmask[i] == 1:
            freedofs.extend((DOF * i, DOF * i + 1, DOF * i + 2))
        else:
            fixeddofs.extend((DOF * i, DOF * i + 1, DOF * i + 2))

    _log('formulated loading scenario and boundary condition')

    # solve KU=F
    rfree = np.take(rall, freedofs)
    dfree = np.empty(len(freedofs))

    alldofs = np.arange(ksize)
    rcfixed = np.where(np.in1d(alldofs, fixeddofs), 0, 1)
    kfree = kall
    kfree.delete_rowcols(rcfixed)

    _log('removed constrained elements')

    if iter:
        kfree = kfree.to_sss()
        prek = precon.ssor(kfree)
        (info, numitr, relerr) = itsolvers.pcg(kfree, rfree, dfree, 1e-8, 8000,
                                               prek)
        if info >= 0:
            print('converged after ' + str(numitr) +
                  ' iterations with error of ' + str(relerr))
        else:
            print('PySparse error: Type:' + info + ', at' + str(numitr) +
                  'iterations.')
    else:
        kfree = kfree.to_csr()
        lu = superlu.factorize(kfree)
        lu.solve(rfree, dfree)

    _log('solved KU=F')

    dall = np.zeros_like(rall)
    for i in range(0, len(freedofs)):
        dall[freedofs[i]] = dfree[i]

    # compute stress
    cb = C * B
    vonmises = []
    for i in range(0, nz):
        vmplane = []
        for j in range(0, ny):
            vmrow = []
            for k in range(0, nx):
                nodes = _node_nums_3d(nx, ny, nz, k + 1, j + 1, i + 1)
                disps = []
                for n in nodes:
                    disps.extend([
                        dall[DOF * (n - 1)], dall[DOF * (n - 1) + 1],
                        dall[DOF * (n - 1) + 2]
                    ])
                d = np.matrix(disps).transpose()
                sigma = cb * d

                s11 = sigma.item(0, 0)
                s22 = sigma.item(1, 0)
                s33 = sigma.item(2, 0)
                s12 = sigma.item(3, 0) * 0.5  # DOUBLE CHECK THIS
                s23 = sigma.item(4, 0) * 0.5
                s31 = sigma.item(5, 0) * 0.5

                # von Mises stress, cf. Strava et al.'s Stress Relief paper (SIGGRAPH '12)
                vmrow.append(
                    sqrt(0.5 *
                         ((s11 - s22)**2 + (s22 - s33)**2 +
                          (s33 - s11)**2 + 6 * (s12**2 + s23**2 + s31**2))))
            vmplane.append(vmrow)
        vonmises.append(vmplane)

    t1 = _log('computed stress')

    global t0
    print('total time:' + str(t1 - t0) + ' ms')

    return {'displacements': dall.tolist(), 'stress': vonmises}
Example #9
0
A.matvec(x, y)
print y
print 'norm(y) = ', math.sqrt(Numeric.add.reduce(y))

##A.matvec_transp(x, z)
##print z
##print 'norm(z) = ', math.sqrt(Numeric.add.reduce(z))

L = spmatrix.ll_mat(10,10)
for i in range(10):
    L[i,i] = float(i+1)
A = L.to_csr()
print A
x = Numeric.zeros(10, 'd')
b = Numeric.ones(10, 'd')
info, iter, relres = itsolvers.pcg(A, b, x, 1e-8, 100)
print info, iter, relres
print x
if (info != 0):
    print >> sys.stderr, 'cg not converged'

L2 = L.copy()
x = Numeric.zeros(10, 'd')
info, iter, relres = itsolvers.pcg(A, b, x, 1e-8, 100)
print info, iter, relres

# -----------------------------------------------------------
print 'remove test'
n = 100
L = spmatrix.ll_mat(n, n)
Example #10
0
 def _solveSystem(self, matrix, rhs, ans):
     info, iter, relres = its.pcg(matrix, rhs, ans, 1e-10, 100)