Python API#
cytodataframe.frame#
Defines a CytoDataFrame class.
- class src.cytodataframe.frame.CytoDataFrame(data: CytoDataFrame_type | DataFrame | str | Path, data_context_dir: str | None = None, data_image_paths: DataFrame | None = None, data_bounding_box: DataFrame | None = None, compartment_center_xy: DataFrame | bool | None = None, data_mask_context_dir: str | None = None, data_outline_context_dir: str | None = None, segmentation_file_regex: Dict[str, str] | None = None, image_adjustment: Callable | None = None, display_options: Dict[str, Any] | None = None, *args: Any, **kwargs: Dict[str, Any])[source]#
Bases:
DataFrameA class designed to enhance single-cell data handling by wrapping pandas DataFrame capabilities, providing advanced methods for quality control, comprehensive analysis, and image-based data processing.
This class can initialize with either a pandas DataFrame or a file path (CSV, TSV, TXT, or Parquet). When initialized with a file path, it reads the data into a pandas DataFrame. It also includes capabilities to export data.
- _metadata#
A class-level attribute that includes custom attributes.
- Type:
ClassVar[list[str]]
- _custom_attrs#
A dictionary to store custom attributes, such as data source, context directory, and bounding box information.
- Type:
dict
- _DEFAULT_TABLE_MAX_HEIGHT: ClassVar[str] = '700px'#
- _HTML_3D_STUB_KEY: ClassVar[str] = '_cyto_3d_html_stub'#
- _add_label_overlay_to_plotter(plotter: Any, volume: ndarray, label_volume: ndarray | None, spacing: Tuple[float, float, float], base_sample: float, display_options: dict[str, Any]) List[Any][source]#
Add a 3D label overlay to an existing PyVista plotter.
- Parameters:
plotter – Target PyVista plotter receiving overlay actors.
volume – Source image volume in
(z, y, x)order.label_volume – Optional label/mask volume aligned to
volume.spacing – Voxel spacing tuple used when building label image data.
base_sample – Base sampling distance used for volume overlays.
display_options – Display options controlling overlay mode/style.
- Returns:
A list of added overlay actor objects.
- _add_label_overlay_toggle_control(plotter: Any, overlay_actors: List[Any], display_options: dict[str, Any]) None[source]#
Add a PyVista checkbox widget to toggle label overlay visibility.
- static _as_rgb(image: ndarray) ndarray[source]#
Return an
(H, W, 3)RGB view of a grayscale/RGB/RGBA array.
- _build_channel_composite_array(row: Any, channel_specs: Sequence[Tuple[Any, Tuple[int, int, int]]], bounding_box: Tuple[int, int, int, int] | None, compartment_center_xy: Tuple[int, int] | None, image_path_cols: Dict[Any, Any]) ndarray | None[source]#
Build a merged, color-tinted composite crop from several channels.
Each channel is cropped to the same single-cell region using the same pipeline as the individual channel columns, so the composite is always the same size as the other images. The clean (pre-overlay) crop of each channel is converted to a grayscale intensity, tinted by the channel’s color, and additively blended (Fiji-style). The segmentation outline and red center dot that appear on the individual channels (when configured) are then laid back on top of the blended result so the composite matches the other images. Returns an
(H, W, 3)uint8 array, or None when no channel could be rendered.
- static _build_composite_legend_html(channel_specs: Sequence[Tuple[Any, Tuple[int, int, int]]]) str[source]#
Build a small color legend for a merged channel composite.
Shows which channel maps to which color so the composite (including the auto-colored
"all"form) can be interpreted and captioned. Returns an empty string when there are no composite channels.
- static _build_filter_distribution_html(values: Series, selected_range: Tuple[float, float], threshold_x: float | None = None, slider_values: Sequence[float] | None = None, y_scale: str = FILTER_PLOT_Y_SCALE_DEFAULT, y_min_percentile: float = FILTER_PLOT_Y_MIN_PERCENTILE_DEFAULT, y_max_percentile: float = FILTER_PLOT_Y_MAX_PERCENTILE_DEFAULT, y_gamma: float = FILTER_PLOT_Y_GAMMA_DEFAULT, y_tail_log_scale: float = FILTER_PLOT_Y_TAIL_LOG_SCALE_DEFAULT, size_px: Tuple[int, int] = (FILTER_SLIDER_TOTAL_WIDTH_PX, 96), track_padding_px: Tuple[int, int] = (FILTER_SLIDER_LABEL_WIDTH_PX, FILTER_SLIDER_READOUT_WIDTH_PX)) str[source]#
Build an inline SVG area/line plot for filter-value counts.
- _build_filter_slider_control_for_column(filter_col: Any) Tuple[Any | None, Any | None][source]#
Return one filter slider and its display control widget.
- _build_filter_slider_controls() Tuple[List[Any], List[Any]][source]#
Return slider widgets and filter controls for all configured columns.
- _build_pyvista_viewer(volume: ndarray, backend: str, widget_height: str, spacing: Tuple[float, float, float] = (1.0, 1.0, 1.0), opacity: Any = 'sigmoid', shade: bool = False, label_volume: ndarray | None = None, include_plotter_overlay_toggle: bool = True, **kwargs: Any) Any[source]#
- _build_result_cdf(data: CytoDataFrame | DataFrame | Series | Any, *args: Any, **kwargs: Dict[str, Any]) CytoDataFrame_type[source]#
Construct a result frame while preserving CytoDataFrame metadata.
- property _constructor: Callable[[...], CytoDataFrame_type]#
Return a constructor that preserves CytoDataFrame display state.
- _enbable_debug_mode() None[source]#
Enable debug mode for the CytoDataFrame instance. This method sets the logger level to DEBUG and enables debug mode for the instance.
- _enqueue_snapshot_tasks(rows: List[Any], columns: List[Any]) None[source]#
Placeholder hook for async snapshot pre-rendering.
TODO: Add optional background workers to precompute _snapshot_cache entries for the provided rows/columns when async rendering is enabled.
- _ensure_filter_range_slider(filter_col: Any | None = None) Any | None[source]#
Build or refresh one range slider for row filtering.
- static _ensure_uint8(array: ndarray) ndarray[source]#
Convert the provided array to uint8 without unnecessary warnings.
- _extract_array_from_ome_arrow(data_value: Any) ndarray | None[source]#
Convert an OME-Arrow struct (dict) into an ndarray.
- _filter_display_indices_by_widget_range(data: DataFrame, display_indices: List[Any]) List[Any][source]#
Filter row labels by all configured slider ranges.
- _find_3d_columns_for_display(max_rows: int = 5) List[Any][source]#
Find columns that contain at least one renderable 3D value.
- static _find_bbox_col_by_substring(bbox_cols: Sequence[Any], tag: str) Any | None[source]#
Find the first bbox column containing
tagas a substring.
- static _find_matching_segmentation_in_dirs(data_value: str, pattern_map: dict | None, candidate_path: Path, file_dirs: Sequence[str | None]) Path | None[source]#
Find the first matching segmentation path across ordered directories.
- Parameters:
data_value – Raw image value from the table row.
pattern_map – Optional regex mapping from segmentation filename patterns to source image patterns.
candidate_path – Best-effort resolved source image path.
file_dirs – Ordered directories to search for segmentation files.
- Returns:
The first matching segmentation file path, or
Nonewhen no match is found in any directory.
- static _find_matching_segmentation_path(data_value: str, pattern_map: dict | None, file_dir: str | None, candidate_path: Path) Path | None[source]#
Resolve a mask/outline file path for an image value.
- Parameters:
data_value – Raw image value from the table row.
pattern_map – Optional regex mapping from segmentation filename patterns to source image patterns. When provided, this method extracts identifiers from
data_valuewith eachoriginal_patternand finds files whose names match the correspondingfile_patternand include one of those identifiers.file_dir – Root directory containing mask/outline files.
candidate_path –
Best-effort resolved source image path returned by
_resolve_volume_candidate. Used as a fallback identifier in regex mode and as the primary stem in non-regex mode.Example (no
pattern_map): Ifcandidate_pathis.../images/plateA/well_B03/site_1.tif, the function looks for files underfile_dirthat start withsite_1.Example (with
pattern_map): Ifdata_valueisplateA/well_B03/site_1.tifandcandidate_pathis the resolved on-disk path to the same image, regex captures fromdata_valueare tried first, then stems from bothdata_valueandcandidate_pathare used as fallback identifiers.
- Returns:
The first matching segmentation file path, or
Nonewhen no match is found.
- static _fit_to_shape(image: ndarray, target_shape: Tuple[int, int], smooth: bool) ndarray[source]#
Resize
imagetotarget_shape(height, width) as uint8.Used to place each channel of a merged composite onto a shared canvas so the composite is always the same size as the other images.
smoothselects bilinear (for intensity) vs. nearest-neighbor (to keep outlines and the center dot crisp) interpolation. Returns the input unchanged when it already matchestarget_shape.
- static _format_filter_slider_label(value: float) str[source]#
Format displayed slider labels with two decimals for float values.
- _generate_jupyter_dataframe_html() str[source]#
Returns HTML representation of the underlying pandas DataFrame for use within Juypyter notebook environments and similar.
Referenced with modifications from: pandas-dev/pandas
Modifications added to help achieve image-based output for single-cell data within the context of CytoDataFrame and coSMicQC.
Mainly for Jupyter notebooks.
- Returns:
The data in a pandas DataFrame.
- Return type:
str
- _generate_trame_snapshot_html() str[source]#
Generate a static HTML table with PyVista 3D snapshots.
- _get_3d_bbox_crop_bounds(row: Any, volume_shape: Tuple[int, ...]) Tuple[int, int, int, int, int, int] | None[source]#
Return clamped 3D bbox crop bounds.
- Parameters:
row – Row label or index used to read bounding-box metadata.
volume_shape –
(z, y, x)shape of the source volume.
- Returns:
A tuple of
(x_min, x_max, y_min, y_max, z_min, z_max)bounds, orNonewhen bounding-box columns are unavailable or cropping is disabled.CellProfiler
AreaShape_BoundingBox...columns are preferred when available. Non-CellProfiler schemas can be mapped explicitly throughdisplay_options["volume_bbox_column_map"]with keys:x_min,x_max,y_min,y_max, and optionallyz_min/z_max.
- _get_3d_label_overlay_from_cell(row: Any, column: Any, expected_shape: Tuple[int, ...]) ndarray | None[source]#
Build a 3D label overlay for a specific table cell.
- Parameters:
row – Row label or index containing the 3D image value.
column – Column label containing the 3D image value.
expected_shape – Target
(z, y, x)shape for the overlay.
- Returns:
A uint8 binary label volume aligned to
expected_shapewhen a compatible mask/outline can be found; otherwiseNone.
- _get_filter_slider_columns() List[Any][source]#
Return configured filter columns, preserving user-specified order.
- _get_image_display_cache() Tuple[OrderedDict[Tuple[str, int], ndarray], bool, int][source]#
Return the 2D image cache plus its disabled flag and size limit.
The cache stores decoded + contrast-enhanced full field-of-view images. It can be turned off with the
image_disable_cachedisplay option and bounded withimage_cache_max_entries(default 32).
- _get_raw_filter_plot_threshold(filter_col: Any) Tuple[bool, Any | None][source]#
Return whether threshold was configured and its raw value.
- static _hex_to_rgb(value: str) Tuple[int, int, int] | None[source]#
Convert a
#RGBor#RRGGBBhex string to an(r, g, b)tuple.Returns None when the string is not a valid 3- or 6-digit hex color.
- static _is_ome_arrow_value(value: Any) bool[source]#
Check whether a value looks like an OME-Arrow struct.
- _load_enhanced_image_for_display(candidate_path: Path, data_value: str, pattern_map: dict | None, layers: Dict[str, ndarray | None]) ndarray | None[source]#
Load and contrast-enhance a 2D field-of-view image, with caching.
Reading a TIFF and running adaptive histogram equalization are the most expensive steps in rendering, and the same field-of-view image is often shared by many displayed objects (and re-processed on every re-render, e.g. brightness/filter changes). Results are therefore cached by (resolved path, brightness, equalize clip limit) so that work happens once per unique image and recomputes when any of those inputs change.
The returned array is always a private copy that the caller may mutate freely (e.g. drawing a center dot) without corrupting the cache.
For 3D inputs, this populates
layerswith the appropriate 3D HTML view/stub and returnsNone. It also returnsNonewhen decoding fails. In both cases the caller should stop and returnlayers.
- static _match_channel_column(identifier: Any, image_cols: Sequence[Any]) Any[source]#
Match a user-provided channel identifier to an image column.
Matching is attempted, in order, by: exact column name, the channel suffix following
FileName_(or the final underscore) and finally a case-insensitive substring. Returns the matched column or None.
- _metadata: ClassVar = ['_custom_attrs']#
- static _normalize_css_width(width: Any) Any[source]#
Normalize a bare numeric width to a CSS pixel string.
Integer/float widths (e.g.
300) and pure-numeric strings (e.g."300") become"300px"so they emit valid CSS and participate in the min-width floor. Values already carrying a unit or keyword (e.g."300px","100%","auto") are returned unchanged.
- static _normalize_labels(labels: Index) Tuple[Index, Dict[str, Any]][source]#
Return (labels_as_str: pd.Index, backmap: dict[str, Any])
- _on_filter_slider_change(change: Dict[str, Any]) None[source]#
Update widget filter state when the selection range changes.
- _on_slider_change(change: Dict[str, Any]) None[source]#
Callback triggered when the image brightness/contrast slider is adjusted.
This method updates the internal _widget_state to reflect the new slider value, clears the current output display, and triggers a re-render of the CytoDataFrame’s HTML representation (including image thumbnails) based on the new scale setting.
- Parameters:
change (dict) – A dictionary provided by the ipywidgets observer mechanism. Expected to contain a ‘new’ key representing the updated slider value.
- _prepare_3d_label_overlay(segmentation_path: Path, expected_shape: Tuple[int, ...], row: Any | None = None) ndarray | None[source]#
Load and normalize a 3D segmentation image for volume overlays.
- Parameters:
segmentation_path – Path to the mask/outline image file.
expected_shape – Expected
(z, y, x)array shape.row – Optional row label/index used to apply 3D bounding-box cropping.
- Returns:
A uint8 binary array (0/255) matching
expected_shape, orNonewhen loading or shape validation fails.
- _prepare_cropped_image_array(data_value: Any, bounding_box: Tuple[int, int, int, int], compartment_center_xy: Tuple[int, int] | None = None, image_path: str | None = None) Tuple[ndarray | None, str | None][source]#
- _prepare_cropped_image_layers(data_value: Any, bounding_box: Tuple[int, int, int, int], compartment_center_xy: Tuple[int, int] | None = None, image_path: str | None = None, include_original: bool = False, include_mask_outline: bool = False, include_composite: bool = True) Dict[str, ndarray | None][source]#
Return requested cropped image layers for downstream consumers.
- _pyvista_volume_snapshot_html(volume: ndarray, dims: Tuple[int, int, int], label_volume: ndarray | None = None) str | None[source]#
Render a static PyVista snapshot for a 3D volume.
- Parameters:
volume – Source volume in
(z, y, x)order.dims – Declared vtk dimensions for the volume.
label_volume – Optional binary label volume aligned to
volume.
- Returns:
A PNG-backed
<img>HTML string, orNoneif snapshot rendering cannot be completed.
- _render_notebook_widget_output(display_options: dict[str, Any]) None[source]#
Render ipywidgets controls and the notebook HTML table output.
- _repr_html_(debug: bool = False) str[source]#
Returns HTML representation of the underlying pandas DataFrame for use within Juypyter notebook environments and similar.
We modify this to be a delivery mechanism for ipywidgets in order to dynamically adjust the dataframe display within Jupyter environments.
Mainly for Jupyter notebooks.
- Returns:
The data in a pandas DataFrame.
- Return type:
str
- static _resolve_3d_bbox_columns(bbox_cols: Sequence[Any], display_options: dict[str, Any]) Tuple[Any | None, Any | None, Any | None, Any | None, Any | None, Any | None][source]#
Resolve bbox columns with custom, CP, then substring matching.
- static _resolve_bbox_columns_from_cp_convention(bbox_cols: Sequence[Any]) Tuple[Any | None, Any | None, Any | None, Any | None, Any | None, Any | None][source]#
Resolve bbox columns using preferred CellProfiler AreaShape names.
- static _resolve_bbox_columns_from_custom_map(bbox_cols: Sequence[Any], custom_map: dict[str, Any]) Tuple[Any | None, Any | None, Any | None, Any | None, Any | None, Any | None][source]#
Resolve bbox columns from display_options custom mapping.
- _resolve_cache_settings(cache_attr: str, disable_option: str, max_entries_option: str, default_max_entries: int = 32) Tuple[OrderedDict[Any, Any], bool, int][source]#
Resolve a display cache and its disabled flag / size limit.
Shared by the 2D image cache and the 3D volume cache so both read their display options, normalize the max-entries value, and wrap any existing cache into an
OrderedDictthe same way.- Parameters:
cache_attr –
_custom_attrskey holding the cache mapping.disable_option – display option that disables the cache when truthy.
max_entries_option – display option overriding the LRU size limit.
default_max_entries – size limit used when the option is unset/invalid.
- Returns:
(cache, disabled, max_entries). When disabled, a throwaway emptyOrderedDictis returned and_custom_attrsis left untouched; callers guard all cache access withdisabled.
- _resolve_composite_channels(image_cols: Sequence[Any]) List[Tuple[Any, Tuple[int, int, int]]][source]#
Resolve the
composite_channelsdisplay option to ordered channel columns paired with the RGB color used to tint each channel.The option may be: -
"all": use every image channel column, colored from the defaultpalette in column order.
a list of channel identifiers: use those channels (color from the default palette in the given order).
a mapping of
{identifier: color}: use those channels with the specified colors (named color or RGB tuple).colormay be None to fall back to the default palette.
- static _resolve_composite_color(value: Any) Tuple[int, int, int] | None[source]#
Resolve a channel color specification to an
(r, g, b)tuple.Accepts a named color (e.g.
"blue"), a hex string (e.g."#0000ff"or"#00f"), or an explicit RGB sequence (e.g.(0, 0, 255)or[0, 0, 255]). Returns None when the value cannot be understood as a color.
- _resolve_filter_plot_threshold(filter_col: Any, values: Series) float | None[source]#
Resolve an optional threshold marker for a filter-column distribution.
- static _resolve_image_min_width(width: Any) str | None[source]#
Return a CSS
min-widthfloor for a displayed image, or None.Only explicit pixel widths larger than
IMAGE_MIN_DISPLAY_WIDTH_PXget a floor (so custom small/auto widths stay fully responsive). SeeIMAGE_MIN_DISPLAY_WIDTH_PXfor why the floor exists.
- static _resolve_overlay_toggle_position(plotter: Any, display_options: dict[str, Any], size: int) Tuple[int, int][source]#
Resolve checkbox position in display pixels (default lower-right).
- static _resolve_plotter_window_height(plotter: Any, display_options: dict[str, Any]) int[source]#
Resolve plotter pixel height for viewport text placement.
- _resolve_volume_candidate(raw_value: str | Path) Tuple[str, Path][source]#
Resolve normalized 3D image value and best-effort candidate path.
- Parameters:
raw_value – Raw path-like cell value for a 3D image.
- Returns:
A tuple of
(data_value, candidate_path)wheredata_valueis normalized for context-dir lookups andcandidate_pathpoints to a best-effort on-disk match when available.
- _return_cytodataframe(method: Callable, method_name: str, *args: Any, **kwargs: Dict[str, Any]) Any[source]#
Wraps a given method to ensure that the returned result is an CytoDataFrame if applicable.
- Parameters:
method (Callable) – The method to be called and wrapped.
method_name (str) – The name of the method to be wrapped.
*args (Any) – Positional arguments to be passed to the method.
**kwargs (Dict[str, Any]) – Keyword arguments to be passed to the method.
- Returns:
The result of the method call. If the result is a pandas DataFrame, it is wrapped in an CytoDataFrame instance with additional context information (data context directory and data bounding box).
- Return type:
Any
- static _row_bounding_box(row: Any, bounding_box_cols: Sequence[Any]) Tuple[Any, Any, Any, Any][source]#
Build a
(x_min, y_min, x_max, y_max)bounding box tuple from a row.Bounding box columns are matched by substring so the underlying column order does not matter.
- Parameters:
row (Any) – A row (mapping of column name to value) to read values from.
bounding_box_cols (Sequence[Any]) – The bounding box column names to match against.
- Returns:
The
(x_min, y_min, x_max, y_max)bounding box values.- Return type:
Tuple[Any, Any, Any, Any]
- static _set_overlay_actor_visibility(actor: Any, visible: bool) None[source]#
Set visibility for supported actor object variants.
- _show_output_loading_indicator(message: str = 'Updating table...') None[source]#
Render a lightweight loading indicator in the output area.
- static _slider_relative_position(value: float, slider_domain: ndarray) float[source]#
Map a numeric value to SelectionRangeSlider’s normalized track position.
- _toggle_overlay_actors_visibility(plotter: Any, overlay_actors: List[Any], visible: bool) None[source]#
Toggle all overlay actors and trigger a render.
- _try_render_trame_widget_table(debug: bool, display_options: dict[str, Any]) bool[source]#
Try rendering the trame widget table and return
Trueon success.
- _wrap_method(method_name: str) Callable[source]#
Creates a wrapper for the specified method to ensure it returns a CytoDataFrame.
This method dynamically wraps a given method of the CytoDataFrame class to ensure that the returned result is a CytoDataFrame instance, preserving custom attributes.
- Parameters:
method_name (str) – The name of the method to wrap.
- Returns:
The wrapped method that ensures the result is a CytoDataFrame.
- Return type:
Callable
- _wrap_methods() None[source]#
Method to wrap extended Pandas DataFrame methods so they return a CytoDataFrame instead of a Pandas DataFrame.
- export(file_path: str, **kwargs: Dict[str, Any]) None[source]#
Exports the underlying pandas DataFrame to a file.
- Parameters:
file_path (str) – The path where the DataFrame should be saved.
**kwargs – Additional keyword arguments to pass to the pandas to_* methods.
- find_image_columns() List[str][source]#
Find columns containing image file names.
This method searches for columns in the DataFrame that contain image file names with extensions .tif or .tiff (case insensitive).
- Performance note:
Single-cell profiles typically have thousands of numeric feature columns and only a handful of image-name columns. Scanning every value of every column on each render is expensive, so columns whose dtype cannot hold a filename string (numeric, boolean, datetime) are skipped before the per-value regex check.
- Returns:
A list of column names that contain image file names.
- Return type:
List[str]
- find_image_path_columns(image_cols: List[str], all_cols: List[str]) Dict[str, str][source]#
Find columns containing image path names (the directory storing the images but not the file names). We do this by seeking the pattern: Image_FileName_X –> Image_PathName_X.
- Parameters:
image_cols – List[str]: A list of column names that contain image file names.
all_cols – List[str]: A list of all column names.
- Returns:
A list of column names that contain image file names.
- Return type:
Dict[str, str]
- find_ome_arrow_columns(data: DataFrame) List[str][source]#
Identify columns that contain OME-Arrow structs.
- get_bounding_box_from_data() CytoDataFrame_type | None[source]#
Retrieves bounding box data from the DataFrame based on predefined column groups.
This method identifies specific groups of columns representing bounding box coordinates for different cellular components (cytoplasm, nuclei, cells). If those are not present, it falls back to a generic AreaShape bounding box. If all required columns are present, it filters and returns a new CytoDataFrame instance containing only these columns.
- Returns:
A new instance of CytoDataFrame containing the bounding box columns if they exist in the DataFrame. Returns None if the required columns are not found.
- Return type:
Optional[CytoDataFrame_type]
- get_compartment_center_xy_from_data() CytoDataFrame_type | None[source]#
Retrieves compartment center xy data from the DataFrame based on predefined column groups.
This method identifies specific groups of columns representing center xy coordinates for different cellular components (cytoplasm, nuclei, cells) and checks for their presence in the DataFrame. If all required columns are present, it filters and returns a new CytoDataFrame instance containing only these columns.
- Returns:
A new instance of CytoDataFrame containing the bounding box columns if they exist in the DataFrame. Returns None if the required columns are not found.
- Return type:
Optional[CytoDataFrame_type]
- get_displayed_rows() List[int][source]#
Get the indices of the rows that are currently displayed based on the pandas display settings.
- Returns:
A list of indices of the rows that are currently displayed.
- Return type:
List[int]
- get_image_paths_from_data(image_cols: List[str]) Dict[str, str][source]#
Gather data containing image path names (the directory storing the images but not the file names). We do this by seeking the pattern: Image_FileName_X –> Image_PathName_X.
- Parameters:
image_cols – List[str]: A list of column names that contain image file names.
- Returns:
A list of column names that contain image file names.
- Return type:
Dict[str, str]
- static is_notebook_or_lab() bool[source]#
Determines if the code is being executed in a Jupyter notebook (.ipynb) returning false if it is not.
This method attempts to detect the interactive shell environment using IPython’s get_ipython function. It checks the class name of the current IPython shell to distinguish between different execution environments.
- Returns:
- True
if the code is being executed in a Jupyter notebook (.ipynb).
- False
otherwise (e.g., standard Python shell, terminal IPython shell, or scripts).
- Return type:
bool
- process_channel_composite_as_html_display(row: Any, channel_specs: Sequence[Tuple[Any, Tuple[int, int, int]]], bounding_box: Tuple[int, int, int, int] | None, compartment_center_xy: Tuple[int, int] | None, image_path_cols: Dict[Any, Any]) str[source]#
Render a merged multi-channel composite crop for a row as HTML.
Returns an HTML
<img>string for the blended composite, or an empty string when no channel could be rendered for the row.
- process_image_data_as_html_display(data_value: Any, bounding_box: Tuple[int, int, int, int], compartment_center_xy: Tuple[int, int] | None = None, image_path: str | None = None) str[source]#
Process the image data based on the provided data value and bounding box, applying masks or outlines where applicable, and return an HTML representation of the cropped image for display.
- Parameters:
data_value (Any) – The value to search for in the file system or as the image data.
bounding_box (Tuple[int, int, int, int]) – The bounding box to crop the image.
compartment_center_xy (Optional[Tuple[int, int]]) – The center coordinates of the compartment.
image_path (Optional[str]) – The path to the image file.
- Returns:
The HTML image display string, or the unmodified data value if the image cannot be processed.
- Return type:
str
- process_ome_arrow_data_as_html_display(data_value: Any) str[source]#
Render an OME-Arrow struct as an HTML <img> element.
- search_for_mask_or_outline(data_value: str, pattern_map: dict, file_dir: str, candidate_path: Path, orig_image: ndarray, mask: bool = True) Tuple[ndarray | None, Path | None][source]#
Search for a mask or outline image file based on the provided patterns and apply it to the target image.
- Parameters:
data_value (str) – The value used to match patterns for locating mask or outline files.
pattern_map (dict) – A dictionary of file patterns and their corresponding original patterns for matching.
file_dir (str) – The directory where image files are stored.
candidate_path (pathlib.Path) – The path to the candidate image file to apply the mask or outline to.
orig_image (np.ndarray) – The image which will have a mask or outline applied.
mask (bool, optional) – Whether to search for a mask (True) or an outline (False). Default is True.
- Returns:
The target image with the applied mask or outline, or None if no relevant file is found.
- Return type:
np.ndarray
- show_trame(row: Any, column: Any, backend: str | None = 'trame', **kwargs: Any) Any[source]#
Render the dataframe HTML with a trame-backed 3D view.
- Parameters:
row – Row label or index of the 3D cell.
column – Column label containing the 3D data.
backend – PyVista Jupyter backend name.
**kwargs – Extra options forwarded to the viewer builder.
- Returns:
A trame layout when available, otherwise an ipywidgets container.
- show_widget_table(column: Any, rows: List[Any] | None = None, backend: str | None = 'trame', **kwargs: Any) Any[source]#
Render a widget-based table with 3D views embedded in columns.
Use
table_height(ortable_max_height) to override the default notebook table height.Row rendering follows pandas display limits. If the DataFrame is larger than
display.max_rows, the widget table inserts a midpoint ellipsis marker row (…) to indicate omitted rows.
cytodataframe.image#
Helper functions for working with images in the context of CytoDataFrames.
- src.cytodataframe.image.add_image_scale_bar(img: ndarray, um_per_pixel: float, *, length_um: float = 10.0, thickness_px: int = 4, color: Tuple[int, int, int] = (255, 255, 255), location: str = 'lower right', margin_px: int = 10, **_: Dict[Any, Any]) ndarray[source]#
Add a scale bar to the lower or upper corner of an image.
The function overlays a solid rectangular scale bar onto a grayscale, RGB, or RGBA image. The bar’s physical length in micrometers is converted to pixels using the provided microns-per-pixel value. Non-finite or out-of-range input values are sanitized before drawing.
- Parameters:
img (np.ndarray) – Input image, either 2-D grayscale or 3-D RGB/RGBA.
um_per_pixel (float) – Micrometers per pixel. If None or ≤ 0, the image is returned unchanged.
length_um (float, optional) – Desired length of the scale bar in micrometers. Defaults to 10.0.
thickness_px (int, optional) – Thickness of the bar in pixels. Defaults to 4.
color (Tuple[int, int, int], optional) – RGB color of the bar. Defaults to white
(255, 255, 255).location (str, optional) – Placement of the bar:
"lower right","lower left","upper right", or"upper left". Defaults to"lower right".margin_px (int, optional) – Distance in pixels between the bar and the image edges. Defaults to 10.
**_ (Dict[Any, Any]) – Additional keyword arguments ignored for forward compatibility.
- Returns:
A new RGB image with the scale bar drawn. The array is always of type
uint8and has shape(H, W, 3).- Return type:
np.ndarray
- Raises:
ValueError – If the input image has an unsupported number of channels.
Notes
The bar length is clamped to fit within image bounds after margins. The function does not rely on
skimage.colorand is safe against NaN or Inf input values.
- src.cytodataframe.image.adjust_image_brightness(image: Image) Image[source]#
Adjust the brightness of an image using histogram equalization.
- Parameters:
image (Image) – The input PIL Image.
- Returns:
The brightness-adjusted PIL Image.
- Return type:
Image
- src.cytodataframe.image.adjust_with_adaptive_histogram_equalization(image: ndarray, brightness: int = 50, clip_limit: float | None = None) ndarray[source]#
Adaptive histogram equalization with brightness and contrast tuning via gamma.
- Parameters:
image (np.ndarray) – Input image.
brightness (int) – 0 = dark, 50 = neutral, 100 = bright.
clip_limit (Optional[float]) – Contrast clip limit passed to
skimage.exposure.equalize_adapthist. When None (default), the clip limit is derived frombrightness. Provide a small value (e.g.0.01) for a milder, less over-saturated equalization, which is often preferable for merged channel composites.
- Returns:
Adjusted image.
- Return type:
np.ndarray
- src.cytodataframe.image.draw_outline_on_image_from_mask(orig_image: ndarray, mask_image_path: str, outline_color: tuple = (0, 255, 0)) ndarray[source]#
Draws green outlines on an image based on a binary mask and returns the combined result.
Please note: masks are inherently challenging to use when working with multi-compartment datasets and may result in outlines that do not pertain to the precise compartment. For example, if an object mask overlaps with one or many other object masks the outlines may not differentiate between objects.
- Parameters:
orig_image (np.ndarray) – Image which a mask will be applied to. Must be a NumPy array.
mask_image_path (str) – Path to the binary mask image file.
outline_color (tuple) – RGB color for the outline (default: green).
- Returns:
The resulting image with the green outline applied.
- Return type:
np.ndarray
- src.cytodataframe.image.draw_outline_on_image_from_outline(orig_image: ndarray, outline_image_path: str, outline_color: tuple = (0, 255, 0)) ndarray[source]#
Draws green outlines on an image based on a provided outline image and returns the combined result.
- Parameters:
orig_image (np.ndarray) – The original image on which the outlines will be drawn. It must be a grayscale or RGB image with shape (H, W) for grayscale or (H, W, 3) for RGB.
outline_image_path (str) – The file path to the outline image. This image will be used to determine the areas where the outlines will be drawn. It can be grayscale or RGB.
outline_color (tuple) – RGB color for the outline (default: green).
- Returns:
The original image with green outlines drawn on the non-black areas from the outline image. The result is returned as an RGB image with shape (H, W, 3).
- Return type:
np.ndarray
- src.cytodataframe.image.get_pixel_bbox_from_offsets(center_x: float, center_y: float, rel_bbox: tuple[int, int, int, int]) tuple[int, int, int, int][source]#
Compute a pixel bbox given a center point and pixel offsets.
- Parameters:
center_x – Center x-coordinate in pixels.
center_y – Center y-coordinate in pixels.
rel_bbox – 4-tuple of pixel offsets: (dx_min, dy_min, dx_max, dy_max)
- Returns:
A 4-tuple (x_min, x_max, y_min, y_max), where x_min and y_min are clamped to be ≥ 0. x_max and y_max are returned as-is.
- src.cytodataframe.image.image_array_to_grayscale(img_array: ndarray) ndarray[source]#
Convert an image array to a 2D grayscale array.
Supports single-channel grayscale (2D or
(H, W, 1)), RGB ((H, W, 3)), and RGBA ((H, W, 4)) inputs. Microscopy images are frequently single-channel, so handling those without error is important for real-world stability.- Parameters:
img_array (np.ndarray) – The input image array.
- Returns:
A 2D grayscale array.
- Return type:
np.ndarray
- Raises:
ValueError – If the array does not have a supported channel layout.
- src.cytodataframe.image.is_image_too_dark(image: Image, pixel_brightness_threshold: float = 10.0) bool[source]#
Check if the image is too dark based on the mean brightness. By “too dark” we mean not as visible to the human eye.
- Parameters:
image (Image) – The input PIL Image.
threshold (float) – The brightness threshold below which the image is considered too dark.
- Returns:
True if the image is too dark, False otherwise.
- Return type:
bool