Esempio n. 1
0
def test(filename, control_values):
    # read the mesh
    this_path = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(this_path, filename)
    mesh, point_data, field_data, _ = meshplex.read(filename)
    mu = 1.0e-2

    # build the model evaluator
    modeleval = modelevaluator_nls.NlsModelEvaluator(
        mesh, V=point_data["V"], A=point_data["A"]
    )

    # compute the Ginzburg-Landau residual
    psi = point_data["psi"][:, 0] + 1j * point_data["psi"][:, 1]
    r = modeleval.compute_f(psi, mu, 1.0)

    # scale with D for compliance with the Nosh (C++) tests
    if mesh.control_volumes is None:
        mesh.compute_control_volumes()
    r *= mesh.control_volumes.reshape(r.shape)

    tol = 1.0e-13
    # For C++ Nosh compatibility:
    # Compute 1-norm of vector (Re(psi[0]), Im(psi[0]), Re(psi[1]), ... )
    alpha = numpy.linalg.norm(r.real, ord=1) + numpy.linalg.norm(r.imag, ord=1)
    assert abs(control_values[0] - alpha) < tol
    assert abs(control_values[1] - numpy.linalg.norm(r, ord=2)) < tol
    # For C++ Nosh compatibility:
    # Compute inf-norm of vector (Re(psi[0]), Im(psi[0]), Re(psi[1]), ... )
    alpha = max(
        numpy.linalg.norm(r.real, ord=numpy.inf),
        numpy.linalg.norm(r.imag, ord=numpy.inf),
    )
    assert abs(control_values[2] - alpha) < tol
    return
Esempio n. 2
0
def test_mark_subdomain2d():
    filename = download_mesh("pacman.msh", "2da8ff96537f844a95a83abb48471b6a")
    mesh, _, _, _ = meshplex.read(filename)

    class Subdomain1(object):
        is_boundary_only = True

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] < 0.0

    class Subdomain2(object):
        is_boundary_only = False

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] > 0.0

    sd1 = Subdomain1()
    vertex_mask = mesh.get_vertex_mask(sd1)
    assert vertex_mask.sum() == 27
    face_mask = mesh.get_face_mask(sd1)
    assert face_mask.sum() == 26
    cell_mask = mesh.get_cell_mask(sd1)
    assert cell_mask.sum() == 0

    sd2 = Subdomain2()
    vertex_mask = mesh.get_vertex_mask(sd2)
    assert vertex_mask.sum() == 214
    face_mask = mesh.get_face_mask(sd2)
    assert face_mask.sum() == 1137
    cell_mask = mesh.get_cell_mask(sd2)
    assert cell_mask.sum() == 371
    return
Esempio n. 3
0
def test(filename, control_values):
    this_path = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(this_path, filename)
    mu = 1.0e-2

    # read the mesh
    mesh, point_data, field_data, _ = meshplex.read(filename)

    # build the model evaluator
    modeleval = modelevaluator_nls.NlsModelEvaluator(mesh,
                                                     V=point_data["V"],
                                                     A=point_data["A"])

    # Assemble the KEO.
    keo = modeleval._get_keo(mu)

    tol = 1.0e-13

    # Check that the matrix is Hermitian.
    KK = keo - keo.H
    assert abs(KK.sum()) < tol

    # Check the matrix sum.
    assert abs(control_values[0] - keo.sum()) < tol

    # Check the 1-norm of the matrix |Re(K)| + |Im(K)|.
    # This equals the 1-norm of the matrix defined by the block
    # structure
    #   Re(K) -Im(K)
    #   Im(K)  Re(K).
    K = abs(keo.real) + abs(keo.imag)
    assert abs(control_values[1] - numpy.max(K.sum(0))) < tol
    return
Esempio n. 4
0
def test_mark_subdomain2d():
    mesh = meshplex.read(this_dir / "meshes" / "pacman.vtu")

    class Subdomain1:
        is_boundary_only = True

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] < 0.0

    class Subdomain2:
        is_boundary_only = False

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] > 0.0

    sd1 = Subdomain1()
    vertex_mask = mesh.get_vertex_mask(sd1)
    assert vertex_mask.sum() == 45
    face_mask = mesh.get_face_mask(sd1)
    assert face_mask.sum() == 44
    cell_mask = mesh.get_cell_mask(sd1)
    assert cell_mask.sum() == 0

    sd2 = Subdomain2()
    vertex_mask = mesh.get_vertex_mask(sd2)
    assert vertex_mask.sum() == 395
    face_mask = mesh.get_face_mask(sd2)
    assert face_mask.sum() == 2148
    cell_mask = mesh.get_cell_mask(sd2)
    assert cell_mask.sum() == 706
Esempio n. 5
0
def test_mark_subdomain3d():
    filename = download_mesh("tetrahedron.msh",
                             "27a5d7e102e6613a1e58629c252cb293")
    mesh, _, _, _ = meshplex.read(filename)

    class Subdomain1(object):
        is_boundary_only = True

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] < 0.5

    class Subdomain2(object):
        is_boundary_only = False

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] > 0.5

    sd1 = Subdomain1()
    vertex_mask = mesh.get_vertex_mask(sd1)
    assert vertex_mask.sum() == 16
    face_mask = mesh.get_face_mask(sd1)
    assert face_mask.sum() == 20
    cell_mask = mesh.get_cell_mask(sd1)
    assert cell_mask.sum() == 0

    sd2 = Subdomain2()
    vertex_mask = mesh.get_vertex_mask(sd2)
    assert vertex_mask.sum() == 10
    face_mask = mesh.get_face_mask(sd2)
    assert face_mask.sum() == 25
    cell_mask = mesh.get_cell_mask(sd2)
    assert cell_mask.sum() == 5
    return
Esempio n. 6
0
def test_keo(filename, control_values):
    filename = download_mesh(filename)
    mu = 1.0e-2

    # read the mesh
    mesh, point_data, field_data, _ = meshplex.read(filename)

    keo = pyfvm.get_fvm_matrix(mesh, edge_kernels=[Energy(mu)])

    tol = 1.0e-13

    # Check that the matrix is Hermitian.
    KK = keo - keo.H
    assert abs(KK.sum()) < tol

    # Check the matrix sum.
    assert abs(control_values[0] - keo.sum()) < tol

    # Check the 1-norm of the matrix |Re(K)| + |Im(K)|.
    # This equals the 1-norm of the matrix defined by the block
    # structure
    #   Re(K) -Im(K)
    #   Im(K)  Re(K).
    K = abs(keo.real) + abs(keo.imag)
    assert abs(control_values[1] - numpy.max(K.sum(0))) < tol
    return
Esempio n. 7
0
def _main():
    args = _parse_input_arguments()

    # read the mesh
    print("Reading the mesh...")
    mesh, _, _, _ = meshplex.read(args.filename)
    print("done.")

    # Hardcode V, A
    n = mesh.node_coords.shape[0]
    X = mesh.node_coords.T
    A = 0.5 * np.column_stack([-X[1], X[0], np.zeros(n)])
    point_data = {"V": -np.ones(n), "A": A}

    # build the model evaluator
    modeleval = gm.NlsModelEvaluator(mesh,
                                     V=point_data["V"],
                                     A=point_data["A"])

    mu_range = np.linspace(args.mu_range[0], args.mu_range[1],
                           args.num_parameter_steps)
    print("Looking for solutions for mu in")
    print(mu_range)
    print()
    find_beautiful_states(modeleval, mu_range, args.forcing_term)
    return
