loki2.plot
Helpers for mapping high-dimensional embeddings to low-dimensional coordinates and hex colors for visualization.
Module Contents
- loki2.plot.UMAP = None
- loki2.plot.plot_cell_types(pos: numpy.ndarray, cells: List[Dict[str, Any]], size: float = 0.1, min_count: int = 100, min_fraction: float = 0.01, title: str = 'Loki2 Predicted Cell Types') None
Plot Loki2 cell-type map with a filtered legend.
- The legend only shows categories meeting BOTH:
count >= min_count
fraction >= min_fraction
- Parameters:
pos – Array of shape (N, 2) containing cell positions.
cells – List of cell dictionaries, each containing a ‘type’ key.
size – Scatter point size. Defaults to 0.1.
min_count – Minimum cell count for legend inclusion. Defaults to 100.
min_fraction – Minimum fraction for legend inclusion. Defaults to 0.01.
title – Plot title. Defaults to “Loki2 Predicted Cell Types”.
- loki2.plot.embeddings_to_hex(embeddings: numpy.ndarray, method: str = 'umap', n_components: int = 3, random_state: int | None = None) Tuple[numpy.ndarray, List[str], numpy.ndarray]
Reduce high-dimensional embeddings and map to hex colors using UMAP or PCA.
- Parameters:
embeddings – Array of shape (N, D) with input vectors.
method – ‘umap’ or ‘pca’ to choose reduction algorithm.
n_components – Number of output dimensions (default: 3).
random_state – Seed for reproducibility.
- Returns:
Array of shape (N, n_components) with reduced embeddings. hex_colors:
List of length N containing ‘#RRGGBB’ strings.
- normalized_coords:
Array of shape (N, n_components), each dimension scaled to [0, 1].
- Return type:
coords
- loki2.plot.labels_to_hex(pred: numpy.ndarray, color_dict: Dict[Any, str], default: str = '#808080') numpy.ndarray
Convert label array to hex color array.
- Parameters:
pred – Array of labels.
color_dict – Dictionary mapping labels to hex color strings.
default – Default hex color for unmapped labels. Defaults to “#808080”.
- Returns:
Array of hex color strings with the same shape as pred.
- Return type:
np.ndarray
- loki2.plot.plot_gene(sc_ad: Any, indices: numpy.ndarray, data_morph: Dict[str, Any], gene: str, scatter_size: float = 0.3, perc: float = 0.95, show: bool = True) Any | None
Plot gene expression on spatial coordinates.
- Parameters:
sc_ad – AnnData object containing single-cell data.
indices – Array of indices for matching cells.
data_morph – Dictionary containing ‘positions’ key with spatial coordinates.
gene – Gene name to plot.
scatter_size – Size of scatter points. Defaults to 0.3.
perc – Percentile for vmax normalization. Defaults to 0.95.
show – Whether to display the plot. Defaults to True.
- Returns:
Figure object if show=False, otherwise None.
- Return type:
Optional[Any]
- loki2.plot.scatter_plot(embedding: numpy.ndarray, annotations, *, palette: str | dict | None = 'tab10', invert_y: bool = False, equal_aspect: bool = True, save_path: str | pathlib.Path | None = None, save_dpi: int = 200, figsize: tuple[int, int] | None = (5, 5), dpi: int | None = 150, figure_kwargs: dict | None = None, **kwargs) None
Simple scatter helper that supports numeric, categorical, or per-point colors.
- Parameters:
embedding – Array of shape (N, 2) containing 2D coordinates.
annotations – Array or list of annotations for coloring points. Can be numeric values, categorical labels, or hex color strings.
palette – Color palette name (str) or dictionary mapping labels to colors. Defaults to “tab10”.
invert_y – Whether to invert the y-axis. Defaults to False.
equal_aspect – Whether to set equal aspect ratio. Defaults to True.
save_path – Optional path to save the figure. Defaults to None.
save_dpi – Resolution for saved figure. Defaults to 200.
figsize – Figure size tuple. Defaults to (5, 5).
dpi – Figure resolution. Defaults to 150.
figure_kwargs – Additional keyword arguments for figure creation. Defaults to None.
**kwargs – Additional keyword arguments passed to scatter plot.
- loki2.plot.plot_indices_on_patch(wsi_path: str, egdf: geopandas.GeoDataFrame, idxs: Iterable[int], *, window: Tuple[int, int, int, int] | None = None, pad: int = 50, override_color: Tuple[float, float, float] | str | None = None, clip_to_window: bool = True, eps: float = 0.5, draw: str = 'fill', edge_width: float = 0.6, draw_holes: bool = False, alpha: float = 0.5, title: str | None = None, dpi: int = 150) None
Plot selected cell indices on a WSI patch.
- Parameters:
wsi_path – Path to WSI file.
egdf – GeoDataFrame containing cell geometries and colors.
idxs – Iterable of indices to plot.
window – Optional window coordinates (x, y, w, h). If None, computed from selected geometries. Defaults to None.
pad – Padding around window in pixels. Defaults to 50.
override_color – Optional color to override all polygons. Defaults to None.
clip_to_window – Whether to clip polygons to window. Defaults to True.
eps – Epsilon for geometry operations. Defaults to 0.5.
draw – Drawing mode, “fill” or “edge”. Defaults to “fill”.
edge_width – Edge width when draw=”edge”. Defaults to 0.6.
draw_holes – Whether to draw hole outlines. Defaults to False.
alpha – Transparency value. Defaults to 0.5.
title – Optional plot title. Defaults to None.
dpi – Resolution for output. Defaults to 150.
- Raises:
ValueError – If draw is not “fill” or “edge”.
- loki2.plot.plot_type_legend(egdf: geopandas.GeoDataFrame, color_col: str = 'rgb_norm', label_col: str = 'type', title: str = 'Cell classes', ncol: int | None = None, max_label_chars: int = 32, marker_size: int = 12, frameon: bool = False, sort: bool = True, ax: Any | None = None, savepath: str | pathlib.Path | None = None, dpi: int = 150) Tuple[Any, Any]
Plot a legend for cell types from a GeoDataFrame.
- Parameters:
egdf – GeoDataFrame containing cell type information.
color_col – Column name for colors. Defaults to “rgb_norm”.
label_col – Column name for labels. Defaults to “type”.
title – Legend title. Defaults to “Cell classes”.
ncol – Number of columns in legend. If None, auto-determined. Defaults to None.
max_label_chars – Maximum characters per label. Defaults to 32.
marker_size – Size of legend markers. Defaults to 12.
frameon – Whether to draw frame around legend. Defaults to False.
sort – Whether to sort labels alphabetically. Defaults to True.
ax – Optional matplotlib axes. If None, creates new figure. Defaults to None.
savepath – Optional path to save the legend. Defaults to None.
dpi – Resolution for output. Defaults to 150.
- Returns:
Figure and axes objects.
- Return type:
Tuple[Any, Any]
- loki2.plot.load_attention_df(txt_path: str, case_prefix: str) pandas.DataFrame
Load attention data from text file.
- Parameters:
txt_path – Path to text file containing attention data (TSV format).
case_prefix – Case ID prefix for filtering data.
- Returns:
- DataFrame with X, Y, Attention columns, and log10_Attention
if available.
- Return type:
pd.DataFrame
- Raises:
ValueError – If required columns X/Y/Attention are missing.
- loki2.plot.make_slide_thumbnail(svs_path: str, max_dim: int = 2048) Tuple[Any, Tuple[int, int], Tuple[int, int]]
Generate thumbnail from SVS file.
- Parameters:
svs_path – Path to SVS file.
max_dim – Maximum side length for thumbnail. Defaults to 2048.
- Returns:
thumb: PIL Image thumbnail
(W, H): Original level 0 dimensions
(w, h): Thumbnail dimensions
- Return type:
Tuple[Any, Tuple[int, int], Tuple[int, int]]
- loki2.plot.normalize(v: numpy.ndarray, qmin: float = 1.0, qmax: float = 99.0) numpy.ndarray
Normalize array values to [0, 1] range using percentiles.
- Parameters:
v – Input array.
qmin – Minimum percentile for clipping. Defaults to 1.0.
qmax – Maximum percentile for clipping. Defaults to 99.0.
- Returns:
Normalized array with values in [0, 1].
- Return type:
np.ndarray
- loki2.plot.plot_attention_on_slide(svs_path: str, att_txt: str, case_prefix: str, save_path: pathlib.Path | None = None, max_dim: int = 2048, point_size: float = 8, alpha: float = 0.6, cmap: str = 'rainbow') None
Plot attention heatmap on SVS thumbnail.
Always displays the image. Saves the image if save_path is provided.
- Parameters:
svs_path – Path to SVS file.
att_txt – Path to attention data text file.
case_prefix – Case ID prefix for filtering data.
save_path – Optional path to save the figure. Defaults to None.
max_dim – Maximum dimension for thumbnail. Defaults to 2048.
point_size – Size of scatter points. Defaults to 8.
alpha – Transparency of scatter points. Defaults to 0.6.
cmap – Colormap name. Defaults to “rainbow”.
- loki2.plot.TYPE_MAP_JSON
- loki2.plot.COLOR_DICT: dict[int, list[int]]
- loki2.plot.COLOR_DICT_FLOAT: dict[int, numpy.ndarray]
- loki2.plot.COLOR_DICT_NORM
- loki2.plot.max_code
- loki2.plot.color_list
- loki2.plot.LOKI2_CMAP
- loki2.plot.bounds
- loki2.plot.norm
- loki2.plot.SC_COLOR_DICT