Esempio n. 1
0
def test_example_03():
    from hermes2d.examples.c03 import set_bc

    set_verbose(False)

    P_INIT = 5  # Uniform polynomial degree of mesh elements.

    # Problem parameters.
    CONST_F = 2.0

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_example_mesh())

    # Sample "manual" mesh refinement
    mesh.refine_all_elements()

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm(1)
    set_forms(wf)

    # Initialize the linear system
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem.
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 2
0
def test_example_03():
    set_verbose(False)

    mesh = Mesh()
    mesh.load(domain_mesh)
    mesh.refine_element(0)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(5)
    from hermes2d.examples.c03 import set_bc

    set_bc(space)
    space.assign_dofs()

    # initialize the discrete problem
    wf = WeakForm(1)
    set_forms(wf)

    solver = DummySolver()
    sys = LinSystem(wf, solver)
    sys.set_spaces(space)
    sys.set_pss(pss)

    # assemble the stiffness matrix and solve the system
    sln = Solution()
    sys.assemble()
    sys.solve_system(sln)
    assert abs(sln.l2_norm() - 0.25493) < 1e-4
    assert abs(sln.h1_norm() - 0.89534) < 1e-4
Esempio n. 3
0
def test_example_04():
    from hermes2d.examples.c04 import set_bc

    set_verbose(False)

    # Below you can play with the parameters CONST_F, P_INIT, and UNIFORM_REF_LEVEL.
    INIT_REF_NUM = 2         # number of initial uniform mesh refinements
    P_INIT = 2               # initial polynomial degree in all elements

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_example_mesh())

    # Perform initial mesh refinements
    for i in range(INIT_REF_NUM):
        mesh.refine_all_elements()

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm()
    set_forms(wf)

    # Initialize the linear system
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 4
0
def test_example_08():
    from hermes2d.examples.c08 import set_bc, set_forms

    set_verbose(False)

    # The following parameter can be changed:
    P_INIT = 4

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_sample_mesh())

    # Perform uniform mesh refinement
    mesh.refine_all_elements()

    # Create the x- and y- displacement space using the default H1 shapeset
    xdisp = H1Space(mesh, P_INIT)
    ydisp = H1Space(mesh, P_INIT)
    set_bc(xdisp, ydisp)

    # Initialize the weak formulation
    wf = WeakForm(2)
    set_forms(wf)

    # Initialize the linear system.
    ls = LinSystem(wf)
    ls.set_spaces(xdisp, ydisp)

    # Assemble and solve the matrix problem
    xsln = Solution()
    ysln = Solution()
    ls.assemble()
    ls.solve_system(xsln, ysln, lib="scipy")
Esempio n. 5
0
def test_example_07():
    from hermes2d.examples.c07 import set_bc, set_forms

    set_verbose(False)

    # The following parameters can be changed:
    P_INIT = 2  # Initial polynomial degree of all mesh elements.
    INIT_REF_NUM = 4  # Number of initial uniform refinements

    # Load the mesh
    mesh = Mesh()
    mesh.load(get_07_mesh())

    # Perform initial mesh refinements.
    for i in range(INIT_REF_NUM):
        mesh.refine_all_elements()

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm()
    set_forms(wf)

    # Initialize the linear system.
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 6
0
def test_example_05():
    from hermes2d.examples.c05 import set_bc
    from hermes2d.examples.c05 import set_forms as set_forms_surf

    set_verbose(False)

    P_INIT = 4  # initial polynomial degree in all elements
    CORNER_REF_LEVEL = 12  # number of mesh refinements towards the re-entrant corner

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_example_mesh())

    # Perform initial mesh refinements.
    mesh.refine_towards_vertex(3, CORNER_REF_LEVEL)

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm()
    set_forms(wf)

    # Initialize the linear system.
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 7
0
def test_example_08():
    from hermes2d.examples.c08 import set_bc, set_forms

    set_verbose(False)

    # The following parameter can be changed:
    P_INIT = 4

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_sample_mesh())

    # Perform uniform mesh refinement
    mesh.refine_all_elements()

    # Create the x- and y- displacement space using the default H1 shapeset
    xdisp = H1Space(mesh, P_INIT)
    ydisp = H1Space(mesh, P_INIT)
    set_bc(xdisp, ydisp)

    # Initialize the weak formulation
    wf = WeakForm(2)
    set_forms(wf)

    # Initialize the linear system.
    ls = LinSystem(wf)
    ls.set_spaces(xdisp, ydisp)

    # Assemble and solve the matrix problem
    xsln = Solution()
    ysln = Solution()
    ls.assemble()
    ls.solve_system(xsln, ysln, lib="scipy")