Esempio n. 8
0
def test(filename, control_values):
    # read the mesh
    this_path = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(this_path, filename)
    mesh, point_data, field_data, _ = meshplex.read(filename)
    mu = 1.0e-2

    # build the model evaluator
    modeleval = modelevaluator_nls.NlsModelEvaluator(mesh,
                                                     V=point_data["V"],
                                                     A=point_data["A"])

    # compute the Ginzburg-Landau residual
    psi = point_data["psi"][:, 0] + 1j * point_data["psi"][:, 1]
    r = modeleval.compute_f(psi, mu, 1.0)

    # scale with D for compliance with the Nosh (C++) tests
    if mesh.control_volumes is None:
        mesh.compute_control_volumes()
    r *= mesh.control_volumes.reshape(r.shape)

    tol = 1.0e-13
    # For C++ Nosh compatibility:
    # Compute 1-norm of vector (Re(psi[0]), Im(psi[0]), Re(psi[1]), ... )
    alpha = numpy.linalg.norm(r.real, ord=1) + numpy.linalg.norm(r.imag, ord=1)
    assert abs(control_values[0] - alpha) < tol
    assert abs(control_values[1] - numpy.linalg.norm(r, ord=2)) < tol
    # For C++ Nosh compatibility:
    # Compute inf-norm of vector (Re(psi[0]), Im(psi[0]), Re(psi[1]), ... )
    alpha = max(
        numpy.linalg.norm(r.real, ord=numpy.inf),
        numpy.linalg.norm(r.imag, ord=numpy.inf),
    )
    assert abs(control_values[2] - alpha) < tol
    return
Esempio n. 9
0
def test_mark_subdomain3d():
    filename = download_mesh("tetrahedron.vtk", "10f3ccd1642b634b22741894fe6e7f1f")
    mesh = meshplex.read(filename)

    class Subdomain1(object):
        is_boundary_only = True

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] < 0.5

    class Subdomain2(object):
        is_boundary_only = False

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] > 0.5

    sd1 = Subdomain1()
    vertex_mask = mesh.get_vertex_mask(sd1)
    assert vertex_mask.sum() == 16
    face_mask = mesh.get_face_mask(sd1)
    assert face_mask.sum() == 20
    cell_mask = mesh.get_cell_mask(sd1)
    assert cell_mask.sum() == 0

    sd2 = Subdomain2()
    vertex_mask = mesh.get_vertex_mask(sd2)
    assert vertex_mask.sum() == 10
    face_mask = mesh.get_face_mask(sd2)
    assert face_mask.sum() == 25
    cell_mask = mesh.get_cell_mask(sd2)
    assert cell_mask.sum() == 5
    return
Esempio n. 10
0
def test_mark_subdomain2d():
    filename = download_mesh("pacman.vtk", "c621cb22f8b87cecd77724c2c0601c36")
    mesh = meshplex.read(filename)

    class Subdomain1(object):
        is_boundary_only = True

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] < 0.0

    class Subdomain2(object):
        is_boundary_only = False

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] > 0.0

    sd1 = Subdomain1()
    vertex_mask = mesh.get_vertex_mask(sd1)
    assert vertex_mask.sum() == 27
    face_mask = mesh.get_face_mask(sd1)
    assert face_mask.sum() == 26
    cell_mask = mesh.get_cell_mask(sd1)
    assert cell_mask.sum() == 0

    sd2 = Subdomain2()
    vertex_mask = mesh.get_vertex_mask(sd2)
    assert vertex_mask.sum() == 214
    face_mask = mesh.get_face_mask(sd2)
    assert face_mask.sum() == 1137
    cell_mask = mesh.get_cell_mask(sd2)
    assert cell_mask.sum() == 371
    return
Esempio n. 11
0
def test(filename, control_values):
    this_path = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(this_path, filename)
    mu = 1.0e-2

    # read the mesh
    mesh, point_data, field_data, _ = meshplex.read(filename)

    # build the model evaluator
    modeleval = modelevaluator_nls.NlsModelEvaluator(
        mesh, V=point_data["V"], A=point_data["A"]
    )

    # Assemble the KEO.
    keo = modeleval._get_keo(mu)

    tol = 1.0e-13

    # Check that the matrix is Hermitian.
    KK = keo - keo.H
    assert abs(KK.sum()) < tol

    # Check the matrix sum.
    assert abs(control_values[0] - keo.sum()) < tol

    # Check the 1-norm of the matrix |Re(K)| + |Im(K)|.
    # This equals the 1-norm of the matrix defined by the block
    # structure
    #   Re(K) -Im(K)
    #   Im(K)  Re(K).
    K = abs(keo.real) + abs(keo.imag)
    assert abs(control_values[1] - numpy.max(K.sum(0))) < tol
    return
Esempio n. 12
0
def test_keo(filename, control_values):
    filename = download_mesh(filename)
    mu = 1.0e-2

    # read the mesh
    mesh = meshplex.read(filename)

    keo = pyfvm.get_fvm_matrix(mesh, edge_kernels=[Energy(mu)])

    tol = 1.0e-13

    # Check that the matrix is Hermitian.
    KK = keo - keo.H
    assert abs(KK.sum()) < tol

    # Check the matrix sum.
    assert abs(control_values[0] - keo.sum()) < tol

    # Check the 1-norm of the matrix |Re(K)| + |Im(K)|.
    # This equals the 1-norm of the matrix defined by the block
    # structure
    #   Re(K) -Im(K)
    #   Im(K)  Re(K).
    K = abs(keo.real) + abs(keo.imag)
    assert abs(control_values[1] - numpy.max(K.sum(0))) < tol
    return
Esempio n. 13
0
def test_show_vertex():
    filename = download_mesh("pacman-optimized.vtk",
                             "5036d9ce5307caa0d9de80cba7ba1c4c")
    mesh = meshplex.read(filename)
    # mesh.plot_vertex(125)
    mesh.show_vertex(125)
    return
Esempio n. 14
0
def test_mark_subdomain3d():
    mesh = meshplex.read(this_dir / "meshes" / "tetrahedron.vtk")

    class Subdomain1:
        is_boundary_only = True

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] < 0.5

    class Subdomain2:
        is_boundary_only = False

        # pylint: disable=no-self-use
        def is_inside(self, x):
            return x[0] > 0.5

    sd1 = Subdomain1()
    vertex_mask = mesh.get_vertex_mask(sd1)
    assert vertex_mask.sum() == 16
    face_mask = mesh.get_face_mask(sd1)
    assert face_mask.sum() == 20
    cell_mask = mesh.get_cell_mask(sd1)
    assert cell_mask.sum() == 0

    sd2 = Subdomain2()
    vertex_mask = mesh.get_vertex_mask(sd2)
    assert vertex_mask.sum() == 10
    face_mask = mesh.get_face_mask(sd2)
    assert face_mask.sum() == 25
    cell_mask = mesh.get_cell_mask(sd2)
    assert cell_mask.sum() == 5
