Пример #1
0
def test_edges():
    _, cells = meshzoo.triangle(2)
    edges_nodes, edges_cells = meshzoo.create_edges(cells)
    assert numpy.all(edges_nodes == [[0, 1], [0, 3], [1, 2], [1, 3], [1, 4],
                                     [2, 4], [3, 4], [3, 5], [4, 5]])
    assert numpy.all(
        edges_cells == [[3, 1, 0], [5, 4, 2], [6, 3, 4], [8, 7, 6]])
Пример #2
0
def _plot_rgb_triangle(xy_to_2d, bright=True):
    # plot sRGB triangle
    # discretization points
    n = 50

    # Get all RGB values that sum up to 1.
    rgb_linear, _ = meshzoo.triangle(n)
    if bright:
        # For the x-y-diagram, it doesn't matter if the values are scaled in any way.
        # After all, the tranlation to XYZ is linear, and then to xyY it's (X/(X+Y+Z),
        # Y/(X+Y+Z), Y), so the factor will only be present in the last component which
        # is discarded. To make the plot a bit brighter, scale the colors up as much as
        # possible.
        rgb_linear /= numpy.max(rgb_linear, axis=0)

    srgb_linear = SrgbLinear()
    xyz = srgb_linear.to_xyz100(rgb_linear)
    xyy_vals = xy_to_2d(_xyy_from_xyz100(xyz)[:2])

    # Unfortunately, one cannot use tripcolors with explicit RGB specification
    # (see <https://github.com/matplotlib/matplotlib/issues/10265>). As a
    # workaround, associate range(n) data with the points and create a colormap
    # that associates the integer values with the respective RGBs.
    z = numpy.arange(xyy_vals.shape[1])
    rgb = srgb_linear.to_srgb1(rgb_linear)
    cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
        "gamut", rgb.T, N=len(rgb.T)
    )

    triang = matplotlib.tri.Triangulation(xyy_vals[0], xyy_vals[1])
    plt.tripcolor(triang, z, shading="gouraud", cmap=cmap)
    return
Пример #3
0
def test_edges():
    _, cells = meshzoo.triangle(2)
    edges_nodes, edges_cells = meshzoo.create_edges(cells)
    assert numpy.all(
        edges_nodes
        == [[0, 1], [0, 3], [1, 2], [1, 3], [1, 4], [2, 4], [3, 4], [3, 5], [4, 5]]
    )
    assert numpy.all(edges_cells == [[3, 1, 0], [5, 4, 2], [6, 3, 4], [8, 7, 6]])
    return
Пример #4
0
def test_triangle():
    bary, cells = meshzoo.triangle(4)
    assert len(bary.T) == 15
    assert _near_equal(numpy.sum(_get_points(bary), axis=0), [0.0, 0.0])
    assert len(cells) == 16

    # make sure the order of the nodes in each cell is counterclockwise
    corner_coords = numpy.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
    coords = numpy.dot(corner_coords, bary)
    assert numpy.all(_get_signed_areas(coords, cells) > 0.0)
Пример #5
0
def plot_single(degrees,
                res=100,
                scaling="normal",
                colorbar=True,
                cmap="RdBu_r",
                corners=None):
    import meshzoo
    from matplotlib import pyplot as plt

    n = sum(degrees)
    r = degrees[0]

    def f(bary):
        for k, level in enumerate(Eval(bary, scaling)):
            if k == n:
                return level[r]

    if corners is None:
        alpha = numpy.pi * numpy.array([7.0 / 6.0, 11.0 / 6.0, 3.0 / 6.0])
        corners = numpy.array([numpy.cos(alpha), numpy.sin(alpha)])

    bary, cells = meshzoo.triangle(res)
    x, y = numpy.dot(corners, bary)
    z = numpy.array(f(bary), dtype=float)

    plt.tripcolor(x, y, cells, z, shading="flat")

    if colorbar:
        plt.colorbar()
    # Choose a diverging colormap such that the zeros are clearly distinguishable.
    plt.set_cmap(cmap)
    # Make sure the color map limits are symmetric around 0.
    clim = plt.gci().get_clim()
    mx = max(abs(clim[0]), abs(clim[1]))
    plt.clim(-mx, mx)

    # triangle outlines
    X = numpy.column_stack([corners, corners[:, 0]])
    plt.plot(X[0], X[1], "-k")

    plt.gca().set_aspect("equal")
    plt.axis("off")
    plt.title(
        f"Orthogonal polynomial on triangle ([{degrees[0]}, {degrees[1]}], {scaling})"
    )
