Пример #1
0
 def assemble_eigenproblem_matrices(self, filename_mat_A=None, filename_mat_M=None,  use_generalized=False,
                                    force_recompute_matrices=False, check_hermitian=False,
                                    differentiate_H_numerically=True, use_real_matrix=True):
     if use_generalized:
         if (self.A == None or self.M == None) or force_recompute_matrices:
             df.tic()
             self.A, self.M, _, _ = compute_generalised_eigenproblem_matrices(
                 self, frequency_unit=1e9, filename_mat_A=filename_mat_A, filename_mat_M=filename_mat_M,
                 check_hermitian=check_hermitian, differentiate_H_numerically=differentiate_H_numerically)
             log.debug("Assembling the eigenproblem matrices took {}".format(
                 helpers.format_time(df.toc())))
         else:
             log.debug(
                 'Re-using previously computed eigenproblem matrices.')
     else:
         if self.D == None or (self.use_real_matrix != use_real_matrix) or force_recompute_matrices:
             df.tic()
             self.D = compute_eigenproblem_matrix(
                 self, frequency_unit=1e9, differentiate_H_numerically=differentiate_H_numerically,
                 dtype=(float if use_real_matrix else complex))
             self.use_real_matrix = use_real_matrix
             log.debug("Assembling the eigenproblem matrix took {}".format(
                 helpers.format_time(df.toc())))
         else:
             log.debug('Re-using previously computed eigenproblem matrix.')
Пример #2
0
def HiptmairMatrixSetupBoundary(mesh, N, M,dim):
    def boundary(x, on_boundary):
        return on_boundary

    # mesh.geometry().dim()
    path = os.path.abspath(os.path.join(inspect.getfile(inspect.currentframe()), ".."))
    # if __version__ == '1.6.0':
    gradient_code = open(os.path.join(path, 'DiscreteGradientSecond.cpp'), 'r').read()
    # else:
        # gradient_code = open(os.path.join(path, 'DiscreteGradient.cpp'), 'r').read()
    compiled_gradient_module = compile_extension_module(code=gradient_code)
    tic()
    if dim == 3:
        EdgeBoundary = BoundaryEdge(mesh)
        EdgeBoundary = numpy.sort(EdgeBoundary)[::2].astype("float_","C")
    else:
        B = BoundaryMesh(mesh,"exterior",False)
        EdgeBoundary = numpy.sort(B.entity_map(1).array().astype("float_","C"))
    end = toc()
    MO.StrTimePrint("Compute edge boundary indices, time: ",end)


    row =  numpy.zeros(2*(mesh.num_edges()-EdgeBoundary.size), order="C") #, dtype="intc")
    column =  numpy.zeros(2*(mesh.num_edges()-EdgeBoundary.size), order="C") #, dtype="intc")
    data =  numpy.zeros(2*(mesh.num_edges()-EdgeBoundary.size), order="C") #, dtype="intc")

    dataX =  numpy.zeros(2*(mesh.num_edges()-EdgeBoundary.size), order="C")
    dataY =  numpy.zeros(2*(mesh.num_edges()-EdgeBoundary.size), order="C")
    dataZ =  numpy.zeros(2*(mesh.num_edges()-EdgeBoundary.size), order="C")
    # print 2*(mesh.num_edges()-EdgeBoundary.size)

    tic()

    # c = compiled_gradient_module.ProlongationGrad(mesh, EdgeBoundary, dataX,dataY,dataZ, data, row, column)
    c = compiled_gradient_module.ProlongationGradBoundary(mesh, EdgeBoundary, dataX,dataY,dataZ, data, row, column)
    # u, indices = numpy.unique(row, return_index=True)
    # indices = numpy.concatenate((indices,indices+1),axis=1)
    # # print VertexBoundary
    # print row
    # # print numpy.concatenate((indices,indices+1),axis=1)
    # # print  data
    # row = row[indices]
    # column = column[indices]
    # data = data[indices]
    # print row
    end = toc()
    MO.StrTimePrint("Data for C and P created, time: ",end)
    C = coo_matrix((data,(row,column)), shape=(N, M)).tocsr()
    Px = coo_matrix((dataX,(row,column)), shape=(N, M)).tocsr()
    Py = coo_matrix((dataY,(row,column)), shape=(N, M)).tocsr()
    Pz = coo_matrix((dataZ,(row,column)), shape=(N, M)).tocsr()
    del dataX, dataY, dataZ, row,column, mesh, EdgeBoundary
    return C, [Px,Py,Pz]
Пример #3
0
def HiptmairBCsetupBoundary(C, P, mesh):

    dim = mesh.geometry().dim()
    tic()
    if dim == 3:
        EdgeBoundary = BoundaryEdge(mesh)
    else:
        B = BoundaryMesh(mesh,"exterior",False)
        EdgeBoundary = numpy.sort(B.entity_map(1).array().astype("int","C"))


    B = BoundaryMesh(mesh,"exterior",False)
    NodalBoundary = B.entity_map(0).array()#.astype("int","C")
    onelagrange = numpy.ones(mesh.num_vertices())
    onelagrange[NodalBoundary] = 0
    Diaglagrange = spdiags(onelagrange,0,mesh.num_vertices(),mesh.num_vertices())

    onemagnetiic = numpy.ones(mesh.num_edges())
    onemagnetiic[EdgeBoundary.astype("int","C")] = 0
    Diagmagnetic = spdiags(onemagnetiic,0,mesh.num_edges(),mesh.num_edges())

    del mesh
    tic()
    C = Diagmagnetic*C*Diaglagrange
    # C = C
    G = PETSc.Mat().createAIJ(size=C.shape,csr=(C.indptr, C.indices, C.data))
    end = toc()
    MO.StrTimePrint("BC applied to gradient, time: ",end)

    if dim == 2:
        tic()
        # Px = P[0]
        # Py = P[1]
        Px = Diagmagnetic*P[0]*Diaglagrange
        Py = Diagmagnetic*P[1]*Diaglagrange
        end = toc()
        MO.StrTimePrint("BC applied to Prolongation, time: ",end)
        P = [PETSc.Mat().createAIJ(size=Px.shape,csr=(Px.indptr, Px.indices, Px.data)),PETSc.Mat().createAIJ(size=Py.shape,csr=(Py.indptr, Py.indices, Py.data))]
    else:
        tic()
        # Px = P[0]
        # Py = P[1]
        # Pz = P[2]
        Px = Diagmagnetic*P[0]*Diaglagrange
        Py = Diagmagnetic*P[1]*Diaglagrange
        Pz = Diagmagnetic*P[2]*Diaglagrange
        end = toc()
        MO.StrTimePrint("BC applied to Prolongation, time: ",end)
        P = [PETSc.Mat().createAIJ(size=Px.shape,csr=(Px.indptr, Px.indices, Px.data)),PETSc.Mat().createAIJ(size=Py.shape,csr=(Py.indptr, Py.indices, Py.data)),PETSc.Mat().createAIJ(size=Pz.shape,csr=(Pz.indptr, Pz.indices, Pz.data))]
    del Px, Py, Diaglagrange
    return  G, P
Пример #4
0
def solve(setup, visualize=False):
    geo, phys, solverp = setup.geo, setup.phys, setup.solverp
    if visualize:
        plotter = Plotter(setup)

    if geo.mesh.num_cells() < solverp.Nmax:
        pb = prerefine(setup, visualize)
    else:
        pb = None

    it = phys.dim == 3

    # solve 1D problem for side BCs
    set_sideBCs(phys, setup.geop, setup.physp)

    # if given, use precomputed ion diffusivity
    set_D_from_data(phys, solverp.diffusivity_data)

    if solverp.hybrid:
        pnps = simplepnps.PNPSHybrid(
            geo,
            phys,
            ipicard=solverp.imax,
            verbose=True,
            nverbose=True,
            tolnewton=solverp.tol,  #taylorhood=True,
            stokesiter=(it and solverp.stokesiter),
            iterative=it,
            cyl=phys.cyl,
            fluid=solverp.fluid)
    else:
        pnps = simplepnps.PNPSFixedPointbV(
            geo,
            phys,
            ipicard=solverp.imax,
            verbose=True,
            tolnewton=solverp.tol,  #taylorhood=True,
            stokesiter=(it and solverp.stokesiter),
            iterative=it,
            cyl=phys.cyl,
            fluid=solverp.fluid)
    #v, cp, cm, u, p = pnps.solutions()
    #plotter.plot(cm, "cm", interactive=True)

    print "Number of cells:", geo.mesh.num_cells()
    print "DOFs:", pnps.dofs()
    dolfin.tic()
    for i in pnps.fixedpoint():  #ipnp=6):
        if visualize:
            v, cp, cm, u, p = pnps.solutions()
            plotter.plot(v, "potential")
            #plotter.plot(cm, "cm")
            #R, H = tuple(setup.geo.params[s] for s in ["R", "H"])
            #nano.plot1D(dict(cm=cm, cp=cp), dim=2, axis="y",
            #            rng=(-H/2., H/2., 100), origin=[R, 0])
            #dolfin.interactive()
            #nano.showplots()
            #plotter.plot_vector(u, "velocity")
    print "CPU time (solve): %.3g s" % (dolfin.toc(), )
    return pb, pnps