Esempio n. 15
0
def test_signed_volume():
    filename = download_mesh("toy.msh", "1d125d3fa9f373823edd91ebae5f7a81")
    mesh, _, _, _ = meshplex.read(filename)

    vols = meshplex.get_signed_simplex_volumes(mesh.cells["nodes"], mesh.node_coords)

    assert numpy.all(abs(abs(vols) - mesh.cell_volumes) < 1.0e-12 * mesh.cell_volumes)
    return
Esempio n. 16
0
def test_get_edges():
    filename = download_mesh("pacman.msh", "2da8ff96537f844a95a83abb48471b6a")
    mesh, _, _, _ = meshplex.read(filename)
    mesh.create_edges()
    edge_mask = mesh.get_edge_mask()
    edge_nodes = mesh.edges["nodes"][edge_mask]
    assert len(edge_nodes) == 1276
    return
Esempio n. 17
0
def test_show_mesh():
    filename = download_mesh("pacman-optimized.vtk",
                             "5036d9ce5307caa0d9de80cba7ba1c4c")
    mesh = meshplex.read(filename)
    print(mesh)  # test __repr__
    # mesh.plot(show_axes=False)
    mesh.show(show_axes=False,
              cell_quality_coloring=("viridis", 0.0, 1.0, True))
Esempio n. 18
0
def test_get_edges():
    filename = download_mesh("pacman.vtk", "c621cb22f8b87cecd77724c2c0601c36")
    mesh = meshplex.read(filename)
    mesh.create_edges()
    edge_mask = mesh.get_edge_mask()
    edge_nodes = mesh.edges["nodes"][edge_mask]
    assert len(edge_nodes) == 1276
    return
Esempio n. 19
0
def test_sphere():
    mesh = meshplex.read(this_dir / "meshes" / "sphere.vtk")
    run(
        mesh,
        12.273645818711595,
        [1.0177358705967492, 0.10419690304323895],
        [366.3982135866799, 1.7062353589387327],
        [0.72653362732751214, 0.05350373815413411],
    )
Esempio n. 20
0
def test_sphere():
    filename = download_mesh("sphere.vtk", "06b163871cc0f23344d71c990dffe577")
    mesh = meshplex.read(filename)
    run(
        mesh,
        12.273645818711595,
        [1.0177358705967492, 0.10419690304323895],
        [366.3982135866799, 1.7062353589387327],
        [0.72653362732751214, 0.05350373815413411],
    )
Esempio n. 21
0
def test_tetrahedron():
    mesh = meshplex.read(this_dir / "meshes" / "tetrahedron.vtk")

    run(
        mesh,
        64.1500299099584,
        [16.308991595922095, 7.0264329635751395],
        [6.898476155562041, 0.34400453539215237],
        [11.571692332290635, 2.9699087921277054],
    )
Esempio n. 22
0
def test_signed_volume():
    filename = download_mesh("toy.vtk", "f48abda972822bab224b91a74d695573")
    mesh = meshplex.read(filename)

    vols = meshplex.get_signed_simplex_volumes(mesh.cells["nodes"],
                                               mesh.node_coords)

    assert numpy.all(
        abs(abs(vols) - mesh.cell_volumes) < 1.0e-12 * mesh.cell_volumes)
    return
Esempio n. 23
0
def test_pacman():
    mesh = meshplex.read(this_dir / ".." / "meshes" / "pacman.vtu")

    run(
        mesh,
        54.312974717523744,
        [1.9213504740523146, 0.07954185111555329],
        [403.5307055719196, 0.5512267577002408],
        [1.3816992621175055, 0.0443755870238773],
    )

    assert mesh.num_delaunay_violations == 0
Esempio n. 24
0
def test_pacman():
    mesh = meshplex.read(this_dir / "meshes" / "pacman.vtk")

    run(
        mesh,
        73.64573933105898,
        [3.596101914906618, 0.26638548094154696],
        [379.275476266239, 1.2976923100235962],
        [2.6213234038171014, 0.13841739494523228],
    )

    assert mesh.num_delaunay_violations() == 0
Esempio n. 25
0
def test_tetrahedron():
    filename = download_mesh("tetrahedron.msh", "27a5d7e102e6613a1e58629c252cb293")
    mesh, _, _, _ = meshplex.read(filename)

    run(
        mesh,
        64.1500299099584,
        [16.308991595922095, 7.0264329635751395],
        [6.898476155562041, 0.34400453539215237],
        [11.571692332290635, 2.9699087921277054],
    )
    return
Esempio n. 26
0
def test_jacobian(filename, control_values):
    filename = download_mesh(filename)
    mu = 1.0e-2

    mesh = meshplex.read(filename)
    m2 = meshio.read(filename)

    psi = m2.point_data["psi"][:, 0] + 1j * m2.point_data["psi"][:, 1]

    V = -1.0
    g = 1.0
    keo = pyfvm.get_fvm_matrix(mesh, edge_kernels=[Energy(mu)])

    def jacobian(psi):
        def _apply_jacobian(phi):
            cv = mesh.control_volumes
            y = keo * phi / cv + alpha * phi + gPsi0Squared * phi.conj()
            return y

        alpha = V + g * 2.0 * (psi.real**2 + psi.imag**2)
        gPsi0Squared = g * psi**2

        num_unknowns = len(mesh.node_coords)
        return pykry.LinearOperator(
            (num_unknowns, num_unknowns),
            complex,
            dot=_apply_jacobian,
            dot_adj=_apply_jacobian,
        )

    # Get the Jacobian
    J = jacobian(psi)

    tol = 1.0e-12

    num_unknowns = psi.shape[0]

    # [1+i, 1+i, 1+i, ... ]
    phi = numpy.full(num_unknowns, 1 + 1j)
    val = numpy.vdot(phi, mesh.control_volumes * (J * phi)).real
    assert abs(control_values[0] - val) < tol

    # [1, 1, 1, ... ]
    phi = numpy.full(num_unknowns, 1.0, dtype=complex)
    val = numpy.vdot(phi, mesh.control_volumes * (J * phi)).real
    assert abs(control_values[1] - val) < tol

    # [i, i, i, ... ]
    phi = numpy.full(num_unknowns, 1j, dtype=complex)
    val = numpy.vdot(phi, mesh.control_volumes * (J * phi)).real
    assert abs(control_values[2] - val) < tol
    return
Esempio n. 27
0
def test_sphere():
    filename = download_mesh("sphere.msh", "70a5dbf79c3b259ed993458ff4aa2e93")
    mesh, _, _, _ = meshplex.read(filename)
    run(
        mesh,
        12.273645818711595,
        [1.0177358705967492, 0.10419690304323895],
        [366.3982135866799, 1.7062353589387327],
        [0.72653362732751214, 0.05350373815413411],
    )

    # assertEqual(mesh.num_delaunay_violations(), 60)
    return
Esempio n. 28
0
def test_tetrahedron():
    filename = download_mesh("tetrahedron.vtk",
                             "10f3ccd1642b634b22741894fe6e7f1f")
    mesh = meshplex.read(filename)

    run(
        mesh,
        64.1500299099584,
        [16.308991595922095, 7.0264329635751395],
        [6.898476155562041, 0.34400453539215237],
        [11.571692332290635, 2.9699087921277054],
    )
    return
Esempio n. 29
0
def test_pacman():
    filename = download_mesh("pacman.vtk", "c621cb22f8b87cecd77724c2c0601c36")
    mesh = meshplex.read(filename)

    run(
        mesh,
        73.64573933105898,
        [3.596101914906618, 0.26638548094154696],
        [379.275476266239, 1.2976923100235962],
        [2.6213234038171014, 0.13841739494523228],
    )

    assert mesh.num_delaunay_violations() == 0
