diff --git a/idefix2python/axes.py b/idefix2python/axes.py index 75689fb..cd68392 100644 --- a/idefix2python/axes.py +++ b/idefix2python/axes.py @@ -43,6 +43,7 @@ def __init__(self, quantities, suptitle=None): self.columns = qtyInfo.plot_coords[1] + 1 self.axes = np.empty((self.rows, self.columns), dtype="object") + self.initxt = None def init(self): """ @@ -76,19 +77,28 @@ def generate_figure(self, custom_suptitle=None): if suptitle is not None: fig.suptitle(suptitle) - # TODO move to renderer? Later PR - # if len(self.context.format_inputs_text) > 0: - # padding_top = 0.1 - # tools.annotateInputs( - # fig, self.context.format_inputs_text, padding_top=padding_top - # ) self.used_coords = [list(qtyInfo.plot_coords) for qtyInfo in self.quantities] for i in range(self.rows): for j in range(self.columns): self.axes[i, j].generate_ax(self.fig, axs[i, j]) + def set_initxt(self, initxt): + self.initxt = initxt + def save_and_close(self, path): + if self.initxt: + self.fig.text( + 0.1, + 1, + self.initxt, + family="monospace", + fontsize=7, + va="bottom", + ha="left", + usetex=False, + ) + for ax in self.axes.flat: ax.last_pimp() self.fig.savefig(path, dpi=DPI, bbox_inches="tight") diff --git a/idefix2python/context.py b/idefix2python/context.py index 123b2d1..30353b0 100644 --- a/idefix2python/context.py +++ b/idefix2python/context.py @@ -4,6 +4,7 @@ import argparse from . import tools from .vtk_io import readVTK +import inifix import numpy as np CARTESIAN_DIMENSION_NAMES = { @@ -184,9 +185,9 @@ class RunContext: * partFolder (str): Folder path containing the particles data. * frameFolder (str): Folder name where the rendered frames will be stored. * active_directions (list): List of active coordinate directions. - * debug (bool): debug mode will show the .ini file. + * show_ini (bool): show_ini mode will show the .ini file content at the top of the frame. Defaults to False. - * iniPath (Path): Custom path to the .ini input file. Defaults to + * iniPath (Path): Custom path to the .ini input file. The .ini content is accessible as a dict through context.inidata. Defaults to `projectPath/inputs/{runName}.ini`. Note: @@ -199,7 +200,7 @@ def __init__(self, runName, projectPath=".", **kwargs): self.projectPath = Path(projectPath) self.projectPath.resolve(strict=True) - self.debug = kwargs.get("debug", False) + self.show_ini = kwargs.get("show_ini", False) self.userArgs = kwargs.get("args", _get_args()) @@ -216,14 +217,16 @@ def __init__(self, runName, projectPath=".", **kwargs): self.iniPath = Path( kwargs.get("iniPath", self.projectPath / "inputs" / f"{runName}.ini") ) - self.format_inputs_text = "" - if self.debug: - if self.iniPath.is_file(): - self.format_inputs_text = tools.formatInputs(self.iniPath) - else: + self.inidata = None + self.initxt = None + if self.show_ini: + if not self.iniPath.exists(): raise FileNotFoundError( - f"debug requested but {self.iniPath} doesn't exist" + f"show_ini requested but {self.iniPath} doesn't exist" ) + with self.iniPath.open("rb") as fh: + self.inidata = inifix.load(fh, sections="require") + self.initxt = inifix.format_string(self.iniPath.read_text(encoding="utf-8")) self.partFolder = kwargs.get("partFolder", None) self.framepath_basename = kwargs.get("custom_name", self.runName) diff --git a/idefix2python/renderer.py b/idefix2python/renderer.py index 8d8cfba..390d1a5 100644 --- a/idefix2python/renderer.py +++ b/idefix2python/renderer.py @@ -133,6 +133,7 @@ def _pre_render(self): self.figsMovie.append(fig) else: self.figsTimeline.append(fig) + fig.set_initxt(self.context.initxt) for qtyInfo in fig.quantities: if isinstance(qtyInfo, MapMovie2D): diff --git a/idefix2python/tools.py b/idefix2python/tools.py index 71f41ed..85e8077 100644 --- a/idefix2python/tools.py +++ b/idefix2python/tools.py @@ -1,6 +1,7 @@ import numpy as np import json from itertools import zip_longest +import inifix def LOG(*args): @@ -37,91 +38,6 @@ def fmt(x, pos): return r"${} \times 10^{{{}}}$".format(a, b) -def formatInputs(iniPath): - """ - Formats the .ini file into a decent dict - """ - with open(iniPath) as ini: - content = ini.read() - - sections = {} - current_section = None - - MAX_VAL_LEN = 22 - - for line in content.splitlines(): - line = line.strip() - if not line or line.startswith("#"): - continue - - if line.startswith("[") and line.endswith("]"): - current_section = line[1:-1] - sections[current_section] = [] - elif current_section: - parts = line.split() - if len(parts) >= 2: - key = parts[0] - val = " ".join(parts[1:]) - val = "".join(val.split("#")[0]) - if len(val) > MAX_VAL_LEN: - val = "..." + val[MAX_VAL_LEN - 3 :] - sections[current_section].append(f"{key:<14} {val}") - - return {k: "\n".join(v) for k, v in sections.items() if v} - - -def annotateInputs(fig, ini_dict, padding_top=0.0): - """ - Writes text on the `fig` with distinctive sections. - """ - if ini_dict == {}: - return - - COL_WIDTH = 42 - COLS_NB = 3 - - all_panels = [] - keys = list(ini_dict.keys()) - table = [keys[i : i + COLS_NB] for i in range(0, len(keys), COLS_NB)] - - for section_group in table: - formatted_columns = [ - [f"[{name}]", *ini_dict[name].split("\n")] - for name in section_group - if name in ini_dict - ] - - if not formatted_columns: - continue - - printable_rows = [ - "".join(f"{section_line:<{COL_WIDTH}}" for section_line in horizontal_slice) - for horizontal_slice in zip_longest(*formatted_columns, fillvalue="") - ] - - text_panel = "\n".join(printable_rows) - all_panels.append(text_panel) - - final_display_string = "\n\n\n".join(all_panels) - - total_lines = final_display_string.count("\n") + 1 - header_space = total_lines * 0.014 - margin_top = header_space + padding_top - - fig.text( - 0.55, - 1 - margin_top, - final_display_string, - family="monospace", - fontsize=7, - va="bottom", - ha="center", - usetex=False, - ) - - fig.subplots_adjust(top=1.0 - margin_top - 0.05) - - def divide_discardingNullDenominator(a, b): """ Returns a/b but with None wherever b=0 diff --git a/pyproject.toml b/pyproject.toml index b56ad03..acffe8e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,8 @@ version = "0.1.0" dependencies = [ "numpy", "matplotlib", + "inifix>=5.1.0", ] [tool.setuptools.packages.find] -where = ["."] \ No newline at end of file +where = ["."]