Skip to content
Closed
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
10 changes: 2 additions & 8 deletions tardis/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@
from tardis.simulation import Simulation
from tardis.workflows.standard_tardis_workflow import StandardTARDISWorkflow
from tardis.tests.fixtures.atom_data import *
from tardis.transport.montecarlo.progress_bars import (
iterations_pbar,
packet_pbar,
)
from tardis.transport.montecarlo.progress_bars import close_progress_bars
from tardis.tests.test_util import monkeysession

try:
Expand Down Expand Up @@ -337,7 +334,4 @@ def workflow_simple(config_verysimple, atomic_data_fname):


def pytest_sessionfinish(session, exitstatus):
if packet_pbar is not None:
packet_pbar.close()
if iterations_pbar is not None:
iterations_pbar.close()
close_progress_bars()
68 changes: 48 additions & 20 deletions tardis/transport/montecarlo/progress_bars.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,33 @@

from tardis.util.environment import Environment

# Global progress bar instances - initialized at import time for thread safety
# Use tqdm.auto which automatically detects environment
iterations_pbar = tqdm(
desc="Iterations:",
bar_format="{desc:<}{bar}{n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]",
)
packet_pbar = tqdm(
desc="Packets: ",
postfix="0",
bar_format="{desc:<}{bar}{n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]",
)
# Global progress bar instances - created on first use to avoid
# rendering at import time in CLI environments (see #3287)
iterations_pbar = None
packet_pbar = None


def _get_iterations_pbar():
"""Return the iterations progress bar, creating it if needed."""
global iterations_pbar
if iterations_pbar is None:
iterations_pbar = tqdm(
desc="Iterations:",
bar_format="{desc:<}{bar}{n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]",
)
return iterations_pbar


def _get_packet_pbar():
"""Return the packet progress bar, creating it if needed."""
global packet_pbar
if packet_pbar is None:
packet_pbar = tqdm(
desc="Packets: ",
postfix="0",
bar_format="{desc:<}{bar}{n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]",
)
return packet_pbar

def update_packets_pbar(i: int, no_of_packets: int) -> None:
"""
Expand All @@ -32,11 +48,11 @@ def update_packets_pbar(i: int, no_of_packets: int) -> None:
no_of_packets : int
Total number of packets in one iteration.
"""
# Initialize packet progress bar if needed
if packet_pbar.total is None:
fix_bar_layout(packet_pbar, no_of_packets=no_of_packets)
pbar = _get_packet_pbar()
if pbar.total is None:
fix_bar_layout(pbar, no_of_packets=no_of_packets)

packet_pbar.update(i)
pbar.update(i)


def reset_packet_pbar(no_of_packets: int) -> None:
Expand All @@ -48,7 +64,7 @@ def reset_packet_pbar(no_of_packets: int) -> None:
no_of_packets : int
Total number of packets in the iteration.
"""
packet_pbar.reset(total=no_of_packets)
_get_packet_pbar().reset(total=no_of_packets)


def refresh_packet_pbar() -> None:
Expand All @@ -58,7 +74,7 @@ def refresh_packet_pbar() -> None:
This function refreshes the visual display of the packet progress bar
to ensure accurate rendering after each iteration completes.
"""
packet_pbar.refresh()
_get_packet_pbar().refresh()


def update_iterations_pbar(i: int) -> None:
Expand All @@ -70,7 +86,7 @@ def update_iterations_pbar(i: int) -> None:
i : int
Amount by which the progress bar needs to be updated.
"""
iterations_pbar.update(i)
_get_iterations_pbar().update(i)


def initialize_iterations_pbar(total_iterations: int) -> None:
Expand All @@ -82,8 +98,20 @@ def initialize_iterations_pbar(total_iterations: int) -> None:
total_iterations : int
Total number of iterations.
"""
if iterations_pbar.total is None:
fix_bar_layout(iterations_pbar, total_iterations=total_iterations)
pbar = _get_iterations_pbar()
if pbar.total is None:
fix_bar_layout(pbar, total_iterations=total_iterations)


