Пример #1
0
def test_up():
    points, cells = meshzoo.rectangle_tri((0, 0), (1, 1), 11, variant="up")
    assert len(points) == 121
    assert _near_equal(np.sum(points, axis=0), [60.5, 60.5])
    assert len(cells) == 200
    assert np.all(_get_signed_areas(points.T, cells) > 0.0)

    points, cells = meshzoo.rectangle_tri((0, 0), (1, 1), (3, 2), variant="up")
    assert len(points) == 6
    assert _near_equal(np.sum(points, axis=0), [3.0, 3.0])
    assert len(cells) == 4
    assert set(cells[0]) == {0, 1, 4}
    assert set(cells[2]) == {0, 3, 4}
    assert np.all(_get_signed_areas(points.T, cells) > 0.0)
Пример #2
0
def test_jacobian():
    from test_ginzburg_landau import GinzburgLandau

    a = 10.0
    n = 10
    points, cells = meshzoo.rectangle_tri((-a / 2, -a / 2), (a / 2, a / 2), n)
    # add column with zeros for magnetic potential
    points = np.column_stack([points, np.zeros(points.shape[0])])

    mesh = meshplex.MeshTri(points, cells)

    gl = GinzburgLandau(mesh)
    glr = GinzburgLandauReal(mesh)

    n = points.shape[0]

    np.random.seed(123)

    for _ in range(10):
        psi = np.random.rand(n) + 1j * np.random.rand(n)
        mu = np.random.rand(1)[0]
        jac0 = gl.jacobian(psi, mu)
        jac1 = glr.jacobian(to_real(psi), mu)
        for _ in range(10):
            phi = np.random.rand(n) + 1j * np.random.rand(n)
            out0 = (jac0 * phi) * mesh.control_volumes
            out1 = to_complex(jac1 * to_real(phi))
            assert np.all(np.abs(out0 - out1) < 1.0e-12)
Пример #3
0
def test_df_dlmbda():
    from test_ginzburg_landau import GinzburgLandau

    a = 10.0
    n = 10
    points, cells = meshzoo.rectangle_tri(np.linspace(-a / 2, a / 2, n),
                                          np.linspace(-a / 2, a / 2, n))
    # add column with zeros for magnetic potential
    points = np.column_stack([points, np.zeros(points.shape[0])])

    mesh = meshplex.Mesh(points, cells)

    gl = GinzburgLandau(mesh)
    glr = GinzburgLandauReal(mesh)

    n = points.shape[0]

    np.random.seed(123)

    for _ in range(10):
        psi = np.random.rand(n) + 1j * np.random.rand(n)
        mu = np.random.rand(1)[0]
        out = gl.df_dlmbda(psi, mu) * mesh.control_volumes
        out2 = glr.df_dlmbda(to_real(psi), mu)
        assert np.all(np.abs(out - to_complex(out2)) < 1.0e-12)
Пример #4
0
def test_2d(solver, write_file=False):
    n = 200
    rng = np.random.default_rng(123)
    x0 = rng.random((n, 2)) - 0.5
    # y0 = np.ones(n)
    # y0 = x0[:, 0]
    # y0 = x0[:, 0]**2
    # y0 = np.cos(np.pi*x0.T[0])
    # y0 = np.cos(np.pi*x0.T[0]) * np.cos(np.pi*x0.T[1])
    y0 = np.cos(np.pi * np.sqrt(x0.T[0]**2 + x0.T[1]**2))

    points, cells = meshzoo.rectangle_tri(np.linspace(-1.0, 1.0, 32),
                                          np.linspace(-1.0, 1.0, 32))

    # import pygmsh
    # geom = pygmsh.built_in.Geometry()
    # geom.add_circle([0.0, 0.0, 0.0], 1.0, 0.1)
    # points, cells, _, _, _ = pygmsh.generate_mesh(geom)
    # cells = cells['triangle']

    basis, u = smoothfit.fit(x0,
                             y0,
                             points,
                             cells,
                             lmbda=1.0e-5,
                             solver=solver)

    # ref = 991.0323831016119
    # val = np.dot(u, u)
    # print(solver, val)
    # assert abs(val - ref) < 1.0e-10 * ref

    if write_file:
        basis.mesh.save(f"out-{solver}.vtu", point_data={"u": u})
