Exemplo n.º 1
0
 def calculate(self):
     print '\n=============================='
     tim = dbg.start_time()
     if self.physics == 'scalar':
         homogenize.applications.scalar(self)
     elif self.physics == 'elasticity':
         homogenize.applications.elasticity(self)
     else:
         raise ValueError("Not implemented physics (%s)." % self.physics)
     tim = dbg.get_time(tim)
     print 'total time for problem', tim
Exemplo n.º 2
0
def postprocess(pb, A, mat, solutions, results, primaldual):
    """
    The function post-process the results.
    """
    tim = dbg.start_time()
    print '\npostprocessing'
    matrices = {}
    for pp in pb.postprocess:
        if pp['kind'] in ['GaNi', 'gani']:
            order_name = ''
            Nname = ''
            if A.name is not 'A_GaNi':
                A = mat.get_A_GaNi(pb.solve['N'], primaldual)

        elif pp['kind'] in ['Ga', 'ga']:
            if 'order' in pp:
                Nbarpp = 2 * pb.solve['N'] - 1
                if pp['order'] is None:
                    Nname = ''
                    order_name = ''
                    A = mat.get_A_Ga(Nbar=Nbarpp,
                                     primaldual=primaldual,
                                     order=pp['order'])
                else:
                    order_name = '_o' + str(pp['order'])
                    Nname = '_P%d' % np.mean(pp['P'])
                    A = mat.get_A_Ga(Nbar=Nbarpp,
                                     primaldual=primaldual,
                                     order=pp['order'],
                                     P=pp['P'])
            else:
                order_name = ''
                Nname = ''
        else:
            ValueError()

        name = 'AH_%s%s%s_%s' % (pp['kind'], order_name, Nname, primaldual)
        print 'calculated: ' + name

        AH = assembly_matrix(A, solutions)

        if primaldual is 'primal':
            matrices[name] = AH
        else:
            matrices[name] = np.linalg.inv(AH)
    tim = dbg.get_time(tim)
    print 'postprocess time', tim

    pb.output.update({
        'sol_' + primaldual: solutions,
        'res_' + primaldual: results,
        'mat_' + primaldual: matrices
    })
Exemplo n.º 3
0
def postprocess(pb, A, mat, solutions, results, primaldual):
    """
    The function post-process the results.
    """
    tim = dbg.start_time()
    print '\npostprocessing'
    matrices = {}
    for pp in pb.postprocess:
        if pp['kind'] in ['GaNi', 'gani']:
            order_name = ''
            Nname = ''
            if A.name is not 'A_GaNi':
                A = mat.get_A_GaNi(pb.solve['N'], primaldual)

        elif pp['kind'] in ['Ga', 'ga']:
            if 'order' in pp:
                Nbarpp = 2*pb.solve['N'] - 1
                if pp['order'] is None:
                    Nname = ''
                    order_name = ''
                    A = mat.get_A_Ga(Nbar=Nbarpp, primaldual=primaldual,
                                     order=pp['order'])
                else:
                    order_name = '_o' + str(pp['order'])
                    Nname = '_P%d' % np.mean(pp['P'])
                    A = mat.get_A_Ga(Nbar=Nbarpp, primaldual=primaldual,
                                     order=pp['order'], P=pp['P'])
            else:
                order_name = ''
                Nname = ''
        else:
            ValueError()

        name = 'AH_%s%s%s_%s' % (pp['kind'], order_name, Nname, primaldual)
        print 'calculated: ' + name

        AH = assembly_matrix(A, solutions)

        if primaldual is 'primal':
            matrices[name] = AH
        else:
            matrices[name] = np.linalg.inv(AH)
    tim = dbg.get_time(tim)
    print 'postprocess time', tim

    pb.output.update({'sol_' + primaldual: solutions,
                      'res_' + primaldual: results,
                      'mat_' + primaldual: matrices})
Exemplo n.º 4
0
    def calculate(self):
        """
        Calculates the problem according to physical model.
        """
        print '\n=============================='
        tim = dbg.start_time()
        if hasattr(homogenize.applications, self.physics):
            eval('homogenize.applications.%s(self)' % self.physics)
        else:
            msg = 'Not implemented physics (%s).\n' \
                'Hint: Implement function (%s) into module' \
                ' homogenize.applications!' % (self.physics, self.physics)
            raise NotImplementedError(msg)

        tim = dbg.get_time(tim)
        print 'total time for problem', tim