def close_progress_bars() -> None:
"""Close and reset both progress bars if they have been created."""
global iterations_pbar, packet_pbar
if packet_pbar is not None:
packet_pbar.close()
packet_pbar = None
if iterations_pbar is not None:
iterations_pbar.close()
iterations_pbar = None


def fix_bar_layout(bar, no_of_packets=None, total_iterations=None):
Expand Down
17 changes: 6 additions & 11 deletions tardis/util/panel_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@

def ssh_jh():
"""Initialize panel for JupyterHub (colab comms)"""
pn.extension(comms="ipywidgets")
pn.extension("tabulator", "plotly", comms="ipywidgets")

def notebook():
"""Initialize panel for standard Jupyter notebook (default comms)"""
pn.extension(comms="ipywidgets")
pn.extension("tabulator", "plotly", comms="ipywidgets")

def vscode():
"""Initialize panel for VSCode (ipywidgets comms)"""
pn.extension(comms="ipywidgets")
pn.extension("tabulator", "plotly", comms="ipywidgets")

def vscode_noipy():
"""Initialize panel for VSCode without ipywidgets (vscode comms)"""
pn.extension(comms="vscode")
pn.extension("tabulator", "plotly", comms="vscode")

def sphinx():
"""Initialize panel for Sphinx documentation builds"""
pn.extension("ipywidgets")
pn.extension("tabulator", "plotly", "ipywidgets")

def auto():
"""Auto-detect environment and initialize panel"""
Expand All @@ -43,18 +43,13 @@ def auto():

# Otherwise auto-detect
if Environment.is_sshjh():
print("Auto-detected JupyterHub environment")
ssh_jh()
elif Environment.is_vscode():
print("Auto-detected VSCode environment")
vscode()
elif Environment.is_notebook():
print("Auto-detected Jupyter notebook environment")
notebook()
elif Environment.is_sphinx():
print("Auto-detected Sphinx build environment")
sphinx()
else:
print("Defaulting to default panel comms.")
elif not Environment.is_terminal():
pn.extension()

5 changes: 0 additions & 5 deletions tardis/visualization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,3 @@
shell_info_from_hdf,
shell_info_from_simulation,
)


print("Initializing tabulator and plotly panel extensions for widgets to work")
import panel as pn
pn.extension("tabulator", "plotly")
17 changes: 8 additions & 9 deletions tardis/visualization/tools/convergence_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,6 @@

import tardis.visualization.plot_util as pu

plotly.offline.init_notebook_mode(connected=True)
# mathjax needs to be loaded for latex labels to render correctly
# see https://github.com/tardis-sn/tardis/issues/2446
display(
HTML(
'<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_SVG"></script>'
)
)