Пример #5
0
 def __init__(self):
     points, cells = meshzoo.rectangle_tri((0.0, 0.0), (1.0, 1.0), 30)
     self.mesh = meshplex.MeshTri(points, cells)
     # This matrix self.A is negative semidefinite
     self.A, _ = pyfvm.discretize_linear(Poisson(), self.mesh)
     tol = 1.0e-12
     self.idx_left = np.where(self.mesh.points[:, 0] < tol)[0]
     self.idx_right = np.where(self.mesh.points[:, 0] > 1.0 - tol)[0]
     self.idx_bottom = np.where(self.mesh.points[:, 1] < tol)[0]
     self.idx_top = np.where(self.mesh.points[:, 1] > 1.0 - tol)[0]
Пример #6
0
def test_ginzburg_landau(max_steps=5, n=20):
    a = 10.0
    points, cells = meshzoo.rectangle_tri(np.linspace(-a / 2, a / 2, n),
                                          np.linspace(-a / 2, a / 2, n))
    # add column with zeros for magnetic potential
    points = np.column_stack([points, np.zeros_like(points[:, 0])])

    mesh = meshplex.Mesh(points, cells)

    problem = GinzburgLandau(mesh)
    n = problem.mesh.control_volumes.shape[0]
    u0 = np.ones(n, dtype=complex)
    mu0 = 0.0

    mu_list = []

    filename = "sol.xdmf"
    with meshio.xdmf.TimeSeriesWriter(filename) as writer:
        writer.write_points_cells(problem.mesh.points,
                                  {"triangle": problem.mesh.cells("points")})

        def callback(k, mu, sol):
            mu_list.append(mu)
            # Store the solution
            psi = np.array([np.real(sol), np.imag(sol)]).T
            writer.write_data(k, point_data={"psi": psi})
            with open("data.yml", "w") as fh:
                yaml.dump(
                    {
                        "filename": filename,
                        "mu": [float(m) for m in mu_list]
                    }, fh)

        # pacopy.natural(
        #     problem,
        #     u0,
        #     mu0,
        #     callback,
        #     max_steps=1000,
        #     lambda_stepsize0=1.0e-2,
        #     newton_max_steps=5,
        #     newton_tol=1.0e-10,
        # )
        pacopy.euler_newton(
            problem,
            u0,
            mu0,
            callback,
            max_steps=max_steps,
            stepsize0=1.0e-2,
            stepsize_max=1.0,
            newton_tol=1.0e-10,
        )
Пример #7
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"))
Пример #8
0
    def __init__(self):
        a = 24.0
        points, cells = meshzoo.rectangle_tri((-a / 2, -a / 2), (a / 2, a / 2),
                                              50)
        self.mesh = meshplex.MeshTri(points, cells)

        x, y, z = self.mesh.points.T
        assert np.all(np.abs(z) < 1.0e-15)

        self.omega = 0.2
        self.V = 0.5 * self.omega**2 * (x**2 + y**2)

        # For the preconditioner
        assert np.all(self.V >= 0)

        self.A, _ = pyfvm.discretize_linear(Poisson(), self.mesh)
Пример #9
0
    def __init__(self):
        a = 20.0
        points, cells = meshzoo.rectangle_tri(
            np.linspace(-a / 2, a / 2, 40), np.linspace(-a / 2, a / 2, 40)
        )
        self.mesh = meshplex.Mesh(points, cells)
        self.A, _ = pyfvm.get_fvm_matrix(self.mesh, [Poisson()])

        # k = 1
        # ka = 4.5
        # DD = 8
        # nu = np.sqrt(1 / DD)
        # kbcrit = np.sqrt(1 + ka * nu)

        self.a = 4.0
        self.d1 = 1.0
        self.d2 = 2.0