Esempio n. 8
0
def test_example_03():
    from hermes2d.examples.c03 import set_bc

    set_verbose(False)

    P_INIT = 5                # Uniform polynomial degree of mesh elements.

    # Problem parameters.
    CONST_F = 2.0

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_example_mesh())

    # Sample "manual" mesh refinement
    mesh.refine_all_elements()

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm(1)
    set_forms(wf)

    # Initialize the linear system
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem.
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 9
0
def test_example_07():
    from hermes2d.examples.c07 import set_bc, set_forms

    set_verbose(False)

    # The following parameters can be changed:
    P_INIT = 2             # Initial polynomial degree of all mesh elements.
    INIT_REF_NUM = 4       # Number of initial uniform refinements

    # Load the mesh
    mesh = Mesh()
    mesh.load(get_07_mesh())

    # Perform initial mesh refinements.
    for i in range(INIT_REF_NUM):
        mesh.refine_all_elements()

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm()
    set_forms(wf)

    # Initialize the linear system.
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 10
0
def test_matrix():
    set_verbose(False)

    mesh = Mesh()
    mesh.load(domain_mesh)
    mesh.refine_element(0)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(5)
    space.assign_dofs()

    # initialize the discrete problem
    wf = WeakForm(1)
    set_forms(wf)

    solver = DummySolver()
    sys = LinSystem(wf, solver)
    sys.set_spaces(space)
    sys.set_pss(pss)

    # assemble the stiffness matrix and solve the system
    sln = Solution()
    sys.assemble()
    A = sys.get_matrix()
Esempio n. 11
0
def test_example_05():
    from hermes2d.examples.c05 import set_bc
    from hermes2d.examples.c05 import set_forms as set_forms_surf

    set_verbose(False)

    P_INIT = 4                           # initial polynomial degree in all elements
    CORNER_REF_LEVEL = 12                # number of mesh refinements towards the re-entrant corner

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_example_mesh())

    # Perform initial mesh refinements.
    mesh.refine_towards_vertex(3, CORNER_REF_LEVEL)

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm()
    set_forms(wf)

    # Initialize the linear system.
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 12
0
def test_example_04():
    from hermes2d.examples.c04 import set_bc

    set_verbose(False)

    # Below you can play with the parameters CONST_F, P_INIT, and UNIFORM_REF_LEVEL.
    INIT_REF_NUM = 2  # number of initial uniform mesh refinements
    P_INIT = 2  # initial polynomial degree in all elements

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_example_mesh())

    # Perform initial mesh refinements
    for i in range(INIT_REF_NUM):
        mesh.refine_all_elements()

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm()
    set_forms(wf)

    # Initialize the linear system
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 13
0
def test_example_08():
    from hermes2d.examples.c08 import set_bc, set_forms

    set_verbose(False)

    mesh = Mesh()
    mesh.load(cylinder_mesh)
    #mesh.refine_element(0)
    #mesh.refine_all_elements()
    mesh.refine_towards_boundary(5, 3)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    xvel = H1Space(mesh, shapeset)
    yvel = H1Space(mesh, shapeset)
    press = H1Space(mesh, shapeset)
    xvel.set_uniform_order(2)
    yvel.set_uniform_order(2)
    press.set_uniform_order(1)

    set_bc(xvel, yvel, press)

    ndofs = 0
    ndofs += xvel.assign_dofs(ndofs)
    ndofs += yvel.assign_dofs(ndofs)
    ndofs += press.assign_dofs(ndofs)

    xprev = Solution()
    yprev = Solution()

    xprev.set_zero(mesh)
    yprev.set_zero(mesh)

    # initialize the discrete problem
    wf = WeakForm(3)
    set_forms(wf, xprev, yprev)

    solver = DummySolver()
    sys = LinSystem(wf, solver)
    sys.set_spaces(xvel, yvel, press)
    sys.set_pss(pss)
    #dp.set_external_fns(xprev, yprev)

    # visualize the solution

    EPS_LOW = 0.0014

    for i in range(3):
        psln = Solution()
        sys.assemble()
        sys.solve_system(xprev, yprev, psln)
Esempio n. 14
0
def test_example_02():
    set_verbose(False)
    P_INIT = 3

    # Load the mesh file
    domain_mesh = get_example_mesh()  # Original L-shape domain
    mesh = Mesh()
    mesh.load(domain_mesh)

    # Refine all elements (optional)
    mesh.refine_all_elements()

    # Create a shapeset and an H1 space
    space = H1Space(mesh)

    # Assign element orders and initialize the space
    space.set_uniform_order(P_INIT)  # Set uniform polynomial order
Esempio n. 15
0
def test_example_02():
    set_verbose(False)    
    P_INIT = 3

    # Load the mesh file
    domain_mesh = get_example_mesh()    # Original L-shape domain
    mesh = Mesh()
    mesh.load(domain_mesh)

    # Refine all elements (optional)
    mesh.refine_all_elements()

    # Create a shapeset and an H1 space
    space = H1Space(mesh)

    # Assign element orders and initialize the space
    space.set_uniform_order(P_INIT)    # Set uniform polynomial order