Пример #5
0
def solve(setup, visualize=False):
    geo, phys, solverp = setup.geo, setup.phys, setup.solverp
    if visualize:
        plotter = Plotter(setup)

    if geo.mesh.num_cells() < solverp.Nmax:
        pb = prerefine(setup, visualize)
    else:
        pb = None

    it = phys.dim==3
    # solve 1D problem for side BCs
    set_sideBCs(phys, setup.geop, setup.physp)

    # if given, use precomputed ion diffusivity
    set_D(setup)
    #if visualize:
    #    plotter.plot(setup.phys.Dp[setup.phys.dim-1, setup.phys.dim-1], interactive=True)

    pnps = simplepnps.PNPSFixedPointbV(geo, phys, ipicard=solverp.imax,
               verbose=True, tolnewton=solverp.tol, #taylorhood=True,
               stokesiter=(it and solverp.stokesiter), iterative=it,
               cyl=phys.cyl)

    print "Number of cells:", geo.mesh.num_cells()
    print "DOFs:", pnps.dofs()
    dolfin.tic()
    for i in pnps.fixedpoint(ipnp=6):
        if visualize:
            v, cp, cm, u, p = pnps.solutions()
            plotter.plot(v, "potential")
            #plotter.plot_vector(u, "velocity")
    print "CPU time (solve): %.3g s" %(dolfin.toc(),)
    return pb, pnps
Пример #6
0
def prerefine(setup, visualize=False, debug=False):
    geo, phys, p = setup.geo, setup.phys, setup.solverp
    dolfin.tic()
    if setup.geop.x0 is None:
        goal = phys.CurrentPB
    else:
        goal = lambda v: phys.CurrentPB(v) + phys.Fbare(v, phys.dim - 1)
    if debug:
        plotter = Plotter(setup)
    pb = simplepnps.SimpleLinearPBGO(geo, phys, goal=goal, cheapest=p.cheapest)

    for i in pb.adaptive_loop(p.Nmax, p.frac, verbose=True):
        if visualize:
            if phys.dim == 3:
                nano.plot_sliced_mesh(geo,
                                      title="adapted mesh",
                                      key="b",
                                      elevate=-90. if i == 1 else 0.)
            if phys.dim == 2:
                dolfin.plot(geo.boundaries,
                            key="b",
                            title="adapted mesh",
                            scalarbar=False)
        if debug:
            u = pb.solution
            plotter.plot(u, "pb")
            #dolfin.interactive()
    print "CPU time (PB): %.3g s" % (dolfin.toc(), )
    return pb
Пример #7
0
def HiptmairMatrixSetup(mesh, N, M):

    path = os.path.abspath(os.path.join(inspect.getfile(inspect.currentframe()), ".."))
    if __version__ == '1.6.0':
        gradient_code = open(os.path.join(path, 'DiscreteGradientSecond.cpp'), 'r').read()
    else:
        gradient_code = open(os.path.join(path, 'DiscreteGradient.cpp'), 'r').read()
    compiled_gradient_module = compile_extension_module(code=gradient_code)

    column =  numpy.zeros(2*mesh.num_edges(), order="C") #, dtype="intc")
    row =  numpy.zeros(2*mesh.num_edges(), order="C") #, dtype="intc")
    data =  numpy.zeros(2*mesh.num_edges(), order="C") #, dtype="intc")

    dataX =  numpy.zeros(2*mesh.num_edges(), order="C")
    dataY =  numpy.zeros(2*mesh.num_edges(), order="C")
    dataZ =  numpy.zeros(2*mesh.num_edges(), order="C")

    tic()
    c = compiled_gradient_module.ProlongationGradsecond(mesh, dataX,dataY,dataZ, data, row, column)
    end = toc()
    MO.StrTimePrint("Data for C and P created, time: ",end)
    # print row
    # print column
    # print  data
    C = csr_matrix((data,(row,column)), shape=(N, M)).tocsr()
    Px = csr_matrix((dataX,(row,column)), shape=(N, M)).tocsr()
    Py = csr_matrix((dataY,(row,column)), shape=(N, M)).tocsr()
    Pz = csr_matrix((dataZ,(row,column)), shape=(N, M)).tocsr()
    return C, [Px,Py,Pz]
Пример #8
0
    def apply(self, pc, x, y):


        x1 = x.getSubVector(self.u_is)
        y1 = x1.duplicate()
        y11 = x1.duplicate()
        x2 = x.getSubVector(self.p_is)
        y2 = x2.duplicate()
        y3 = x2.duplicate()
        y4 = x2.duplicate()

        self.kspA.solve(x2,y2)
        self.Fp.mult(y2,y3)
        self.kspQ.solve(y3,y4)
        self.Bt.mult(y4,y11)
        self.kspF.solve(x1-y11,y1)

        x1 = x.getSubVector(self.b_is)
        yy1 = x1.duplicate()
        x2 = x.getSubVector(self.r_is)
        yy2 = x2.duplicate()

        # tic()
        yy1, its, self.HiptmairTime = HiptmairSetup.HiptmairApply(self.A, x1, self.kspScalar, self.kspVector, self.G, self.P, self.tol)
        # print "Hiptmair time: ", toc()
        self.HiptmairIts += its
        tic()
        self.kspCGScalar.solve(x2, yy2)
        self.CGtime = toc()

        y.array = (np.concatenate([y1.array, y4.array,yy1.array,yy2.array]))
Пример #9
0
    def apply(self, pc, x, y):

        x1 = x.getSubVector(self.b_is)
        yy1 = x1.duplicate()
        x2 = x.getSubVector(self.r_is)
        yy2 = x2.duplicate()
        # tic()
        yy1, its, self.HiptmairTime = HiptmairSetup.HiptmairApply(
            self.A, x1, self.kspScalar, self.kspVector, self.G, self.P,
            self.tol)
        # print "Hiptmair time: ", toc()
        self.HiptmairIts += its
        tic()
        self.kspCGScalar.solve(x2, yy2)
        self.CGtime = toc()

        x1 = x.getSubVector(self.u_is)
        y1 = x1.duplicate()
        y11 = x1.duplicate()
        y111 = x1.duplicate()

        x2 = x.getSubVector(self.p_is)
        y2 = x2.duplicate()
        y3 = x2.duplicate()
        y4 = x2.duplicate()

        self.kspA.solve(x2, y2)
        self.Fp.mult(y2, y3)
        self.kspQ.solve(y3, y4)
        self.Bt.mult(y4, y11)
        self.C.mult(yy1, y111)
        self.kspF.solve(x1 - y11 - y111, y1)

        y.array = (np.concatenate([y1.array, y4.array, yy1.array, yy2.array]))
Пример #10
0
def compute_normal_modes(D, n_values=10, sigma=0., tol=1e-8, which='LM'):
    logger.debug("Solving eigenproblem. This may take a while...")
    df.tic()
    omega, w = scipy.sparse.linalg.eigs(D,
                                        n_values,
                                        which=which,
                                        sigma=0.,
                                        tol=tol,
                                        return_eigenvectors=True)
    logger.debug(
        "Computing the eigenvalues and eigenvectors took {:.2f} seconds".
        format(df.toc()))

    return omega, w
Пример #11
0
def HiptmairApply(A, b, kspVector, kspScalar, G, P,tol):
    x = b.duplicate()

    kspA = PETSc.KSP().create()
    kspA.setType('cg')
    pcA = kspA.getPC()
    pcA.setType('icc')
    # pcA.setPythonContext(HiptmairPrecond.SGS(A))
    OptDB = PETSc.Options()
    OptDB['pc_factor_mat_ordering_type'] = 'rcm'
    OptDB['pc_factor_fill'] = 2
    # OptDB['pc_factor_levels'] = 2

    kspA.max_it = 3
    kspA.setFromOptions()
    kspA.setOperators(A,A)

    ksp = PETSc.KSP().create()
    ksp.setTolerances(tol)
    # ksp.max_it = 4
    ksp.setType('cg')
    ksp.setOperators(A,A)
    pc = ksp.getPC()
    pc.setType(PETSc.PC.Type.PYTHON)

    pc.setPythonContext(HiptmairPrecond.GSvector(G, P, kspVector, kspScalar, kspA))


    scale = b.norm()
    b = b/scale
    tic()
    ksp.solve(b, x)
    time = toc()
    print "Hiptmair, its  ", ksp.its," time ", toc()
    x = x*scale
    return x, ksp.its, time