Пример #10
0
def test_f_i_psi():
    """Assert that <f(psi), i psi> == 0."""
    points, cells = meshzoo.rectangle_tri((-5.0, -5.0), (5.0, 5.0), 30)
    # add column with zeros for magnetic potential
    points = np.column_stack([points, np.zeros(points.shape[0])])

    mesh = meshplex.MeshTri(points, cells)

    problem = GinzburgLandau(mesh)
    n = problem.mesh.control_volumes.shape[0]

    np.random.seed(0)

    for _ in range(100):
        mu = np.random.rand(1)
        psi = np.random.rand(n) + 1j * np.random.rand(n)
        f = problem.f(psi, mu)
        assert abs(problem.inner(1j * psi, f)) < 1.0e-13
Пример #11
0
def test_self_adjointness():
    a = 10.0
    n = 10
    points, cells = meshzoo.rectangle_tri((-a / 2, -a / 2), (a / 2, a / 2), n)
    # add column with zeros for magnetic potential
    points = np.column_stack([points, np.zeros(points.shape[0])])

    mesh = meshplex.MeshTri(points, cells)

    problem = GinzburgLandauReal(mesh)
    n = problem.mesh.control_volumes.shape[0]
    psi = np.random.rand(2 * n)
    jac = problem.jacobian(psi, 0.1)

    for _ in range(1000):
        u = np.random.rand(2 * n)
        v = np.random.rand(2 * n)
        a0 = problem.inner(u, jac * v)
        a1 = problem.inner(jac * u, v)
        assert abs(a0 - a1) < 1.0e-12
Пример #12
0
def test_df_dlmbda():
    points, cells = meshzoo.rectangle_tri((-5.0, -5.0), (5.0, 5.0), 30)
    # add column with zeros for magnetic potential
    points = np.column_stack([points, np.zeros(points.shape[0])])

    mesh = meshplex.MeshTri(points, cells)

    problem = GinzburgLandau(mesh)
    n = problem.mesh.control_volumes.shape[0]
    np.random.seed(0)

    for _ in range(100):
        mu = np.random.rand(1)
        psi = np.random.rand(n) + 1j * np.random.rand(n)
        out = problem.df_dlmbda(psi, mu)

        # finite difference
        eps = 1.0e-5
        diff = (problem.f(psi, mu + eps) - problem.f(psi, mu - eps)) / (2 * eps)
        nrm = np.dot((out - diff).conj(), out - diff).real
        assert nrm < 1.0e-12
Пример #13
0
def setup(n):
    x0 = rng.random((n, 2)) - 0.5
    # y0 = np.ones(n)
    # y0 = x0[:, 0]
    # y0 = x0[:, 0]**2
    # y0 = np.cos(np.pi*x0.T[0])
    # y0 = np.cos(np.pi*x0.T[0]) * np.cos(np.pi*x0.T[1])
    y0 = np.cos(np.pi * np.sqrt(x0.T[0]**2 + x0.T[1]**2))

    points, cells = meshzoo.rectangle_tri((-1.0, -1.0), (1.0, 1.0), n)

    mesh = skfem.MeshTri(points.T.copy(), cells.T.copy())
    element = skfem.ElementTriP1()

    @skfem.BilinearForm
    def mass(u, v, _):
        return u * v

    @skfem.BilinearForm
    def flux(u, v, w):
        return dot(w.n, u.grad) * v

    basis = skfem.InteriorBasis(mesh, element)
    facet_basis = skfem.FacetBasis(basis.mesh, basis.elem)

    lap = skfem.asm(laplace, basis)
    boundary_terms = skfem.asm(flux, facet_basis)

    A = lap - boundary_terms
    # A *= lmbda

    # get the evaluation matrix
    E = basis.probes(x0.T)

    # mass matrix
    M = skfem.asm(mass, basis)

    # x = _solve(A, M, E, y0, solver)

    # # Neumann preconditioner
    # An = _assemble_eigen(dot(grad(u), grad(v)) * dx).sparray()

    # # Dirichlet preconditioner
    # Ad = _assemble_eigen(dot(grad(u), grad(v)) * dx)
    # bc = DirichletBC(V, 0.0, "on_boundary")
    # bc.apply(Ad)
    # # Ad = Ad.sparray()

    # Aq = _assemble_eigen(
    #     dot(grad(u), grad(v)) * dx - dot(n, grad(u)) * v * ds - dot(n, grad(v)) * u * ds
    # ).sparray()

    # ml = pyamg.smoothed_aggregation_solver(A, coarse_solver="jacobi", max_coarse=100)
    # mln = pyamg.smoothed_aggregation_solver(An, coarse_solver="jacobi", max_coarse=100)
    # mld = pyamg.smoothed_aggregation_solver(Ad, coarse_solver="jacobi", max_coarse=100)
    # mlq = pyamg.smoothed_aggregation_solver(Aq, coarse_solver="jacobi", max_coarse=100)

    ml = pyamg.smoothed_aggregation_solver(A,
                                           coarse_solver="jacobi",
                                           symmetry="nonsymmetric",
                                           max_coarse=100)
    # mlT = pyamg.smoothed_aggregation_solver(
    #     A.T, coarse_solver="jacobi", symmetry="nonsymmetric", max_coarse=100
    # )

    P = ml.aspreconditioner()
    # PT = mlT.aspreconditioner()

    # construct transpose -- dense, super expensive!
    I = np.eye(P.shape[0])
    PT = (P @ I).T
    PT = scipy.sparse.csr_matrix(PT)

    # # make sure it's really the transpose
    # x = rng.random(A.shape[1])
    # y = rng.random(A.shape[1])
    # print(np.dot(x, P @ y))
    # print(np.dot(PT @ x, y))

    def matvec(x):
        return P @ x

    def rmatvec(y):
        return PT @ y

    precs = [
        scipy.sparse.linalg.LinearOperator(A.shape,
                                           matvec=matvec,
                                           rmatvec=rmatvec)
        # not working well:
        # (ml.aspreconditioner(), mlT.aspreconditioner())
    ]

    return A, E, M, precs, y0