Esempio n. 16
0
def main():
    set_verbose(False)
    mesh = Mesh()
    print "Loading mesh..."
    mesh.load(get_GAMM_channel_mesh())
    #mesh.load("domain-quad.mesh")
    #mesh.refine_element(0, 2)
    mesh.refine_element(1, 2)
    mesh.refine_all_elements()
    mesh.refine_all_elements()
    mesh.refine_all_elements()
    mesh.refine_all_elements()

    print "Constructing edges..."
    nodes = mesh.nodes_dict
    edges = Edges(mesh)
    elements = mesh.elements
    print "Done."

    print "Solving..."
    state_on_elements = {}
    for e in mesh.active_elements:
        state_on_elements[e.id] = array([1., 50., 0., 1.e5])
    #print "initial state"
    #print state_on_elements
    tau = 1e-3
    t = 0.
    for i in range(100):
        A, rhs, dof_map = assembly(edges, state_on_elements, tau)
        #print "A:"
        #print A
        #print "rhs:"
        #print rhs
        #stop
        #print "x:"
        x = spsolve(A, rhs)
        #print x
        #print state_on_elements
        state_on_elements = set_fvm_solution(x, dof_map)
        #print state_on_elements
        t += tau
        print "t = ", t
    plot_state(state_on_elements, mesh)
    #print "state_on_elements:"
    #print state_on_elements
    print "Done."
Esempio n. 17
0
def test_example_07():
    from hermes2d.examples.c07 import set_bc, set_forms

    set_verbose(False)

    mesh = Mesh()
    mesh.load(sample_mesh)
    #mesh.refine_element(0)
    #mesh.refine_all_elements()
    #mesh.refine_towards_boundary(5, 3)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    xdisp = H1Space(mesh, shapeset)
    ydisp = H1Space(mesh, shapeset)
    xdisp.set_uniform_order(8)
    ydisp.set_uniform_order(8)

    set_bc(xdisp, ydisp)

    ndofs = xdisp.assign_dofs(0)
    ndofs += ydisp.assign_dofs(ndofs)

    # initialize the discrete problem
    wf = WeakForm(2)
    set_forms(wf)

    solver = DummySolver()
    sys = LinSystem(wf, solver)
    sys.set_spaces(xdisp, ydisp)
    sys.set_pss(pss)

    xsln = Solution()
    ysln = Solution()
    old_flag = set_warn_integration(False)
    sys.assemble()
    set_warn_integration(old_flag)
    sys.solve_system(xsln, ysln)

    E = float(200e9)
    nu = 0.3
    stress = VonMisesFilter(xsln, ysln, E / (2*(1 + nu)),
            (E * nu) / ((1 + nu) * (1 - 2*nu)))
Esempio n. 18
0
def test_example_06():
    from hermes2d.examples.c06 import set_bc, set_forms

    set_verbose(False)

    # The following parameters can be changed:

    UNIFORM_REF_LEVEL = 2
    # Number of initial uniform mesh refinements.
    CORNER_REF_LEVEL = 12
    # Number of mesh refinements towards the re-entrant corner.
    P_INIT = 6
    # Uniform polynomial degree of all mesh elements.

    # Boundary markers
    NEWTON_BDY = 1

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_example_mesh())

    # Perform initial mesh refinements.
    for i in range(UNIFORM_REF_LEVEL):
        mesh.refine_all_elements()
    mesh.refine_towards_vertex(3, CORNER_REF_LEVEL)

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm()
    set_forms(wf)

    # Initialize the linear system.
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 19
0
def test_matrix():
    set_verbose(False)

    mesh = Mesh()
    mesh.load(domain_mesh)
    mesh.refine_element(0)

    # create an H1 space with default shapeset
    space = H1Space(mesh, 1)

    # initialize the discrete problem
    wf = WeakForm(1)
    set_forms(wf)

    sys = LinSystem(wf)
    sys.set_spaces(space)

    # assemble the stiffness matrix and solve the system
    sln = Solution()
    sys.assemble()
    A = sys.get_matrix()
Esempio n. 20
0
def test_matrix():
    set_verbose(False)

    mesh = Mesh()
    mesh.load(domain_mesh)
    mesh.refine_element_id(0)

    # create an H1 space with default shapeset
    space = H1Space(mesh, 1)

    # initialize the discrete problem
    wf = WeakForm(1)
    set_forms(wf)

    sys = LinSystem(wf)
    sys.set_spaces(space)

    # assemble the stiffness matrix and solve the system
    sln = Solution()
    sys.assemble()
    A = sys.get_matrix()