Пример #6
0
def _plot_ellipse_data(
    centers,
    offsets,
    xy_to_2d=lambda xy: xy,
    axes_labels=("x", "y"),
    plot_rgb_triangle=False,
    ellipse_scaling=10,
    ellipse_color="k",
    mesh_resolution=None,
):
    import meshzoo

    plot_flat_gamut(
        plot_planckian_locus=False,
        xy_to_2d=xy_to_2d,
        axes_labels=axes_labels,
        plot_rgb_triangle=plot_rgb_triangle,
        fill_horseshoe=mesh_resolution is None,
    )

    if mesh_resolution is not None:
        # dir_path = os.path.dirname(os.path.realpath(__file__))
        # with open(os.path.join(dir_path, 'data/gamut_triangulation.yaml')) as f:
        #     data = yaml.safe_load(f)
        # points = numpy.array(data['points'])
        # cells = numpy.array(data['cells'])

        points, cells = meshzoo.triangle(
            mesh_resolution,
            corners=numpy.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0],
                                 [0.0, 1.0, 0.0]]),
        )
        points = points[:, :2]

        edges, _ = meshzoo.create_edges(cells)
        pts = xy_to_2d(points.T).T
        lines = pts[edges].T
        plt.plot(*lines, color="0.8", zorder=0)

    _plot_ellipses(centers,
                   offsets,
                   xy_to_2d,
                   ellipse_scaling,
                   facecolor=ellipse_color)
    return
Пример #7
0
def plot_tree(n,
              res=100,
              scaling="normal",
              colorbar=False,
              cmap="RdBu_r",
              clim=None):
    import dufte
    import meshzoo
    from matplotlib import pyplot as plt

    plt.style.use(dufte.style)

    bary, cells = meshzoo.triangle(res)
    evaluator = Eval(bary, scaling)

    plt.set_cmap(cmap)
    plt.gca().set_aspect("equal")
    plt.axis("off")

    for k, level in enumerate(itertools.islice(evaluator, n + 1)):
        for r, z in enumerate(level):
            alpha = numpy.pi * numpy.array([7.0 / 6.0, 11.0 / 6.0, 3.0 / 6.0])
            corners = numpy.array([numpy.cos(alpha), numpy.sin(alpha)])
            corners[0] += 2.1 * (r - k / 2)
            corners[1] -= 1.9 * k
            x, y = numpy.dot(corners, bary)

            plt.tripcolor(x, y, cells, z, shading="flat")
            plt.clim(clim)

            # triangle outlines
            X = numpy.column_stack([corners, corners[:, 0]])
            plt.plot(X[0], X[1], "-k")

    if colorbar:
        plt.colorbar()
Пример #8
0
def test_plot2d():
    bary, cells = meshzoo.triangle(4)
    meshzoo.show2d(_get_points(bary), cells)
Пример #9
0
def test_triangle():
    bary, cells = meshzoo.triangle(4)
    assert len(bary.T) == 15
    assert _near_equal(numpy.sum(_get_points(bary), axis=0), [0.0, 0.0])
    assert len(cells) == 16

    # make sure the order of the nodes in each cell is counterclockwise
    corner_coords = numpy.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
    coords = numpy.dot(corner_coords, bary)
    assert numpy.all(_get_signed_areas(coords, cells) > 0.0)