Exemplo n.º 5
0
def postprocess(pb, A, mat, solutions, results, primaldual):
    tim = dbg.start_time()
    print "\npostprocessing"
    matrices = {}
    for pp in pb.postprocess:
        if pp["kind"] in ["GaNi", "gani"]:
            order_name = ""
            Nname = ""
            if A.name is not "A_GaNi":
                A = mat.get_A_GaNi(pb.solve["N"], primaldual)

        elif pp["kind"] in ["Ga", "ga"]:
            if "order" in pp:
                Nbarpp = 2 * pb.solve["N"] - 1
                if pp["order"] is None:
                    Nname = ""
                    order_name = ""
                    A = mat.get_A_Ga(Nbar=Nbarpp, primaldual=primaldual, order=pp["order"])
                else:
                    order_name = "_o" + str(pp["order"])
                    Nname = "_P%d" % np.mean(pp["P"])
                    A = mat.get_A_Ga(Nbar=Nbarpp, primaldual=primaldual, order=pp["order"], P=pp["P"])
            else:
                order_name = ""
                Nname = ""
        else:
            ValueError()

        name = "AH_%s%s%s_%s" % (pp["kind"], order_name, Nname, primaldual)
        print "calculated: " + name

        AH = assembly_matrix(A, solutions)

        if primaldual is "primal":
            matrices[name] = AH
        else:
            matrices[name] = np.linalg.inv(AH)
    tim = dbg.get_time(tim)
    print "postprocess time", tim

    pb.output.update({"sol_" + primaldual: solutions, "res_" + primaldual: results, "mat_" + primaldual: matrices})
Exemplo n.º 6
0
def CG(Afun, B, x0=None, par=None, callback=None):
    """
    Conjugate gradients solver.

    Parameters
    ----------
    Afun : Matrix, LinOper, or numpy.array of shape (n, n)
        it stores the matrix data of linear system and provides a matrix by
        vector multiplication
    B : VecTri or numpy.array of shape (n,)
        it stores a right-hand side of linear system
    x0 : VecTri or numpy.array of shape (n,)
        initial approximation of solution of linear system
    par : dict
        parameters of the method
    callback :

    Returns
    -------
    x : VecTri or numpy.array of shape (n,)
        resulting unknown vector
    res : dict
        results
    """
    if x0 is None:
        x0 = B
    if par is None:
        par = dict()
    if 'tol' not in par.keys():
        par['tol'] = 1e-6
    if 'maxiter' not in par.keys():
        par['maxiter'] = 1e3

    res = dict()
    res['time'] = dbg.start_time()
    xCG = x0
    Ax = Afun(x0)
    R = B - Ax
    P = R
    rr = R*R
    res['kit'] = 0
    res['norm_res'] = np.double(rr)**0.5 # /np.norm(E_N)
    norm_res_log = []
    norm_res_log.append(res['norm_res'])
    while (res['norm_res'] > par['tol']) and (res['kit'] < par['maxiter']):
        res['kit'] += 1 # number of iterations
        AP = Afun(P)
        alp = rr/(P*AP)
        xCG = xCG + alp*P
        R = R - alp*AP
        rrnext = R*R
        bet = rrnext/rr
        rr = rrnext
        P = R + bet*P
        res['norm_res'] = np.double(rr)**0.5
        norm_res_log.append(res['norm_res'])
        if callback is not None:
            callback(xCG)
    res['time'] = dbg.get_time(res['time'])
    if res['kit'] == 0:
        res['norm_res'] = 0
    return xCG, res
