Skip to content

tikz

fdpyutils.tikz.matshow.TikzMatrix

TikzMatrix(mat: Union[Tensor, ndarray])

Class to visualize a matrix with TikZ.

Attributes:

  • TEMPLATE (str) –

    Template TikZ code containing placeholders that will be substituted with content when saving a figure.

Examples:

>>> from numpy import linspace
>>> mat = linspace(0, 1, num=9).reshape(3, 3)
>>> savepath = "mat.tex"
>>> # NOTE to compile, you need `pdflatex`
>>> TikzMatrix(mat).save(savepath, compile=False)

Store the matrix internally.

Parameters:

  • mat (Union[Tensor, ndarray]) –

    The matrix that will be visualized as PyTorch tensor or NumPy array.

Raises:

  • ValueError

    If the supplied array is not 2d.

Source code in fdpyutils/tikz/matshow.py
def __init__(self, mat: Union[Tensor, ndarray]) -> None:
    """Store the matrix internally.

    Args:
        mat: The matrix that will be visualized as PyTorch tensor or NumPy array.

    Raises:
        ValueError: If the supplied array is not 2d.
    """
    if mat.ndim != 2:
        raise ValueError(f"Expected 2d array. Got {mat.ndim}d.")
    self.mat = mat

    self.grid = "major"
    self.colormap = "colormap/blackwhite"
    self.vmin: Union[float, None] = 0.0  # color bar minimum
    self.vmax: Union[float, None] = 1.0  # color bar maximum

save

save(savepath: str, compile: bool = False)

Save the matrix plot as standalone TikZ figure and maybe build to pdf.

Parameters:

  • savepath (str) –

    Path to save the figure to (including '.tex').

  • compile (bool, default: False ) –

    Whether to compile the TikZ figure to pdf. Default is False.

Source code in fdpyutils/tikz/matshow.py
def save(self, savepath: str, compile: bool = False):
    """Save the matrix plot as standalone TikZ figure and maybe build to pdf.

    Args:
        savepath: Path to save the figure to (including `'.tex'`).
        compile: Whether to compile the TikZ figure to pdf. Default is `False`.
    """
    template = self.TEMPLATE
    rows, cols = self.mat.shape

    content = ["x\ty\tz"]
    content.extend(
        f"{float(col + 0.5)}\t{float(row + 0.5)}\t{self.mat[row, col]}"
        for row, col in product(range(rows), range(cols))
    )
    content = "\n".join(content)

    for placeholder, replacement in [
        ("PLACEHOLDER_CONTENT", content),
        ("PLACEHOLDER_ROWS", str(rows)),
        ("PLACEHOLDER_COLS", str(cols)),
        ("PLACEHOLDER_COLORMAP", self.colormap),
        ("PLACEHOLDER_GRID", self.grid),
        (
            "PLACEHOLDER_COLORBAR_MIN",
            f"% color bar minimum\n    point meta min={self.vmin}"
            if self.vmin is not None
            else "",
        ),
        (
            "PLACEHOLDER_COLORBAR_MAX",
            f"% color bar maximum\n    point meta max={self.vmax}"
            if self.vmax is not None
            else "",
        ),
    ]:
        template = template.replace(placeholder, replacement)

    with open(savepath, "w") as f:
        f.write(template)

    if compile:
        cmd = [
            "pdflatex",
            "-output-directory",
            path.dirname(savepath),
            path.basename(savepath),
        ]
        run(cmd, check=True)