def test_plot2d():
    bary, cells = meshzoo.triangle(4)
    meshzoo.show2d(_get_points(bary), cells)


def test_edges():
    _, cells = meshzoo.triangle(2)
    edges_nodes, edges_cells = meshzoo.create_edges(cells)
    assert numpy.all(edges_nodes == [[0, 1], [0, 3], [1, 2], [1, 3], [1, 4],
                                     [2, 4], [3, 4], [3, 5], [4, 5]])
    assert numpy.all(
        edges_cells == [[3, 1, 0], [5, 4, 2], [6, 3, 4], [8, 7, 6]])


if __name__ == "__main__":
    points, cells = meshzoo.triangle(5000)
    # import meshio
    # meshio.write_points_cells('triangle.vtk', points, {'triangle': cells})
Пример #10
0
    def _plot_srgb_gamut(self, k0, level, bright=False):
        import meshzoo

        # Get all RGB values that sum up to 1.
        bary, triangles = meshzoo.triangle(n=50)
        corners = numpy.array([[0, 0], [1, 0], [0, 1]]).T
        srgb_vals = numpy.dot(corners, bary).T
        srgb_vals = numpy.column_stack([srgb_vals, 1.0 - numpy.sum(srgb_vals, axis=1)])

        # matplotlib is sensitive when it comes to srgb values, so take good care here
        assert numpy.all(srgb_vals > -1.0e-10)
        srgb_vals[srgb_vals < 0.0] = 0.0

        # Use bisection to
        srgb_linear = SrgbLinear()
        tol = 1.0e-5
        # Use zeros() instead of empty() here to avoid invalid values when setting up
        # the cmap below.
        self_vals = numpy.zeros((srgb_vals.shape[0], 3))
        srgb_linear_vals = numpy.zeros((srgb_vals.shape[0], 3))
        mask = numpy.ones(srgb_vals.shape[0], dtype=bool)
        for k, val in enumerate(srgb_vals):
            alpha_min = 0.0
            xyz100 = srgb_linear.to_xyz100(val * alpha_min)
            self_val_min = self.from_xyz100(xyz100)
            if self_val_min[k0] > level:
                mask[k] = False
                continue

            alpha_max = 1.0 / numpy.max(val)

            xyz100 = srgb_linear.to_xyz100(val * alpha_max)
            self_val_max = self.from_xyz100(xyz100)
            if self_val_max[k0] < level:
                mask[k] = False
                continue

            while True:
                alpha = (alpha_max + alpha_min) / 2
                srgb_linear_vals[k] = val * alpha
                xyz100 = srgb_linear.to_xyz100(srgb_linear_vals[k])
                self_val = self.from_xyz100(xyz100)
                if abs(self_val[k0] - level) < tol:
                    break
                elif self_val[k0] < level:
                    alpha_min = alpha
                else:
                    assert self_val[k0] > level
                    alpha_max = alpha
            self_vals[k] = self_val

        # Remove all triangles which have masked corner points
        tri_mask = numpy.all(mask[triangles], axis=1)
        if ~numpy.any(tri_mask):
            return
        triangles = triangles[tri_mask]

        # Unfortunately, one cannot use tripcolors with explicit RGB specification (see
        # <https://github.com/matplotlib/matplotlib/issues/10265>). As a workaround,
        # associate range(n) data with the points and create a colormap that associates
        # the integer values with the respective RGBs.
        z = numpy.arange(srgb_vals.shape[0])
        rgb = srgb_linear.to_srgb1(srgb_linear_vals)
        cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
            "gamut", rgb, N=len(rgb)
        )

        k1, k2 = [k for k in [0, 1, 2] if k != k0]

        plt.tripcolor(
            self_vals[:, k1],
            self_vals[:, k2],
            triangles,
            z,
            shading="gouraud",
            cmap=cmap,
        )