Esempio n. 30
0
def test_jacobian(filename, control_values):
    filename = download_mesh(filename)
    mu = 1.0e-2

    mesh, point_data, field_data, _ = meshplex.read(filename)

    psi = point_data["psi"][:, 0] + 1j * point_data["psi"][:, 1]

    V = -1.0
    g = 1.0
    keo = pyfvm.get_fvm_matrix(mesh, edge_kernels=[Energy(mu)])

    def jacobian(psi):
        def _apply_jacobian(phi):
            cv = mesh.control_volumes
            y = keo * phi / cv + alpha * phi + gPsi0Squared * phi.conj()
            return y

        alpha = V + g * 2.0 * (psi.real ** 2 + psi.imag ** 2)
        gPsi0Squared = g * psi ** 2

        num_unknowns = len(mesh.node_coords)
        return pykry.LinearOperator(
            (num_unknowns, num_unknowns),
            complex,
            dot=_apply_jacobian,
            dot_adj=_apply_jacobian,
        )

    # Get the Jacobian
    J = jacobian(psi)

    tol = 1.0e-12

    num_unknowns = psi.shape[0]

    # [1+i, 1+i, 1+i, ... ]
    phi = numpy.full(num_unknowns, 1 + 1j)
    val = numpy.vdot(phi, mesh.control_volumes * (J * phi)).real
    assert abs(control_values[0] - val) < tol

    # [1, 1, 1, ... ]
    phi = numpy.full(num_unknowns, 1.0, dtype=complex)
    val = numpy.vdot(phi, mesh.control_volumes * (J * phi)).real
    assert abs(control_values[1] - val) < tol

    # [i, i, i, ... ]
    phi = numpy.full(num_unknowns, 1j, dtype=complex)
    val = numpy.vdot(phi, mesh.control_volumes * (J * phi)).real
    assert abs(control_values[2] - val) < tol
    return
Esempio n. 31
0
def test_io_2d():
    vertices, cells = meshzoo.rectangle_tri(np.linspace(0.0, 1.0, 3),
                                            np.linspace(0.0, 1.0, 3))
    mesh = meshplex.MeshTri(vertices, cells)
    # mesh = meshplex.read('pacman.vtu')
    assert mesh.num_delaunay_violations == 0

    # mesh.show(show_axes=False, boundary_edge_color="g")
    # mesh.show_vertex(0)

    with tempfile.TemporaryDirectory() as tmpdir:
        mesh.write(tmpdir + "test.vtk")
        mesh2 = meshplex.read(tmpdir + "test.vtk")

    assert np.all(mesh.cells("points") == mesh2.cells("points"))
Esempio n. 32
0
def test_pacman():
    filename = download_mesh("pacman.msh", "2da8ff96537f844a95a83abb48471b6a")
    mesh, _, _, _ = meshplex.read(filename)

    run(
        mesh,
        73.64573933105898,
        [3.596101914906618, 0.26638548094154696],
        [379.275476266239, 1.2976923100235962],
        [2.6213234038171014, 0.13841739494523228],
    )

    assert mesh.num_delaunay_violations() == 0

    return
Esempio n. 33
0
def test_io_2d():
    vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 2, 2)
    mesh = meshplex.MeshTri(vertices, cells)
    # mesh = meshplex.read('pacman.vtu')

    assert mesh.num_delaunay_violations() == 0

    # mesh.show(show_axes=False, boundary_edge_color="g")
    # mesh.show_vertex(0)

    _, fname = tempfile.mkstemp(suffix=".vtk")
    mesh.write(fname)

    mesh2 = meshplex.read(fname)

    for k in range(len(mesh.cells["nodes"])):
        assert tuple(mesh.cells["nodes"][k]) == tuple(mesh2.cells["nodes"][k])
Esempio n. 34
0
def _main():
    """Main function.
    """
    args = _parse_input_arguments()

    # Setting the default file_mvp.
    if args.file_mvp is None:
        args.file_mvp = args.filename

    # Read the magnetic vector potential.
    mesh, point_data, field_data = meshplex.read(args.file_mvp)

    # build the model evaluator
    print(("Creating model evaluator...", ))
    start = time.time()
    num_coords = len(mesh.node_coords)
    nls_modeleval = pynosh.modelevaluator_nls.NlsModelEvaluator(
        mesh,
        V=-np.ones(num_coords),
        A=point_data["A"],
        preconditioner_type=args.preconditioner_type,
        num_amg_cycles=args.num_amg_cycles,
    )
    if args.bordering:
        modeleval = pynosh.bordered_modelevaluator.BorderedModelEvaluator(
            nls_modeleval)
    else:
        modeleval = nls_modeleval
    end = time.time()
    print(("done. (%gs)" % (end - start)))

    # Run through all time steps.
    assert len(args.timesteps) == len(
        args.mu), ("There must be as many time steps as mus (%d != %d)." %
                   (len(args.timesteps), len(args.mu)))
    for (timestep, mu) in zip(args.timesteps, args.mu):
        relresvec = _solve_system(modeleval, args.filename, timestep, mu, args)
        print("relresvec:")
        print(relresvec)
        print(("num iters:", len(relresvec) - 1))
        if args.show_relres:
            pp.semilogy(relresvec, "k")
            pp.show()

    return
Esempio n. 35
0
def _main():
    """Main function.
    """
    args = _parse_input_arguments()

    # Setting the default file_mvp.
    if args.file_mvp is None:
        args.file_mvp = args.filename

    # Read the magnetic vector potential.
    mesh, point_data, field_data = meshplex.read(args.file_mvp)

    # build the model evaluator
    print(("Creating model evaluator...",))
    start = time.time()
    num_coords = len(mesh.node_coords)
    nls_modeleval = pynosh.modelevaluator_nls.NlsModelEvaluator(
        mesh,
        V=-np.ones(num_coords),
        A=point_data["A"],
        preconditioner_type=args.preconditioner_type,
        num_amg_cycles=args.num_amg_cycles,
    )
    if args.bordering:
        modeleval = pynosh.bordered_modelevaluator.BorderedModelEvaluator(nls_modeleval)
    else:
        modeleval = nls_modeleval
    end = time.time()
    print(("done. (%gs)" % (end - start)))

    # Run through all time steps.
    assert len(args.timesteps) == len(args.mu), (
        "There must be as many time steps as mus (%d != %d)."
        % (len(args.timesteps), len(args.mu))
    )
    for (timestep, mu) in zip(args.timesteps, args.mu):
        relresvec = _solve_system(modeleval, args.filename, timestep, mu, args)
        print("relresvec:")
        print(relresvec)
        print(("num iters:", len(relresvec) - 1))
        if args.show_relres:
            pp.semilogy(relresvec, "k")
            pp.show()

    return
