Пример #1
0
def test_for_breakdown(seed):
    np.random.seed(seed)

    n = np.random.randint(10, 20)
    pts, cells = create_random_circle(n=n, radius=1.0)

    optimesh.optimize_points_cells(pts,
                                   cells,
                                   "lloyd",
                                   omega=1.0,
                                   tol=1.0e-10,
                                   max_num_steps=10)
Пример #2
0
def xy_gamut_mesh(lcar):
    import optimesh
    import pygmsh

    observer = observers.cie_1931_2()

    # Gather all points on the horseshoe outline
    lmbda = 1.0e-9 * np.arange(380, 701)
    all_points = np.empty((len(lmbda), 2))
    for k in range(len(lmbda)):
        data = np.zeros(len(lmbda))
        data[k] = 1.0
        all_points[k] = _xyy_from_xyz100(
            spectrum_to_xyz100((lmbda, data), observer))[:2]

    # Generate gmsh geometry: spline + straight line
    all_points = np.column_stack([all_points, np.zeros(len(all_points))])
    with pygmsh.geo.Geometry() as geom:
        gmsh_points = [geom.add_point(pt, lcar) for pt in all_points]
        s1 = geom.add_spline(gmsh_points)
        s2 = geom.add_line(gmsh_points[-1], gmsh_points[0])
        ll = geom.add_curve_loop([s1, s2])
        geom.add_plane_surface(ll)
        mesh = geom.generate_mesh()

    # Work around numpy bug <https://github.com/numpy/numpy/issues/17760>
    cells = mesh.get_cells_type("triangle").astype(int)
    points, cells = optimesh.optimize_points_cells(mesh.points,
                                                   cells,
                                                   "lloyd",
                                                   1.0e-2,
                                                   100,
                                                   omega=2.0)
    return points, cells
Пример #3
0
def test_surface():
    points, cells = meshzoo.tetra_sphere(20)

    # points, cells = meshzoo.octa_sphere(10)
    # points, cells = meshzoo.icosa_sphere(10)

    class Sphere:
        def f(self, x):
            return 1.0 - (x[0]**2 + x[1]**2 + x[2]**2)

        def grad(self, x):
            return -2 * x

    # points, cells = optimesh.cpt.fixed_point_uniform(
    # points, cells = optimesh.odt.fixed_point_uniform(
    points, cells = optimesh.optimize_points_cells(
        points,
        cells,
        "cvt (full)",
        1.0e-2,
        100,
        verbose=False,
        implicit_surface=Sphere(),
        step_filename_format="out{:03d}.vtk",
    )
Пример #4
0
    def optimize(self,
                 *,
                 method='CVT (block-diagonal)',
                 tol: float = 1.0e-3,
                 max_num_steps: int = 10,
                 **kwargs) -> TriangleMesh:
        """Optimize mesh using `optimesh`.

        Parameters
        ----------
        method : str, optional
            Method name
        tol : float, optional
            Tolerance
        max_num_steps : int, optional
            Maximum number of optimization steps.
        **kwargs
            Arguments to pass to `optimesh.optimize_points_cells`

        Returns
        -------
        TriangleMesh
        """
        import optimesh
        points, cells = optimesh.optimize_points_cells(
            X=self.points,
            cells=self.cells,
            method=method,
            tol=tol,
            max_num_steps=max_num_steps,
            **kwargs,
        )
        return TriangleMesh(points=points, cells=cells)
Пример #5
0
def test_cvt_lloyd(mesh, num_steps, ref):
    print(num_steps)
    m = copy.deepcopy(mesh)
    optimesh.optimize(m, "Lloyd", 1.0e-2, num_steps, verbose=False)
    assert_norm_equality(m.points, ref, 1.0e-12)

    # try the other way of calling optimesh
    X, c = mesh.points.copy(), mesh.cells("points").copy()
    X, _ = optimesh.optimize_points_cells(X, c, "lloyd", 1.0e-2, num_steps)
    assert_norm_equality(X, ref, 1.0e-12)
Пример #6
0
def test_methods(method, mesh, ref):
    X_in, cells_in = mesh.points, mesh.cells("points")

    # X_before = X_in.copy()
    # cells_before = cells_in.copy()

    X, _ = optimesh.optimize_points_cells(X_in, cells_in, method, 1.0e-12, 100)

    # assert np.all(cells_in == cells_before)
    # assert np.all(np.abs(X_in == X_before) < 1.0e-15)

    # Test if we're dealing with the mesh we expect.
    assert_norm_equality(X, ref, 1.0e-12)
Пример #7
0
def test_circle():
    def boundary_step(x):
        x0 = [0.0, 0.0]
        r = 1.0
        # simply project onto the circle
        y = (x.T - x0).T
        r = np.sqrt(np.einsum("ij,ij->j", y, y))
        return ((y / r * r).T + x0).T

    X, cells = meshes.circle_random2(150, 1.0)
    X, cells = optimesh.optimize_points_cells(X,
                                              cells,
                                              "cpt (fixed-point)",
                                              1.0e-3,
                                              100,
                                              boundary_step=boundary_step)