Exemplo n.º 7
0
def scalar(problem):
    """
    Homogenization of scalar elliptic problem.

    Parameters
    ----------
    problem : object
    """
    print ' '
    pb = problem
    print pb

    # Fourier projections
    _, hG1N, hG2N = proj.scalar(pb.solve['N'],
                                pb.Y,
                                centered=True,
                                NyqNul=True)

    if pb.solve['kind'] is 'GaNi':
        Nbar = pb.solve['N']
    elif pb.solve['kind'] is 'Ga':
        Nbar = 2 * pb.solve['N'] - 1
        hG1N = hG1N.enlarge(Nbar)
        hG2N = hG2N.enlarge(Nbar)

    FN = DFT(name='FN', inverse=False, N=Nbar)
    FiN = DFT(name='FiN', inverse=True, N=Nbar)

    G1N = LinOper(name='G1', mat=[[FiN, hG1N, FN]])
    G2N = LinOper(name='G2', mat=[[FiN, hG2N, FN]])

    for primaldual in pb.solve['primaldual']:
        tim = dbg.start_time()
        print '\nproblem: ' + primaldual
        solutions = np.zeros(pb.shape).tolist()
        results = np.zeros(pb.shape).tolist()

        # material coefficients
        mat = Material(pb.material)

        if pb.solve['kind'] is 'GaNi':
            A = mat.get_A_GaNi(pb.solve['N'], primaldual)
        elif pb.solve['kind'] is 'Ga':
            A = mat.get_A_Ga(Nbar=Nbar, primaldual=primaldual)

        if primaldual is 'primal':
            GN = G1N
        else:
            GN = G2N

        Afun = LinOper(name='FiGFA', mat=[[GN, A]])

        for iL in np.arange(pb.dim):  # iteration over unitary loads
            E = np.zeros(pb.dim)
            E[iL] = 1
            print 'macroscopic load E = ' + str(E)
            EN = VecTri(name='EN', macroval=E, N=Nbar, Fourier=False)
            # initial approximation for solvers
            x0 = VecTri(name='x0', N=Nbar, Fourier=False)

            B = Afun(-EN)  # RHS

            if not hasattr(pb.solver, 'callback'):
                cb = CallBack(A=Afun, B=B)
            elif pb.solver['callback'] == 'detailed':
                cb = CallBack_GA(A=Afun, B=B, EN=EN, A_Ga=A, GN=GN)
            else:
                raise NotImplementedError("The solver callback (%s) is not \
                    implemented" % (pb.solver['callback']))

            print 'solver : %s' % pb.solver['kind']
            X, info = linear_solver(solver=pb.solver['kind'],
                                    Afun=Afun,
                                    B=B,
                                    x0=x0,
                                    par=pb.solver,
                                    callback=cb)

            solutions[iL] = add_macro2minimizer(X, E)
            results[iL] = {'cb': cb, 'info': info}
            print cb
        tim = dbg.get_time(tim)
        print 'calculation times for each load:\n', tim

        # POSTPROCESSING
        del Afun, B, E, EN, GN, X
        postprocess(pb, A, mat, solutions, results, primaldual)
Exemplo n.º 8
0
def scalar(problem):
    """
    Homogenization of scalar elliptic problem.

    Parameters
    ----------
    problem : object
    """
    print ' '
    pb = problem
    print pb

    # Fourier projections
    _, hG1N, hG2N = proj.scalar(pb.solve['N'], pb.Y, centered=True,
                                NyqNul=True)

    if pb.solve['kind'] is 'GaNi':
        Nbar = pb.solve['N']
    elif pb.solve['kind'] is 'Ga':
        Nbar = 2*pb.solve['N'] - 1
        hG1N = hG1N.enlarge(Nbar)
        hG2N = hG2N.enlarge(Nbar)

    FN = DFT(name='FN', inverse=False, N=Nbar)
    FiN = DFT(name='FiN', inverse=True, N=Nbar)

    G1N = LinOper(name='G1', mat=[[FiN, hG1N, FN]])
    G2N = LinOper(name='G2', mat=[[FiN, hG2N, FN]])

    for primaldual in pb.solve['primaldual']:
        tim = dbg.start_time()
        print '\nproblem: ' + primaldual
        solutions = np.zeros(pb.shape).tolist()
        results = np.zeros(pb.shape).tolist()

        # material coefficients
        mat = Material(pb.material)

        if pb.solve['kind'] is 'GaNi':
            A = mat.get_A_GaNi(pb.solve['N'], primaldual)
        elif pb.solve['kind'] is 'Ga':
            A = mat.get_A_Ga(Nbar=Nbar, primaldual=primaldual)

        if primaldual is 'primal':
            GN = G1N
        else:
            GN = G2N

        Afun = LinOper(name='FiGFA', mat=[[GN, A]])

        for iL in np.arange(pb.dim): # iteration over unitary loads
            E = np.zeros(pb.dim)
            E[iL] = 1
            print 'macroscopic load E = ' + str(E)
            EN = VecTri(name='EN', macroval=E, N=Nbar, Fourier=False)
            # initial approximation for solvers
            x0 = VecTri(name='x0', N=Nbar, Fourier=False)

            B = Afun(-EN) # RHS

            if not hasattr(pb.solver, 'callback'):
                cb = CallBack(A=Afun, B=B)
            elif pb.solver['callback'] == 'detailed':
                cb = CallBack_GA(A=Afun, B=B, EN=EN, A_Ga=A, GN=GN)
            else:
                raise NotImplementedError("The solver callback (%s) is not \
                    implemented" % (pb.solver['callback']))

            print 'solver : %s' % pb.solver['kind']
            X, info = linear_solver(solver=pb.solver['kind'], Afun=Afun, B=B,
                                    x0=x0, par=pb.solver, callback=cb)

            solutions[iL] = add_macro2minimizer(X, E)
            results[iL] = {'cb': cb, 'info': info}
            print cb
        tim = dbg.get_time(tim)
        print 'calculation times for each load:\n', tim

        # POSTPROCESSING
        del Afun, B, E, EN, GN, X
        postprocess(pb, A, mat, solutions, results, primaldual)
