def _main():
    parser = argparse.ArgumentParser(
        description="Refresh the reference TeX files.")
    parser.add_argument("files", nargs="+", help="Files to refresh")
    args = parser.parse_args()

    this_dir = os.path.dirname(os.path.abspath(__file__))
    exclude_list = ["test_rotated_labels.py", "test_deterministic_output.py"]

    for filename in args.files:
        if filename in exclude_list:
            continue
        if filename.startswith("test_") and filename.endswith(".py"):
            spec = importlib.util.spec_from_file_location("plot", filename)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            module.plot()

            code = m2t.get_tikz_code(include_disclaimer=False)
            plt.close()

            tex_filename = filename[:-3] + "_reference.tex"
            with open(os.path.join(this_dir, tex_filename), "w") as f:
                f.write(code)
    return
Ejemplo n.º 2
0
def assert_equality(plot, filename, **extra_get_tikz_code_args):
    plot()
    code = matplotlib2tikz.get_tikz_code(include_disclaimer=False,
                                         **extra_get_tikz_code_args)
    plt.close()

    this_dir = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(this_dir, filename), "r", encoding="utf-8") as f:
        reference = f.read()
    assert reference == code, _unidiff_output(code, reference)

    code = matplotlib2tikz.get_tikz_code(include_disclaimer=False,
                                         standalone=True,
                                         **extra_get_tikz_code_args)
    assert _compile(code) is not None
    return
Ejemplo n.º 3
0
    def bode(self, wmin=1e-3, tikz=False):
        """Plot a bode graph
		return tikz code if tikz is True, otherwise display it"""
        # get the frequency, magnitude and phase
        w, mag, phase = dbode(self.toTransferFunction(),
                              linspace(wmin, 3.14159, 500))

        import matplotlib.pyplot as plt
        plt.figure(3)
        plt.subplot(2, 1, 1)
        plt.semilogx(w, mag, 'b-', linewidth=1)
        plt.xlim((wmin, 3.5))
        plt.grid(b=True, which='major', color='gray', linestyle='-')
        plt.grid(b=True, which='minor', color='silver', linestyle='--')
        plt.ylabel('Magnitude (dB)')
        plt.axvline(x=3.14159, color='grey', zorder=2)
        plt.subplot(2, 1, 2)
        plt.semilogx(w, phase, 'b-', linewidth=1)
        plt.xlim((wmin, 3.5))
        plt.grid(b=True, which='major', color='gray', linestyle='-')
        plt.grid(b=True, which='minor', color='silver', linestyle='--')
        plt.axvline(x=3.14159, color='grey', zorder=2)
        plt.ylabel('Phase')
        plt.xlabel('Frequency ($rad.s^{-1}$)')
        if tikz:
            import matplotlib2tikz
            return matplotlib2tikz.get_tikz_code(figurewidth='15cm',
                                                 figureheight='7cm')
        else:
            plt.show()
Ejemplo n.º 4
0
def assert_equality(plot, filename, **extra_get_tikz_code_args):
    plot()
    code = matplotlib2tikz.get_tikz_code(
        include_disclaimer=False, **extra_get_tikz_code_args
    )
    plt.close()

    this_dir = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(this_dir, filename), "r", encoding="utf-8") as f:
        reference = f.read()
    assert reference == code, _unidiff_output(reference, code)

    code = matplotlib2tikz.get_tikz_code(
        include_disclaimer=False, standalone=True, **extra_get_tikz_code_args
    )
    assert _compile(code) is not None
    return
Ejemplo n.º 5
0
def _does_compile(code):
    _, tmp_base = tempfile.mkstemp()
    matplotlib2tikz.get_tikz_code()

    # create a latex wrapper for the tikz
    # <https://tex.stackexchange.com/a/361070/13262>
    wrapper = """\\documentclass{{standalone}}
\\usepackage[utf8]{{inputenc}}
\\usepackage{{pgfplots}}
\\usepgfplotslibrary{{groupplots}}
\\usetikzlibrary{{shapes.arrows}}
\\pgfplotsset{{compat=newest}}
\\DeclareUnicodeCharacter{{2212}}{{-}}
\\begin{{document}}
{}
\\end{{document}}""".format(
        code
    )
    tex_file = tmp_base + ".tex"
    with open(tex_file, "w", encoding="utf-8") as f:
        f.write(wrapper)

    # change into the directory of the TeX file
    os.chdir(os.path.dirname(tex_file))

    # compile the output to pdf
    try:
        subprocess.check_output(
            ["pdflatex", "--interaction=nonstopmode", tex_file],
            stderr=subprocess.STDOUT,
        )
    except subprocess.CalledProcessError as e:
        print("Command output:")
        print("=" * 70)
        print(e.output)
        print("=" * 70)
        does_compile = False
    else:
        does_compile = True

    return does_compile