Пример #11
0
def test_triangle():
    bary, cells = meshzoo.triangle(4)
    assert len(bary.T) == 15
    assert _near_equal(numpy.sum(_get_points(bary), axis=0), [0.0, 0.0])
    assert len(cells) == 16
Пример #12
0
    for k, cell in enumerate(cells.astype(numpy.uintp)):
        editor.add_cell(k, cell)
    editor.close()
    return mesh


if __name__ == "__main__":
    # # 1d mesh
    # mesh = IntervalMesh(300, -1.0, +1.0)
    # Eps = numpy.array([[1.0]])

    # 2d mesh

    # Triangle:
    # Dirichlet points _must_ be the corners of the triangle
    points, cells = meshzoo.triangle(10, corners=[[0, 0], [1, 0], [0, 1]])
    # points, cells = meshzoo.rectangle(0.0, 1.0, 0.0, 1.0, 10, 10, zigzag=True)
    # import meshplex
    # meshplex.MeshTri(points, cells).show()
    # points, cells = meshzoo.hexagon(3)

    # Triangle (unstructured).
    # Two nodes must be in a corner, the third as close as possible to the
    # third corner.
    # Degree 2: At least 5 nodes, two in two corners, one in the middle
    # import pygmsh
    # geom = pygmsh.built_in.Geometry()
    # geom.add_polygon([
    #     [0.0, 0.0, 0.0],
    #     [1.0, 0.0, 0.0],
    #     [0.0, 1.0, 0.0],
Пример #13
0
def _main():
    args = _parse_cmd_arguments()

    content = np.load(args.infile)

    data = content.item()["data"]
    n = content.item()["n"]

    # # plot statistics
    # axes0 = problem.get_ellipse_axes(alpha0).T.flatten()
    # plt.plot(axes0, label='axes lengths before')
    # axes1 = problem.get_ellipse_axes(out.x).T.flatten()
    # plt.plot(axes1, label='axes lengths opt')
    # plt.legend()
    # plt.grid()

    # Plot unperturbed MacAdam
    # colorio.plot_luo_rigg(
    #     ellipse_scaling=1,
    colorio.save_macadam("macadam-native.png",
                         ellipse_scaling=10,
                         plot_rgb_triangle=False,
                         n=n)

    points, cells = meshzoo.triangle(corners=np.array([[0.0, 0.0, 0.0],
                                                       [1.0, 0.0, 0.0],
                                                       [0.0, 1.0, 0.0]]),
                                     n=n)

    # https://bitbucket.org/fenics-project/dolfin/issues/845/initialize-mesh-from-vertices
    editor = MeshEditor()
    mesh = Mesh()
    editor.open(mesh, "triangle", 2, 2)
    editor.init_vertices(points.shape[0])
    editor.init_cells(cells.shape[0])
    for k, point in enumerate(points):
        editor.add_vertex(k, point[:2])
    for k, cell in enumerate(cells):
        editor.add_cell(k, cell)
    editor.close()

    V = FunctionSpace(mesh, "CG", 1)

    def get_u(alpha):
        n = V.dim()
        ax = alpha[:n]
        ay = alpha[n:]

        ux = Function(V)
        ux.vector().set_local(ax)
        ux.vector().apply("")

        uy = Function(V)
        uy.vector().set_local(ay)
        uy.vector().apply("")
        return ux, uy

    # Plot perturbed MacAdam
    def transform(XY, data=data):
        is_solo = len(XY.shape) == 1
        if is_solo:
            XY = np.array([XY]).T
        # print(XY)
        ux, uy = get_u(data)
        out = np.array([[ux(x, y) for x, y in XY.T],
                        [uy(x, y) for x, y in XY.T]])
        if is_solo:
            out = out[..., 0]
        return out

    # colorio.plot_luo_rigg(
    #     ellipse_scaling=1,
    plt.figure()
    colorio.plot_macadam(
        ellipse_scaling=10,
        # xy_to_2d=problem.pade2d.eval,
        xy_to_2d=transform,
        plot_rgb_triangle=False,
        mesh_resolution=n,
    )
    # plt.xlim(-0.2, 0.9)
    # plt.ylim(+0.0, 0.7)
    plt.savefig(f"macadam-{n:03d}.png")
    return