Exemplo n.º 9
0
def BiCG(Afun, ATfun, B, x0=None, par=None, callback=None):
    """
    BiConjugate gradient solver.

    Parameters
    ----------
    Afun : Matrix, LinOper, or numpy.array of shape (n, n)
        it stores the matrix data of linear system and provides a matrix by
        vector multiplication
    B : VecTri or numpy.array of shape (n,)
        it stores a right-hand side of linear system
    x0 : VecTri or numpy.array of shape (n,)
        initial approximation of solution of linear system
    par : dict
        parameters of the method
    callback :

    Returns
    -------
    x : VecTri or numpy.array of shape (n,)
        resulting unknown vector
    res : dict
        results
    """
    if x0 is None:
        x0 = B
    if par is None:
        par = dict()
    if 'tol' not in par:
        par['tol'] = 1e-6
    if 'maxiter' not in par:
        par['maxiter'] = 1e3

    res = dict()
    res['time'] = dbg.start_time()
    xBiCG = x0
    Ax = Afun*x0
    R = B - Ax
    Rs = R
    rr = float(R.T*Rs)
    P = R
    Ps = Rs
    res['kit'] = 0
    res['norm_res'] = rr**0.5 # /np.norm(E_N)
    norm_res_log = []
    norm_res_log.append(res['norm_res'])
    while (res['norm_res'] > par['tol']) and (res['kit'] < par['maxiter']):
        res['kit'] += 1 # number of iterations
        AP = Afun*P
        alp = rr/float(AP.T*Ps)
        xBiCG = xBiCG + alp*P
        R = R - alp*AP
        Rs = Rs - alp*ATfun*Ps
        rrnext = float(R.T*Rs)
        bet = rrnext/rr
        rr = rrnext
        P = R + bet*P
        Ps = Rs + bet*Ps
        res['norm_res'] = rr**0.5
        norm_res_log.append(res['norm_res'])
        if callback is not None:
            callback(xBiCG)
    res['time'] = dbg.get_time(res['time'])
    if res['kit'] == 0:
        res['norm_res'] = 0
    return xBiCG, res
Exemplo n.º 10
0
def CG(Afun, B, x0=None, par=None, callback=None):
    """
    Conjugate gradients solver.

    Parameters
    ----------
    Afun : Matrix, LinOper, or numpy.array of shape (n, n)
        it stores the matrix data of linear system and provides a matrix by
        vector multiplication
    B : VecTri or numpy.array of shape (n,)
        it stores a right-hand side of linear system
    x0 : VecTri or numpy.array of shape (n,)
        initial approximation of solution of linear system
    par : dict
        parameters of the method
    callback :

    Returns
    -------
    x : VecTri or numpy.array of shape (n,)
        resulting unknown vector
    res : dict
        results
    """
    if x0 is None:
        x0 = B
    if par is None:
        par = dict()
    if 'tol' not in par.keys():
        par['tol'] = 1e-6
    if 'maxiter' not in par.keys():
        par['maxiter'] = 1e3

    res = dict()
    res['time'] = dbg.start_time()
    xCG = x0
    Ax = Afun * x0
    R = B - Ax
    P = R
    rr = float(R.T * R)
    res['kit'] = 0
    res['norm_res'] = np.double(rr)**0.5  # /np.norm(E_N)
    norm_res_log = []
    norm_res_log.append(res['norm_res'])
    while (res['norm_res'] > par['tol']) and (res['kit'] < par['maxiter']):
        res['kit'] += 1  # number of iterations
        AP = Afun * P
        alp = float(rr / (P.T * AP))
        xCG = xCG + alp * P
        R = R - alp * AP
        rrnext = float(R.T * R)
        bet = rrnext / rr
        rr = rrnext
        P = R + bet * P
        res['norm_res'] = np.double(rr)**0.5
        norm_res_log.append(res['norm_res'])
        if callback is not None:
            callback(xCG)
    res['time'] = dbg.get_time(res['time'])
    if res['kit'] == 0:
        res['norm_res'] = 0
    return xCG, res