Esempio n. 21
0
def test_example_02():
    set_verbose(False)

    mesh = Mesh()
    mesh.load(domain_mesh)
    mesh.refine_element(0)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(5)
    space.assign_dofs()

    # initialize the discrete problem
    wf = WeakForm(1)
    set_forms(wf)

    solver = DummySolver()
    sys = LinSystem(wf, solver)
    sys.set_spaces(space)
    sys.set_pss(pss)
Esempio n. 22
0
def test_example_04():
    from hermes2d.examples.c04 import set_bc

    set_verbose(False)

    mesh = Mesh()
    mesh.load(domain_mesh)
    # mesh.refine_element(0)
    # mesh.refine_all_elements()
    mesh.refine_towards_boundary(5, 3)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(5)

    set_bc(space)

    space.assign_dofs()

    xprev = Solution()
    yprev = Solution()

    # initialize the discrete problem
    wf = WeakForm()
    set_forms(wf, -4)

    solver = DummySolver()
    sys = LinSystem(wf, solver)
    sys.set_spaces(space)
    sys.set_pss(pss)

    # assemble the stiffness matrix and solve the system
    sys.assemble()
    sln = Solution()
    sys.solve_system(sln)
    assert abs(sln.l2_norm() - 1.22729) < 1e-4
    assert abs(sln.h1_norm() - 2.90006) < 1e-4
Esempio n. 23
0
def test_example_06():
    from hermes2d.examples.c06 import set_bc, set_forms

    set_verbose(False)

    # The following parameters can be changed:

    UNIFORM_REF_LEVEL = 2;   # Number of initial uniform mesh refinements.
    CORNER_REF_LEVEL = 12;   # Number of mesh refinements towards the re-entrant corner.
    P_INIT = 6;              # Uniform polynomial degree of all mesh elements.

    # Boundary markers
    NEWTON_BDY = 1

    # Load the mesh file
    mesh = Mesh()
    mesh.load(get_example_mesh())

    # Perform initial mesh refinements.
    for i in range(UNIFORM_REF_LEVEL):
        mesh.refine_all_elements()
    mesh.refine_towards_vertex(3, CORNER_REF_LEVEL)

    # Create an H1 space with default shapeset
    space = H1Space(mesh, P_INIT)
    set_bc(space)

    # Initialize the weak formulation
    wf = WeakForm()
    set_forms(wf)

    # Initialize the linear system.
    ls = LinSystem(wf)
    ls.set_spaces(space)

    # Assemble and solve the matrix problem
    sln = Solution()
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 24
0
def test_example_05():
    from hermes2d.examples.c05 import set_bc
    from hermes2d.examples.c05 import set_forms as set_forms_surf

    set_verbose(False)

    mesh = Mesh()
    mesh.load(domain_mesh)
    mesh.refine_towards_vertex(3, 12)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(4)

    set_bc(space)

    space.assign_dofs()

    xprev = Solution()
    yprev = Solution()

    # initialize the discrete problem
    wf = WeakForm(1)
    set_forms(wf, -1)
    set_forms_surf(wf)

    sln = Solution()
    solver = DummySolver()
    sys = LinSystem(wf, solver)
    sys.set_spaces(space)
    sys.set_pss(pss)
    sys.assemble()
    sys.solve_system(sln)
    assert abs(sln.l2_norm() - 0.535833) < 1e-4
    assert abs(sln.h1_norm() - 1.332908) < 1e-4
Esempio n. 25
0
def test_example_07():
    from hermes2d.examples.c07 import set_bc, set_forms

    set_verbose(False)

    P_INIT = 2  # Initial polynomial degree of all mesh elements.

    mesh = Mesh()
    mesh.load(get_07_mesh())

    # Initialize the shapeset and the cache
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create finite element space
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(P_INIT)
    set_bc(space)

    # Enumerate basis functions
    space.assign_dofs()

    # weak formulation
    wf = WeakForm(1)
    set_forms(wf)

    # matrix solver
    solver = DummySolver()

    # Solve the problem
    sln = Solution()
    ls = LinSystem(wf, solver)
    ls.set_spaces(space)
    ls.set_pss(pss)
    ls.assemble()
    ls.solve_system(sln)
Esempio n. 26
0
def poisson_solver(mesh_tuple):
    """
    Poisson solver.

    mesh_tuple ... a tuple of (nodes, elements, boundary, nurbs)
    """
    set_verbose(False)
    mesh = Mesh()
    mesh.create(*mesh_tuple)
    mesh.refine_element(0)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(5)
    space.assign_dofs()

    # initialize the discrete problem
    wf = WeakForm(1)
    set_forms(wf)

    solver = DummySolver()
    sys = LinSystem(wf, solver)
    sys.set_spaces(space)
    sys.set_pss(pss)

    # assemble the stiffness matrix and solve the system
    sys.assemble()
    A = sys.get_matrix()
    b = sys.get_rhs()
    from scipy.sparse.linalg import cg
    x, res = cg(A, b)
    sln = Solution()
    sln.set_fe_solution(space, pss, x)
    return sln