Ejemplo n.º 6
0
def assert_equality(plot, filename):
    plot()
    code = matplotlib2tikz.get_tikz_code(include_disclaimer=False)
    plt.close()

    this_dir = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(this_dir, filename), "r", encoding="utf-8") as f:
        reference = f.read()
    assert reference == code, _unidiff_output(reference, code)

    assert _does_compile(code)
    return
Ejemplo n.º 7
0
def texify_lr_sensitivity(fig, ax):
    """Write a ``.tex`` file with the learning rate sensitivity plot.

    The function will create a file named `tuning_plot.tex` with the latex code
    for the learning rate sensitivity plot.

    Args:
        fig (matplotlib.figure): Handle to the matplotlib figure of the learning
            rate sensitivity plot.
        ax (list): List of lists of matplotlib axis of the learning rate
            sensitivity plots.

    Returns:
        str: String of the latex code for the learning rate sensitivity plot.

    """
    tikz_code = get_tikz_code('tuning_plot_new.tex',
                              figureheight='\\figureheight',
                              figurewidth='0.33\\figurewidth')

    tikz_code = tikz_code.replace(
        '\\begin{groupplot}[group style={group size=4 by 2}]',
        '\\begin{groupplot}[group style={group size=4 by 2, horizontal sep=0.02\\figurewidth, vertical sep=0.15cm}]'
    )
    tikz_code = r"\pgfplotsset{every axis/.append style={label style={font=\tiny}, tick label style={font=\tiny}, legend style={font=\tiny, line width=1pt}}}" + tikz_code
    tikz_code = tikz_code.replace('minor', '%minor')  # comment minor tick
    tikz_code = tikz_code.replace('x grid',
                                  '%x grid')  # remove grid xmajorticks=false,
    tikz_code = tikz_code.replace('y grid', '%y grid')  # remove grid
    tikz_code = tikz_code.replace('tick align',
                                  '%tick align')  # ugly outside ticks
    tikz_code = tikz_code.replace(
        'nextgroupplot[', 'nextgroupplot[axis x line*=bottom,\nhide y axis,'
    )  # ugly outside ticks
    tikz_code = tikz_code.replace(
        '(current bounding box.south west)!0.98!(current bounding box.north west)',
        '(current bounding box.south west)!1.05!(current bounding box.north west)'
    )  # position title higher
    tikz_code = tikz_code.replace('title={',
                                  'title={\small ')  # shrink title size

    # Write the file out again
    with open('tuning_plot.tex', 'w') as file:
        file.write(tikz_code)

    return tikz_code
Ejemplo n.º 8
0
def compare_mpl_latex(plot):
    plot()
    code = matplotlib2tikz.get_tikz_code(standalone=True)
    directory = os.getcwd()
    filename = "test-0.png"
    plt.savefig(filename)
    plt.close()

    pdf_file = _compile(code)
    pdf_dirname = os.path.dirname(pdf_file)

    # Convert PDF to PNG.
    subprocess.check_output(
        ["pdftoppm", "-r", "1000", "-png", pdf_file, "test"],
        stderr=subprocess.STDOUT)
    png_path = os.path.join(pdf_dirname, "test-1.png")

    os.rename(png_path, os.path.join(directory, "test-1.png"))
    return
Ejemplo n.º 9
0
def compare_mpl_latex(plot):
    plot()
    code = matplotlib2tikz.get_tikz_code(standalone=True)
    directory = os.getcwd()
    filename = "test-0.png"
    plt.savefig(filename)
    plt.close()

    pdf_file = _compile(code)
    pdf_dirname = os.path.dirname(pdf_file)

    # Convert PDF to PNG.
    subprocess.check_output(
        ["pdftoppm", "-r", "1000", "-png", pdf_file, "test"], stderr=subprocess.STDOUT
    )
    png_path = os.path.join(pdf_dirname, "test-1.png")

    os.rename(png_path, os.path.join(directory, "test-1.png"))
    return
Ejemplo n.º 10
0
def _main():
    this_dir = os.path.dirname(os.path.abspath(__file__))
    exclude_list = ["test_rotated_labels.py", "test_deterministic_output.py"]
    for filename in os.listdir(this_dir):
        if filename.startswith("test_") and filename.endswith(".py"):
            spec = importlib.util.spec_from_file_location("plot", filename)

            if filename in exclude_list:
                continue

            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            module.plot()

            code = m2t.get_tikz_code(include_disclaimer=False)
            plt.close()

            tex_filename = filename[:-3] + "_reference.tex"
            with open(os.path.join(this_dir, tex_filename), "w") as f:
                f.write(code)
    return