Пример #12
0
    def apply(self, pc, x, y):
        # self.kspCurlCurl.setOperators(self.B)
        x1 = x.getSubVector(self.u_is)
        y1 = x1.duplicate()
        x2 = x.getSubVector(self.p_is)
        y2 = x2.duplicate()

        # tic()
        y1, its, self.HiptmairTime = HiptmairSetup.HiptmairApply(self.A, x1, self.kspScalar, self.kspVector, self.G, self.P, self.tol)
        # print "Hiptmair time: ", toc()
        self.HiptmairIts += its
        tic()
        self.kspCGScalar.solve(x2, y2)
        self.CGtime = toc()
        # print "Laplacian, its ", self.kspCGScalar.its, "  time ",  self.CGtime

        # print "CG time: ", toc()
        # print "Laplacian inner iterations: ", self.kspCGScalar.its
        y.array = (np.concatenate([y1.array, y2.array]))
        self.CGits += self.kspCGScalar.its
Пример #13
0
#)

# prerefine with PB
dolfin.tic()
goal = phys.CurrentPB
pb = simplepnps.SimpleLinearPBGO(geo,
                                 phys,
                                 goal=goal,
                                 cheapest=solverp.cheapest)
#print pb.solvers["primal"].problem.bcs
#print [bc.g([-R,0.,0.]) for bc in pb.solvers["primal"].problem.bcs]

for i in pb.adaptive_loop(solverp.Nmax, solverp.frac):
    nano.plot_cross(pb.solution, mesh2D, title="pb potential", key="pb")

print "CPU time (PB): %.3g s" % (dolfin.toc(), )
#nano.plot1D(dict(pbx=pb.solution), (-R, R, 1001), axis="x",
#            dim=3, axlabels=("x [nm]", "pb potential [V]"))
#nano.plot1D(dict(pby=pb.solution), (-R, R, 1001), axis="y",
#            dim=3, axlabels=("x [nm]", "pb potential [V]"), newfig=False)
#
#nano.plot1D(dict(pbleft=pb.solution), (-H, H, 1001), axis="z",
#            origin=(-R-0.1,0.,0.),
#            dim=3, axlabels=("x [nm]", "pb potential [V]"))
#nano.plot1D(dict(pbfront=pb.solution), (-H, H, 1001), axis="z",
#            origin=(0,-R-0.1,0.),
#            dim=3, axlabels=("x [nm]", "pb potential [V]"), newfig=False)

#pb.visualize("fluid")
#nano.showplots()
#dolfin.interactive()
Пример #14
0
n_steps = 5000
t_end = 80.
while t < t_end:  #and cnt <= n_steps:
    problem = dlfn.LinearVariationalProblem(lhs, rhs, sol, bcs=bcs)
    solver = dlfn.LinearVariationalSolver(problem)
    solver.solve()
    v, p = sol.split()
    if cnt % 3200 == 0:
        print "t = {0:6.4f}".format(t)
        pvd_velocity << (v, t)
        pvd_pressure << (p, t)
    cd, cl = integrateFluidStress(v, p, nu, space_dim)
    drag_coeff_list.append(cd)
    lift_coeff_list.append(cl)
    iter_list.append(cnt)
    t_dim = t * t_ref
    t_list.append(t_dim)
    # update for next iteration
    sol00.assign(sol0)
    sol0.assign(sol)
    t += delta_t
    v_inlet.t += delta_t
    cnt += 1
print 'total simulation time in seconds: ', dlfn.toc()
#==============================================================================
import numpy as np
header = "0.iteration 1.t in s 2.drag_coeff 3.lift_coeff"
np.savetxt('coeff_comp_8s_re{0}_imex_final.gz'.format(int(reynolds)),\
           np.column_stack((iter_list, t_list, drag_coeff_list,\
                            lift_coeff_list)), fmt='%1.4e',\
                            header = header)
                        Expression, project, dx, inner)
    N = 4
    mesh = UnitCubeMesh(N, N, N)

    class Left(SubDomain):
        def inside(self, x, on_boundary):
            return x[0] > 0.7

    from cbcpost.utils import create_submesh

    markers = MeshFunction("size_t", mesh, 3)
    markers.set_all(0)
    Left().mark(markers, 1)
    tic()
    mesh2 = create_submesh(mesh, markers, 1)
    print "Time create submesh: ", toc()
    #bmesh.coordinates()[:] += 0.1
    #bmesh2 = Mesh("submesh.xml")

    #print bmesh2.size_global(0)
    #print bmesh2.size_global(2)
    V = FunctionSpace(mesh, "CG", 1)
    Vb = FunctionSpace(mesh2, "CG", 1)

    tic()
    mapping = restriction_map(V, Vb)
    print "Time restriction_map: ", toc()

    expr = Expression("x[0]*x[1]+x[2]*x[2]+3.0", degree=2)
    u = project(expr, V)
    u2 = Function(Vb)