Esempio n. 36
0
def _run(filename, control_values):
    """Test $\int_{\Omega} A^2$."""

    # read the mesh
    mesh, _, _, _ = meshplex.read(filename)
    if mesh.control_volumes is None:
        mesh.compute_control_volumes()

    tol = 1.0e-10

    A = mvp.constant_field(mesh.node_coords, numpy.array([0, 0, 1]))
    integral = numpy.sum(mesh.control_volumes * numpy.sum(A ** 2, axis=1))
    assert numpy.all(numpy.abs(control_values["z"] - integral) < tol)

    # If this is a 2D mesh, append the z-component 0 to each node
    # to make sure that the magnetic vector potentials can be
    # calculated.
    points = mesh.node_coords.copy()
    if points.shape[1] == 2:
        points = numpy.column_stack((points, numpy.zeros(len(points))))

    A = mvp.magnetic_dipole(
        points, x0=numpy.array([0, 0, 10]), m=numpy.array([0, 0, 1])
    )
    integral = numpy.sum(mesh.control_volumes * numpy.sum(A ** 2, axis=1))
    assert numpy.all(numpy.abs(control_values["dipole"] - integral) < tol)

    # import time
    # start = time.time()
    A = mvp.magnetic_dot(mesh.node_coords, 2.0, [10.0, 11.0])
    # A = numpy.empty((len(points), 3), dtype=float)
    # for k, node in enumerate(points):
    # A[k] = mvp.magnetic_dot(node[0], node[1], 2.0, 10.0, 11.0)
    # end = time.time()
    # print end-start
    integral = numpy.sum(mesh.control_volumes * numpy.sum(A ** 2, axis=1))
    assert numpy.all(numpy.abs(control_values["dot"] - integral) < tol)
    return
Esempio n. 37
0
def _main():
    args = _parse_input_arguments()

    # read the mesh
    print("Reading the mesh...")
    mesh, _, _, _ = meshplex.read(args.filename)
    print("done.")

    # Hardcode V, A
    n = mesh.node_coords.shape[0]
    X = mesh.node_coords.T
    A = 0.5 * np.column_stack([-X[1], X[0], np.zeros(n)])
    point_data = {"V": -np.ones(n), "A": A}

    # build the model evaluator
    modeleval = gm.NlsModelEvaluator(mesh, V=point_data["V"], A=point_data["A"])

    mu_range = np.linspace(args.mu_range[0], args.mu_range[1], args.num_parameter_steps)
    print("Looking for solutions for mu in")
    print(mu_range)
    print()
    find_beautiful_states(modeleval, mu_range, args.forcing_term)
    return
Esempio n. 38
0
def test(filename, control_values):
    # read the mesh
    this_path = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(this_path, filename)
    mu = 1.0e-2

    mesh, point_data, field_data, _ = meshplex.read(filename)

    psi = point_data["psi"][:, 0] + 1j * point_data["psi"][:, 1]
    num_unknowns = len(psi)
    psi = psi.reshape(num_unknowns, 1)

    # build the model evaluator
    modeleval = modelevaluator_nls.NlsModelEvaluator(
        mesh, V=point_data["V"], A=point_data["A"]
    )

    # Get the Jacobian
    J = modeleval.get_jacobian(psi, mu, 1.0)

    tol = 1.0e-12

    # [1+i, 1+i, 1+i, ... ]
    phi = (1 + 1j) * numpy.ones((num_unknowns, 1), dtype=complex)
    val = numpy.vdot(phi, mesh.control_volumes.reshape(phi.shape) * (J * phi)).real
    assert abs(control_values[0] - val) < tol

    # [1, 1, 1, ... ]
    phi = numpy.ones((num_unknowns, 1), dtype=complex)
    val = numpy.vdot(phi, mesh.control_volumes[:, None] * (J * phi)).real
    assert abs(control_values[1] - val) < tol

    # [i, i, i, ... ]
    phi = 1j * numpy.ones((num_unknowns, 1), dtype=complex)
    val = numpy.vdot(phi, mesh.control_volumes[:, None] * (J * phi)).real
    assert abs(control_values[2] - val) < tol
    return
Esempio n. 39
0
def test_f(filename, control_values):
    filename = download_mesh(filename)
    mesh, point_data, field_data, _ = meshplex.read(filename)

    mu = 1.0e-2
    V = -1.0
    g = 1.0

    keo = pyfvm.get_fvm_matrix(mesh, edge_kernels=[Energy(mu)])

    # compute the Ginzburg-Landau residual
    psi = point_data["psi"][:, 0] + 1j * point_data["psi"][:, 1]
    cv = mesh.control_volumes
    # One divides by the control volumes here. No idea why this has been done in pynosh.
    # Perhaps to make sure that even the small control volumes have a significant
    # contribution to the residual?
    r = keo * psi / cv + psi * (V + g * abs(psi) ** 2)

    # scale with D for compliance with the Nosh (C++) tests
    if mesh.control_volumes is None:
        mesh.compute_control_volumes()
    r *= mesh.control_volumes

    tol = 1.0e-13
    # For C++ Nosh compatibility:
    # Compute 1-norm of vector (Re(psi[0]), Im(psi[0]), Re(psi[1]), ... )
    alpha = numpy.linalg.norm(r.real, ord=1) + numpy.linalg.norm(r.imag, ord=1)
    assert abs(control_values[0] - alpha) < tol
    assert abs(control_values[1] - numpy.linalg.norm(r, ord=2)) < tol
    # For C++ Nosh compatibility:
    # Compute inf-norm of vector (Re(psi[0]), Im(psi[0]), Re(psi[1]), ... )
    alpha = max(
        numpy.linalg.norm(r.real, ord=numpy.inf),
        numpy.linalg.norm(r.imag, ord=numpy.inf),
    )
    assert abs(control_values[2] - alpha) < tol
    return
Esempio n. 40
0
def _main():
    # get the command line arguments
    args = _parse_options()

    # read the mesh
    print("Reading mesh...", end=" ")
    start = time.time()
    mesh, point_data, field_data = meshplex.read(args.infile)
    elapsed = time.time() - start
    print("done. (%gs)" % elapsed)

    num_nodes = len(mesh.node_coords)

    # create values
    if not args.force_override and "psi" in point_data:
        psi = point_data["psi"]
    else:
        print("Creating psi...", end=" ")
        start = time.time()
        psi = np.empty(num_nodes, dtype=complex)
        psi[:] = complex(1.0, 0.0)
        # for k, node in enumerate(mesh.node_coords):
        # import random, cmath
        # psi[k] = cmath.rect( random.random(), 2.0 * pi * random.random() )
        # psi[k] = 0.9 * np.cos(0.5 * node[0])
        elapsed = time.time() - start
        print("done. (%gs)" % elapsed)

    if not args.force_override and "V" in point_data:
        V = point_data["V"]
    else:
        # create values
        print("Creating V...", end=" ")
        start = time.time()
        V = np.empty(num_nodes)
        V[:] = -1.0
        # for k, node in enumerate(mesh.node_coords):
        # import random, cmath
        # X[k] = cmath.rect( random.random(), 2.0 * pi * random.random() )
        # X[k] = 0.9 * np.cos(0.5 * node[0])
        elapsed = time.time() - start
        print("done. (%gs)" % elapsed)

    if not args.force_override and "A" in point_data:
        A = point_data["A"]
    else:
        # If this is a 2D mesh, append the z-component 0 to each node
        # to make sure that the magnetic vector potentials can be
        # calculated.
        points = mesh.node_coords.copy()
        if points.shape[1] == 2:
            points = np.column_stack((points, np.zeros(len(points))))
        # Add magnetic vector potential.
        print("Creating A...", end=" ")
        start = time.time()
        # A = points # field A(X) = X -- test case
        import pynosh.magnetic_vector_potentials as mvp

        # A = np.zeros((num_nodes,3))
        # B = np.array([np.cos(theta) * np.cos(phi),
        # np.cos(theta) * np.sin(phi),
        # np.sin(theta)])
        A = mvp.constant_field(points, np.array([0, 0, 1]))
        # A = mvp.magnetic_dipole(points,
        #                        x0 = np.array([0,0,2]),
        #                        m = np.array([0,0,1])
        #                        )
        # A = mvp.magnetic_dot(points, radius=2.0, heights=[0.1, 1.1])
        # A = np.empty((num_nodes, 3), dtype=float)
        # for k, node in enumerate(points):
        # A[k] = mvp.magnetic_dot(node, radius=2.0, height0=0.1, height1=1.1)
        elapsed = time.time() - start
        print("done. (%gs)" % elapsed)

    # if 'thickness' in point_data:
    #    thickness = point_data['thickness']
    # else:
    #    # Add values for thickness:
    #    thickness = np.empty(num_nodes, dtype = float)
    #    alpha = 0.5 # thickness at the center of the tube
    #    beta = 2.0 # thickness at the boundary
    #    t = (beta-alpha) / b**2
    #    for k, x in enumerate(mesh.nodes):
    #        thickness[k] = alpha + t * x[1]**2

    # if not args.force_override and 'g' in field_data:
    #    g = field_data['g']
    # else:
    #    g = 1.0

    # if not args.force_override and 'mu' in field_data:
    #    mu = field_data['mu']
    # else:
    #    mu = 1.0

    # write the mesh
    print("Writing mesh...", end=" ")
    start = time.time()
    mesh.write(
        args.outfile,
        point_data={"psi": psi, "V": V, "A": A},
        # field_data={'g': g, 'mu': mu}
    )
    elapsed = time.time() - start
    print("done. (%gs)" % elapsed)
    return
