示例#1
0
文件: topology.py 项目: yaohuic/topy
    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
示例#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 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
示例#3
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)
示例#4
0
 def _applyToMatrix(self, A):
     """
     Returns (preconditioning matrix, resulting matrix)
     """
     A = A.to_sss()
     return precon.ssor(A), A
示例#5
0
            nof += 1
            if nof >= nofPrimes:
                break
        i = i + 2
    return primes


n = 20000

primes = get_primes(n)

A = spmatrix.ll_mat_sym(n, n * 8)
d = 1
while d < n:
    for i in range(d, n):
        A[i, i - d] = 1.0
    d *= 2
for i in range(n):
    A[i, i] = primes[i]

A = A.to_sss()
K = precon.ssor(A)

b = Numeric.zeros(n, 'd')
b[0] = 1.0
x = Numeric.zeros(n, 'd')
info, iter, relres = itsolvers.minres(A, b, x, 1e-16, n, K)

print info, iter, relres
print '%.16e' % x[0]
示例#6
0
x = Numeric.zeros(n*n, 'd')
info, iter, relres = itsolvers.gmres(L, b, x, 1e-12, 200)
print 'info=%d, iter=%d, relres=%e' % (info, iter, relres)

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

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

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

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

x = Numeric.zeros(n*n, 'd')
info, iter, relres = itsolvers.gmres(S, b, x, 1e-12, 500, K_ssor, 20)
print 'info=%d, iter=%d, relres=%e' % (info, iter, relres)

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

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

r = Numeric.zeros(n*n, 'd')
S.matvec(x, r)
r = b - r
print 'norm(b - A*x) = %g' % math.sqrt(Numeric.dot(r, r))
示例#7
0
 def _applyToMatrix(self, A):
     """
     Returns (preconditioning matrix, resulting matrix)
     """
     A = A.to_sss()
     return precon.ssor(A), A
from numpy import *
import sys
from pysparse import jdsym, spmatrix, itsolvers, precon
matfiles = sys.argv[1:5]
target_value = eval(sys.argv[3])
eigenval_num = eval(sys.argv[4])
jdtol = eval(sys.argv[5])
max_iter = eval(sys.argv[6])
mat_left = spmatrix.ll_mat_from_mtx(matfiles[0])
mat_right = spmatrix.ll_mat_from_mtx(matfiles[1])
shape = mat_left.shape
T = mat_left.copy()
T.shift(-target_value, mat_right)
K = precon.ssor(T.to_sss(), 1.0, 1) # K is preconditioner.
A = mat_left.to_sss()
M = mat_right.to_sss()
k_conv, lmbd, Q, it, itall = jdsym.jdsym(A, M, K, eigenval_num, target_value, jdtol, max_iter, itsolvers.minres)
NEIG = len(lmbd)
#for lam in lmbd:
#    print "value:", lam
eivecfile = open("eivecs.dat", "w")
N = len(Q[:,0])
print >> eivecfile, N
print >> eivecfile, NEIG
for ieig in range(len(lmbd)):
    eivec = Q[:,ieig]
    print >> eivecfile, lmbd[ieig] # printing eigenvalue
    for val in eivec:              # printing eigenvector
        print >> eivecfile, val
eivecfile.close()
示例#9
0
        if i%p <> 0:
            primes[nof] = i
            nof += 1
            if nof >= nofPrimes:
                break
        i = i+2
    return primes

n = 20000

primes = get_primes(n)

A = spmatrix.ll_mat_sym(n, n*8)
d = 1
while d < n:
    for i in range(d, n):
        A[i,i-d] = 1.0
    d *= 2
for i in range(n):
    A[i,i] = primes[i]

A = A.to_sss()
K = precon.ssor(A)

b = Numeric.zeros(n, 'd'); b[0] = 1.0
x = Numeric.zeros(n, 'd')
info, iter, relres = itsolvers.minres(A, b, x, 1e-16, n, K)

print info, iter, relres
print '%.16e' % x[0]
示例#10
0
 def __init__(self, A, n11):
     n = A.shape[0]
     self.n11 = n11
     self.lu11 = superlu.factorize(A[:n11,:n11].to_csr(), diag_pivot_thresh=0)
     self.K22 = precon.ssor(A[n11:,n11:].to_sss())
     self.shape = (n, n)
示例#11
0
    Asigma.shift(-sigma, M)
    K = precon.jacobi(Asigma.to_sss())
    
    b = Numeric.ones(n, 'd')
    x = Numeric.zeros(n, 'd')
    K.precon(b, x)
    print 'norm(idiag) = %.16g' % (math.sqrt(Numeric.dot(x, x)), )

    k_conv, lmbd, Q, it, it_inner  = jdsym.jdsym(A.to_sss(), M.to_sss(), K, 5, sigma, 1e-10, 150, itsolvers.qmrs,
                                       jmin=5, jmax=10, eps_tr=1e-4, toldecay=2.0, linitmax=200, clvl=1, strategy=1)

