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
151 changes: 110 additions & 41 deletions server/features_server.py
Original file line number Diff line number Diff line change
@@ -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)

Expand Down
2 changes: 1 addition & 1 deletion ui/features_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
40 changes: 37 additions & 3 deletions utils/plot_utils.py
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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)
label.set_fontfamily(fontfamily)