Пример #8
0
 def smoothPoints(self):
     pts, cells = self.__pts.copy(), self.__triangles.copy()
     pts, cells = optimesh.optimize_points_cells(pts, cells, "cpt (fixed-point)", 0.0, 100, omega=.8)
     if not numpy.isnan(pts).any():
         isv = self.__materData.s1.internal_state_variables.copy() # Elastic strain tensor (4), plastic strain (1)
         #sig = self.__materData.s1.thermodynamic_forces.copy() # Stress (4)
         grad = self.__materData.s1.gradients.copy() # Total strain (4)
         acc = self.__acc.reshape(-1,2)
         vel = self.__vel.reshape(-1,2)
         disp = self.__disp.reshape(-1,2)
         var = numpy.column_stack([isv, grad, acc, vel, disp])
         interp = LinearNDInterpolator(self.__pts, var)
         res = interp(pts)
         self.__pts = pts.copy()
         self.__updateMaterialData(res[:,:9])
         self.__acc = res[:,9:11].reshape(-1)
         self.__vel = res[:,11:13].reshape(-1)
         self.__disp = res[:,13:].reshape(-1)
         self.__dt = self.__updateMeshBmatrixFint()
Пример #9
0
def test_circle():
    def boundary_step(x):
        x0 = [0.0, 0.0]
        r = 1.0
        # simply project onto the circle
        y = (x.T - x0).T
        r = np.sqrt(np.einsum("ij,ij->j", y, y))
        return ((y / r * r).T + x0).T

    # ODT can't handle the random circle; some cells too flat near the boundary lead to
    # a breakdown.
    # X, cells = circle_random2(150, 1.0, seed=1)
    X, cells = meshes.circle_gmsh2()
    X, cells = optimesh.optimize_points_cells(X,
                                              cells,
                                              "ODT (fixed-point)",
                                              1.0e-3,
                                              100,
                                              boundary_step=boundary_step)
Пример #10
0
def test_comparison():
    plt.style.use(dufte.style)

    X, cells = circle_random(40, 1.0)

    # Do a few steps of a robust method to avoid too crazy meshes.
    tol = 0.0
    n = 10
    # X, cells = optimesh.cpt.fixed_point_uniform(X, cells, tol, n)
    # X, cells = optimesh.odt.fixed_point_uniform(X, cells, tol, n)
    X, cells = optimesh.optimize_points_cells(X,
                                              cells,
                                              "lloyd",
                                              tol,
                                              n,
                                              omega=2.0)

    # from meshplex import MeshTri
    # mesh = MeshTri(X, cells)
    # mesh.write("out.vtk")
    # exit(1)

    num_steps = 50
    names = [
        "cpt-fixed-point",
        "cpt-quasi-newton",
        #
        "lloyd",
        "lloyd(2.0)",
        "cvt-block-diagonal",
        "cvt-full",
        #
        "odt-fixed-point",
        "odt-bfgs",
    ]

    avg_quality = np.empty((len(names), num_steps + 1))

    for i, name in enumerate(names):

        def callback(k, mesh):
            avg_quality[i, k] = np.average(mesh.q_radius_ratio)
            return

        X_in = X.copy()
        cells_in = cells.copy()

        if name == "lloyd(2.0)":
            optimesh.optimize_points_cells(X_in,
                                           cells_in,
                                           "lloyd",
                                           0.0,
                                           num_steps,
                                           omega=2.0,
                                           callback=callback)
        else:
            optimesh.optimize_points_cells(X_in,
                                           cells_in,
                                           name,
                                           0.0,
                                           num_steps,
                                           callback=callback)

    # sort by best final quality
    idx = np.argsort(avg_quality[:, -1])[::-1]

    sorted_labels = [names[i] for i in idx]

    for i, label, values in zip(idx, sorted_labels, avg_quality[idx]):
        plt.plot(values, "-", label=label, zorder=i)

    plt.xlim(0, num_steps)
    plt.ylim(0.93, 1.0)
    plt.xlabel("step")
    plt.title("average cell quality")
    dufte.legend()

    plt.savefig("comparison.svg", transparent=True, bbox_inches="tight")
Пример #11
0
def test_density_preserving(mesh, ref):
    X, cells = mesh.points, mesh.cells("points")
    X, cells = optimesh.optimize_points_cells(X, cells, "cpt (linear solve)",
                                              0.0, 10)
    assert_norm_equality(X, ref, 1.0e-12)
Пример #12
0
import numpy as np
import optimesh

import dmsh


def save(X, cells, filename):
    meshio.Mesh(X, {"triangle": cells}).write(
        filename, image_width=100, stroke_width=0.5
    )


geo = dmsh.Circle([0.0, 0.0], 1.0)
X, cells = dmsh.generate(geo, 0.1)
# optionally optimize the mesh
X, cells = optimesh.optimize_points_cells(X, cells, "CVT (full)", 1.0e-10, 100)
save(X, cells, "circle.svg")


geo = dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0)
X, cells = dmsh.generate(geo, 0.1)
save(X, cells, "rectangle.svg")

geo = dmsh.Polygon(
    [
        [0.0, 0.0],
        [1.1, 0.0],
        [1.2, 0.5],
        [0.7, 0.6],
        [2.0, 1.0],
        [1.0, 2.0],