class ConvergencePlots:
"""
Expand Down Expand Up @@ -287,6 +278,14 @@ def build(self, display_plot=True):
self.create_t_inner_luminosities_plot()

if display_plot:
plotly.offline.init_notebook_mode(connected=True)
# mathjax needs to be loaded for latex labels to render correctly
# see https://github.com/tardis-sn/tardis/issues/2446
display(
HTML(
'<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_SVG"></script>'
)
)
self.display_handle = display(
widgets.VBox(
[self.plasma_plot, self.t_inner_luminosities_plot],
Expand Down
34 changes: 17 additions & 17 deletions tardis/visualization/tools/tests/test_sdec_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,18 +274,18 @@ def test_generate_plot_mpl(
regression_file = f"test_generate_plot_mpl__plotter_generate_plot_mpl{param_idx}__.h5"

regression_data.fname = regression_file
# expected = regression_data.sync_hdf_store(generate_plot_plotly_hdf)
expected = pd.HDFStore(sdec_regression_data / regression_file, mode='r')
# expected_fh = regression_data.sync_hdf_store(generate_plot_plotly_hdf)
expected_fh = pd.HDFStore(sdec_regression_data / regression_file, mode='r')

# expected = regression_data.sync_hdf_store(generate_plot_mpl_hdf)
# expected_fh = regression_data.sync_hdf_store(generate_plot_mpl_hdf)

for item in ["_species_name", "_color_list"]:
np.testing.assert_array_equal(
expected.get("plot_data_hdf/" + item).values.flatten(),
expected_fh.get("plot_data_hdf/" + item).values.flatten(),
getattr(generate_plot_mpl_hdf, item),
)

labels = expected["plot_data_hdf/scalars"]
labels = expected_fh["plot_data_hdf/scalars"]
for index1, data in enumerate(fig.get_children()):
if isinstance(data.get_label(), str):
assert (
Expand All @@ -296,20 +296,20 @@ def test_generate_plot_mpl(
if isinstance(data, Line2D):
np.testing.assert_allclose(
data.get_xydata(),
expected.get("plot_data_hdf/" + "data" + str(index1)),
expected_fh.get("plot_data_hdf/" + "data" + str(index1)),
atol=0, rtol=RELATIVE_TOLERANCE_SDEC
)
np.testing.assert_allclose(
data.get_path().vertices,
expected.get("plot_data_hdf/" + "linepath" + str(index1)),
expected_fh.get("plot_data_hdf/" + "linepath" + str(index1)),
atol=0, rtol=RELATIVE_TOLERANCE_SDEC
)
# save artists which correspond to element contributions
if isinstance(data, PolyCollection):
for index2, path in enumerate(data.get_paths()):
np.testing.assert_allclose(
path.vertices,
expected.get(
expected_fh.get(
"plot_data_hdf/"
"polypath"
"ind_"
Expand All @@ -320,7 +320,7 @@ def test_generate_plot_mpl(
atol=0,
rtol=RELATIVE_TOLERANCE_SDEC
)
expected.close()
expected_fh.close()

@pytest.fixture(scope="class", params=list(enumerate(combinations)))
def plotter_generate_plot_ply(self, request, observed_spectrum, plotter):
Expand Down Expand Up @@ -384,12 +384,12 @@ def test_generate_plot_ply(
regression_file = f"test_generate_plot_mpl__plotter_generate_plot_ply{param_idx}__.h5"

regression_data.fname = regression_file
# expected = regression_data.sync_hdf_store(generate_plot_plotly_hdf)
expected = pd.HDFStore(sdec_regression_data / regression_file, mode='r')
# expected_fh = regression_data.sync_hdf_store(generate_plot_plotly_hdf)
expected_fh = pd.HDFStore(sdec_regression_data / regression_file, mode='r')

for item in ["_species_name", "_color_list"]:
np.testing.assert_array_equal(
expected.get("plot_data_hdf/" + item).values.flatten(),
expected_fh.get("plot_data_hdf/" + item).values.flatten(),
getattr(generate_plot_plotly_hdf, item),
)

Expand All @@ -399,26 +399,26 @@ def test_generate_plot_ply(
assert (
data.stackgroup
== getattr(
expected["/plot_data_hdf/scalars"],
expected_fh["/plot_data_hdf/scalars"],
"_" + str(index) + "stackgroup",
).decode()
)
if data.name:
assert (
data.name
== getattr(
expected["/plot_data_hdf/scalars"],
expected_fh["/plot_data_hdf/scalars"],
"_" + str(index) + "name",
).decode()
)
np.testing.assert_allclose(
data.x, expected.get(group + "x").values.flatten(), atol=0, rtol=RELATIVE_TOLERANCE_SDEC
data.x, expected_fh.get(group + "x").values.flatten(), atol=0, rtol=RELATIVE_TOLERANCE_SDEC
)
np.testing.assert_allclose(
data.y, expected.get(group + "y").values.flatten(), atol=0, rtol=RELATIVE_TOLERANCE_SDEC
data.y, expected_fh.get(group + "y").values.flatten(), atol=0, rtol=RELATIVE_TOLERANCE_SDEC
)

expected.close()
expected_fh.close()

def test_mpl_image(self, plotter_generate_plot_mpl, tmp_path, regression_data):
fig, _ = plotter_generate_plot_mpl
Expand Down
Loading