def _main():
    parser = argparse.ArgumentParser(description="Refresh the reference TeX files.")
    parser.add_argument("files", nargs="+", help="Files to refresh")
    args = parser.parse_args()

    this_dir = os.path.dirname(os.path.abspath(__file__))
    exclude_list = ["test_rotated_labels.py", "test_deterministic_output.py"]

    for filename in args.files:
        if filename in exclude_list:
            continue
        if filename.startswith("test_") and filename.endswith(".py"):
            spec = importlib.util.spec_from_file_location("plot", filename)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            module.plot()

            code = m2t.get_tikz_code(include_disclaimer=False)
            plt.close()

            tex_filename = filename[:-3] + "_reference.tex"
            with open(os.path.join(this_dir, tex_filename), "w") as f:
                f.write(code)
    return
Ejemplo n.º 12
0
def texify_plot_performance(fig, ax, problem_set):
    """Write a ``.tex`` file with the performance plot.

    The function will create a file named `benchmark_small.tex` or
    `benchmark_large.tex` with the latex code for the performance plot.

    Args:
        fig (matplotlib.figure): Handle to the matplotlib figure of the
            performance plot.
        ax (list): List of lists of matplotlib axis of the performance plot.
        problem_set (str): Can either be ``small`` or ``large`` to switch
            between which benchmark set is being plotted.

    Returns:
        str: String of the latex code for the learning rate sensitivity plot.

    """
    file_name = 'benchmark_' + str(problem_set) + '.tex'
    tikz_code = get_tikz_code(file_name,
                              figureheight='\\figureheight',
                              figurewidth='\\figurewidth')

    tikz_code = r"\pgfplotsset{every axis/.append style={label style={font=\tiny}, tick label style={font=\tiny}, legend style={font=\tiny, line width=1pt}}}" + tikz_code
    tikz_code = tikz_code.replace('minor', '%minor')  # comment minor tick
    tikz_code = tikz_code.replace('x grid', '%x grid')  # remove grid
    tikz_code = tikz_code.replace('y grid', '%y grid')  # remove grid
    tikz_code = tikz_code.replace('tick align',
                                  '%tick align')  # ugly outside ticks
    tikz_code = tikz_code.replace(
        'nextgroupplot[',
        'nextgroupplot[axis x line*=bottom,\naxis y line*=left,'
    )  # ugly outside ticks
    tikz_code = tikz_code.replace('xlabel={Epochs},\nxmajorticks=false,',
                                  'xlabel={Epochs},\nxmajorticks=true,'
                                  )  # if x label is epoch, show ticks
    tikz_code = tikz_code.replace('ymajorticks=false,',
                                  'ymajorticks=true,')  # show y labels
    tikz_code = tikz_code.replace('\mathdefault',
                                  '')  # remove mathdefault in labels
    tikz_code = tikz_code.replace(
        '\path [draw=white!80.0!black, fill opacity=0]',
        '%\path [draw=white!80.0!black, fill opacity=0]'
    )  # remove lines that are created for some reason
    tikz_code = tikz_code.replace(
        '(current bounding box.south west)!0.98!(current bounding box.north west)',
        '(current bounding box.south west)!1.05!(current bounding box.north west)'
    )  # position title higher
    tikz_code = tikz_code.replace('title={',
                                  'title={\small ')  # shrink title size
    tikz_code = tikz_code.replace(
        'group style={group size=4 by 4',
        'group style={group size=4 by 4, horizontal sep=1cm, vertical sep=0.4cm '
    )  # reduce separation between plots
    tikz_code = tikz_code.replace(
        'ylabel={Test Loss}', r'ylabel style={align=left}, ylabel=Test\\Loss'
    )  # y label in two lines
    tikz_code = tikz_code.replace(
        'ylabel={Test Accuracy}',
        r'ylabel style={align=left}, ylabel=Test\\Accuracy'
    )  # y label in two lines
    tikz_code = tikz_code.replace(
        'ylabel={Train Loss}', r'ylabel style={align=left}, ylabel=Train\\Loss'
    )  # y label in two lines
    tikz_code = tikz_code.replace(
        'ylabel={Train Accuracy}',
        r'ylabel style={align=left}, ylabel=Train\\Accuracy'
    )  # y label in two lines

    # Write the file out again
    with open(file_name, 'w') as file:
        file.write(tikz_code)

    return tikz_code