Esempio n. 27
0
def demo_layer(lib="mayavi"):
    """
    Shows off the example 22-layer.

    It adaptively refines things and shows the final solution and a convergence
    graph.
    """
    from hermes2d import (
        Mesh,
        MeshView,
        H1Shapeset,
        PrecalcShapeset,
        H1Space,
        WeakForm,
        Solution,
        DummySolver,
        LinSystem,
        ScalarView,
        RefSystem,
        H1Adapt,
        H1ProjBasedSelector,
        CandList,
        set_verbose,
    )
    from hermes2d.examples.c22 import set_bc, set_forms

    set_verbose(False)

    def calc(
        threshold=0.3,
        strategy=0,
        h_only=False,
        error_tol=1,
        interactive_plotting=False,
        show_mesh=False,
        show_graph=True,
    ):
        mesh = Mesh()
        mesh.create(
            [[0, 0], [1, 0], [1, 1], [0, 1]], [[2, 3, 0, 1, 0]], [[0, 1, 1], [1, 2, 1], [2, 3, 1], [3, 0, 1]], []
        )

        mesh.refine_all_elements()

        shapeset = H1Shapeset()
        pss = PrecalcShapeset(shapeset)

        space = H1Space(mesh, shapeset)
        set_bc(space)
        space.set_uniform_order(1)

        wf = WeakForm(1)
        set_forms(wf)

        sln = Solution()
        rsln = Solution()
        solver = DummySolver()

        selector = H1ProjBasedSelector(CandList.HP_ANISO, 1.0, -1, shapeset)

        view = ScalarView("Solution")
        iter = 0
        graph = []
        while 1:
            space.assign_dofs()

            sys = LinSystem(wf, solver)
            sys.set_spaces(space)
            sys.set_pss(pss)
            sys.assemble()
            sys.solve_system(sln)
            dofs = sys.get_matrix().shape[0]
            if interactive_plotting:
                view.show(sln, lib=lib, notebook=True, filename="a%02d.png" % iter)

            rsys = RefSystem(sys)
            rsys.assemble()

            rsys.solve_system(rsln)

            hp = H1Adapt([space])
            hp.set_solutions([sln], [rsln])
            err_est = hp.calc_error() * 100

            err_est = hp.calc_error(sln, rsln) * 100
            print "iter=%02d, err_est=%5.2f%%, DOFS=%d" % (iter, err_est, dofs)
            graph.append([dofs, err_est])
            if err_est < error_tol:
                break
            hp.adapt(selector, threshold, strategy)
            iter += 1

        if not interactive_plotting:
            view.show(sln, lib=lib, notebook=True)

        if show_mesh:
            mview = MeshView("Mesh")
            mview.show(mesh, lib="mpl", notebook=True, filename="b.png")

        if show_graph:
            from numpy import array

            graph = array(graph)
            import pylab

            pylab.clf()
            pylab.plot(graph[:, 0], graph[:, 1], "ko", label="error estimate")
            pylab.plot(graph[:, 0], graph[:, 1], "k-")
            pylab.title("Error Convergence for the Inner Layer Problem")
            pylab.legend()
            pylab.xlabel("Degrees of Freedom")
            pylab.ylabel("Error [%]")
            pylab.yscale("log")
            pylab.grid()
            pylab.savefig("graph.png")

    calc()
Esempio n. 28
0
File: 22.py Progetto: solin/hermes2d
    RefSystem,
    H1OrthoHP,
    set_verbose,
)
from hermes2d.examples.c22 import set_bc, set_forms

threshold = 0.3
strategy = 0
h_only = False
error_tol = 1
interactive_plotting = False  # should the plot be interactively updated
# during the calculation? (slower)
show_mesh = True
show_graph = True

set_verbose(False)

mesh = Mesh()
mesh.create([[0, 0], [1, 0], [1, 1], [0, 1]], [[2, 3, 0, 1, 0]], [[0, 1, 1], [1, 2, 1], [2, 3, 1], [3, 0, 1]], [])

mesh.refine_all_elements()

shapeset = H1Shapeset()
pss = PrecalcShapeset(shapeset)

space = H1Space(mesh, shapeset)
set_bc(space)
space.set_uniform_order(1)