Esempio n. 41
0
def _main():
    """Main function.
    """
    args = _parse_input_arguments()

    # read the mesh
    mesh, point_data, field_data = meshplex.read(args.filename, timestep=args.timestep)

    num_nodes = len(mesh.node_coords)

    if not args.mu is None:
        mu = args.mu
        print("Using mu=%g from command line." % mu)
    elif "mu" in field_data:
        mu = field_data["mu"]
    else:
        raise ValueError(
            "Parameter " "mu" " not found in file. Please provide on command line."
        )

    if not args.g is None:
        g = args.g
        print("Using g=%g from command line." % g)
    elif "g" in field_data:
        g = field_data["g"]
    else:
        raise ValueError(
            "Parameter " "g" " not found in file. Please provide on command line."
        )

    # build the model evaluator
    nls_modeleval = nme.NlsModelEvaluator(
        mesh=mesh,
        V=point_data["V"],
        A=point_data["A"],
        preconditioner_type="exact",
        num_amg_cycles=1,
    )

    psi0 = point_data["psi"][:, 0] + 1j * point_data["psi"][:, 1]

    if args.bordering:
        # Build bordered system.
        x0 = np.empty(num_nodes + 1, dtype=complex)
        x0[0:num_nodes] = psi0
        x0[-1] = 0.0
        # Use psi0 as initial bordering.
        modeleval = bme.BorderedModelEvaluator(nls_modeleval)
    else:
        x0 = psi0
        modeleval = nls_modeleval

    if not args.series:
        # compute the eigenvalues once
        # p0 = 1j * psi0
        # p0 /= np.sqrt(modeleval.inner_product(p0, p0))
        # y0 = modeleval.get_jacobian(psi0) * p0
        # print '||(ipsi) J (ipsi)|| =', np.linalg.norm(y0)

        ## Check with the rotation vector.
        # grad_psi0 = mesh.compute_gradient(psi0)
        # x_tilde = np.array( [-mesh.node_coords[:,1], mesh.node_coords[:,0]] ).T
        # p1 = np.sum(x_tilde * grad_psi0, axis=1)
        # mesh.write('test.e', point_data={'x grad': p1})
        # nrm_p1 = np.sqrt(modeleval.inner_product(p1, p1))
        # p1 /= nrm_p1
        # y1 = modeleval.get_jacobian(psi0) * p1
        # print '||(grad) J (grad)|| =', np.linalg.norm(y1)

        # Check the equality
        #    grad(|psi|^2 psi) = 2 |psi|^2 grad(psi) + psi^2 grad(psi)*.
        #
        # p2 = mesh.compute_gradient(psi0 * abs(psi0)**2)
        # gradPsi0 = mesh.compute_gradient(psi0)
        # p2d = 2 * np.multiply(abs(psi0)**2, gradPsi0.T).T \
        #    + np.multiply(psi0**2, gradPsi0.conjugate().T).T
        # mesh.write('diff.vtu',
        # point_data = {'psi': psi0, 'p2': p2, 'p2d': p2d, 'diff': diff}
        # )

        # Check the equality
        #    grad(|psi|^2) = 2 Re(psi* grad(psi)).
        #
        # p2 = mesh.compute_gradient(abs(psi0)**2)
        # p2d = 2 * np.multiply(psi0.conjugate(), mesh.compute_gradient(psi0).T).T.real
        # diff = p2 - p2d
        # mesh.write('diff.vtu',
        #           point_data = {'psi': psi0, 'p2': p2, 'p2d': p2d, 'diff': diff}
        #           )

        # J = modeleval.get_jacobian(psi0)
        # K = modeleval._keo
        # x = np.random.rand(len(psi0))
        # print 'x', np.linalg.norm(J*x - K*x/ mesh.control_volumes.reshape(x.shape))

        eigenvals, X = _compute_eigenvalues(
            args.operator,
            args.eigenvalue_type,
            args.num_eigenvalues,
            None,
            x0[:, None],
            modeleval,
            mu,
            g,
        )

        print("The following eigenvalues were computed:")
        print(sorted(eigenvals))

        # Check residuals.
        print("Residuals:")
        for k in range(len(eigenvals)):
            # Convert to complex representation.
            z = X[0::2, k] + 1j * X[1::2, k]
            z /= np.sqrt(modeleval.inner_product(z, z))
            y0 = modeleval.get_jacobian(x0, mu, g) * z
            print(np.linalg.norm(y0 - eigenvals[k] * z))

        # Normalize and store all eigenvectors & values.
        print("Storing corresponding eigenstates...", end=" ")
        k = 0
        for k in range(len(eigenvals)):
            filename = "eigen%d.vtu" % k
            # Convert to complex representation.
            z = X[0::2, k] + 1j * X[1::2, k]
            z /= np.sqrt(modeleval.inner_product(z, z))
            mesh.write(
                filename,
                point_data={
                    "psi": point_data["psi"],
                    "A": point_data["A"],
                    "V": point_data["V"],
                    "eigen": z,
                },
                field_data={"g": g, "mu": mu, "eigenvalue": eigenvals[k]},
            )
        print("done.")
    else:
        # initial guess for the eigenvectors
        X = np.ones((len(mesh.node_coords), 1))

        # set the range of parameters
        steps = 51
        mus = np.linspace(0.0, 0.5, steps)
        eigenvals_list = []
        # small_eigenvals_approx = []
        for mu in mus:
            modeleval.set_parameter(mu)
            eigenvals, X = _compute_eigenvalues(
                args.operator,
                args.eigenvalue_type,
                args.num_eigenvalues,
                X[:, 0],
                modeleval,
                mu,
                g,
            )
            # small_eigenval, X = my_lobpcg( modeleval._keo,
            # X,
            # tolerance = 1.0e-5,
            # maxiter = len(pynoshmesh.nodes),
            # verbosity = 1
            # )
            # print 'Calculated values: ', small_eigenval
            # alpha = modeleval.keo_smallest_eigenvalue_approximation()
            # print 'Linear approximation: ', alpha
            # small_eigenvals_approx.append( alpha )
            # print
            eigenvals_list.append(eigenvals)
        # plot all the eigenvalues as balls
        _plot_eigenvalue_series(mus, eigenvals_list)
        # pp.legend()
        pp.title("%s eigenvalues of %s" % (args.eigenvalue_type, args.operator))
        # pp.ylim( ymin = 0.0 )
        pp.xlabel("$\mu$")
        pp.show()
        # matplotlib2tikz.save('eigenvalues.tikz',
        # figurewidth = '\\figurewidth',
        # figureheight = '\\figureheight'
        # )
    return
