|
| 1 | +import subprocess |
| 2 | +import os |
| 3 | +import tempfile |
| 4 | + |
| 5 | +class TikzFigure: |
| 6 | + def __init__(self, **kwargs): |
| 7 | + """ |
| 8 | + Initialize the TikzFigure class for creating TikZ figures. |
| 9 | +
|
| 10 | + Parameters: |
| 11 | + **kwargs: Arbitrary keyword arguments. |
| 12 | + - figsize (tuple): Figure size (default is (10, 6)). |
| 13 | + - caption (str): Caption for the figure. |
| 14 | + - description (str): Description of the figure. |
| 15 | + - label (str): Label for the figure. |
| 16 | + - grid (bool): Whether to display grid lines (default is False). |
| 17 | + TODO: Add all options |
| 18 | + """ |
| 19 | + # Set default values |
| 20 | + self._figsize = kwargs.get('figsize', (10, 6)) |
| 21 | + self._caption = kwargs.get('caption', None) |
| 22 | + self._description = kwargs.get('description', None) |
| 23 | + self._label = kwargs.get('label', None) |
| 24 | + self._grid = kwargs.get('grid', False) |
| 25 | + |
| 26 | + # Initialize nodes and lines |
| 27 | + self.nodes = [] |
| 28 | + self.lines = [] |
| 29 | + |
| 30 | + def add_node(self, name, x, y, **kwargs): |
| 31 | + """ |
| 32 | + Add a node to the TikZ figure. |
| 33 | +
|
| 34 | + Parameters: |
| 35 | + - name (str): Name of the node. |
| 36 | + - x (float): X-coordinate of the node. |
| 37 | + - y (float): Y-coordinate of the node. |
| 38 | + - **kwargs: Additional TikZ node options (e.g., shape, color). |
| 39 | + """ |
| 40 | + node = { |
| 41 | + 'name': name, |
| 42 | + 'x': x, |
| 43 | + 'y': y, |
| 44 | + 'options': kwargs |
| 45 | + } |
| 46 | + self.nodes.append(node) |
| 47 | + |
| 48 | + def add_line(self, nodes, **kwargs): |
| 49 | + """ |
| 50 | + Add a line or path connecting multiple nodes. |
| 51 | +
|
| 52 | + Parameters: |
| 53 | + - nodes (list of str): List of node names to connect. |
| 54 | + - **kwargs: Additional TikZ line options (e.g., style, color). |
| 55 | +
|
| 56 | + Examples: |
| 57 | + - add_line(['A', 'B', 'C'], color='blue') |
| 58 | + Connects nodes A -> B -> C with a blue line. |
| 59 | + """ |
| 60 | + if not isinstance(nodes, list): |
| 61 | + raise ValueError("nodes parameter must be a list of node names.") |
| 62 | + |
| 63 | + line = { |
| 64 | + 'nodes': nodes, |
| 65 | + 'options': kwargs |
| 66 | + } |
| 67 | + self.lines.append(line) |
| 68 | + |
| 69 | + def generate_tikz(self): |
| 70 | + """ |
| 71 | + Generate the TikZ script for the figure. |
| 72 | +
|
| 73 | + Returns: |
| 74 | + - tikz_script (str): The TikZ script as a string. |
| 75 | + """ |
| 76 | + tikz_script = "\\begin{tikzpicture}\n" |
| 77 | + |
| 78 | + # Add grid if enabled |
| 79 | + if self._grid: |
| 80 | + tikz_script += " \\draw[step=1cm, gray, very thin] (-10,-10) grid (10,10);\n" |
| 81 | + |
| 82 | + # Add nodes |
| 83 | + for node in self.nodes: |
| 84 | + options = ', '.join(f"{k.replace('_',' ')}={{{v}}}" for k, v in node['options'].items()) |
| 85 | + if options: |
| 86 | + options = f"[{options}]" |
| 87 | + tikz_script += f" \\node{options} ({node['name']}) at ({node['x']}, {node['y']}) {{{node['name']}}};\n" |
| 88 | + |
| 89 | + # Add lines |
| 90 | + for line in self.lines: |
| 91 | + options = ', '.join(f"{k.replace('_',' ')}={{{v}}}" for k, v in line['options'].items()) |
| 92 | + if options: |
| 93 | + options = f"[{options}]" |
| 94 | + # Create the path by connecting all nodes in the list |
| 95 | + path = ' -- '.join(f"({node_name})" for node_name in line['nodes']) |
| 96 | + tikz_script += f" \\draw{options} {path};\n" |
| 97 | + |
| 98 | + tikz_script += "\\end{tikzpicture}" |
| 99 | + |
| 100 | + # Wrap in figure environment if necessary |
| 101 | + if self._caption or self._description or self._label: |
| 102 | + figure_env = "\\begin{figure}\n" + tikz_script + "\n" |
| 103 | + if self._caption: |
| 104 | + figure_env += f" \\caption{{{self._caption}}}\n" |
| 105 | + if self._label: |
| 106 | + figure_env += f" \\label{{{self._label}}}\n" |
| 107 | + figure_env += "\\end{figure}" |
| 108 | + tikz_script = figure_env |
| 109 | + |
| 110 | + return tikz_script |
| 111 | + |
| 112 | + def compile_pdf(self, filename='output.pdf'): |
| 113 | + """ |
| 114 | + Compile the TikZ script into a PDF using pdflatex. |
| 115 | +
|
| 116 | + Parameters: |
| 117 | + - filename (str): The name of the output PDF file (default is 'output.pdf'). |
| 118 | +
|
| 119 | + Notes: |
| 120 | + - Requires 'pdflatex' to be installed and accessible from the command line. |
| 121 | + """ |
| 122 | + tikz_code = self.generate_tikz() |
| 123 | + |
| 124 | + # Create a minimal LaTeX document |
| 125 | + latex_document = ( |
| 126 | + "\\documentclass[border=10pt]{standalone}\n" |
| 127 | + "\\usepackage{tikz}\n" |
| 128 | + "\\begin{document}\n" |
| 129 | + f"{tikz_code}\n" |
| 130 | + "\\end{document}" |
| 131 | + ) |
| 132 | + |
| 133 | + # Use a temporary directory to store the LaTeX files |
| 134 | + with tempfile.TemporaryDirectory() as tempdir: |
| 135 | + tex_file = os.path.join(tempdir, 'figure.tex') |
| 136 | + with open(tex_file, 'w') as f: |
| 137 | + f.write(latex_document) |
| 138 | + |
| 139 | + # Run pdflatex |
| 140 | + try: |
| 141 | + subprocess.run( |
| 142 | + ['pdflatex', '-interaction=nonstopmode', tex_file], |
| 143 | + cwd=tempdir, |
| 144 | + check=True, |
| 145 | + stdout=subprocess.PIPE, |
| 146 | + stderr=subprocess.PIPE |
| 147 | + ) |
| 148 | + except subprocess.CalledProcessError as e: |
| 149 | + print("An error occurred while compiling the LaTeX document:") |
| 150 | + print(e.stderr.decode()) |
| 151 | + return |
| 152 | + |
| 153 | + # Move the output PDF to the desired location |
| 154 | + pdf_output = os.path.join(tempdir, 'figure.pdf') |
| 155 | + if os.path.exists(pdf_output): |
| 156 | + os.rename(pdf_output, filename) |
| 157 | + print(f"PDF successfully compiled and saved as '{filename}'.") |
| 158 | + else: |
| 159 | + print("PDF compilation failed. Please check the LaTeX log for details.") |
0 commit comments