wf = WeakForm(1)
set_forms(wf)
Esempio n. 29
0
def demo_layer(lib="mayavi"):
    """
    Shows off the example 22-layer.

    It adaptively refines things and shows the final solution and a convergence
    graph.
    """
    from hermes2d import (Mesh, MeshView, H1Shapeset, PrecalcShapeset, H1Space,
                          WeakForm, Solution, DummySolver, LinSystem,
                          ScalarView, RefSystem, H1Adapt, H1ProjBasedSelector,
                          CandList, set_verbose)
    from hermes2d.examples.c22 import set_bc, set_forms

    set_verbose(False)

    def calc(threshold=0.3,
             strategy=0,
             h_only=False,
             error_tol=1,
             interactive_plotting=False,
             show_mesh=False,
             show_graph=True):
        mesh = Mesh()
        mesh.create([
            [0, 0],
            [1, 0],
            [1, 1],
            [0, 1],
        ], [
            [2, 3, 0, 1, 0],
        ], [
            [0, 1, 1],
            [1, 2, 1],
            [2, 3, 1],
            [3, 0, 1],
        ], [])

        mesh.refine_all_elements()

        shapeset = H1Shapeset()
        pss = PrecalcShapeset(shapeset)

        space = H1Space(mesh, shapeset)
        set_bc(space)
        space.set_uniform_order(1)

        wf = WeakForm(1)
        set_forms(wf)

        sln = Solution()
        rsln = Solution()
        solver = DummySolver()

        selector = H1ProjBasedSelector(CandList.HP_ANISO, 1.0, -1, shapeset)

        view = ScalarView("Solution")
        iter = 0
        graph = []
        while 1:
            space.assign_dofs()

            sys = LinSystem(wf, solver)
            sys.set_spaces(space)
            sys.set_pss(pss)
            sys.assemble()
            sys.solve_system(sln)
            dofs = sys.get_matrix().shape[0]
            if interactive_plotting:
                view.show(sln,
                          lib=lib,
                          notebook=True,
                          filename="a%02d.png" % iter)

            rsys = RefSystem(sys)
            rsys.assemble()

            rsys.solve_system(rsln)

            hp = H1Adapt([space])
            hp.set_solutions([sln], [rsln])
            err_est = hp.calc_error() * 100

            err_est = hp.calc_error(sln, rsln) * 100
            print "iter=%02d, err_est=%5.2f%%, DOFS=%d" % (iter, err_est, dofs)
            graph.append([dofs, err_est])
            if err_est < error_tol:
                break
            hp.adapt(selector, threshold, strategy)
            iter += 1

        if not interactive_plotting:
            view.show(sln, lib=lib, notebook=True)

        if show_mesh:
            mview = MeshView("Mesh")
            mview.show(mesh, lib="mpl", notebook=True, filename="b.png")

        if show_graph:
            from numpy import array
            graph = array(graph)
            import pylab
            pylab.clf()
            pylab.plot(graph[:, 0], graph[:, 1], "ko", label="error estimate")
            pylab.plot(graph[:, 0], graph[:, 1], "k-")
            pylab.title("Error Convergence for the Inner Layer Problem")
            pylab.legend()
            pylab.xlabel("Degrees of Freedom")
            pylab.ylabel("Error [%]")
            pylab.yscale("log")
            pylab.grid()
            pylab.savefig("graph.png")

    calc()
Esempio n. 30
0
disabled=True

import matplotlib
matplotlib.use('Agg')

from hermes2d import (Mesh, H1Shapeset, PrecalcShapeset, H1Space, WeakForm,
        Solution, ScalarView, LinSystem, DummySolver, raises, MeshView,
        set_verbose, plot_mesh_mpl)
from hermes2d.forms import set_forms
from hermes2d.examples import get_example_mesh
set_verbose(False)

domain_mesh = get_example_mesh()

def test_ScalarView_mpl_default():
    mesh = Mesh()
    mesh.load(domain_mesh)
    mesh.refine_element(0)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(5)
    space.assign_dofs()

    # initialize the discrete problem
    wf = WeakForm(1)
    set_forms(wf)

    solver = DummySolver()