Esempio n. 42
0
def _main():
    """Main function.
    """
    args = _parse_input_arguments()

    mesh, point_data, field_data = meshplex.read(args.filename, timestep=args.timestep)
    N = len(mesh.node_coords)
    # build the model evaluator
    nls_modeleval = pynosh.modelevaluator_nls.NlsModelEvaluator(
        mesh,
        V=-np.ones(N),
        A=point_data["A"],
        preconditioner_type=args.preconditioner_type,
        num_amg_cycles=args.num_amg_cycles,
    )

    current_psi = np.random.rand(N, 1) + 1j * np.random.rand(N, 1)

    if args.bordering:
        modeleval = pynosh.bordered_modelevaluator.BorderedModelEvaluator(nls_modeleval)
        # right hand side
        x = np.empty((N + 1, 1), dtype=complex)
        x[0:N] = current_psi
        x[N] = 1.0
    else:
        modeleval = nls_modeleval
        x = current_psi

    print(("machine eps = %g" % np.finfo(np.complex).eps))

    mu = args.mu
    g = 1.0

    # check the jacobian operator
    J = modeleval.get_jacobian(x, mu, g)
    print(
        (
            "max(|<v,Ju> - <Jv,u>|) = %g"
            % _check_selfadjointness(J, modeleval.inner_product)
        )
    )

    if args.preconditioner_type != "none":
        # check the preconditioner
        P = modeleval.get_preconditioner(x, mu, g)
        print(
            (
                "max(|<v,Pu> - <Pv,u>|) = %g"
                % _check_selfadjointness(P, modeleval.inner_product)
            )
        )
        # Check positive definiteness of P.
        print(
            (
                "min(<u,Pu>) = %g"
                % _check_positivedefiniteness(P, modeleval.inner_product)
            )
        )

        # check the inverse preconditioner
        # Pinv = modeleval.get_preconditioner_inverse(x, mu, g)
        # print('max(|<v,P^{-1}u> - <P^{-1}v,u>|) = %g'
        #      % _check_selfadjointness(Pinv, modeleval.inner_product
        #      )
        # check positive definiteness of P^{-1}
        # print('min(<u,P^{-1}u>) = %g'
        #      % _check_positivedefiniteness(Pinv, inner_product)
        #      )
    return
Esempio n. 43
0
def _main():
    """Main function.
    """
    args = _parse_input_arguments()

    # read the mesh
    mesh, point_data, field_data = meshplex.read(args.filename, timestep=args.timestep)

    # build the model evaluator
    modeleval = pynosh.modelevaluator_nls.NlsModelEvaluator(
        mesh=mesh, A=point_data["A"], V=point_data["V"], preconditioner_type="exact"
    )

    # set the range of parameters
    steps = 10
    mus = np.linspace(0.5, 5.5, steps)

    num_unknowns = len(mesh.node_coords)

    # initial guess for the eigenvectors
    # psi = np.random.rand(num_unknowns) + 1j * np.random.rand(num_unknowns)
    psi = np.ones(num_unknowns)  # + 1j * np.ones(num_unknowns)
    psi *= 0.5
    # psi = 4.0 * 1.0j * np.ones(num_unknowns)
    print(num_unknowns)
    eigenvals_list = []

    g = 10.0
    for mu in mus:
        if args.operator == "k":
            # build dense KEO
            A = modeleval._get_keo(mu).toarray()
            B = None
        elif args.operator == "p":
            # build dense preconditioner
            P = modeleval.get_preconditioner(psi, mu, g)
            A = P.toarray()
            B = None
        elif args.operator == "j":
            # build dense jacobian
            J1, J2 = modeleval.get_jacobian_blocks(psi, mu, g)
            A = _build_stacked_operator(J1.toarray(), J2.toarray())
            B = None
        elif args.operator == "kj":
            J1, J2 = modeleval.get_jacobian_blocks(psi)
            A = _build_stacked_operator(J1.toarray(), J2.toarray())

            modeleval._assemble_keo()
            K = _modeleval._keo
            B = _build_stacked_operator(K.toarray())
        elif args.operator == "pj":
            J1, J2 = modeleval.get_jacobian_blocks(psi)
            A = _build_stacked_operator(J1.toarray(), J2.toarray())

            P = modeleval.get_preconditioner(psi)
            B = _build_stacked_operator(P.toarray())
        else:
            raise ValueError("Unknown operator '", args.operator, "'.")

        print("Compute eigenvalues for mu =", mu, "...")
        # get smallesteigenvalues
        start_time = time.clock()
        # use eig as the problem is not symmetric (but it is self-adjoint)
        eigenvals, U = eig(
            A,
            b=B,
            # lower = True,
        )
        end_time = time.clock()
        print("done. (", end_time - start_time, "s).")

        # sort by ascending eigenvalues
        assert norm(eigenvals.imag, np.inf) < 1.0e-14
        eigenvals = eigenvals.real
        sort_indices = np.argsort(eigenvals.real)
        eigenvals = eigenvals[sort_indices]
        U = U[:, sort_indices]

        # rebuild complex-valued U
        U_complex = _build_complex_vector(U)
        # normalize
        for k in range(U_complex.shape[1]):
            norm_Uk = np.sqrt(
                modeleval.inner_product(U_complex[:, [k]], U_complex[:, [k]])
            )
            U_complex[:, [k]] /= norm_Uk

        ## Compare the different expressions for the eigenvalues.
        # for k in xrange(len(eigenvals)):
        #    JU_complex = J1 * U_complex[:,[k]] + J2 * U_complex[:,[k]].conj()
        #    uJu = modeleval.inner_product(U_complex[:,k], JU_complex)[0]

        #    PU_complex = P * U_complex[:,[k]]
        #    uPu = modeleval.inner_product(U_complex[:,k], PU_complex)[0]

        #    KU_complex = modeleval._keo * U_complex[:,[k]]
        #    uKu = modeleval.inner_product(U_complex[:,k], KU_complex)[0]

        #    # expression 1
        #    lambd = uJu / uPu
        #    assert abs(eigenvals[k] - lambd) < 1.0e-10, abs(eigenvals[k] - lambd)

        #    # expression 2
        #    alpha = modeleval.inner_product(U_complex[:,k]**2, psi**2)
        #    lambd = uJu / (-uJu + 1.0 - alpha)
        #    assert abs(eigenvals[k] - lambd) < 1.0e-10

        #    # expression 3
        #    alpha = modeleval.inner_product(U_complex[:,k]**2, psi**2)
        #    beta = modeleval.inner_product(abs(U_complex[:,k])**2, abs(psi)**2)
        #    lambd = -1.0 + (1.0-alpha) / (uKu + 2*beta)
        #    assert abs(eigenvals[k] - lambd) < 1.0e-10

        #    # overwrite for plotting
        #    eigenvals[k] = 1- alpha

        eigenvals_list.append(eigenvals)

    # plot the eigenvalues
    # _plot_eigenvalue_series( mus, eigenvals_list )
    for ev in eigenvals_list:
        pp.plot(ev, ".")

    # pp.plot( mus,
    # small_eigenvals_approx,
    # '--'
    # )
    # pp.legend()
    pp.title("eigenvalues of %s" % args.operator)

    # pp.ylim( ymin = 0.0 )

    # pp.xlabel( '$\mu$' )

    pp.show()

    # matplotlib2tikz.save('eigenvalues.tikz',
    # figurewidth = '\\figurewidth',
    # figureheight = '\\figureheight'
    # )
    return
