def test_rectangle(): points, cells = meshzoo.rectangle(nx=11, ny=11, zigzag=False) assert len(points) == 121 assert _near_equal(numpy.sum(points, axis=0), [60.5, 60.5, 0.0]) assert len(cells) == 200 points, cells = meshzoo.rectangle(nx=11, ny=11, zigzag=True) assert len(points) == 121 assert _near_equal(numpy.sum(points, axis=0), [60.5, 60.5, 0.0]) assert len(cells) == 200 points, cells = meshzoo.rectangle(nx=2, ny=2, zigzag=True) assert len(points) == 4 assert _near_equal(numpy.sum(points, axis=0), [2.0, 2.0, 0.0]) assert len(cells) == 2 points, cells = meshzoo.rectangle(nx=3, ny=2, zigzag=False) assert len(points) == 6 assert _near_equal(numpy.sum(points, axis=0), [3.0, 3.0, 0.0]) assert len(cells) == 4 assert set(cells[0]) == set([0, 1, 4]) assert set(cells[2]) == set([0, 3, 4]) points, cells = meshzoo.rectangle(nx=3, ny=2, zigzag=True) assert len(points) == 6 assert _near_equal(numpy.sum(points, axis=0), [3.0, 3.0, 0.0]) assert len(cells) == 4 assert set(cells[0]) == set([0, 1, 4]) assert set(cells[2]) == set([0, 3, 4]) return
def test_rectangle(): points, cells = meshzoo.rectangle(nx=11, ny=11, variant="up") assert len(points) == 121 assert _near_equal(numpy.sum(points, axis=0), [60.5, 60.5]) assert len(cells) == 200 points, cells = meshzoo.rectangle(nx=11, ny=11, variant="zigzag") assert len(points) == 121 assert _near_equal(numpy.sum(points, axis=0), [60.5, 60.5]) assert len(cells) == 200 points, cells = meshzoo.rectangle(nx=2, ny=2, variant="zigzag") assert len(points) == 4 assert _near_equal(numpy.sum(points, axis=0), [2.0, 2.0]) assert len(cells) == 2 points, cells = meshzoo.rectangle(nx=3, ny=2, variant="up") assert len(points) == 6 assert _near_equal(numpy.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} points, cells = meshzoo.rectangle(nx=3, ny=2, variant="zigzag") assert len(points) == 6 assert _near_equal(numpy.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}
def test(): class EnergyEdgeKernel(object): def __init__(self): self.subdomains = [None] return def eval(self, mesh, cell_mask): edge_ce_ratio = mesh.ce_ratios[..., cell_mask] beta = 1.0 return numpy.array( [ [edge_ce_ratio, -edge_ce_ratio * numpy.exp(1j * beta)], [-edge_ce_ratio * numpy.exp(-1j * beta), edge_ce_ratio], ] ) vertices, cells = meshzoo.rectangle(0.0, 2.0, 0.0, 1.0, 101, 51) mesh = meshplex.MeshTri(vertices, cells) matrix = pyfvm.get_fvm_matrix(mesh, [EnergyEdgeKernel()], [], [], []) rhs = mesh.control_volumes.copy() sa = pyamg.smoothed_aggregation_solver(matrix, smooth="energy") u = sa.solve(rhs, tol=1e-10) # Cannot write complex data ot VTU; split real and imaginary parts first. # <http://stackoverflow.com/a/38902227/353337> mesh.write("out.vtk", point_data={"u": u.view("(2,)float")}) return
def test(): class Bratu: def apply(self, u): return integrate(lambda x: -n_dot_grad(u(x)), dS) - integrate( lambda x: 2.0 * exp(u(x)), dV) def dirichlet(self, u): return [(u, Boundary())] vertices, cells = meshzoo.rectangle(0.0, 2.0, 0.0, 1.0, 101, 51) mesh = meshplex.MeshTri(vertices, cells) f, jac_u = pyfvm.discretize(Bratu(), mesh) def jacobian_solver(u0, rhs): from scipy.sparse import linalg jac = jac_u.get_linear_operator(u0) return linalg.spsolve(jac, rhs) u0 = numpy.zeros(len(vertices)) u = pyfvm.newton(lambda u: f.eval(u), jacobian_solver, u0) # import scipy.optimize # u = scipy.optimize.newton_krylov(f_eval, u0) mesh.write("out.vtk", point_data={"u": u}) return
def plot_tree_2d(n, *args, res=100, colorbar=True, cmap="RdBu_r", clim=None, **kwargs): import dufte import meshzoo from matplotlib import pyplot as plt plt.style.use(dufte.style) points, cells = meshzoo.rectangle(-1.0, 1.0, -1.0, 1.0, res, res) evaluator = Eval(points.T, *args, **kwargs) plt.set_cmap(cmap) plt.gca().set_aspect("equal") plt.axis("off") for k, values in enumerate(itertools.islice(evaluator, n + 1)): for r, z in enumerate(values): offset = [2.8 * (r - k / 2), -2.6 * k] pts = points + offset plt.tripcolor(pts[:, 0], pts[:, 1], cells, z, shading="flat") plt.clim(clim) # rectangle outlines corners = numpy.array([[-1, 1, 1, -1, -1], [-1, -1, 1, 1, -1]]) corners = (corners.T + offset).T plt.plot(corners[0], corners[1], "-k") if colorbar: plt.colorbar()
def test_jacobian(): from test_ginzburg_landau import GinzburgLandau a = 10.0 n = 10 points, cells = meshzoo.rectangle(-a / 2, a / 2, -a / 2, a / 2, n, n) mesh = meshplex.MeshTri(points, cells) gl = GinzburgLandau(mesh) glr = GinzburgLandauReal(mesh) n = points.shape[0] numpy.random.seed(123) for _ in range(10): psi = numpy.random.rand(n) + 1j * numpy.random.rand(n) mu = numpy.random.rand(1)[0] jac0 = gl.jacobian(psi, mu) jac1 = glr.jacobian(to_real(psi), mu) for _ in range(10): phi = numpy.random.rand(n) + 1j * numpy.random.rand(n) out0 = (jac0 * phi) * mesh.control_volumes out1 = to_complex(jac1 * to_real(phi)) assert numpy.all(numpy.abs(out0 - out1) < 1.0e-12)
def test(): class Bratu(object): def apply(self, u): return integrate(lambda x: -n_dot_grad(u(x)), dS) - integrate( lambda x: 2.0 * exp(u(x)), dV ) def dirichlet(self, u): return [(u, Boundary())] vertices, cells = meshzoo.rectangle(0.0, 2.0, 0.0, 1.0, 101, 51) mesh = meshplex.MeshTri(vertices, cells) f, jac_u = pyfvm.discretize(Bratu(), mesh) def jacobian_solver(u0, rhs): from scipy.sparse import linalg jac = jac_u.get_linear_operator(u0) return linalg.spsolve(jac, rhs) u0 = numpy.zeros(len(vertices)) u = pyfvm.newton(lambda u: f.eval(u), jacobian_solver, u0) # import scipy.optimize # u = scipy.optimize.newton_krylov(f_eval, u0) mesh.write("out.vtk", point_data={"u": u}) return
def test(): class D1(Subdomain): def is_inside(self, x): return x[1] < 0.5 is_boundary_only = True class Poisson(object): def apply(self, u): return ( integrate(lambda x: -n_dot_grad(u(x)), dS) + integrate(lambda x: 3.0, dGamma) - integrate(lambda x: 1.0, dV) ) def dirichlet(self, u): return [(u, D1())] vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 51, 51) mesh = meshplex.MeshTri(vertices, cells) matrix, rhs = pyfvm.discretize_linear(Poisson(), mesh) u = linalg.spsolve(matrix, rhs) mesh.write("out.vtk", point_data={"u": u}) return
def test(): class EnergyEdgeKernel: def __init__(self): self.subdomains = [None] return def eval(self, mesh, cell_mask): edge_ce_ratio = mesh.ce_ratios[..., cell_mask] beta = 1.0 return numpy.array([ [edge_ce_ratio, -edge_ce_ratio * numpy.exp(1j * beta)], [-edge_ce_ratio * numpy.exp(-1j * beta), edge_ce_ratio], ]) vertices, cells = meshzoo.rectangle(0.0, 2.0, 0.0, 1.0, 101, 51) mesh = meshplex.MeshTri(vertices, cells) matrix = pyfvm.get_fvm_matrix(mesh, [EnergyEdgeKernel()], [], [], []) rhs = mesh.control_volumes.copy() sa = pyamg.smoothed_aggregation_solver(matrix, smooth="energy") u = sa.solve(rhs, tol=1e-10) # Cannot write complex data ot VTU; split real and imaginary parts first. # <http://stackoverflow.com/a/38902227/353337> mesh.write("out.vtk", point_data={"u": u.view("(2,)float")}) return
def test_2d(solver, write_file=False): n = 200 np.random.seed(123) x0 = np.random.rand(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)) import meshzoo points, cells = meshzoo.rectangle(-1.0, 1.0, -1.0, 1.0, 32, 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'] u = smoothfit.fit(x0, y0, points, cells, lmbda=1.0e-5, solver=solver) # ref = 4.411_214_155_799_310_5 # val = assemble(u * u * dx) # assert abs(val - ref) < 1.0e-10 * ref if write_file: from dolfin import XDMFFile xdmf = XDMFFile("temp.xdmf") xdmf.write(u)
def test(): class D1(Subdomain): def is_inside(self, x): return x[1] < 0.5 is_boundary_only = True class Poisson: def apply(self, u): return (integrate(lambda x: -n_dot_grad(u(x)), dS) + integrate(lambda x: 3.0, dGamma) - integrate(lambda x: 1.0, dV)) def dirichlet(self, u): return [(u, D1())] vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 51, 51) mesh = meshplex.MeshTri(vertices, cells) matrix, rhs = pyfvm.discretize_linear(Poisson(), mesh) u = linalg.spsolve(matrix, rhs) mesh.write("out.vtk", point_data={"u": u}) return
def get_mesh(self, k): n = 2**(k + 1) vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, n + 1, n + 1, zigzag=True) return meshplex.MeshTri(vertices, cells)
def __init__(self): points, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 30, 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 = numpy.where(self.mesh.node_coords[:, 0] < tol)[0] self.idx_right = numpy.where(self.mesh.node_coords[:, 0] > 1.0 - tol)[0] self.idx_bottom = numpy.where(self.mesh.node_coords[:, 1] < tol)[0] self.idx_top = numpy.where(self.mesh.node_coords[:, 1] > 1.0 - tol)[0]
def test_ginzburg_landau(max_steps=5, n=20): a = 10.0 points, cells = meshzoo.rectangle(-a / 2, a / 2, -a / 2, a / 2, n, n) mesh = meshplex.MeshTri(points, cells) problem = GinzburgLandau(mesh) n = problem.mesh.control_volumes.shape[0] u0 = numpy.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.node_coords, {"triangle": problem.mesh.cells["nodes"]}) def callback(k, mu, sol): mu_list.append(mu) # Store the solution psi = numpy.array([numpy.real(sol), numpy.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, )
def __init__(self): a = 24.0 points, cells = meshzoo.rectangle(-a / 2, a / 2, -a / 2, a / 2, 50, 50) self.mesh = meshplex.MeshTri(points, cells) x, y, z = self.mesh.node_coords.T assert numpy.all(numpy.abs(z) < 1.0e-15) self.omega = 0.2 self.V = 0.5 * self.omega**2 * (x**2 + y**2) # For the preconditioner assert numpy.all(self.V >= 0) self.A, _ = pyfvm.discretize_linear(Poisson(), self.mesh)
def __init__(self): a = 20.0 points, cells = meshzoo.rectangle(-a / 2, a / 2, -a / 2, a / 2, 40, 40) self.mesh = meshplex.MeshTri(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
def test_f_i_psi(): """Assert that <f(psi), i psi> == 0. """ points, cells = meshzoo.rectangle(-5.0, 5.0, -5.0, 5.0, 30, 30) mesh = meshplex.MeshTri(points, cells) problem = GinzburgLandau(mesh) n = problem.mesh.control_volumes.shape[0] numpy.random.seed(0) for _ in range(100): mu = numpy.random.rand(1) psi = numpy.random.rand(n) + 1j * numpy.random.rand(n) f = problem.f(psi, mu) assert abs(problem.inner(1j * psi, f)) < 1.0e-13
def test_self_adjointness(): a = 10.0 n = 10 points, cells = meshzoo.rectangle(-a / 2, a / 2, -a / 2, a / 2, n, n) mesh = meshplex.MeshTri(points, cells) problem = GinzburgLandauReal(mesh) n = problem.mesh.control_volumes.shape[0] psi = numpy.random.rand(2 * n) jac = problem.jacobian(psi, 0.1) for _ in range(1000): u = numpy.random.rand(2 * n) v = numpy.random.rand(2 * n) a0 = problem.inner(u, jac * v) a1 = problem.inner(jac * u, v) assert abs(a0 - a1) < 1.0e-12
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])
def test(): class Singular: def apply(self, u): return (integrate(lambda x: -1.0e-2 * n_dot_grad(u(x)), dS) + integrate(u, dV) - integrate(lambda x: 1.0, dV)) def dirichlet(self, u): return [(u, Boundary())] vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 51, 51) mesh = meshplex.MeshTri(vertices, cells) matrix, rhs = pyfvm.discretize_linear(Singular(), mesh) u = linalg.spsolve(matrix, rhs) mesh.write("out.vtk", point_data={"u": u}) return
def test_io_2d(): vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 2, 2, zigzag=True) mesh = voropy.mesh_tri.MeshTri(vertices, cells) # mesh, _, _, _ = voropy.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='.msh') mesh.write(fname) mesh2, _, _, _ = voropy.read(fname) for k in range(len(mesh.cells['nodes'])): assert tuple(mesh.cells['nodes'][k]) == tuple(mesh2.cells['nodes'][k]) return
def generate_2D_mesh(H, W): _, faces = meshzoo.rectangle(xmin=-1., xmax=1., ymin=-1., ymax=1., nx=W, ny=H, zigzag=True) x = torch.arange(0, W, 1).float().cuda() y = torch.arange(0, H, 1).float().cuda() xx = x.repeat(H, 1) yy = y.view(H, 1).repeat(1, W) grid = torch.stack([xx, yy], dim=0) return grid, faces
def test(): class DC(object): def apply(self, u): a = numpy.array([2, 1, 0]) return integrate(lambda x: -n_dot_grad(u(x)) + n_dot(a) * u(x), dS) - integrate(lambda x: 1.0, dV) def dirichlet(self, u): return [(u, Boundary())] vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 51, 51) mesh = meshplex.MeshTri(vertices, cells) matrix, rhs = pyfvm.discretize_linear(DC(), mesh) u = linalg.spsolve(matrix, rhs) mesh.write("out.vtk", point_data={"u": u}) return
def test_df_dlmbda(): points, cells = meshzoo.rectangle(-5.0, 5.0, -5.0, 5.0, 30, 30) mesh = meshplex.MeshTri(points, cells) problem = GinzburgLandau(mesh) n = problem.mesh.control_volumes.shape[0] numpy.random.seed(0) for _ in range(100): mu = numpy.random.rand(1) psi = numpy.random.rand(n) + 1j * numpy.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 = numpy.dot((out - diff).conj(), out - diff).real assert nrm < 1.0e-12
def test(): class DC(object): def apply(self, u): a = numpy.array([2, 1, 0]) return integrate( lambda x: -n_dot_grad(u(x)) + n_dot(a) * u(x), dS ) - integrate(lambda x: 1.0, dV) def dirichlet(self, u): return [(u, Boundary())] vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 51, 51) mesh = meshplex.MeshTri(vertices, cells) matrix, rhs = pyfvm.discretize_linear(DC(), mesh) u = linalg.spsolve(matrix, rhs) mesh.write("out.vtk", point_data={"u": u}) return
def test_readme_images(): from dolfin import ( MeshEditor, Mesh, FunctionSpace, assemble, EigenMatrix, dot, grad, dx, TrialFunction, TestFunction ) import meshzoo points, cells = meshzoo.rectangle(-1.0, 1.0, -1.0, 1.0, 20, 20) # Convert points, cells to dolfin mesh editor = MeshEditor() mesh = Mesh() # topological and geometrical dimension 2 editor.open(mesh, 'triangle', 2, 2, 1) editor.init_vertices(len(points)) editor.init_cells(len(cells)) for k, point in enumerate(points): editor.add_vertex(k, point[:2]) for k, cell in enumerate(cells.astype(numpy.uintp)): editor.add_cell(k, cell) editor.close() V = FunctionSpace(mesh, 'CG', 1) u = TrialFunction(V) v = TestFunction(V) L = EigenMatrix() assemble(dot(grad(u), grad(v)) * dx, tensor=L) A = L.sparray() # M = A.T.dot(A) M = A with tempfile.TemporaryDirectory() as temp_dir: filepath = os.path.join(temp_dir, 'test.png') betterspy.write_png(filepath, M, border_width=2) # betterspy.write_png( # 'ATA.png', M, border_width=2, # colormap='viridis' # ) return
def test_df_dlmbda(): from test_ginzburg_landau import GinzburgLandau a = 10.0 n = 10 points, cells = meshzoo.rectangle(-a / 2, a / 2, -a / 2, a / 2, n, n) mesh = meshplex.MeshTri(points, cells) gl = GinzburgLandau(mesh) glr = GinzburgLandauReal(mesh) n = points.shape[0] numpy.random.seed(123) for _ in range(10): psi = numpy.random.rand(n) + 1j * numpy.random.rand(n) mu = numpy.random.rand(1)[0] out = gl.df_dlmbda(psi, mu) * mesh.control_volumes out2 = glr.df_dlmbda(to_real(psi), mu) assert numpy.all(numpy.abs(out - to_complex(out2)) < 1.0e-12)
def test(): class Singular(object): def apply(self, u): return ( integrate(lambda x: -1.0e-2 * n_dot_grad(u(x)), dS) + integrate(u, dV) - integrate(lambda x: 1.0, dV) ) def dirichlet(self, u): return [(u, Boundary())] vertices, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 51, 51) mesh = meshplex.MeshTri(vertices, cells) matrix, rhs = pyfvm.discretize_linear(Singular(), mesh) u = linalg.spsolve(matrix, rhs) mesh.write("out.vtk", point_data={"u": u}) return
def test_2d(solver): n = 200 numpy.random.seed(123) x0 = numpy.random.rand(n, 2) - 0.5 # y0 = numpy.ones(n) # y0 = x0[:, 0] # y0 = x0[:, 0]**2 # y0 = numpy.cos(numpy.pi*x0.T[0]) # y0 = numpy.cos(numpy.pi*x0.T[0]) * numpy.cos(numpy.pi*x0.T[1]) y0 = numpy.cos(numpy.pi * numpy.sqrt(x0.T[0]**2 + x0.T[1]**2)) import meshzoo points, cells = meshzoo.rectangle(-1.0, 1.0, -1.0, 1.0, 20, 20) # 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'] u = smoothfit.fit2d(x0, y0, points, cells, eps=1.0e-0, verbose=True, solver=solver) ref = 2.277266345700909 val = assemble(u * u * dx) assert abs(val - ref) < 1.0e-10 * ref # from dolfin import XDMFFile # xdmf = XDMFFile('temp.xdmf') # xdmf.write(u) return
def generate_mesh(): """Generates a fairly large mesh. """ points, cells = meshzoo.rectangle(nx=300, ny=300) return meshio.Mesh(points, {"triangle": cells})
def test_center(): points, cells = meshzoo.rectangle(nx=11, ny=9, variant="center") meshzoo.show2d(points, cells) assert len(points) == 99 assert len(cells) == 160
def __init__(self, delta, n, ufunc=None, coarseMesh=None, dim=2, outdim=1, ansatz="CG", boundaryConditionType="Dirichlet", is_constructAdjaciencyGraph=True, zigzag=False): ### TEST 27.07.2020 #self.Zeta = np.arange(12, dtype=np.int).reshape(4, 3) ##### self.n = n self.dim = dim self.delta = delta self.sqdelta = delta**2 # Construct Meshgrid ------------------------------------------------------------- if self.dim == 2: self.h = 12 / n / 10 points, cells = meshzoo.rectangle(xmin=-self.delta, xmax=1.0 + self.delta, ymin=-self.delta, ymax=1.0 + self.delta, nx=n + 1, ny=n + 1, variant="up") self.vertices = np.array(points[:, :2]) # Set up Delaunay Triangulation -------------------------------------------------- # Construct and Sort Vertices ---------------------------------------------------- self.vertexLabels = np.array( [self.get_vertexLabel(v) for v in self.vertices]) self.argsort_labels = np.argsort(-self.vertexLabels) self.vertices = self.vertices[self.argsort_labels] self.vertexLabels = self.vertexLabels[self.argsort_labels] # Get Number of Vertices in Omega ------------------------------------------------ self.omega = np.where(self.vertexLabels > 0)[0] self.nV = self.vertices.shape[0] self.nV_Omega = self.omega.shape[0] # Set up Delaunay Triangulation -------------------------------------------------- self.elements = np.array(cells, dtype=np.int) self.remapElements() # Get Triangle Labels ------------------------------------------------------------ self.nE = self.elements.shape[0] self.elementLabels = np.zeros(self.nE, dtype=np.int) for k, E in enumerate(self.elements): self.elementLabels[k] = self.get_elementLabel(E) self.nE_Omega = np.sum(self.elementLabels > 0) order = np.argsort(-self.elementLabels) self.elements = self.elements[order] self.elementLabels = self.elementLabels[order] # Read adjaciency list if is_constructAdjaciencyGraph: self.neighbours = constructAdjaciencyGraph(self.elements) self.nNeighbours = self.neighbours.shape[1] else: self.neighbours = None # Set Matrix Dimensions ---------------------------------------------------------- # In case of Neumann conditions we assemble a Maitrx over Omega + OmegaI. # In order to achieve that we "redefine" Omega := Omega + OmegaI # This is rather a shortcut to make things work quickly. self.is_NeumannBoundary = False if boundaryConditionType == "Neumann": self.nE_Omega = self.nE self.nV_Omega = self.nV self.is_NeumannBoundary = True self.outdim = outdim if ansatz == "DG": self.K = self.nE * 3 * self.outdim self.K_Omega = self.nE_Omega * 3 * self.outdim self.is_DiscontinuousGalerkin = True else: self.K = self.nV * self.outdim self.K_Omega = self.nV_Omega * self.outdim self.is_DiscontinuousGalerkin = False # Set Mesh Data if provided ------------------------------------------------------ self.u_exact = None self.ud = None self.diam = self.h * np.sqrt(2) if ufunc is not None: if hasattr(ufunc, '__call__'): self.set_u_exact(ufunc) if coarseMesh is not None: if coarseMesh.is_DiscontinuousGalerkin: coarseDGverts = np.zeros( ((coarseMesh.K // coarseMesh.outdim), coarseMesh.dim)) for i, E in enumerate(coarseMesh.elements): for ii, vdx in enumerate(E): vert = coarseMesh.vertices[vdx] coarseDGverts[3 * i + ii] = vert self.interpolator = LinearNDInterpolator( coarseDGverts, coarseMesh.ud) ud_aux = self.interpolator(self.vertices) self.ud = np.zeros(((self.K // self.outdim), self.outdim)) for i, E in enumerate(self.elements): for ii, vdx in enumerate(E): self.ud[3 * i + ii] = ud_aux[vdx] pass else: self.interpolator = LinearNDInterpolator( coarseMesh.vertices, coarseMesh.ud) self.ud = self.interpolator(self.vertices)
def test(): mu = 5.0e-2 V = -1.0 g = 1.0 class Energy(object): """Specification of the kinetic energy operator. """ def __init__(self): self.magnetic_field = mu * numpy.array([0.0, 0.0, 1.0]) self.subdomains = [None] return def eval(self, mesh, cell_mask): nec = mesh.idx_hierarchy[..., cell_mask] X = mesh.node_coords[nec] edge_midpoint = 0.5 * (X[0] + X[1]) edge = X[1] - X[0] edge_ce_ratio = mesh.ce_ratios[..., cell_mask] # project the magnetic potential on the edge at the midpoint magnetic_potential = 0.5 * numpy.cross(self.magnetic_field, edge_midpoint) # The dot product <magnetic_potential, edge>, executed for many # points at once; cf. <http://stackoverflow.com/a/26168677/353337>. beta = numpy.einsum("...k,...k->...", magnetic_potential, edge) return numpy.array( [ [edge_ce_ratio, -edge_ce_ratio * numpy.exp(-1j * beta)], [-edge_ce_ratio * numpy.exp(1j * beta), edge_ce_ratio], ] ) vertices, cells = meshzoo.rectangle(-5.0, 5.0, -5.0, 5.0, 51, 51) mesh = meshplex.MeshTri(vertices, cells) keo = pyfvm.get_fvm_matrix(mesh, edge_kernels=[Energy()]) def f(psi): cv = mesh.control_volumes return keo * psi + cv * psi * (V + g * abs(psi) ** 2) def jacobian(psi): def _apply_jacobian(phi): cv = mesh.control_volumes y = keo * phi + cv * alpha * phi + cv * 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, ) def jacobian_solver(psi0, rhs): jac = jacobian(psi0) out = pykry.gmres( A=jac, b=rhs, inner_product=lambda a, b: numpy.dot(a.T.conj(), b).real, maxiter=1000, tol=1.0e-10, ) return out.xk u0 = numpy.ones(len(vertices), dtype=complex) u = pyfvm.newton(f, jacobian_solver, u0) mesh.write("out.vtk", point_data={"u": u.view("(2,)float")}) return
def test_continuation(max_steps=5): a = 10.0 n = 20 points, cells = meshzoo.rectangle(-a / 2, a / 2, -a / 2, a / 2, n, n) mesh = meshplex.MeshTri(points, cells) problem = GinzburgLandauReal(mesh) num_unknowns = 2 * problem.mesh.control_volumes.shape[0] u0 = numpy.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.node_coords, {"triangle": problem.mesh.cells["nodes"]}) def callback(k, mu, sol): mu_list.append(mu) # Store the solution psi = numpy.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, )
def get_mesh(self, k): n = 2 ** (k + 1) vertices, cells = meshzoo.rectangle( 0.0, 1.0, 0.0, 1.0, n + 1, n + 1, zigzag=True ) return meshplex.MeshTri(vertices, cells)
def __init__(self, delta, n, ufunc=None, coarseMesh=None, dim=2, outdim=1, n_start=12, ansatz="CG", is_constructAdjaciencyGraph=True, variant="up"): ### TEST 27.07.2020 #self.Zeta = np.arange(12, dtype=np.int).reshape(4, 3) ##### deltaK = int(np.round(delta * 10)) if not deltaK: raise ValueError("Delta has to be of the form delta = deltaK/10. for deltaK in N.") n_start = 10 + 2*deltaK self.n = n self.dim = dim self.delta = delta self.sqdelta = delta**2 # Construct Meshgrid ------------------------------------------------------------- if self.dim == 2: self.h = n_start/n/10. points, cells = meshzoo.rectangle( xmin=-self.delta, xmax=1.0+self.delta, ymin=-self.delta, ymax=1.0+self.delta, nx=n+1, ny=n+1, variant=variant ) self.vertices = np.array(points[:, :2]) # Set up Delaunay Triangulation -------------------------------------------------- # Construct and Sort Vertices ---------------------------------------------------- self.vertexLabels = np.array([self.get_vertexLabel(v) for v in self.vertices]) # Get Number of Vertices in Omega ------------------------------------------------ self.nV = self.vertices.shape[0] self.nV_Omega = np.sum(self.vertexLabels > 0) # Set up Delaunay Triangulation -------------------------------------------------- self.elements = np.array(cells, dtype=np.int) # Get Triangle Labels ------------------------------------------------------------ self.nE = self.elements.shape[0] self.elementLabels = np.zeros(self.nE, dtype=np.int) for k, E in enumerate(self.elements): self.elementLabels[k] = self.get_elementLabel(E) self.nE_Omega = np.sum(self.elementLabels > 0) # Read adjaciency list ----------------------------------------------------------- if is_constructAdjaciencyGraph: self.neighbours = constructAdjaciencyGraph(self.elements) self.nNeighbours = self.neighbours.shape[1] else: self.neighbours = None # Set Matrix Dimensions ---------------------------------------------------------- self.is_NeumannBoundary = False # This option is deprecated. It is sufficient to simply not self.outdim = outdim if ansatz == "DG": self.K = self.nE*(self.dim+1)*self.outdim self.K_Omega = self.nE_Omega*(self.dim+1)*self.outdim self.nodeLabels = np.repeat(self.elementLabels, (self.dim+1)*self.outdim) self.is_DiscontinuousGalerkin = True else: self.K = self.nV*self.outdim self.K_Omega = self.nV_Omega*self.outdim self.nodeLabels = np.repeat(self.vertexLabels, self.outdim) self.is_DiscontinuousGalerkin = False # Set Mesh Data if provided ------------------------------------------------------ self.u_exact = None self.ud = None self.diam = self.h*np.sqrt(2) if ufunc is not None: if hasattr(ufunc, '__call__'): self.set_u_exact(ufunc) if coarseMesh is not None: if coarseMesh.is_DiscontinuousGalerkin: coarseDGverts = np.zeros(((coarseMesh.K // coarseMesh.outdim), coarseMesh.dim)) for i, E in enumerate(coarseMesh.elements): for ii, vdx in enumerate(E): vert = coarseMesh.vertices[vdx] coarseDGverts[(self.dim+1)*i + ii] = vert self.interpolator = LinearNDInterpolator(coarseDGverts, coarseMesh.ud) ud_aux = self.interpolator(self.vertices) self.ud = np.zeros(((self.K // self.outdim), self.outdim)) for i, E in enumerate(self.elements): for ii, vdx in enumerate(E): self.ud[(self.dim + 1)*i + ii] = ud_aux[vdx] pass else: self.interpolator = LinearNDInterpolator(coarseMesh.vertices, coarseMesh.ud) self.ud = self.interpolator(self.vertices)