Esempio n. 31
0
def schroedinger_solver(n_eigs=4, iter=2, verbose_level=1, plot=False,
        potential="hydrogen", report=False, report_filename="report.h5",
        force=False, sim_name="sim", potential2=None):
    """
    One particle Schroedinger equation solver.

    n_eigs ... the number of the lowest eigenvectors to calculate
    iter ... the number of adaptive iterations to do
    verbose_level ...
            0 ... quiet
            1 ... only moderate output (default)
            2 ... lot's of output
    plot ........ plot the progress (solutions, refined solutions, errors)
    potential ... the V(x) for which to solve, one of:
                    well, oscillator, hydrogen
    potential2 .. other terms that should be added to potential
    report ...... it will save raw data to a file, useful for creating graphs
                    etc.

    Returns the eigenvalues and eigenvectors.
    """
    set_verbose(verbose_level == 2)
    set_warn_integration(False)
    pot = {"well": 0, "oscillator": 1, "hydrogen": 2, "three-points": 3}
    pot_type = pot[potential]
    if report:
        from timeit import default_timer as clock
        from tables import IsDescription, UInt32Col, Float32Col, openFile, \
                Float64Col, Float64Atom, Col, ObjectAtom
        class Iteration(IsDescription):
            n = UInt32Col()
            DOF = UInt32Col()
            DOF_reference = UInt32Col()
            cpu_solve = Float32Col()
            cpu_solve_reference = Float32Col()
            eig_errors = Float64Col(shape=(n_eigs,))
            eigenvalues = Float64Col(shape=(n_eigs,))
            eigenvalues_reference = Float64Col(shape=(n_eigs,))
        h5file = openFile(report_filename, mode = "a",
                title = "Simulation data")
        if hasattr(h5file.root, sim_name):
            if force:
                h5file.removeNode(getattr(h5file.root, sim_name),
                        recursive=True)
            else:
                print "The group '%s' already exists. Use -f to overwrite it." \
                        % sim_name
                return
        group = h5file.createGroup("/", sim_name, 'Simulation run')
        table = h5file.createTable(group, "iterations", Iteration,
                "Iterations info")
        h5eigs = h5file.createVLArray(group, 'eigenvectors', ObjectAtom())
        h5eigs_ref = h5file.createVLArray(group, 'eigenvectors_reference',
                ObjectAtom())
        iteration = table.row

    mesh = Mesh()
    mesh.load("square.mesh")
    if potential == "well":
        # Read the width of the mesh automatically. This assumes there is just
        # one square element:
        a = sqrt(mesh.get_element(0).get_area())
        # set N high enough, so that we get enough analytical eigenvalues:
        N = 10
        levels = []
        for n1 in range(1, N):
            for n2 in range(1, N):
                levels.append(n1**2 + n2**2)
        levels.sort()

        E_exact = [pi**2/(2.*a**2) * m for m in levels]
    elif potential == "oscillator":
        E_exact = [1] + [2]*2 + [3]*3 + [4]*4 + [5]*5 + [6]*6
    elif potential == "hydrogen":
        Z = 1 # atom number
        E_exact = [-float(Z)**2/2/(n-0.5)**2/4 for n in [1]+[2]*3+[3]*5 +\
                                    [4]*8 + [5]*15]
    else:
        E_exact = [1.]*50
    if len(E_exact) < n_eigs:
        print n_eigs
        print E_exact
        raise Exception("We don't have enough analytical eigenvalues.")
    #mesh.refine_element(0)
    mesh.refine_all_elements()
    #mesh.refine_all_elements()
    #mesh.refine_all_elements()
    #mesh.refine_all_elements()

    #mview = MeshView()
    #mview.show(mesh)

    shapeset = H1Shapeset()
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(2)
    space.assign_dofs()

    pss = PrecalcShapeset(shapeset)
    #bview = BaseView()
    #bview.show(space)

    wf1 = WeakForm(1)
    # this is induced by set_verbose():
    #dp1.set_quiet(not verbose)
    set_forms8(wf1, pot_type, potential2)
    wf2 = WeakForm(1)
    # this is induced by set_verbose():
    #dp2.set_quiet(not verbose)
    set_forms7(wf2)

    solver = DummySolver()

    w = 320
    h = 320
    views = [ScalarView("", i*w, 0, w, h) for i in range(4)]
    viewsm = [ScalarView("", i*w, h, w, h) for i in range(4)]
    viewse = [ScalarView("", i*w, 2*h, w, h) for i in range(4)]
    #for v in viewse:
    #    v.set_min_max_range(0, 10**-4)
    ord = OrderView("Polynomial Orders", 0, 2*h, w, h)

    rs = None

    precision = 30.0

    if verbose_level >= 1:
        print "Problem initialized. Starting calculation."

    for it in range(iter):
        if verbose_level >= 1:
            print "-"*80
            print "Starting iteration %d." % it
        if report:
            iteration["n"] = it

        #mesh.save("refined2.mesh")
        sys1 = LinSystem(wf1, solver)
        sys1.set_spaces(space)
        sys1.set_pss(pss)
        sys2 = LinSystem(wf2, solver)
        sys2.set_spaces(space)
        sys2.set_pss(pss)

        if verbose_level >= 1:
            print "Assembling the matrices A, B."
        sys1.assemble()
        sys2.assemble()
        if verbose_level == 2:
            print "converting matrices A, B"
        A = sys1.get_matrix()
        B = sys2.get_matrix()
        if verbose_level >= 1:
            n = A.shape[0]
            print "Solving the problem Ax=EBx  (%d x %d)." % (n, n)
        if report:
            n = A.shape[0]
            iteration["DOF"] = n
        if report:
            t = clock()
        eigs, sols = solve(A, B, n_eigs, verbose_level == 2)
        if report:
            t = clock() - t
            iteration["cpu_solve"] = t
            iteration["eigenvalues"] = array(eigs)
            #h5eigs.append(sols)
        if verbose_level >= 1:
            print "   \-Done."
            print_eigs(eigs, E_exact)
        s = []

        n = sols.shape[1]
        for i in range(n):
            sln = Solution()
            vec = sols[:, i]
            sln.set_fe_solution(space, pss, vec)
            s.append(sln)

        if verbose_level >= 1:
            print "Matching solutions."
        if rs is not None:
            def minus2(sols, i):
                sln = Solution()
                vec = sols[:, i]
                sln.set_fe_solution(space, pss, -vec)
                return sln
            pairs, flips = make_pairs(rs, s, d1, d2)
            #print "_"*40
            #print pairs, flips
            #print len(rs), len(s)
            #from time import sleep
            #sleep(3)
            #stop
            s2 = []
            for j, flip in zip(pairs, flips):
                if flip:
                    s2.append(minus2(sols,j))
                else:
                    s2.append(s[j])
            s = s2

        if plot:
            if verbose_level >= 1:
                print "plotting: solution"
            ord.show(space)
            for i in range(min(len(s), 4)):
                views[i].show(s[i])
                views[i].set_title("Iter: %d, eig: %d" % (it, i))
            #mat1.show(dp1)

        if verbose_level >= 1:
            print "reference: initializing mesh."

        rsys1 = RefSystem(sys1)
        rsys2 = RefSystem(sys2)
        if verbose_level >= 1:
            print "reference: assembling the matrices A, B."
        rsys1.assemble()
        rsys2.assemble()
        if verbose_level == 2:
            print "converting matrices A, B"
        A = rsys1.get_matrix()
        B = rsys2.get_matrix()
        if verbose_level >= 1:
            n = A.shape[0]
            print "reference: solving the problem Ax=EBx  (%d x %d)." % (n, n)
        if report:
            n = A.shape[0]
            iteration["DOF_reference"] = n
        if report:
            t = clock()
        eigs, sols = solve(A, B, n_eigs, verbose_level == 2)
        if report:
            t = clock() - t
            iteration["cpu_solve_reference"] = t
            iteration["eigenvalues_reference"] = array(eigs)
            #h5eigs_ref.append(sols)
        if verbose_level >= 1:
            print "   \-Done."
            print_eigs(eigs, E_exact)
        rs = []
        rspace = rsys1.get_ref_space(0)

        n = sols.shape[1]
        for i in range(n):
            sln = Solution()
            vec = sols[:, i]
            sln.set_fe_solution(rspace, pss, vec)
            rs.append(sln)

        if verbose_level >= 1:
            print "reference: matching solutions."
        def minus(sols, i):
            sln = Solution()
            vec = sols[:, i]
            sln.set_fe_solution(rspace, pss, -vec)
            return sln

        # segfaults
        #mat2.show(rp1)

        def d1(x, y):
            return (x-y).l2_norm()
        def d2(x, y):
            return (x+y).l2_norm()
        from pairs import make_pairs
        pairs, flips = make_pairs(s, rs, d1, d2)
        rs2 = []
        for j, flip in zip(pairs, flips):
            if flip:
                rs2.append(minus(sols,j))
            else:
                rs2.append(rs[j])
        rs = rs2

        if plot:
            if verbose_level >= 1:
                print "plotting: solution, reference solution, errors"
            for i in range(min(len(s), len(rs), 4)):
                #views[i].show(s[i])
                #views[i].set_title("Iter: %d, eig: %d" % (it, i))
                viewsm[i].show(rs[i])
                viewsm[i].set_title("Ref. Iter: %d, eig: %d" % (it, i))
                viewse[i].show((s[i]-rs[i])**2)
                viewse[i].set_title("Error plot Iter: %d, eig: %d" % (it, i))


        if verbose_level >= 1:
            print "Calculating errors."
        hp = H1OrthoHP(space)
        if verbose_level == 2:
            print "-"*60
            print "calc error (iter=%d):" % it
        eig_converging = 0
        errors = []
        for i in range(min(len(s), len(rs))):
            error = hp.calc_error(s[i], rs[i]) * 100
            errors.append(error)
            prec = precision
            if verbose_level >= 1:
                print "eig %d: %g%%  precision goal: %g%%" % (i, error, prec)
        if report:
            iteration["eig_errors"] = array(errors)
        if errors[0] > precision:
            eig_converging = 0
        elif errors[3] > precision:
            eig_converging = 3
        elif errors[1] > precision:
            eig_converging = 1
        elif errors[2] > precision:
            eig_converging = 2
        else:
            precision /= 2
        # uncomment the following line to only converge to some eigenvalue:
        #eig_converging = 3
        if verbose_level >= 1:
            print "picked: %d" % eig_converging
        error = hp.calc_error(s[eig_converging], rs[eig_converging]) * 100
        if verbose_level >= 1:
            print "Adapting the mesh."
        hp.adapt(0.3)
        space.assign_dofs()
        if report:
            iteration.append()
            table.flush()
    if report:
        h5file.close()
    return s