Esempio n. 44
0
def _solve_system(modeleval, filename, timestep, mu, args):
    # read the mesh
    print(("Reading current psi...",))
    start = time.time()
    mesh, point_data, field_data = meshplex.read(filename, timestep=timestep)
    total = time.time() - start
    print(("done (%gs)." % total))

    num_coords = len(mesh.node_coords)

    # set psi at which to create the Jacobian
    print(("Creating initial guess and right-hand side...",))
    start = time.time()
    current_psi = (point_data["psi"][:, 0] + 1j * point_data["psi"][:, 1]).reshape(
        -1, 1
    )

    # Perturb a bit.
    eps = 1.0e-10
    perturbation = eps * (np.random.rand(num_coords) + 1j * np.random.rand(num_coords))
    current_psi += perturbation.reshape(current_psi.shape)

    if args.bordering:
        phi0 = np.zeros((num_coords + 1, 1), dtype=complex)
        # right hand side
        x = np.empty((num_coords + 1, 1), dtype=complex)
        x[0:num_coords] = current_psi
        x[num_coords] = 0.0
    else:
        # create right hand side and initial guess
        phi0 = np.zeros((num_coords, 1), dtype=complex)
        x = current_psi
    # right hand side
    # rhs = np.ones( (num_coords,1), dtype=complex )

    # rhs = np.empty( num_coords, dtype = complex )
    # radius = np.random.rand( num_coords )
    # arg    = np.random.rand( num_coords ) * 2.0 * cmath.pi
    # for k in range( num_coords ):
    # rhs[ k ] = cmath.rect(radius[k], arg[k])
    rhs = modeleval.compute_f(x=x, mu=mu, g=1.0)
    end = time.time()
    print(("done. (%gs)" % (end - start)))
    print(("||rhs|| = %g" % np.sqrt(modeleval.inner_product(rhs, rhs))))

    # create the linear operator
    print(("Getting Jacobian...",))
    start_time = time.clock()
    jacobian = modeleval.get_jacobian(x=x, mu=mu, g=1.0)
    end_time = time.clock()
    print(("done. (%gs)" % (end_time - start_time)))

    # create precondictioner object
    print(("Getting preconditioner...",))
    start_time = time.clock()
    prec = modeleval.get_preconditioner_inverse(x=x, mu=mu, g=1.0)
    end_time = time.clock()
    print(("done. (%gs)" % (end_time - start_time)))

    # Get reference solution
    # print 'Get reference solution (dim = %d)...' % (2*num_coords),
    # start_time = time.clock()
    # ref_sol, info, relresvec, errorvec = nm.minres_wrap( jacobian, rhs,
    # x0 = phi0,
    # tol = 1.0e-14,
    # M = prec,
    # inner_product = modeleval.inner_product,
    # explicit_residual = True
    # )
    # end_time = time.clock()
    # if info == 0:
    # print 'success!',
    # else:
    # print 'no convergence.',
    # print ' (', end_time - start_time, 's,', len(relresvec)-1 ,' iters).'

    if args.use_deflation:
        W = 1j * x
        AW = jacobian * W
        P, x0new = nm.get_projection(
            W, AW, rhs, phi0, inner_product=modeleval.inner_product
        )
    else:
        # AW = np.zeros((len(current_psi),1), dtype=np.complex)
        P = None
        x0new = phi0

    if args.krylov_method == "cg":
        lin_solve = nm.cg
    elif args.krylov_method == "minres":
        lin_solve = nm.minres
    # elif args.krylov_method == 'minresfo':
    # lin_solve = nm.minres
    # lin_solve_args.update({'full_reortho': True})
    elif args.krylov_method == "gmres":
        lin_solve = nm.gmres
    else:
        raise ValueError("Unknown Krylov solver " "%s" "." % args.krylov_method)

    print(
        (
            "Solving the system (len(x) = %d, bordering: %r)..."
            % (len(x), args.bordering),
        )
    )
    start_time = time.clock()
    timer = False
    out = lin_solve(
        jacobian,
        rhs,
        x0new,
        tol=args.tolerance,
        Mr=P,
        M=prec,
        # maxiter = 2*num_coords,
        maxiter=500,
        inner_product=modeleval.inner_product,
        explicit_residual=True,
        # timer=timer
        # exact_solution = ref_sol
    )
    end_time = time.clock()
    print(("done. (%gs)" % (end_time - start_time)))
    print(("(%d,%d)" % (2 * num_coords, len(out["relresvec"]) - 1)))

    # compute actual residual
    # res = rhs - jacobian * out['xk']
    # print '||b-Ax|| = %g' % np.sqrt(modeleval.inner_product(res, res))

    if timer:
        # pretty-print timings
        print(
            (
                " " * 22
                + "sum".rjust(14)
                + "mean".rjust(14)
                + "min".rjust(14)
                + "std dev".rjust(14)
            )
        )
        for key, item in list(out["times"].items()):
            print(
                (
                    "'%s': %12g  %12g  %12g  %12g"
                    % (key.ljust(20), item.sum(), item.mean(), item.min(), item.std())
                )
            )

    # Get the number of MG cycles.
    # 'modeleval.num_cycles' contains the number of MG cycles executed
    # for all AMG calls run.
    # In nm.minres, two calls to the precondictioner are done prior to the
    # actual iteration for the normalization of the residuals.
    # With explicit_residual=True, *two* calls to the preconditioner are done
    # in each iteration.
    # What we would like to have here is the number of V-cycles done per loop
    # when explicit_residual=False. Also, forget about the precondictioner
    # calls for the initialization.
    # Hence, cut of the first two and replace it by 0, and out of the
    # remainder take every other one.
    # nc = [0] + modeleval.tot_amg_cycles[2::2]
    # nc_cumsum = np.cumsum(nc)
    # pp.semilogy(nc_cumsum, out['relresvec'], color='0.0')
    # pp.show()
    # import matplotlib2tikz
    # matplotlib2tikz.save('cycle10.tex')

    # matplotlib2tikz.save('inf.tex')

    return out["relresvec"]