Пример #16
0
def compute_eigenproblem_matrix(sim,
                                frequency_unit=1e9,
                                filename=None,
                                differentiate_H_numerically=True,
                                dtype=complex):
    """
    Compute and return the square matrix `D` defining the eigenproblem which
    has the normal mode frequencies and oscillation patterns as its solution.

    Note that `sim` needs to be in a relaxed state, otherwise the results will
    be wrong.

    """
    # Create the helper simulation which we use to compute
    # the effective field for various values of m.
    #Ms = sim.Ms
    #A = sim.get_interaction('Exchange').A
    #unit_length = sim.unit_length
    # try:
    #    sim.get_interaction('Demag')
    #    demag_solver = 'FK'
    # except ValueError:
    #    demag_solver = None
    #sim_aux = sim_with(sim.mesh, Ms=Ms, m_init=[1, 0, 0], A=A, unit_length=unit_length, demag_solver=demag_solver)
    # In order to compute the derivative of the effective field, the magnetisation needs to be set
    # to many different values. Thus we store a backup so that we can restore
    # it later.
    m_orig = sim.m

    def effective_field_for_m(m, normalise=True):
        if np.iscomplexobj(m):
            raise NotImplementedError(
                "XXX TODO: Implement the version for complex arrays!")
        sim.set_m(m, normalise=normalise, debug=False)
        return sim.effective_field()

    # N is the number of degrees of freedom of the magnetisation vector.
    # It may be smaller than the number of mesh nodes if we are using
    # periodic boundary conditions.
    N = sim.llg.S3.dim()
    n = N // 3
    assert (N == 3 * n)

    m0_array = sim.m.copy()
    # this corresponds to the vector 'm0_flat' in Simlib
    m0_3xn = m0_array.reshape(3, n)
    m0_column_vector = m0_array.reshape(3, 1, n)
    H0_array = effective_field_for_m(m0_array)
    H0_3xn = H0_array.reshape(3, n)
    h0 = H0_3xn[0] * m0_3xn[0] + H0_3xn[1] * m0_3xn[1] + H0_3xn[2] * m0_3xn[2]

    logger.debug(
        "Computing basis of the tangent space and transition matrices.")
    Q, R, S, Mcross = compute_tangential_space_basis(m0_column_vector)
    Qt = mf_transpose(Q).copy()

    # Returns the product of the linearised llg times vector
    def linearised_llg_times_vector(v):
        assert v.shape == (3, 1, n)
        # The linearised equation is
        # dv/dt = - gamma m0 x (H' v - h_0 v)
        v_array = v.view()
        v_array.shape = (-1, )
        # Compute H'(m_0)*v, i.e. the "directional derivative" of H at
        # m_0 in the direction of v. Since H is linear in m (at least
        # theoretically, although this is not quite true in the case
        # of our demag computation), this is the same as H(v)!
        if differentiate_H_numerically:
            res = differentiate_fd4(effective_field_for_m, m0_array, v_array)
        else:
            res = effective_field_for_m(v_array, normalise=False)
        res.shape = (3, -1)
        # Subtract h0 v
        res[0] -= h0 * v[0, 0]
        res[1] -= h0 * v[1, 0]
        res[2] -= h0 * v[2, 0]
        # Multiply by -gamma m0x
        res *= sim.gamma
        res.shape = (3, 1, -1)
        # Put res on the left in case v is complex
        res = mf_cross(res, m0_column_vector)
        return res

    # The linearised equation in the tangential basis
    def linearised_llg_times_tangential_vector(w):
        w = w.view()
        w.shape = (2, 1, n)
        # Go to the 3d space
        v = mf_mult(Q, w)
        # Compute the linearised llg
        L = linearised_llg_times_vector(v)
        # Go back to 2d space
        res = np.empty(w.shape, dtype=dtype)
        res[:] = mf_mult(Qt, L)
        if dtype == complex:
            # Multiply by -i/(2*pi*U) so that we get frequencies as the real
            # part of eigenvalues
            res *= -1j / (2 * pi * frequency_unit)
        else:
            # This will yield imaginary eigenvalues, but we divide by 1j in the
            # calling routine.
            res *= 1. / (2 * pi * frequency_unit)
        res.shape = (-1, )
        return res

    df.tic()
    logger.info("Assembling eigenproblem matrix.")
    D = np.zeros((2 * n, 2 * n), dtype=dtype)
    logger.debug(
        "Eigenproblem matrix D will occupy {:.2f} MB of memory.".format(
            D.nbytes / 1024.**2))
    for i, w in enumerate(np.eye(2 * n)):
        if i % 50 == 0:
            t_cur = df.toc()
            completion_info = '' if (
                i == 0) else ', estimated remaining time: {}'.format(
                    helpers.format_time(t_cur * (2 * n / i - 1)))
            logger.debug("Processing row {}/{}  (time elapsed: {}{})".format(
                i, 2 * n, helpers.format_time(t_cur), completion_info))
        D[:, i] = linearised_llg_times_tangential_vector(w)
    logger.debug("Eigenproblem matrix D occupies {:.2f} MB of memory.".format(
        D.nbytes / 1024.**2))
    logger.info("Finished assembling eigenproblem matrix.")

    if filename != None:
        logger.info("Saving eigenproblem matrix to file '{}'".format(filename))
        np.save(filename, D)

    # Restore the original magnetisation.
    # XXX TODO: Is this method safe, or does it leave any trace of the
    # temporary changes we did above?
    sim.set_m(m_orig)

    return D
    def run(self):
        self._print_info_message()

        self._setup_function_spaces()

        self._setup_boundary_conditions()

        self._update_imex_coefficients()

        if self._parameters.solver_type is SolverType.linear_imex_solver:
            self._setup_imex_problem()
        elif self._parameters.solver_type is SolverType.nonlinear_implicit_solver:
            self._setup_implicit_problem()

        self._setup_initial_conditions()

        velocity, pressure, temperature = self._sol0.split()
        self._output_results(velocity, temperature, pressure, 0, 0, True)
        self._output_global_averages(velocity, temperature, 0, 0, True)

        # initialize timestep
        timestep = self._parameters.timestep
        omega = 1.0
        # initialize timestepping
        from time_stepping import TimestepControl
        timestep_control = TimestepControl((
            self._parameters.min_cfl,
            self._parameters.max_cfl,
        ), (
            self._parameters.min_timestep,
            self._parameters.max_timestep,
        ))
        # update flag
        timestep_modified = False
        # dolfin timer
        dlfn.tic()
        # time loop
        time = 0.0
        step = 0
        while time < self._parameters.t_end and step < self._parameters.n_steps + 1:
            print "Iteration: {0:08d}, time = {1:10.5f}, time step = {2:5.4e}"\
                  .format(step, time, timestep)
            if timestep_modified:
                self._timestep.assign(timestep)
                self._omega.assign(omega)
                self._update_imex_coefficients(step, omega)
                self._rebuild_matrices = True
            # compute solution
            self._solve(step)
            # extract solution
            velocity, pressure, temperature = self._sol.split()
            # compute cfl number
            cfl = self._compute_cfl_number(velocity, timestep)
            if step % self._parameters.cfl_frequency == 0:
                print "   current cfl number:\t{0:03.2e}".format(cfl)
            #===================================================================
            # modify time step
            if self._parameters.adaptive_time_stepping:
                timestep_modified, timestep, omega \
                    = timestep_control.adjust_time_step(cfl, timestep)
            elif step == 0:
                # update coefficients after initial step to switch to SBF2
                timestep_modified = True
            elif step == 1:
                timestep_modified = False
            # write output
            if step % self._parameters.output_frequency == 0:
                self._output_results(velocity, temperature, pressure, step,
                                     time)
            # compute rms values
            if step % self._parameters.global_avg_frequency == 0:
                self._output_global_averages(velocity, temperature, step, time)
            # write checkpoint
            if step % self._parameters.checkpoint_frequency == 0 and step != 0:
                self._write_checkpoint(step, time)
            # update solutions for next iteration
            self._sol00.assign(self._sol0)
            self._sol0.assign(self._sol)
            # update time
            time += timestep
            # increase counter
            step += 1
        print "elapsed simulation time: ", dlfn.toc(), " sec"
        # save checkpoint time
        checkpoint_logging[checkpoint_cnt] = step, time
        checkpoint_cnt += 1
    #===========================================================================
    # update solutions for next iteration
    sol00.assign(sol0)
    sol0.assign(sol)
    time += dt
    #===========================================================================
    # increase counter
    step += 1
    #===========================================================================
    # asserts to guarantee that variable type are correct
    assert isinstance(time_step, dlfn.Constant)
    assert isinstance(dt, float) and isinstance(dt_old, float)