elif test == 3:
    
    Asigma = A.copy()
    Asigma.shift(-sigma, M)
    K = precon.ssor(Asigma.to_sss())
    k_conv, lmbd, Q, it, it_inner  = jdsym.jdsym(A.to_sss(), M.to_sss(), K, 5, sigma, 1e-10, 150, itsolvers.qmrs,
                                       jmin=5, jmax=10, eps_tr=1e-4, toldecay=2.0, linitmax=200, clvl=1, strategy=1)
    
elif test == 4:
    
    Asigma = A.copy()
    Asigma.shift(-sigma, M)
    K = precon.jacobi(Asigma.to_sss())
    k_conv, lmbd, Q, it, it_inner  = jdsym.jdsym(A.to_sss(), M.to_sss(), K, 5, sigma, 1e-10, 150, itsolvers.cgs,
                                       jmin=5, jmax=10, eps_tr=1e-4, toldecay=2.0, linitmax=200, clvl=1,
                                       strategy=1, optype=1)

elif test == 5:

    # time jdtest -e1 -k1 -o linsolver=QMRS,optype=SYM,jmin=5,jmax=10,linitmax=1000,jdtol=1e-6,strategy=1 1.4 1 ~/matrices/cop18_el5_A.mtx ~/matrices/cop18_el5_M.mtx
示例#12
0
from numpy import *
import sys
from pysparse import jdsym, spmatrix, itsolvers, precon
matfiles = sys.argv[1:5]
target_value = eval(sys.argv[3])
eigenval_num = eval(sys.argv[4])
jdtol = eval(sys.argv[5])
max_iter = eval(sys.argv[6])
mat_left = spmatrix.ll_mat_from_mtx(matfiles[0])
mat_right = spmatrix.ll_mat_from_mtx(matfiles[1])
shape = mat_left.shape
T = mat_left.copy()
T.shift(-target_value, mat_right)
K = precon.ssor(T.to_sss(), 1.0, 1)  # K is preconditioner.
A = mat_left.to_sss()
M = mat_right.to_sss()
k_conv, lmbd, Q, it, itall = jdsym.jdsym(A, M, K, eigenval_num, target_value,
                                         jdtol, max_iter, itsolvers.minres)
NEIG = len(lmbd)
#for lam in lmbd:
#    print "value:", lam
eivecfile = open("eivecs.dat", "w")
N = len(Q[:, 0])
print >> eivecfile, N
print >> eivecfile, NEIG
for ieig in range(len(lmbd)):
    eivec = Q[:, ieig]
    print >> eivecfile, lmbd[ieig]  # printing eigenvalue
    for val in eivec:  # printing eigenvector
        print >> eivecfile, val
eivecfile.close()
示例#13
0
x = numpy.zeros(n*n, 'd')
info, iter, relres = itsolvers.pcg(L, b, x, tol, 2000)
print 'info=%d, iter=%d, relres=%e' % (info, iter, relres)

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

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

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

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

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

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

print 'Time for solving the system using SSS matrix and SSOR preconditioner: %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))
示例#14
0
MAXIT = 800
SSOR_STEPS = 2

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:
示例#15
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}
示例#16
0
        n = self.shape[0]
        self.dinv = Numeric.zeros(n, 'd')
        for i in xrange(n):
            self.dinv[i] = 1.0 / A[i,i]
    def precon(self, x, y):
        Numeric.multiply(x, self.dinv, y)

def resid(A, b, x):
    r = x.copy()
    A.matvec(x, r)
    r = b - r
    return math.sqrt(Numeric.dot(r, r))

K_diag = diag_prec(A)
K_jac = precon.jacobi(A, 1.0, 1)
K_ssor = precon.ssor(A, 1.0, 1)
# K_ilu = precon.ilutp(L)

n = L.shape[0];
b = Numeric.arange(n).astype(Numeric.Float)
x = Numeric.zeros(n, 'd')
info, iter, relres = itsolvers.pcg(A, b, x, 1e-6, 1000)
print 'pcg, K_none: ', info, iter, relres, resid(A, b, x)
x = Numeric.zeros(n, 'd')
info, iter, relres = itsolvers.pcg(A, b, x, 1e-6, 1000, K_diag)
print 'pcg, K_diag: ', info, iter, relres, resid(A, b, x)
x = Numeric.zeros(n, 'd')
info, iter, relres = itsolvers.pcg(A, b, x, 1e-6, 1000, K_jac)
print 'pcg, K_jac: ', info, iter, relres, resid(A, b, x)
x = Numeric.zeros(n, 'd')
info, iter, relres = itsolvers.pcg(A, b, x, 1e-6, 1000, K_ssor)