Пример #14
0
def test_plot2d():
    points, cells = meshzoo.triangle(4)
    meshzoo.show2d(points, cells)
    return
Пример #15
0
def test_triangle():
    points, cells = meshzoo.triangle(4)
    assert len(points) == 15
    assert _near_equal(numpy.sum(points, axis=0), [0.0, 0.0, 0.0])
    assert len(cells) == 16
    return
Пример #16
0
    def __init__(self, centers, J, n):
        self.centers = centers
        self.J = J

        self.target = 0.002
        self.J /= self.target

        # dir_path = os.path.dirname(os.path.realpath(__file__))
        # with open(os.path.join(dir_path, '../colorio/data/gamut_triangulation.yaml')) as f:
        #     data = yaml.safe_load(f)

        # self.points = numpy.column_stack([
        #     data['points'], numpy.zeros(len(data['points']))
        #     ])
        # self.cells = numpy.array(data['cells'])

        # self.points, self.cells = colorio.xy_gamut_mesh(0.15)

        self.points, self.cells = meshzoo.triangle(n,
                                                   corners=numpy.array(
                                                       [[0.0, 0.0], [1.0, 0.0],
                                                        [0.0, 1.0]]))

        # https://bitbucket.org/fenics-project/dolfin/issues/845/initialize-mesh-from-vertices
        editor = MeshEditor()
        mesh = Mesh()
        editor.open(mesh, "triangle", 2, 2)
        editor.init_vertices(self.points.shape[0])
        editor.init_cells(self.cells.shape[0])
        for k, point in enumerate(self.points):
            editor.add_vertex(k, point)
        for k, cell in enumerate(self.cells):
            editor.add_cell(k, cell)
        editor.close()

        self.V = FunctionSpace(mesh, "CG", 1)
        self.Vgrad = VectorFunctionSpace(mesh, "DG", 0)

        # self.ux0 = Function(self.V)
        # self.uy0 = Function(self.V)

        # 0 starting guess
        # ax = numpy.zeros(self.V.dim())
        # ay = numpy.zeros(self.V.dim())

        # Use F(x, y) = (x, y) as starting guess
        self.ux0 = project(Expression("x[0]", degree=1), self.V)
        self.uy0 = project(Expression("x[1]", degree=1), self.V)
        ax = self.ux0.vector().get_local()
        ay = self.uy0.vector().get_local()
        # Note that alpha doesn't contain the values in the order that one might expect,
        # see
        # <https://www.allanswered.com/post/awevg/projectexpressionx0-v-vector-get_local-not-in-order/>.
        self.alpha = numpy.concatenate([ax, ay])

        self.num_f_eval = 0

        # Build L as scipy.csr_matrix
        u = TrialFunction(self.V)
        v = TestFunction(self.V)
        L = assemble(dot(grad(u), grad(v)) * dx)
        Lmat = as_backend_type(L).mat()
        indptr, indices, data = Lmat.getValuesCSR()

        size = Lmat.getSize()
        self.L = sparse.csr_matrix((data, indices, indptr), shape=size)
        self.LT = self.L.getH()

        self.dx, self.dy = build_grad_matrices(self.V, centers)
        self.dxT = self.dx.getH()
        self.dyT = self.dy.getH()
        return