Пример #14
0
def test_continuation(max_steps=5):
    a = 10.0
    n = 20
    points, cells = meshzoo.rectangle_tri((-a / 2, -a / 2), (a / 2, a / 2), n)
    # add column with zeros for magnetic potential
    points = np.column_stack([points, np.zeros(points.shape[0])])

    mesh = meshplex.MeshTri(points, cells)

    problem = GinzburgLandauReal(mesh)
    num_unknowns = 2 * problem.mesh.control_volumes.shape[0]
    u0 = np.ones(num_unknowns)
    u0[1::2] = 0.0
    mu0 = 0.0

    # plt.ion()
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # plt.axis("square")
    # plt.xlabel("$\\mu$")
    # plt.ylabel("$||\\psi||_2$")
    # plt.grid()
    # b_list = []
    # values_list = []
    # line1, = ax.plot(b_list, values_list, "-", color="#1f77f4")

    mu_list = []

    filename = "sol.xdmf"
    with meshio.xdmf.TimeSeriesWriter(filename) as writer:
        writer.write_points_cells(problem.mesh.points,
                                  [("triangle", problem.mesh.cells["points"])])

        def callback(k, mu, sol):
            mu_list.append(mu)
            # Store the solution
            psi = np.array([sol[0::2], sol[1::2]]).T
            writer.write_data(k, point_data={"psi": psi})
            with open("data.yml", "w") as fh:
                yaml.dump(
                    {
                        "filename": filename,
                        "mu": [float(m) for m in mu_list]
                    }, fh)

        # pacopy.natural(
        #     problem,
        #     u0,
        #     b0,
        #     callback,
        #     max_steps=1,
        #     lambda_stepsize0=1.0e-2,
        #     newton_max_steps=5,
        #     newton_tol=1.0e-10,
        # )
        pacopy.euler_newton(
            problem,
            u0,
            mu0,
            callback,
            max_steps=max_steps,
            stepsize0=1.0e-2,
            stepsize_max=1.0,
            newton_tol=1.0e-10,
        )
Пример #15
0
def test_center():
    points, cells = meshzoo.rectangle_tri((0, 0), (1, 1), (11, 9), variant="center")
    meshzoo.show2d(points, cells)
    assert len(points) == 99
    assert len(cells) == 160
    assert np.all(_get_signed_areas(points.T, cells) > 0.0)
Пример #16
0
def test_down():
    points, cells = meshzoo.rectangle_tri((0, 0), (1, 1), (5, 4), variant="down")
    assert len(points) == 20
    assert len(cells) == 24
    assert np.all(_get_signed_areas(points.T, cells) > 0.0)