From d68a0de073a64c4705199acf256c0706220d354c Mon Sep 17 00:00:00 2001 From: Boqiang Date: Thu, 20 Aug 2026 23:23:28 -0500 Subject: [PATCH 1/6] refactor(features): use canonical AnnData source --- server/features_server.py | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/server/features_server.py b/server/features_server.py index b2207c3..862d8a0 100644 --- a/server/features_server.py +++ b/server/features_server.py @@ -1,11 +1,15 @@ from shiny import ui, render, reactive -import anndata as ad import numpy as np -import pandas as pd import spac.visualization def features_server(input, output, session, shared): + + @reactive.calc + def get_adata(): + """Get the main AnnData object from shared state.""" + return shared['adata_main'].get() + def on_layer_check(): return input.h1_layer() if input.h1_layer() != "Original" else None @@ -14,14 +18,7 @@ def on_layer_check(): @render.plot @reactive.event(input.go_h1, ignore_none=True) def spac_Histogram_1(): - adata = ad.AnnData( - X=shared['X_data'].get(), - obs=pd.DataFrame(shared['obs_data'].get()), - var=pd.DataFrame(shared['var_data'].get()), - layers=shared['layers_data'].get(), - dtype=shared['X_data'].get().dtype - ) - + adata = get_adata() if adata is None: return None From 138025da3b342a8b8972229b010e687620bf79e4 Mon Sep 17 00:00:00 2001 From: Boqiang Date: Sat, 22 Aug 2026 15:05:26 -0400 Subject: [PATCH 2/6] refactor(features): centralize histogram input parameters --- server/features_server.py | 57 ++++++++++++++++++++++----------------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/server/features_server.py b/server/features_server.py index 862d8a0..a2bd1f6 100644 --- a/server/features_server.py +++ b/server/features_server.py @@ -10,9 +10,27 @@ def get_adata(): """Get the main AnnData object from shared state.""" return shared['adata_main'].get() - def on_layer_check(): - return input.h1_layer() if input.h1_layer() != "Original" else None - + @reactive.calc + def get_features_inputs(): + """Read Features controls and build the current histogram inputs.""" + + group_by_enabled = input.h1_group_by_check() + group_by = input.h1_anno() if group_by_enabled else None + together = input.h1_together_check() if group_by_enabled else False + multiple = input.h1_together_drop() if together else "stack" + + return { + "feature": input.h1_feat(), + "layer": ( + input.h1_layer() if input.h1_layer() != "Original" else None + ), + "x_log_scale": input.h1_log_x(), + "y_log_scale": input.h1_log_y(), + "group_by": group_by, + "together": together, + "multiple": multiple, + "x_axis_label_rotation": input.feat_slider(), + } @output @render.plot @@ -22,31 +40,20 @@ def spac_Histogram_1(): if adata is None: return None - feature = input.h1_feat() - rotation = input.feat_slider() - btn_log_x = input.h1_log_x() - btn_log_y = input.h1_log_y() - layer = on_layer_check() - - kwargs = { - "adata": adata, - "feature": feature, - "layer": layer, - "x_log_scale": btn_log_x, - "y_log_scale": btn_log_y, - } - - if input.h1_group_by_check(): - kwargs["group_by"] = input.h1_anno() - kwargs["together"] = input.h1_together_check() - if input.h1_together_check(): - kwargs["multiple"] = input.h1_together_drop() - - fig1, ax, df = spac.visualization.histogram(**kwargs).values() + features_inputs = get_features_inputs() + rotation = features_inputs.pop("x_axis_label_rotation") + fig1, ax, df = spac.visualization.histogram( + adata=adata, + **features_inputs, + ).values() axes = ax if isinstance(ax, (list, np.ndarray)) else [ax] for a in axes: - a.tick_params(axis='x', rotation=rotation, labelsize=10) + a.tick_params( + axis="x", + rotation=rotation, + labelsize=10, + ) shared['df_histogram1'].set(df) return fig1 From 2b7382b5df1d7f13d5d36296847c9bc356f09a24 Mon Sep 17 00:00:00 2001 From: Boqiang Date: Tue, 1 Sep 2026 14:16:05 -0400 Subject: [PATCH 3/6] refactor(features): delegate histogram to template - map semantic inputs to Histogram template parameters - pass canonical AnnData through the memory registry - publish template results after guaranteed cleanup --- server/features_server.py | 57 ++++++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 16 deletions(-) diff --git a/server/features_server.py b/server/features_server.py index a2bd1f6..49566a1 100644 --- a/server/features_server.py +++ b/server/features_server.py @@ -1,6 +1,12 @@ from shiny import ui, render, reactive -import numpy as np -import spac.visualization + +# Import template wrapper utilities. +from utils.template_wrapper import ( + register_memory_object, + unregister_memory_object, +) +# Import the specific template +from spac.templates.histogram_template import run_from_json def features_server(input, output, session, shared): @@ -32,31 +38,50 @@ def get_features_inputs(): "x_axis_label_rotation": input.feat_slider(), } + def build_template_params(input_values, virtual_path): + """Convert normalized semantic values to template parameters. + + The template supplies defaults for controls not exposed by the UI. + """ + + return { + "Upstream_Analysis": virtual_path, + "Feature": input_values["feature"] or "None", + "Table_": input_values["layer"] or "Original", + "Group_by": input_values["group_by"] or "None", + "Together": input_values["together"], + "Take_X_Log": input_values["x_log_scale"], + "Take_Y_log": input_values["y_log_scale"], + "Multiple": input_values["multiple"], + "X_Axis_Label_Rotation": input_values["x_axis_label_rotation"], + "Plot_By": "Feature", # Features tab invariant + "Facet": False, # Facet UI deferred + } + @output @render.plot @reactive.event(input.go_h1, ignore_none=True) def spac_Histogram_1(): + """Generate a feature histogram through the SPAC template.""" + adata = get_adata() if adata is None: return None - features_inputs = get_features_inputs() - rotation = features_inputs.pop("x_axis_label_rotation") - fig1, ax, df = spac.visualization.histogram( - adata=adata, - **features_inputs, - ).values() - - axes = ax if isinstance(ax, (list, np.ndarray)) else [ax] - for a in axes: - a.tick_params( - axis="x", - rotation=rotation, - labelsize=10, + + virtual_path = register_memory_object(adata) + try: + params = build_template_params(features_inputs, virtual_path) + fig, df = run_from_json( + json_path=params, + save_to_disk=False, + show_plot=False, ) + finally: + unregister_memory_object(virtual_path) shared['df_histogram1'].set(df) - return fig1 + return fig histogram_ui_initialized = reactive.Value(False) From 4ec93f095291496c554e7b63f05bad9f8c3e08a6 Mon Sep 17 00:00:00 2001 From: Boqiang Date: Tue, 1 Sep 2026 14:16:39 -0400 Subject: [PATCH 4/6] docs(features): clarify template adapter boundary - describe template delegation in module and server docstrings - clarify the semantic input snapshot responsibility --- server/features_server.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/server/features_server.py b/server/features_server.py index 49566a1..f232ca4 100644 --- a/server/features_server.py +++ b/server/features_server.py @@ -1,3 +1,10 @@ +""" +Feature histogram visualization module for SPAC Shiny application. + +This module handles the server-side logic for generating feature histograms +through the standard SPAC Histogram template workflow. +""" + from shiny import ui, render, reactive # Import template wrapper utilities. @@ -10,6 +17,20 @@ def features_server(input, output, session, shared): + """ + Server logic for the feature histogram visualization. + + Parameters + ---------- + input : shiny.session.Inputs + Shiny input object + output : shiny.session.Outputs + Shiny output object + session : shiny.session.Session + Shiny session object + shared : dict + Shared reactive values across server modules + """ @reactive.calc def get_adata(): @@ -18,7 +39,7 @@ def get_adata(): @reactive.calc def get_features_inputs(): - """Read Features controls and build the current histogram inputs.""" + """Return normalized semantic state from the Features controls.""" group_by_enabled = input.h1_group_by_check() group_by = input.h1_anno() if group_by_enabled else None From 54320ccae6b21c60dbb5efbadab5a240d9108ff5 Mon Sep 17 00:00:00 2001 From: Boqiang Date: Tue, 1 Sep 2026 23:55:59 -0400 Subject: [PATCH 5/6] fix(features): preserve template figure layout - Adapt the PNG conversion boundary from plot-caching commit 5d65369 to preserve the template DPI and intrinsic figure boundary while retaining Shiny's render.plot interface. - Close source figures after serialization to avoid retained Matplotlib state. Co-authored-by: Heaven Golladay-Watkins --- server/features_server.py | 6 ++- utils/plot_utils.py | 78 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/server/features_server.py b/server/features_server.py index f232ca4..973f5db 100644 --- a/server/features_server.py +++ b/server/features_server.py @@ -7,6 +7,8 @@ from shiny import ui, render, reactive +# Import plot display utilities. +from utils.plot_utils import fig_to_png_bytes, png_bytes_to_figure # Import template wrapper utilities. from utils.template_wrapper import ( register_memory_object, @@ -101,8 +103,10 @@ def spac_Histogram_1(): finally: unregister_memory_object(virtual_path) + png_bytes = fig_to_png_bytes(fig) + display_fig = png_bytes_to_figure(png_bytes) shared['df_histogram1'].set(df) - return fig + return display_fig histogram_ui_initialized = reactive.Value(False) diff --git a/utils/plot_utils.py b/utils/plot_utils.py index 5a7c352..f2ef605 100644 --- a/utils/plot_utils.py +++ b/utils/plot_utils.py @@ -5,10 +5,86 @@ plots, such as axis label formatting and styling. """ +import io from typing import List + +import matplotlib.image as mpimg +import matplotlib.pyplot as plt from matplotlib.text import Text +def fig_to_png_bytes(fig) -> bytes: + """Serialize a figure to uncropped PNG bytes and close it. + + The figure's configured DPI is preserved. Objects exposing an underlying + Matplotlib figure through ``.fig`` are also supported. + + Parameters + ---------- + fig + Matplotlib figure or figure-owning object to serialize. + + Returns + ------- + bytes + PNG data preserving the figure's intrinsic boundary. + """ + + underlying = fig.fig if hasattr(fig, "fig") else fig + try: + with io.BytesIO() as buffer: + underlying.savefig( + buffer, + format="png", + dpi=underlying.get_dpi(), + bbox_inches=None, + ) + return buffer.getvalue() + finally: + plt.close(underlying) + + +def png_bytes_to_figure(png_bytes: bytes): + """Create a display-only Matplotlib wrapper for PNG bytes. + + The returned figure contains the rasterized image rather than the + original plot artists. Its DPI and layout exist only to support stable + presentation through Shiny's ``render.plot``. + + Parameters + ---------- + png_bytes : bytes + PNG data to display. + + Returns + ------- + matplotlib.figure.Figure + Decoration-free wrapper containing the complete PNG. + """ + + image = mpimg.imread(io.BytesIO(png_bytes)) + height_px, width_px = image.shape[:2] + display_dpi = 100 + + fig, ax = plt.subplots( + figsize=(width_px / display_dpi, height_px / display_dpi), + dpi=display_dpi, + ) + ax.imshow(image) + ax.axis("off") + fig.subplots_adjust(left=0, right=1, bottom=0, top=1) + + # Keep the image flush with the wrapper during Shiny redraws. + fig.set_layout_engine( + "tight", + pad=0, + h_pad=0, + w_pad=0, + rect=(0, 0, 1, 1), + ) + return fig + + def abbreviate_labels(labels: List[Text], limit: int) -> List[str]: """ Abbreviate a list of matplotlib Text objects. @@ -61,4 +137,4 @@ def apply_axis_style(labels: List[Text], fontsize: int, """ for label in labels: label.set_fontsize(fontsize) - label.set_fontfamily(fontfamily) \ No newline at end of file + label.set_fontfamily(fontfamily) From da242c6fd38b3003d308312256f0ff49d3974384 Mon Sep 17 00:00:00 2001 From: Boqiang Date: Wed, 2 Sep 2026 09:55:04 -0400 Subject: [PATCH 6/6] refactor(features): deliver canonical PNG directly - Replace the Matplotlib display wrapper with direct render.image delivery. - Preserve the template PNG geometry and let Shiny delete delivered temporary files. - Remove the unused PNG-to-figure conversion helper. --- server/features_server.py | 23 ++++++++++++++++---- ui/features_ui.py | 2 +- utils/plot_utils.py | 46 ++------------------------------------- 3 files changed, 22 insertions(+), 49 deletions(-) diff --git a/server/features_server.py b/server/features_server.py index 973f5db..e12e501 100644 --- a/server/features_server.py +++ b/server/features_server.py @@ -5,10 +5,12 @@ through the standard SPAC Histogram template workflow. """ +import tempfile + from shiny import ui, render, reactive # Import plot display utilities. -from utils.plot_utils import fig_to_png_bytes, png_bytes_to_figure +from utils.plot_utils import fig_to_png_bytes # Import template wrapper utilities. from utils.template_wrapper import ( register_memory_object, @@ -82,7 +84,7 @@ def build_template_params(input_values, virtual_path): } @output - @render.plot + @render.image(delete_file=True) @reactive.event(input.go_h1, ignore_none=True) def spac_Histogram_1(): """Generate a feature histogram through the SPAC template.""" @@ -104,9 +106,22 @@ def spac_Histogram_1(): unregister_memory_object(virtual_path) png_bytes = fig_to_png_bytes(fig) - display_fig = png_bytes_to_figure(png_bytes) + with tempfile.NamedTemporaryFile( + prefix="spac_feature_histogram_", + suffix=".png", + delete=False, + ) as temp_file: + temp_file.write(png_bytes) + temp_path = temp_file.name + shared['df_histogram1'].set(df) - return display_fig + return { + "src": temp_path, + "width": "100%", + "height": "100%", + "style": "object-fit: contain;", + "alt": "Feature histogram", + } histogram_ui_initialized = reactive.Value(False) diff --git a/ui/features_ui.py b/ui/features_ui.py index 5ade9bb..0a70558 100644 --- a/ui/features_ui.py +++ b/ui/features_ui.py @@ -64,7 +64,7 @@ def features_ui(): 10, ui.div( {"style": "padding-bottom: 100px;"}, - ui.output_plot( + ui.output_image( "spac_Histogram_1", width="100%", height="60vh" diff --git a/utils/plot_utils.py b/utils/plot_utils.py index f2ef605..000bcde 100644 --- a/utils/plot_utils.py +++ b/utils/plot_utils.py @@ -1,14 +1,13 @@ """ Plotting utility functions for SPAC Shiny application. -This module provides reusable helper functions for customizing matplotlib -plots, such as axis label formatting and styling. +This module provides reusable helpers for serializing matplotlib figures and +formatting plot labels. """ import io from typing import List -import matplotlib.image as mpimg import matplotlib.pyplot as plt from matplotlib.text import Text @@ -44,47 +43,6 @@ def fig_to_png_bytes(fig) -> bytes: plt.close(underlying) -def png_bytes_to_figure(png_bytes: bytes): - """Create a display-only Matplotlib wrapper for PNG bytes. - - The returned figure contains the rasterized image rather than the - original plot artists. Its DPI and layout exist only to support stable - presentation through Shiny's ``render.plot``. - - Parameters - ---------- - png_bytes : bytes - PNG data to display. - - Returns - ------- - matplotlib.figure.Figure - Decoration-free wrapper containing the complete PNG. - """ - - image = mpimg.imread(io.BytesIO(png_bytes)) - height_px, width_px = image.shape[:2] - display_dpi = 100 - - fig, ax = plt.subplots( - figsize=(width_px / display_dpi, height_px / display_dpi), - dpi=display_dpi, - ) - ax.imshow(image) - ax.axis("off") - fig.subplots_adjust(left=0, right=1, bottom=0, top=1) - - # Keep the image flush with the wrapper during Shiny redraws. - fig.set_layout_engine( - "tight", - pad=0, - h_pad=0, - w_pad=0, - rect=(0, 0, 1, 1), - ) - return fig - - def abbreviate_labels(labels: List[Text], limit: int) -> List[str]: """ Abbreviate a list of matplotlib Text objects.