print "elapsed simulation time: ", dlfn.toc(), " sec"
#===========================================================================
print "\nCreating plots... "
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 1, sharex=True)
ax[0].semilogy(time_logging[:,2])
ax[0].set_ylabel("dt")
ax[1].plot(time_logging[:,1])
ax[1].set_xlabel("step number")
ax[1].set_ylabel("cfl")
plt.savefig("time_step_history.pdf")
fig, ax = plt.subplots(2, 1, sharex=True)
ax[0].plot(rms_logging[:,1], rms_logging[:,2])
ax[0].set_ylabel("velocity")
ax[1].plot(rms_logging[:,1], rms_logging[:,3])
ax[1].set_xlabel("time")
Пример #19
0
def solve(A,b,u,IS,Fspace,IterType,OuterTol,InnerTol,HiptmairMatrices,KSPlinearfluids,kspF,Fp,MatrixLinearFluids,kspFp):

    if IterType == "Full":
        kspOuter = PETSc.KSP().create()
        kspOuter.setTolerances(OuterTol)
        kspOuter.setType('fgmres')

        u_is = PETSc.IS().createGeneral(range(Fspace[0].dim()))
        p_is = PETSc.IS().createGeneral(range(Fspace[0].dim(),Fspace[0].dim()+Fspace[1].dim()))
        Bt = A.getSubMatrix(u_is,p_is)

        reshist = {}
        def monitor(ksp, its, fgnorm):
            reshist[its] = fgnorm
            print "OUTER:", fgnorm
        kspOuter.setMonitor(monitor)
        pcOutter = kspOuter.getPC()
        pcOutter.setType(PETSc.PC.Type.KSP)

        kspOuter.setOperators(A,A)
        kspOuter.max_it = 500

        kspInner = pcOutter.getKSP()
        kspInner.max_it = 100

        kspInner.max_it = 100
        reshist1 = {}
        def monitor(ksp, its, fgnorm):
            reshist1[its] = fgnorm
            print "INNER:", fgnorm
        # kspInner.setMonitor(monitor)

        kspInner.setType('gmres')
        kspInner.setTolerances(InnerTol)

        pcInner = kspInner.getPC()
        pcInner.setType(PETSc.PC.Type.PYTHON)
        pcInner.setPythonContext(MHDstabPrecond.InnerOuterWITHOUT(Fspace,kspF, KSPlinearfluids[0], KSPlinearfluids[1],Fp, HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],1e-6,A))

        PP = PETSc.Mat().createPython([A.size[0], A.size[0]])
        PP.setType('python')
        p = PrecondMulti.MultiApply(Fspace,A,HiptmairMatrices[6],MatrixLinearFluids[1],MatrixLinearFluids[0],kspFp, HiptmairMatrices[3])

        PP.setPythonContext(p)
        kspInner.setOperators(PP)

        tic()
        scale = b.norm()
        b = b/scale
        print b.norm()
        kspOuter.solve(b, u)
        u = u*scale
        print toc()

        # print s.getvalue()
        NSits = kspOuter.its
        del kspOuter
        Mits = kspInner.its
        del kspInner
        # print u.array
        return u,NSits,Mits

    NS_is = IS[0]
    M_is = IS[1]
    kspNS = PETSc.KSP().create()
    kspM = PETSc.KSP().create()
    kspNS.setTolerances(OuterTol)

    kspNS.setOperators(A.getSubMatrix(NS_is,NS_is))
    kspM.setOperators(A.getSubMatrix(M_is,M_is))
    del A

    uNS = u.getSubVector(NS_is)
    bNS = b.getSubVector(NS_is)
    kspNS.setType('gmres')
    pcNS = kspNS.getPC()
    kspNS.setTolerances(OuterTol)
    pcNS.setType(PETSc.PC.Type.PYTHON)
    if IterType == "MD":
        pcNS.setPythonContext(NSpreconditioner.NSPCD(MixedFunctionSpace([Fspace[0],Fspace[1]]), kspF, KSPlinearfluids[0], KSPlinearfluids[1],Fp))
    else:
        pcNS.setPythonContext(StokesPrecond.MHDApprox(MixedFunctionSpace([Fspace[0],Fspace[1]]), kspF, KSPlinearfluids[1]))

    scale = bNS.norm()
    bNS = bNS/scale
    start_time = time.time()
    kspNS.solve(bNS, uNS)
    print ("{:25}").format("NS, time: "), " ==>  ",("{:4f}").format(time.time() - start_time),("{:9}").format("   Its: "), ("{:4}").format(kspNS.its),  ("{:9}").format("   time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5])
    uNS = scale*uNS

    NSits = kspNS.its
    # kspNS.destroy()
    # for line in reshist.values():
    #     print line

    kspM.setFromOptions()
    kspM.setType(kspM.Type.MINRES)
    kspM.setTolerances(InnerTol)
    pcM = kspM.getPC()
    pcM.setType(PETSc.PC.Type.PYTHON)
    pcM.setPythonContext(MP.Hiptmair(MixedFunctionSpace([Fspace[2],Fspace[3]]), HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],1e-6))


    # x = x*scale
    uM = u.getSubVector(M_is)
    bM = b.getSubVector(M_is)

    scale = bM.norm()
    bM = bM/scale
    start_time = time.time()
    kspM.solve(bM, uM)
    print ("{:25}").format("Maxwell solve, time: "), " ==>  ",("{:4f}").format(time.time() - start_time),("{:9}").format("   Its: "), ("{:4}").format(kspM.its),  ("{:9}").format("   time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5])
    uM = uM*scale

    Mits = kspM.its
    kspM.destroy()
    u = IO.arrayToVec(np.concatenate([uNS.array, uM.array]))

    return u,NSits,Mits
Пример #20
0
def solve(A,b,u,P,IS,Fspace,IterType,OuterTol,InnerTol,Mass=0,L=0,F=0):

    # u = b.duplicate()
    if IterType == "Full":

        kspOuter = PETSc.KSP().create()
        kspOuter.setTolerances(OuterTol)
        kspOuter.setType('fgmres')

        reshist = {}
        def monitor(ksp, its, fgnorm):
            reshist[its] = fgnorm
            print "OUTER:", fgnorm
        kspOuter.setMonitor(monitor)
        pcOutter = kspOuter.getPC()
        pcOutter.setType(PETSc.PC.Type.KSP)

        kspOuter.setOperators(A)

        kspOuter.max_it = 500

        kspInner = pcOutter.getKSP()
        kspInner.max_it = 100

        reshist1 = {}
        def monitor(ksp, its, fgnorm):
            reshist1[its] = fgnorm
            print "INNER:", fgnorm
        # kspInner.setMonitor(monitor)

        kspInner.setType('gmres')
        kspInner.setTolerances(InnerTol)

        pcInner = kspInner.getPC()
        pcInner.setType(PETSc.PC.Type.PYTHON)
        pcInner.setPythonContext(MHDprecond.D(Fspace,P, Mass, F, L))

        PP = PETSc.Mat().createPython([A.size[0], A.size[0]])
        PP.setType('python')
        p = PrecondMulti.P(Fspace,P,Mass,L,F)

        PP.setPythonContext(p)
        kspInner.setOperators(PP)

        tic()
        scale = b.norm()
        b = b/scale
        print b.norm()
        kspOuter.solve(b, u)
        u = u*scale
        print toc()

        # print s.getvalue()
        NSits = kspOuter.its
        del kspOuter
        Mits = kspInner.its
        del kspInner
        # print u.array
        return u,NSits,Mits

    NS_is = IS[0]
    M_is = IS[1]
    kspNS = PETSc.KSP().create()
    kspM = PETSc.KSP().create()
    kspNS.setTolerances(OuterTol)

    kspNS.setOperators(A.getSubMatrix(NS_is,NS_is),P.getSubMatrix(NS_is,NS_is))
    kspM.setOperators(A.getSubMatrix(M_is,M_is),P.getSubMatrix(M_is,M_is))
    # print P.symmetric
    A.destroy()
    P.destroy()
    if IterType == "MD":
        kspNS.setType('gmres')
        kspNS.max_it = 500

        pcNS = kspNS.getPC()
        pcNS.setType(PETSc.PC.Type.PYTHON)
        pcNS.setPythonContext(NSprecond.PCDdirect(MixedFunctionSpace([Fspace[0],Fspace[1]]), Mass, F, L))
    elif IterType == "CD":
        kspNS.setType('minres')
        pcNS = kspNS.getPC()
        pcNS.setType(PETSc.PC.Type.PYTHON)
        pcNS.setPythonContext(StokesPrecond.Approx(MixedFunctionSpace([Fspace[0],Fspace[1]])))
    reshist = {}
    def monitor(ksp, its, fgnorm):
        reshist[its] = fgnorm
        print fgnorm
    # kspNS.setMonitor(monitor)

    uNS = u.getSubVector(NS_is)
    bNS = b.getSubVector(NS_is)
    # print kspNS.view()
    scale = bNS.norm()
    bNS = bNS/scale
    print bNS.norm()
    kspNS.solve(bNS, uNS)
    uNS = uNS*scale
    NSits = kspNS.its
    kspNS.destroy()
    # for line in reshist.values():
    #     print line
    kspM.setFromOptions()
    kspM.setType(kspM.Type.MINRES)
    kspM.setTolerances(InnerTol)
    pcM = kspM.getPC()
    pcM.setType(PETSc.PC.Type.PYTHON)
    pcM.setPythonContext(MP.Direct(MixedFunctionSpace([Fspace[2],Fspace[3]])))

    uM = u.getSubVector(M_is)
    bM = b.getSubVector(M_is)
    scale = bM.norm()
    bM = bM/scale
    print bM.norm()
    kspM.solve(bM, uM)
    uM = uM*scale
    Mits = kspM.its
    kspM.destroy()
    u = IO.arrayToVec(np.concatenate([uNS.array, uM.array]))
    return u,NSits,Mits
Пример #21
0
    def solve_eigenproblem(self, A, M=None, num=None, tol=None):
        """
        Solve the (possibly generalised) eigenvalue problem defined by

           A*v = omega*M*v

        If `M` is `None`, it uses the identity matrix for `M`.


        *Arguments*

        A:  np.array

            The matrix on the left-hand side of the eigenvalue problem.

        M:  np.array | None

            The matrix on the right-hand side of the generalised
            eigenvalue problem. Assumes the identity matrix if not
            given.

        num :  int

            If given, limit the number of returned eigenvalues and
            eigenvectors to at most `num`. Default: `None`.

        tol :  float

            The tolerance for the computed eigensolutions (TODO: what
            exactly does this mean?!? Relative or absolute?!?). The
            meaning depends on the individual solver. Note that not
            all solvers may use/respect this argument (for example,
            the dense Scipy solvers don't). The default is None, which
            means that whatever the solver's default is will be used.


        *Returns*

        A pair `(omega, w)` where `omega` is the list of eigenvalues
        and `w` the list of corresponding eigenvectors. Both lists are
        sorted in in ascending order of the eigenvalues.

        """
        def eigenproblem_is_hermitian():
            return is_hermitian(A) and (M == None or is_hermitian(M))

        if self.is_hermitian() and not eigenproblem_is_hermitian():
            raise ValueError(
                "Eigenproblem matrices are non-Hermitian but solver "
                "assumes Hermitian matrices. Aborting.")
        logger.info("Solving eigenproblem. This may take a while...")
        df.tic()
        omegas, ws = self._solve_eigenproblem(A, M=M, num=num, tol=tol)
        logger.info("Computing the eigenvalues and eigenvectors "
                    "took {}".format(format_time(df.toc())))

        # XXX TODO: Remove this conversion to numpy.arrays once we
        #           have better support for different kinds of
        #           matrices (but the conversion would happen in
        #           compute_relative_error() anyway, so by doing it
        #           here we avoid doing it multiple times.
        if not isinstance(A, np.ndarray):
            logger.warning(
                "Converting sparse matrix A to dense array to check whether it is "
                "Hermitian. This might consume a lot of memory if A is big!.")
            A = as_dense_array(A)
        if not isinstance(M, (np.ndarray, NoneType)):
            logger.warning(
                "Converting sparse matrix M to dense array to check whether it is "
                "Hermitian. This might consume a lot of memory if M is big!.")
            M = as_dense_array(M)

        rel_errors = np.array([
            compute_relative_error(A, M, omega, w)
            for omega, w in zip(omegas, ws)
        ])
        return omegas, ws, rel_errors
Пример #22
0
 def __exit__(self, *args):
     print("%.2g s" % (dolfin.toc(), ))
Пример #23
0
    # regroup
    Isim0 = Isim
    nx = len(bVsim)
    ny = range(int(float(len(Isim0))/nx))
    Isim0p = [Isim0[slice(i*nx,(i+1)*nx)] for i in ny]

    plt.figure()
    for i in ny:
        plt.plot(bV, Isim0p[i], '-x', label='PNPS '+str(qssim[i])+' mC/m$^2$')

# # get experimental data from csv file
# # Experimental Values taken from:
# # Properties of Bacillus cereus hemolysin II: A heptameric transmembrane pore
# csvfile = 'data/ahemIV/ahemIV'
# IV = numpy.genfromtxt(csvfile+'.csv', delimiter=',')
# Vexp = -IV[1:-1,0]*1e-3
# Iexp = -IV[1:-1,1]
# plt.plot(Vexp, Iexp, '-ks', label='experimental')

plt.plot(bV, I, '-^', label='ICR (+ diode)')
plt.plot(bV, bmV/(R+r), '-v', label='ohmic')
plt.xlabel("V [V]")
plt.ylabel("I [pA]")
title = ("relative diffusivity in pore: "+str(args["rDPore"]) if not hasattr(args["rDPore"], '__iter__') else "ahem surface charge: "+str(args["ahemqs"]))
plt.title(title)
plt.legend(loc=0,)
plt.grid('on')
plt.show()

print "\nTotal Time: ", dolfin.toc()
Пример #24
0
while not stop:

    tstep_hook(**vars())

    solve(**vars())

    update(**vars())

    t += dt
    tstep += 1

    stop = save_solution(**vars())

    if tstep % info_intv == 0 or stop:
        info_green("Time = {0:f}, timestep = {1:d}".format(t, tstep))
        split_computing_time = df.toc()
        split_num_tsteps = tstep-tstep_0
        df.tic()
        tstep_0 = tstep
        total_computing_time += split_computing_time
        total_num_tsteps += split_num_tsteps
        info_cyan("Computing time for previous {0:d}"
                  " timesteps: {1:f} seconds"
                  " ({2:f} seconds/timestep)".format(
                      split_num_tsteps, split_computing_time,
                      split_computing_time/split_num_tsteps))
        df.list_timings(df.TimingClear_clear, [df.TimingType_wall])

if total_num_tsteps > 0:
    info_cyan("Total computing time for all {0:d}"
              " timesteps: {1:f} seconds"
Пример #25
0
OptDB['ksp_gmres_restart'] = 200
# FSpace = [Velocity,Magnetic,Pressure,Lagrange]
reshist = {}
def monitor(ksp, its, fgnorm):
    reshist[its] = fgnorm
    print its,"    OUTER:", fgnorm
# ksp.setMonitor(monitor)
ksp.max_it = 500
# W = Fspace
# FFSS = [W.sub(0),W.sub(1),W.sub(2),W.sub(3)]
pc.setPythonContext(MHDprec.Parallel(dim,kspF, Fluid[0], Fluid[1],Fp, HX[3], HX[4], HX[2], HX[0], HX[1], HX[6],1e-6,1))
#OptDB = PETSc.Options()

# OptDB['pc_factor_mat_solver_package']  = "mumps"
# OptDB['pc_factor_mat_ordering_type']  = "rcm"
# ksp.setFromOptions()
scale = b.norm()
b = b/scale
u = b.duplicate()
ksp.setOperators(K,K)
del K
tic()
ksp.solve(b,u)
print toc()
# Mits +=dodim
u = u*scale
print ksp.its
# MO.PrintStr("Number iterations = "+str(ksp.its),60,"+","\n\n","\n\n")


Пример #26
0
    solver_type = sys.argv[1]
except IndexError:
    print("Usage: time_solver_types.py SOLVER_TYPE [N]")
    sys.exit()

try:
    N = int(sys.argv[2])
except IndexError:
    N = 3

from finmag.example import barmini, bar
from finmag.example.normal_modes import disk

timings = []
for i in xrange(N):
    print("[DDD] Starting run #{}".format(i))
    #sim = bar(demag_solver_type=solver_type)
    sim = disk(d=100,
               h=10,
               maxh=3.0,
               relaxed=False,
               demag_solver_type=solver_type)
    df.tic()
    sim.relax()
    timings.append(df.toc())
    print("Latest run took {:.2f} seconds.".format(timings[-1]))
print("Timings (in seconds): {}".format(['{:.2f}'.format(t) for t in timings]))
print("Mean: {:.2f}".format(np.mean(timings)))
print("Median: {:.2f}".format(np.median(timings)))
print("Fastest: {:.2f}".format(np.min(timings)))
Пример #27
0
def solve(A,b,u,IS,Fspace,IterType,OuterTol,InnerTol,HiptmairMatrices,KSPlinearfluids,kspF,Fp,MatrixLinearFluids,kspFp):

    if IterType == "Full":
        ksp = PETSc.KSP().create()
        ksp.setTolerances(OuterTol)
        ksp.setType('fgmres')

        u_is = PETSc.IS().createGeneral(range(Fspace[0].dim()))
        p_is = PETSc.IS().createGeneral(range(Fspace[0].dim(),Fspace[0].dim()+Fspace[1].dim()))
        b_is = PETSc.IS().createGeneral(range(Fspace[0].dim()+Fspace[1].dim(),Fspace[0].dim()+Fspace[1].dim()+Fspace[2].dim()))

        Bt = A.getSubMatrix(u_is,p_is)
        C = A.getSubMatrix(u_is,b_is)
        reshist = {}
        def monitor(ksp, its, fgnorm):
            reshist[its] = fgnorm
            # print "------------------------->>>> ", ksp.buildResidual().array
            print "OUTER:", fgnorm
            return ksp.buildResidual().array
        ksp.setMonitor(monitor)
        pc = ksp.getPC()
        pc.setType(PETSc.PC.Type.KSP)

        ksp.setOperators(A)

        reshist1 = {}
        def monitor(ksp, its, fgnorm):
            reshist1[its] = fgnorm
            print "INNER:", fgnorm
        # ksp.setMonitor(monitor)

        pc = ksp.getPC()
        pc.setType(PETSc.PC.Type.PYTHON)
        pc.setPythonContext(MHDstabPrecond.Test(Fspace,kspF, KSPlinearfluids[0], KSPlinearfluids[1],Fp, HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],1e-3,Bt,C))

        # PP = PETSc.Mat().createPython([A.size[0], A.size[0]])
        # PP.setType('python')
        # p = PrecondMulti.MultiApply(Fspace,A,HiptmairMatrices[6],MatrixLinearFluids[1],MatrixLinearFluids[0],kspFp, HiptmairMatrices[3])



        tic()
        scale = b.norm()
        b = b/scale
        print b.norm()
        ksp.solve(b, u)
        u = u*scale
        print toc()

        # print s.getvalue()
        NSits = ksp.its
        del ksp

        # print u.array
        return u,NSits,1

    NS_is = IS[0]
    M_is = IS[1]
    kspNS = PETSc.KSP().create()
    kspM = PETSc.KSP().create()
    kspNS.setTolerances(OuterTol)

    kspNS.setOperators(A.getSubMatrix(NS_is,NS_is))
    kspM.setOperators(A.getSubMatrix(M_is,M_is))
    del A

    uNS = u.getSubVector(NS_is)
    bNS = b.getSubVector(NS_is)
    kspNS.setType('gmres')
    pcNS = kspNS.getPC()
    kspNS.setTolerances(OuterTol)
    pcNS.setType(PETSc.PC.Type.PYTHON)
    if IterType == "MD":
        pcNS.setPythonContext(NSpreconditioner.NSPCD(MixedFunctionSpace([Fspace[0],Fspace[1]]), kspF, KSPlinearfluids[0], KSPlinearfluids[1],Fp))
    else:
        pcNS.setPythonContext(StokesPrecond.MHDApprox(MixedFunctionSpace([Fspace[0],Fspace[1]]), kspF, KSPlinearfluids[1]))

    scale = bNS.norm()
    bNS = bNS/scale
    start_time = time.time()
    kspNS.solve(bNS, uNS)
    print ("{:25}").format("NS, time: "), " ==>  ",("{:4f}").format(time.time() - start_time),("{:9}").format("   Its: "), ("{:4}").format(kspNS.its),  ("{:9}").format("   time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5])
    uNS = scale*uNS

    NSits = kspNS.its
    # kspNS.destroy()
    # for line in reshist.values():
    #     print line

    kspM.setFromOptions()
    kspM.setType(kspM.Type.MINRES)
    kspM.setTolerances(InnerTol)
    pcM = kspM.getPC()
    pcM.setType(PETSc.PC.Type.PYTHON)
    pcM.setPythonContext(MP.Hiptmair(MixedFunctionSpace([Fspace[2],Fspace[3]]), HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],1e-6))


    # x = x*scale
    uM = u.getSubVector(M_is)
    bM = b.getSubVector(M_is)

    scale = bM.norm()
    bM = bM/scale
    start_time = time.time()
    kspM.solve(bM, uM)
    print ("{:25}").format("Maxwell solve, time: "), " ==>  ",("{:4f}").format(time.time() - start_time),("{:9}").format("   Its: "), ("{:4}").format(kspM.its),  ("{:9}").format("   time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5])
    uM = uM*scale

    Mits = kspM.its
    kspM.destroy()
    u = IO.arrayToVec(np.concatenate([uNS.array, uM.array]))

    return u,NSits,Mits
Пример #28
0
def solve(A,
          b,
          u,
          P,
          IS,
          Fspace,
          IterType,
          OuterTol,
          InnerTol,
          Mass=0,
          L=0,
          F=0):

    # u = b.duplicate()
    if IterType == "Full":

        kspOuter = PETSc.KSP().create()
        kspOuter.setTolerances(OuterTol)
        kspOuter.setType('fgmres')

        reshist = {}

        def monitor(ksp, its, fgnorm):
            reshist[its] = fgnorm
            print "OUTER:", fgnorm

        kspOuter.setMonitor(monitor)
        pcOutter = kspOuter.getPC()
        pcOutter.setType(PETSc.PC.Type.KSP)

        kspOuter.setOperators(A)

        kspOuter.max_it = 500

        kspInner = pcOutter.getKSP()
        kspInner.max_it = 100

        reshist1 = {}

        def monitor(ksp, its, fgnorm):
            reshist1[its] = fgnorm
            print "INNER:", fgnorm

        # kspInner.setMonitor(monitor)

        kspInner.setType('gmres')
        kspInner.setTolerances(InnerTol)

        pcInner = kspInner.getPC()
        pcInner.setType(PETSc.PC.Type.PYTHON)
        pcInner.setPythonContext(MHDprecond.D(Fspace, P, Mass, F, L))

        PP = PETSc.Mat().createPython([A.size[0], A.size[0]])
        PP.setType('python')
        p = PrecondMulti.P(Fspace, P, Mass, L, F)

        PP.setPythonContext(p)
        kspInner.setOperators(PP)

        tic()
        scale = b.norm()
        b = b / scale
        print b.norm()
        kspOuter.solve(b, u)
        u = u * scale
        print toc()

        # print s.getvalue()
        NSits = kspOuter.its
        del kspOuter
        Mits = kspInner.its
        del kspInner
        # print u.array
        return u, NSits, Mits

    NS_is = IS[0]
    M_is = IS[1]
    kspNS = PETSc.KSP().create()
    kspM = PETSc.KSP().create()
    kspNS.setTolerances(OuterTol)

    kspNS.setOperators(A.getSubMatrix(NS_is, NS_is),
                       P.getSubMatrix(NS_is, NS_is))
    kspM.setOperators(A.getSubMatrix(M_is, M_is), P.getSubMatrix(M_is, M_is))
    # print P.symmetric
    A.destroy()
    P.destroy()
    if IterType == "MD":
        kspNS.setType('gmres')
        kspNS.max_it = 500

        pcNS = kspNS.getPC()
        pcNS.setType(PETSc.PC.Type.PYTHON)
        pcNS.setPythonContext(
            NSprecond.PCDdirect(MixedFunctionSpace([Fspace[0], Fspace[1]]),
                                Mass, F, L))
    elif IterType == "CD":
        kspNS.setType('minres')
        pcNS = kspNS.getPC()
        pcNS.setType(PETSc.PC.Type.PYTHON)
        pcNS.setPythonContext(
            StokesPrecond.Approx(MixedFunctionSpace([Fspace[0], Fspace[1]])))
    reshist = {}

    def monitor(ksp, its, fgnorm):
        reshist[its] = fgnorm
        print fgnorm

    # kspNS.setMonitor(monitor)

    uNS = u.getSubVector(NS_is)
    bNS = b.getSubVector(NS_is)
    # print kspNS.view()
    scale = bNS.norm()
    bNS = bNS / scale
    print bNS.norm()
    kspNS.solve(bNS, uNS)
    uNS = uNS * scale
    NSits = kspNS.its
    kspNS.destroy()
    # for line in reshist.values():
    #     print line
    kspM.setFromOptions()
    kspM.setType(kspM.Type.MINRES)
    kspM.setTolerances(InnerTol)
    pcM = kspM.getPC()
    pcM.setType(PETSc.PC.Type.PYTHON)
    pcM.setPythonContext(MP.Direct(MixedFunctionSpace([Fspace[2], Fspace[3]])))

    uM = u.getSubVector(M_is)
    bM = b.getSubVector(M_is)
    scale = bM.norm()
    bM = bM / scale
    print bM.norm()
    kspM.solve(bM, uM)
    uM = uM * scale
    Mits = kspM.its
    kspM.destroy()
    u = IO.arrayToVec(np.concatenate([uNS.array, uM.array]))
    return u, NSits, Mits
Пример #29
0
def compute_generalised_eigenproblem_matrices(
        sim,
        alpha=0.0,
        frequency_unit=1e9,
        filename_mat_A=None,
        filename_mat_M=None,
        check_hermitian=False,
        differentiate_H_numerically=True):
    """
    XXX TODO: write me

    """
    m_orig = sim.m

    def effective_field_for_m(m, normalise=True):
        if np.iscomplexobj(m):
            raise NotImplementedError(
                "XXX TODO: Implement the version for complex arrays!")
        sim.set_m(m, normalise=normalise)
        return sim.effective_field()

    n = sim.mesh.num_vertices()
    N = 3 * n  # number of degrees of freedom

    m0_array = sim.m.copy()
    # this corresponds to the vector 'm0_flat' in Simlib
    m0_3xn = m0_array.reshape(3, n)
    m0_column_vector = m0_array.reshape(3, 1, n)
    H0_array = effective_field_for_m(m0_array)
    H0_3xn = H0_array.reshape(3, n)
    h0 = H0_3xn[0] * m0_3xn[0] + H0_3xn[1] * m0_3xn[1] + H0_3xn[2] * m0_3xn[2]

    logger.debug(
        "Computing basis of the tangent space and transition matrices.")
    Q, R, S, Mcross = compute_tangential_space_basis(m0_column_vector)
    Qt = mf_transpose(Q).copy()

    logger.debug("Q.shape: {} ({} MB)".format(Q.shape, Q.nbytes / 1024.**2))

    def A_times_vector(v):
        # A = H' v - h_0 v
        assert v.shape == (3, 1, n)
        v_array = v.view()
        v_array.shape = (-1, )
        # Compute H'(m_0)*v, i.e. the "directional derivative" of H at
        # m_0 in the direction of v. Since H is linear in m (at least
        # theoretically, although this is not quite true in the case
        # of our demag computation), this is the same as H(v)!
        if differentiate_H_numerically:
            res = differentiate_fd4(effective_field_for_m, m0_array, v_array)
        else:
            res = effective_field_for_m(v_array, normalise=False)
        res.shape = (3, n)
        # Subtract h0 v
        res[0] -= h0 * v[0, 0]
        res[1] -= h0 * v[1, 0]
        res[2] -= h0 * v[2, 0]
        res.shape = (3, 1, n)
        return res

    df.tic()
    logger.info("Assembling eigenproblem matrix.")
    A = np.zeros((2 * n, 2 * n), dtype=complex)
    logger.debug("Eigenproblem matrix A occupies {:.2f} MB of memory.".format(
        A.nbytes / 1024.**2))

    # Compute A
    w = np.zeros(2 * n)
    for i in xrange(2 * n):
        if i % 50 == 0:
            logger.debug(
                "Processing row {}/{}  (time taken so far: {:.2f} seconds)".
                format(i, 2 * n, df.toc()))

        # Ensure that w is the i-th standard basis vector
        w.shape = (2 * n, )
        w[i - 1] = 0.0  # this will do no harm if i==0
        w[i] = 1.0

        w.shape = (2, 1, n)
        Av = A_times_vector(mf_mult(Q, w))
        A[:, i] = mf_mult(Qt, Av).reshape(-1)
        # Multiply by (-gamma)/(2 pi U)
        A[:, i] *= -sim.gamma / (2 * pi * frequency_unit)

    # Compute B, which is -i Mcross 2 pi U / gamma
    # B = np.zeros((2, n, 2, n), dtype=complex)
    # for i in xrange(n):
    #     B[:, i, :, i] = Mcross[:, :, i]
    #     B[:, i, :, i] *= -1j
    # B.shape = (2*n, 2*n)

    M = scipy.sparse.linalg.LinearOperator((2 * n, 2 * n),
                                           M_times_w(Mcross, n, alpha),
                                           NotImplementedOp(),
                                           NotImplementedOp(),
                                           dtype=complex)

    if check_hermitian:
        # Sanity check: A and M should be Hermitian matrices
        check_is_hermitian(A, "A")
        #check_is_hermitian(M, "M")

    if filename_mat_A != None:
        dirname_mat_A = os.path.dirname(os.path.abspath(filename_mat_A))
        if not os.path.exists(dirname_mat_A):
            logger.debug(
                "Creating directory '{}' as it does not exist.".format(
                    dirname_mat_A))
            os.makedirs(dirname_mat_A)
        logger.info(
            "Saving generalised eigenproblem matrix 'A' to file '{}'".format(
                filename_mat_A))
        np.save(filename_mat_A, A)

    if filename_mat_M != None:
        dirname_mat_M = os.path.dirname(os.path.abspath(filename_mat_M))
        if not os.path.exists(dirname_mat_M):
            logger.debug(
                "Creating directory '{}' as it does not exist.".format(
                    dirname_mat_M))
            os.makedirs(dirname_mat_M)
        logger.info(
            "Saving generalised eigenproblem matrix 'M' to file '{}'".format(
                filename_mat_M))
        np.save(filename_mat_M, M)

    # Restore the original magnetisation.
    # XXX TODO: Is this method safe, or does it leave any trace of the
    # temporary changes we did above?
    sim.set_m(m_orig)

    return A, M, Q, Qt
         "delta_t = {0:1.1e}".format(float(delta_t))
        np.savetxt('saved_values/values_inbetween_ray_{0:1.1e}_dt_{1:1.1e}_{2}s.gz'.\
                    format(int(rayleigh), float(delta_t), int(t_end)), \
          np.column_stack((iteration_list, t_list, T_list1, vx_list1, 
                           vy_list1, v_metric_list, skew_metric_list12, \
                           p_diff_list14, p_diff_list51, p_diff_list35, \
                           omega_metric_list, skew_metric_vx_list12, 
                           nusselt_left_list)), 
                           fmt= '%1.6e', header = header)
    # update for next iteration
    sol00.assign(sol0)
    sol0.assign(sol)
    t += delta_t
    cnt += 1
if mpi_rank == 0:
    print 'elapsed simulation time in seconds: ', dlfn.toc()
#==============================================================================
#========================== preparation for post processor ====================
#==============================================================================
# save data
header = "0. Iteration  " + "1. Time  " + "2. Temperature(1)  " +  \
         "3. v_x(1)  " + "4. v_y(1)  " + "5. average velocity metric  " + \
         "6. skewness metric T_eps(12)  " + "7. pressure diff(1-4)  " + \
         "8. pressure diff(5-1)  " + "9. pressure diff(3-5)  " + \
         "10. vorticity metric  " + \
         "11. skewness metric vx_eps(12)  " + "nusselt left  " + \
         "nusselt right  " + \
         "delta_t = {0:1.1e}".format(float(delta_t))
np.savetxt('saved_values/ray_{0:1.1e}_dt_{1:1.1e}_{2}s.gz'.format(int(rayleigh),\
           float(delta_t), int(t)), \
          np.column_stack((iteration_list, t_list, T_list1, vx_list1, 
Пример #31
0
def compute_normal_modes_generalised(A,
                                     M,
                                     n_values=10,
                                     tol=1e-8,
                                     discard_negative_frequencies=False,
                                     sigma=None,
                                     which='LM',
                                     v0=None,
                                     ncv=None,
                                     maxiter=None,
                                     Minv=None,
                                     OPinv=None,
                                     mode='normal'):
    logger.debug("Solving eigenproblem. This may take a while...")
    df.tic()

    if discard_negative_frequencies:
        n_values *= 2

    # XXX TODO: The following call seems to increase memory consumption quite a bit. Why?!?
    #
    # We have to swap M and A when passing them to eigsh since the M matrix
    # has to be positive definite for eigsh!
    omega_inv, w = scipy.sparse.linalg.eigsh(M,
                                             k=n_values,
                                             M=A,
                                             which=which,
                                             tol=tol,
                                             return_eigenvectors=True,
                                             sigma=sigma,
                                             v0=v0,
                                             ncv=ncv,
                                             maxiter=maxiter,
                                             Minv=Minv,
                                             OPinv=OPinv,
                                             mode=mode)
    logger.debug(
        "Computing the eigenvalues and eigenvectors took {:.2f} seconds".
        format(df.toc()))

    # The true eigenfrequencies are given by 1/omega_inv because we swapped M
    # and A above and thus computed the inverse eigenvalues.
    omega = 1. / omega_inv

    # Sanity check: the eigenfrequencies should occur in +/- pairs.
    TOL = 1e-3
    positive_freqs = filter(lambda x: x > 0, omega)
    negative_freqs = filter(lambda x: x < 0, omega)
    freq_pairs = izip(positive_freqs, negative_freqs)
    if (n_values % 2 == 0 and len(positive_freqs) != len(negative_freqs)) or \
            (n_values % 2 == 0 and len(positive_freqs) - len(negative_freqs) not in [0, 1]) or \
            any([abs(x + y) > TOL for (x, y) in freq_pairs]):
        logger.warning(
            "The eigenfrequencies should occur in +/- pairs, but this "
            "does not seem to be the case (with TOL={})! Please "
            "double-check that the results make sense!".format(TOL))

    # Find the indices that sort the frequency by absolute value,
    # with the positive frequencies occurring before the negative ones (where.
    sorted_indices = sorted(np.arange(len(omega)),
                            key=lambda i: (np.round(abs(omega[i]), decimals=4),
                                           -np.sign(omega[i]), abs(omega[i])))

    if discard_negative_frequencies:
        # Discard indices corresponding to negative frequencies
        sorted_indices = filter(lambda i: omega[i] >= 0.0, sorted_indices)

    omega = omega[sorted_indices]
    # XXX TODO: can we somehow avoid copying the columns to save memory?!?
    w = w[:, sorted_indices]

    return omega, w
Пример #32
0
    merge = True

    solid = membrane | dna
    solid.addsubdomains(dna=dna, membrane=membrane)
    solid.addboundaries(
        dnaouterb=dnaouterb,
        dnainnerb=dnainnerb,
        dnaedgeb=dnaedgeb,
        memb=memb,
    )

    #print solid
    from dolfin import tic, toc
    tic()
    geo = solid.create_geometry(lc=2., merge=merge)
    print "time:", toc()
    print geo

    #print dnaedgeb.indexset()
    solid.plot()

    tic()
    geo = domain.create_geometry(lc=2., merge=merge)
    print "time:", toc()
    #domain.plot()
    #print geo

    plot_sliced(geo)

    import dolfin
    dolfin.plot(geo.submesh("solid"))