Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions idefix2python/axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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")
Expand Down
21 changes: 12 additions & 9 deletions idefix2python/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import argparse
from . import tools
from .vtk_io import readVTK
import inifix
import numpy as np

CARTESIAN_DIMENSION_NAMES = {
Expand Down Expand Up @@ -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:
Expand All @@ -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())

Expand All @@ -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"))
Comment on lines +227 to +229

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually there was a more elegant way to do this without reading the file twice

Suggested change
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"))
with self.iniPath.open("rb") as fh:
self.inidata = inifix.load(fh, sections="require")
self.initxt = inifix.dumps(self.inidata)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#33


self.partFolder = kwargs.get("partFolder", None)
self.framepath_basename = kwargs.get("custom_name", self.runName)
Expand Down
1 change: 1 addition & 0 deletions idefix2python/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
86 changes: 1 addition & 85 deletions idefix2python/tools.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np
import json
from itertools import zip_longest
import inifix


def LOG(*args):
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ version = "0.1.0"
dependencies = [
"numpy",
"matplotlib",
"inifix>=5.1.0",
]

[tool.setuptools.packages.find]
where = ["."]
where = ["."]