diff --git a/server/features_server.py b/server/features_server.py index b2207c3..e12e501 100644 --- a/server/features_server.py +++ b/server/features_server.py @@ -1,58 +1,127 @@ +""" +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. +""" + +import tempfile + from shiny import ui, render, reactive -import anndata as ad -import numpy as np -import pandas as pd -import spac.visualization + +# Import plot display utilities. +from utils.plot_utils import fig_to_png_bytes +# 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): - def on_layer_check(): - return input.h1_layer() if input.h1_layer() != "Original" else None + """ + 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(): + """Get the main AnnData object from shared state.""" + return shared['adata_main'].get() + + @reactive.calc + def get_features_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 + 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(), + } + 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 + @render.image(delete_file=True) @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 - ) + """Generate a feature histogram through the SPAC template.""" + adata = get_adata() 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() - - axes = ax if isinstance(ax, (list, np.ndarray)) else [ax] - for a in axes: - a.tick_params(axis='x', rotation=rotation, labelsize=10) + features_inputs = get_features_inputs() + + 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) + + png_bytes = fig_to_png_bytes(fig) + 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 fig1 + 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 5a7c352..000bcde 100644 --- a/utils/plot_utils.py +++ b/utils/plot_utils.py @@ -1,14 +1,48 @@ """ 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.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 abbreviate_labels(labels: List[Text], limit: int) -> List[str]: """ Abbreviate a list of matplotlib Text objects. @@ -61,4 +95,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)