Пример #17
0
def plot_rgb_slice(
    colorspace,
    lightness: float,
    n: int = 51,
    variant: str = "srgb",
    tol: float = 1.0e-5,
):
    # The best way to produce a slice is via a dedicated software, e.g., VTK. To avoid
    # the dependency, we're doing the following here: Take a slice out of the sRGB cube
    # and  project it into the the colorspace lightness level. Cut off all triangles
    # which don't fit. This cutting leads to jagged edges of the slice, but all other
    # methods have their imperfections, too.
    import meshzoo

    # TODO HDR
    assert variant in ["srgb", "rec709"]

    # Get all RGB values that sum up to 1.
    srgb_vals, triangles = meshzoo.triangle(n=n)
    srgb_vals = srgb_vals.T

    srgb_linear = SrgbLinear()
    # Use zeros() instead of empty() here to avoid invalid values when setting up
    # the cmap below.
    colorspace_vals = np.zeros((srgb_vals.shape[0], 3))
    srgb_linear_vals = np.zeros((srgb_vals.shape[0], 3))
    mask = np.ones(srgb_vals.shape[0], dtype=bool)
    for k, val in enumerate(srgb_vals):
        alpha_min = 0.0
        xyz100 = srgb_linear.to_xyz100(val * alpha_min)
        colorspace_val_min = colorspace.from_xyz100(xyz100)[colorspace.k0]
        if colorspace_val_min > lightness:
            mask[k] = False
            continue

        alpha_max = 1.0 / np.max(val)

        xyz100 = srgb_linear.to_xyz100(val * alpha_max)
        colorspace_val_max = colorspace.from_xyz100(xyz100)[colorspace.k0]
        if colorspace_val_max < lightness:
            mask[k] = False
            continue

        def f(alpha):
            srgb_linear_vals[k] = val * alpha
            xyz100 = srgb_linear.to_xyz100(srgb_linear_vals[k])
            colorspace_val = colorspace.from_xyz100(xyz100)
            return colorspace_val[colorspace.k0] - lightness

        a, b = regula_falsi(f, alpha_min, alpha_max, tol)
        a = (a + b) / 2

        srgb_linear_vals[k] = val * a
        xyz100 = srgb_linear.to_xyz100(srgb_linear_vals[k])
        colorspace_val = colorspace.from_xyz100(xyz100)
        colorspace_vals[k] = colorspace_val

    # import meshplex
    # meshplex.MeshTri(colorspace_vals[:, 1:], triangles).show(show_coedges=False)

    # Remove all triangles which have masked corner points
    tri_mask = np.all(mask[triangles], axis=1)
    if ~np.any(tri_mask):
        return
    triangles = triangles[tri_mask]

    # Unfortunately, one cannot use tripcolors with explicit RGB specification (see
    # <https://github.com/matplotlib/matplotlib/issues/10265>). As a workaround,
    # associate range(n) data with the points and create a colormap that associates
    # the integer values with the respective RGBs.
    z = np.arange(srgb_vals.shape[0])
    rgb = srgb_linear.to_rgb1(srgb_linear_vals)
    cmap = matplotlib.colors.LinearSegmentedColormap.from_list("gamut",
                                                               rgb,
                                                               N=len(rgb))

    k1, k2 = [k for k in [0, 1, 2] if k != colorspace.k0]

    plt.tripcolor(
        colorspace_vals[:, k1],
        colorspace_vals[:, k2],
        triangles,
        z,
        shading="gouraud",
        cmap=cmap,
    )
    # plt.triplot(colorspace_vals[:, k1], colorspace_vals[:, k2], triangles=triangles)
    plt.title(f"sRGB gamut slice in {colorspace.name} with "
              f"{colorspace.labels[colorspace.k0]}={lightness}")
    plt.xlabel(colorspace.labels[k1])
    plt.ylabel(colorspace.labels[k2])
    plt.gca().set_aspect("equal")
Пример #18
0
def test_triangle():
    points, cells = meshzoo.triangle()
    assert len(points) == 15
    assert _near_equal(numpy.sum(points, axis=0), [0.0, 0.0, 0.0])
    assert len(cells) == 16
    return