diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py index dc2ec4c99e4..4a340aeccff 100644 --- a/marimo/_plugins/ui/_impl/plotly.py +++ b/marimo/_plugins/ui/_impl/plotly.py @@ -1,8 +1,12 @@ # Copyright 2026 Marimo. All rights reserved. from __future__ import annotations +import datetime import json +import math import numbers +import re +from functools import cached_property from typing import ( TYPE_CHECKING, Any, @@ -23,6 +27,8 @@ if TYPE_CHECKING: from collections.abc import Callable + import numpy as np + import numpy.typing as npt import plotly.graph_objects as go # type:ignore # Selection is a dictionary of the form: @@ -44,126 +50,186 @@ PlotlySelection = dict[str, JSONType] -def _is_orderable_value(value: object) -> bool: - """Check if a value is orderable (numeric or datetime-like). - - Used by fallback functions to determine if direct comparison is possible. - """ - import datetime - - if isinstance(value, (int, float, datetime.datetime, datetime.date)): - return True - - # Check for ISO format datetime strings (sent from frontend via JSON) +def _axis_coordinate(value: Any) -> Any: if isinstance(value, str): try: - datetime.datetime.fromisoformat(value) - return True - except (ValueError, AttributeError): - pass + return datetime.datetime.fromisoformat(value) + except ValueError: + return value + if isinstance(value, datetime.date) and not isinstance( + value, datetime.datetime + ): + return datetime.datetime.combine(value, datetime.time()) + return value - return False +def _is_numpy_datetime(value: object) -> bool: + return getattr(getattr(value, "dtype", None), "kind", None) == "M" -def _parse_datetime_bound(value: Any) -> Any: - """Parse a bound value that might be a datetime string from the frontend. - Returns the original value if it's already a datetime or not a valid - datetime string. - """ - import datetime +_SUBMICROSECOND_DIGITS = re.compile(r"^[\dW-]+\D[\d:]+[.,]\d{6}(\d+)") - if isinstance(value, (datetime.datetime, datetime.date)): - return value - if isinstance(value, str): - try: - return datetime.datetime.fromisoformat(value) - except (ValueError, AttributeError): - pass +def _coordinate_parts(value: Any) -> tuple[Any, str]: + """Keep fractional digits that datetime.fromisoformat would truncate.""" + # A pandas Timestamp can carry nanoseconds beyond datetime.microsecond. + if isinstance(value, datetime.datetime) and getattr( + value, "nanosecond", None + ): + value = value.isoformat() + coordinate = _axis_coordinate(value) + if isinstance(value, str) and isinstance(coordinate, datetime.datetime): + fraction = _SUBMICROSECOND_DIGITS.match(value) + if fraction: + return coordinate, fraction[1].rstrip("0") + return coordinate, "" - return value +def _as_datetime64(value: Any, fraction: str) -> np.datetime64: + import numpy as np -def _is_orderable_axis(arr: Any, bound_value: object) -> bool: - """Check if an axis contains orderable (numeric/datetime) values. + if isinstance(value, datetime.datetime): + value = value.replace(tzinfo=None) + if fraction: + value = value.isoformat(timespec="microseconds") + fraction + return np.datetime64(value) - This checks both numpy dtype and the actual element types to handle: - - Native numpy numeric/datetime64 arrays - - Object arrays containing Python datetime.datetime objects - - Datetime strings from frontend JSON (ISO format) - Args: - arr: A numpy array of axis values - bound_value: A sample bound value (e.g., x_min) to check compatibility +class _AxisRange: + """Inclusive Plotly selection bounds. - Returns: - True if the axis values can be compared with the bound values + `contains` and `mask` return `None` when the trace must supply + the position of a category on the axis. """ - import datetime - import numpy as np + def __init__(self, first: Any, last: Any) -> None: + first, first_fraction = _coordinate_parts(first) + last, last_fraction = _coordinate_parts(last) + if isinstance(first, datetime.datetime) and isinstance( + last, datetime.datetime + ): + if (first.tzinfo is None) != (last.tzinfo is None): + first, last = ( + first.replace(tzinfo=None), + last.replace(tzinfo=None), + ) + ( + (self.lower, self._lower_fraction), + (self.upper, self._upper_fraction), + ) = sorted(((first, first_fraction), (last, last_fraction))) + self.temporal = isinstance( + first, datetime.datetime + ) or _is_numpy_datetime(first) + + @cached_property + def _numpy_bounds(self) -> tuple[np.datetime64, np.datetime64]: + first = _as_datetime64(self.lower, self._lower_fraction) + last = _as_datetime64(self.upper, self._upper_fraction) + return (first, last) if first <= last else (last, first) + + def contains(self, value: Any) -> bool | None: + if not self.temporal: + if isinstance(value, numbers.Real) or ( + isinstance(self.lower, str) and isinstance(value, str) + ): + return bool(self.lower <= value <= self.upper) + return None - # Check numpy dtype first (handles native numpy types) - if np.issubdtype(arr.dtype, np.number): - return True - if np.issubdtype(arr.dtype, np.datetime64): - return True + value, fraction = _coordinate_parts(value) + if isinstance(value, datetime.datetime) and _is_numpy_datetime( + self.lower + ): + value = _as_datetime64(value, fraction) + if _is_numpy_datetime(value): + start, end = self._numpy_bounds + return bool(start <= value <= end) + if not isinstance(value, datetime.datetime): + return False + lower, upper = self.lower, self.upper + if (lower.tzinfo is None) != (value.tzinfo is None): + # Plotly sends naive wall-time bounds even for offset-aware coordinates. + lower, upper = ( + lower.replace(tzinfo=None), + upper.replace(tzinfo=None), + ) + value = value.replace(tzinfo=None) + return ( + (lower, self._lower_fraction) + <= (value, fraction) + <= (upper, self._upper_fraction) + ) - # For object arrays, check element types and bound value compatibility - if arr.dtype == np.object_ and len(arr) > 0: - first_elem = arr[0] - # Check if elements are datetime-like - if isinstance(first_elem, (datetime.datetime, datetime.date)): - # Bound can be datetime object or ISO string from frontend - if isinstance(bound_value, (datetime.datetime, datetime.date)): - return True - # Check for ISO format datetime strings (sent from frontend via JSON) - if isinstance(bound_value, str): - try: - datetime.datetime.fromisoformat(bound_value) - return True - except (ValueError, AttributeError): - pass + def mask(self, values: npt.NDArray[Any]) -> npt.NDArray[np.bool_] | None: + import numpy as np - return False + if not self.temporal: + numeric = np.issubdtype(values.dtype, np.number) + if values.dtype == object and values.size > 0: + numeric = all(isinstance(v, numbers.Real) for v in values) + if numeric: + return np.asarray( + (values >= self.lower) & (values <= self.upper), dtype=bool + ) + return None + if np.issubdtype(values.dtype, np.datetime64): + lower, upper = self._numpy_bounds + return (values >= lower) & (values <= upper) + if ( + values.dtype == object + and len(values) + and isinstance(values[0], datetime.datetime) + and not (self._lower_fraction or self._upper_fraction) + ): + # Native comparisons preserve nanoseconds in pandas Timestamps. + try: + return np.asarray( + (values >= self.lower) & (values <= self.upper), dtype=bool + ) + except TypeError: + pass # Mixed dates, datetimes, or timezone awareness. + return np.fromiter( + (self.contains(v) for v in values), dtype=bool, count=len(values) + ) + + def contains_at(self, value: Any, position: float) -> bool: + """A category occupies one axis unit. Touching its edge is insufficient.""" + match = self.contains(value) + if match is None: + return bool( + self.lower < position + 0.5 and self.upper > position - 0.5 + ) + return match + + def category_mask( + self, positions: npt.NDArray[Any] + ) -> npt.NDArray[np.bool_]: + import numpy as np + + return np.asarray( + (self.lower < positions + 0.5) & (self.upper > positions - 0.5), + dtype=bool, + ) + + def indexed_mask(self, values: npt.NDArray[Any]) -> npt.NDArray[np.bool_]: + """Use the row index for traces that place categories in data order.""" + import numpy as np + + mask = self.mask(values) + if mask is None: + return self.category_mask(np.arange(len(values))) + return mask def _to_numeric_coord(value: object) -> float | None: """Convert a numeric/datetime-like value to a float for geometry tests.""" - import datetime - - def _to_utc_timestamp(dt: datetime.datetime) -> float: - if dt.tzinfo is None: - dt = dt.replace(tzinfo=datetime.UTC) - else: - dt = dt.astimezone(datetime.UTC) - return dt.timestamp() + value = _axis_coordinate(value) if isinstance(value, (int, float)): return float(value) if isinstance(value, datetime.datetime): - return _to_utc_timestamp(value) - if isinstance(value, datetime.date): - return _to_utc_timestamp( - datetime.datetime.combine( - value, - datetime.time(), - tzinfo=datetime.UTC, - ) - ) - if isinstance(value, str): - parsed = _parse_datetime_bound(value) - if isinstance(parsed, datetime.datetime): - return _to_utc_timestamp(parsed) - if isinstance(parsed, datetime.date): - return _to_utc_timestamp( - datetime.datetime.combine( - parsed, - datetime.time(), - tzinfo=datetime.UTC, - ) - ) + if value.tzinfo is None: + value = value.replace(tzinfo=datetime.UTC) + return value.timestamp() return None @@ -333,19 +399,20 @@ def add_selection(selection: go.layout.Selection) -> None: "bar", "histogram", "waterfall", - ): + ) or _trace_needs_scatter_range_fallback(trace): continue x_data = getattr(trace, "x", None) y_data = getattr(trace, "y", None) if x_data is None or y_data is None: continue + x_bounds = _AxisRange(selection.x0, selection.x1) + y_bounds = _AxisRange(selection.y0, selection.y1) for point_idx, (x, y) in enumerate( zip(x_data, y_data, strict=False) ): - # Early exit if x is not in range - if not (selection.x0 <= x <= selection.x1): + if not x_bounds.contains(x): continue - if selection.y0 <= y <= selection.y1: + if y_bounds.contains(y): selected_points.append( { axis.title.text: val @@ -358,14 +425,6 @@ def add_selection(selection: go.layout.Selection) -> None: initial_value["points"] = selected_points initial_value["indices"] = selected_indices - # For heatmaps with a range selection, extract all cells in range - has_heatmap = any( - getattr(trace, "type", None) == "heatmap" - for trace in figure.data - ) - if has_heatmap and initial_value.get("range"): - _append_heatmap_cells_to_selection(figure, initial_value) - # For histograms, pre-compute sample rows using the selection range. # Interactive events use bin payloads (pointNumbers) for extraction; # programmatic initial selections via add_selection only have a range, @@ -663,42 +722,8 @@ def _extract_heatmap_cells_numpy( y_arr = np.asarray(y_data) z_arr = np.asarray(z_data) - # Determine if axes are orderable (numeric or datetime-like) - x_is_orderable = _is_orderable_axis(x_arr, x_min) - y_is_orderable = _is_orderable_axis(y_arr, y_min) - - # Parse datetime bounds (frontend sends ISO strings via JSON) - x_min_parsed = ( - _parse_datetime_bound(x_min) if x_is_orderable else x_min - ) - x_max_parsed = ( - _parse_datetime_bound(x_max) if x_is_orderable else x_max - ) - y_min_parsed = ( - _parse_datetime_bound(y_min) if y_is_orderable else y_min - ) - y_max_parsed = ( - _parse_datetime_bound(y_max) if y_is_orderable else y_max - ) - - # Compute masks for valid indices - if x_is_orderable: - x_mask = (x_arr >= x_min_parsed) & (x_arr <= x_max_parsed) - else: - # Categorical: cell spans (index - 0.5) to (index + 0.5) - # Strict overlap: x_max > cell_x_min and x_min < cell_x_max - x_indices = np.arange(len(x_arr)) - x_mask = (x_max > x_indices - 0.5) & (x_min < x_indices + 0.5) - - if y_is_orderable: - y_mask = (y_arr >= y_min_parsed) & (y_arr <= y_max_parsed) - else: - # Categorical: cell spans (index - 0.5) to (index + 0.5) - # Strict overlap: y_max > cell_y_min and y_min < cell_y_max - y_indices = np.arange(len(y_arr)) - y_mask = (y_max > y_indices - 0.5) & (y_min < y_indices + 0.5) - - # Get indices where masks are True + x_mask = _AxisRange(x_min, x_max).indexed_mask(x_arr) + y_mask = _AxisRange(y_min, y_max).indexed_mask(y_arr) y_idx = np.where(y_mask)[0] x_idx = np.where(x_mask)[0] @@ -931,29 +956,9 @@ def _extract_scatter_points_numpy( x_arr = np.asarray(x_data) y_arr = np.asarray(y_data) - # Check if x is orderable (numeric or datetime-like) - x_is_orderable = _is_orderable_axis(x_arr, x_min) has_y_range = y_min is not None and y_max is not None - y_is_orderable = has_y_range and _is_orderable_axis(y_arr, y_min) - - # Parse datetime bounds (frontend sends ISO strings via JSON) - x_min_parsed = ( - _parse_datetime_bound(x_min) if x_is_orderable else x_min - ) - x_max_parsed = ( - _parse_datetime_bound(x_max) if x_is_orderable else x_max - ) - y_min_parsed = ( - _parse_datetime_bound(y_min) if y_is_orderable else y_min - ) - y_max_parsed = ( - _parse_datetime_bound(y_max) if y_is_orderable else y_max - ) - - # Filter by x-range - if x_is_orderable: - x_mask = (x_arr >= x_min_parsed) & (x_arr <= x_max_parsed) - else: + x_mask = _AxisRange(x_min, x_max).mask(x_arr) + if x_mask is None: # Categorical: compare against axis category positions, not point # indices, so repeated categories map to the same coordinate. x_category_positions = _category_position_map(x_data) @@ -968,9 +973,8 @@ def _extract_scatter_points_numpy( # Filter by y-range when present if has_y_range: - if y_is_orderable: - y_mask = (y_arr >= y_min_parsed) & (y_arr <= y_max_parsed) - else: + y_mask = _AxisRange(y_min, y_max).mask(y_arr) + if y_mask is None: y_category_positions = _category_position_map(y_data) y_positions = np.asarray( [ @@ -1055,63 +1059,21 @@ def _extract_scatter_points_fallback( continue has_y_range = y_min is not None and y_max is not None - selected_indices: set[int] = set() - x_min_p = _parse_datetime_bound(x_min) - x_max_p = _parse_datetime_bound(x_max) - y_min_p = _parse_datetime_bound(y_min) if has_y_range else None - y_max_p = _parse_datetime_bound(y_max) if has_y_range else None - - x_category_positions = _category_position_map(x_data) - y_category_positions = _category_position_map(y_data) + x_bounds = _AxisRange(x_min, x_max) + y_bounds = _AxisRange(y_min, y_max) if has_y_range else None + x_positions = _category_position_map(x_data) + y_positions = _category_position_map(y_data) if has_y_range else {} - # First pass: include points directly inside current selection bounds. for point_idx, (x_val, y_val) in enumerate( zip(x_data, y_data, strict=False) ): - x_in_range = False - - if _is_orderable_value(x_val) and _is_orderable_value(x_min): - x_in_range = x_min_p <= x_val <= x_max_p - else: - # TypeError can occur when x_val is unhashable (e.g. a list or - # dict), which dict.get() cannot accept as a key. - try: - x_position = x_category_positions.get(x_val) - except TypeError: - continue - if x_position is None: + x_pos = _safe_category_get(x_positions, x_val, math.nan) + if not x_bounds.contains_at(x_val, x_pos): + continue + if y_bounds is not None: + y_pos = _safe_category_get(y_positions, y_val, math.nan) + if not y_bounds.contains_at(y_val, y_pos): continue - cell_x_min = x_position - 0.5 - cell_x_max = x_position + 0.5 - x_in_range = not (x_max <= cell_x_min or x_min >= cell_x_max) - - y_in_range = True - if has_y_range: - if _is_orderable_value(y_val) and _is_orderable_value(y_min): - y_in_range = ( - cast(Any, y_min_p) <= y_val <= cast(Any, y_max_p) - ) - else: - # TypeError can occur when y_val is unhashable (e.g. a list or - # dict), which dict.get() cannot accept as a key. - try: - y_position = y_category_positions.get(y_val) - except TypeError: - continue - if y_position is None: - continue - cell_y_min = y_position - 0.5 - cell_y_max = y_position + 0.5 - y_in_range = not ( - y_max <= cell_y_min or y_min >= cell_y_max - ) - - if x_in_range and y_in_range: - selected_indices.add(point_idx) - - for point_idx in sorted(selected_indices): - x_val = x_data[point_idx] - y_val = y_data[point_idx] point_dict = { x_field: x_val, y_field: y_val, @@ -1307,43 +1269,13 @@ def _extract_heatmap_cells_fallback( if x_data is None or y_data is None or z_data is None: continue - # Iterate through the heatmap cells + x_range = _AxisRange(x_min, x_max) + y_range = _AxisRange(y_min, y_max) for i, y_val in enumerate(y_data): + if not y_range.contains_at(y_val, i): + continue for j, x_val in enumerate(x_data): - # Check if cell is within selection range - # Handle both numeric and categorical data - x_in_range = False - y_in_range = False - - if _is_orderable_value(x_val) and _is_orderable_value(x_min): - # Parse datetime bounds (frontend sends ISO strings) - x_min_p = _parse_datetime_bound(x_min) - x_max_p = _parse_datetime_bound(x_max) - x_in_range = x_min_p <= x_val <= x_max_p - else: - # Categorical - each cell spans from (index - 0.5) to (index + 0.5) - # Include cell if selection range strictly overlaps with cell bounds - cell_x_min = j - 0.5 - cell_x_max = j + 0.5 - x_in_range = not ( - x_max <= cell_x_min or x_min >= cell_x_max - ) - - if _is_orderable_value(y_val) and _is_orderable_value(y_min): - # Parse datetime bounds (frontend sends ISO strings) - y_min_p = _parse_datetime_bound(y_min) - y_max_p = _parse_datetime_bound(y_max) - y_in_range = y_min_p <= y_val <= y_max_p - else: - # Categorical - each cell spans from (index - 0.5) to (index + 0.5) - # Include cell if selection range strictly overlaps with cell bounds - cell_y_min = i - 0.5 - cell_y_max = i + 0.5 - y_in_range = not ( - y_max <= cell_y_min or y_min >= cell_y_max - ) - - if x_in_range and y_in_range: + if x_range.contains_at(x_val, j): # Bounds check for z_data to handle malformed/ragged arrays if i >= len(z_data) or j >= len(z_data[i]): continue @@ -1465,19 +1397,8 @@ def _extract_histogram_points_numpy( if axis_arr.size == 0: continue - axis_is_orderable = _is_orderable_axis(axis_arr, axis_min) - axis_min_parsed = ( - _parse_datetime_bound(axis_min) if axis_is_orderable else axis_min - ) - axis_max_parsed = ( - _parse_datetime_bound(axis_max) if axis_is_orderable else axis_max - ) - - if axis_is_orderable: - axis_mask = (axis_arr >= axis_min_parsed) & ( - axis_arr <= axis_max_parsed - ) - else: + axis_mask = _AxisRange(axis_min, axis_max).mask(axis_arr) + if axis_mask is None: category_positions = { value: idx for idx, value in enumerate(dict.fromkeys(axis_data)) @@ -1526,16 +1447,10 @@ def _extract_histogram_points_fallback( value: idx for idx, value in enumerate(dict.fromkeys(axis_data)) } + bounds = _AxisRange(axis_min, axis_max) for point_idx, axis_value in enumerate(axis_data): - axis_in_range = False - - if _is_orderable_value(axis_value) and _is_orderable_value( - axis_min - ): - axis_min_p = _parse_datetime_bound(axis_min) - axis_max_p = _parse_datetime_bound(axis_max) - axis_in_range = axis_min_p <= axis_value <= axis_max_p - else: + axis_in_range = bounds.contains(axis_value) + if axis_in_range is None: position = category_positions[axis_value] bin_min = position - 0.5 bin_max = position + 0.5 @@ -1782,34 +1697,7 @@ def _extract_bars_numpy( pos_min, pos_max = y_min, y_max value_min, value_max = x_min, x_max - # Determine if position axis is orderable (numeric or datetime-like) - pos_is_orderable = _is_orderable_axis(position_data, pos_min) - - # Parse datetime bounds (frontend sends ISO strings via JSON) - pos_min_parsed = ( - _parse_datetime_bound(pos_min) if pos_is_orderable else pos_min - ) - pos_max_parsed = ( - _parse_datetime_bound(pos_max) if pos_is_orderable else pos_max - ) - - # Compute mask for valid indices - if pos_is_orderable: - # Orderable axis: direct range comparison - # TODO: Consider bar width in future implementations - # Currently treating bars as points at their position value - pos_mask = (position_data >= pos_min_parsed) & ( - position_data <= pos_max_parsed - ) - else: - # Categorical axis: each bar spans (index - 0.5) to (index + 0.5) - # Selection overlaps if: pos_max > bar_min AND pos_min < bar_max - pos_indices = np.arange(len(position_data)) - pos_mask = (pos_max > pos_indices - 0.5) & ( - pos_min < pos_indices + 0.5 - ) - - # Get indices where mask is True + pos_mask = _AxisRange(pos_min, pos_max).indexed_mask(position_data) selected_indices = np.where(pos_mask)[0] # Iterate only over selected indices @@ -1884,27 +1772,9 @@ def _extract_bars_fallback( pos_min, pos_max = y_min, y_max value_min, value_max = x_min, x_max - # Iterate through bars + position_range = _AxisRange(pos_min, pos_max) for i, pos_val in enumerate(position_data): - # Check if bar position is within selection range - pos_in_range = False - - if _is_orderable_value(pos_val) and _is_orderable_value(pos_min): - # Orderable axis (numeric or datetime): direct comparison - # Parse datetime bounds (frontend sends ISO strings) - pos_min_p = _parse_datetime_bound(pos_min) - pos_max_p = _parse_datetime_bound(pos_max) - # TODO: Consider bar width in future implementations - # Currently treating bars as points at their position value - pos_in_range = pos_min_p <= pos_val <= pos_max_p - else: - # Categorical axis: each bar spans (index - 0.5) to (index + 0.5) - # Include bar if selection range strictly overlaps with bar bounds - bar_min = i - 0.5 - bar_max = i + 0.5 - pos_in_range = not (pos_max <= bar_min or pos_min >= bar_max) - - if not pos_in_range: + if not position_range.contains_at(pos_val, i): continue if not _bar_value_in_selection_range( trace, i, value_data[i], value_min, value_max @@ -2209,18 +2079,11 @@ def _extract_waterfall_bars_numpy( cat_min, cat_max = x_min, x_max val_min, val_max = y_min, y_max - # Category axis: orderable (numeric/datetime) or positional (categorical) cat_arr = np.asarray(cat_data) - cat_is_orderable = _is_orderable_axis(cat_arr, cat_min) - if cat_is_orderable: - cat_min_p = _parse_datetime_bound(cat_min) - cat_max_p = _parse_datetime_bound(cat_max) - cat_mask = (cat_arr >= cat_min_p) & (cat_arr <= cat_max_p) - else: - cat_positions = np.arange(n, dtype=np.float64) - cat_mask = (cat_max > cat_positions - 0.5) & ( - cat_min < cat_positions + 0.5 - ) + bounds = _AxisRange(cat_min, cat_max) + cat_mask = bounds.mask(cat_arr) + if cat_mask is None: + cat_mask = bounds.category_mask(np.arange(n)) # Value axis: use stacked extents (low, high) for each bar extents = _compute_waterfall_bar_extents(val_data, measures, base) @@ -2282,18 +2145,11 @@ def _extract_waterfall_bars_fallback( extents = _compute_waterfall_bar_extents(val_data, measures, base) + bounds = _AxisRange(cat_min, cat_max) for i, (bar_lo, bar_hi) in enumerate(extents): - # Category check: orderable (numeric/datetime) or positional - cat_val = _get_indexed_value(cat_data, i) - if _is_orderable_value(cat_val) and _is_orderable_value(cat_min): - cat_min_p = _parse_datetime_bound(cat_min) - cat_max_p = _parse_datetime_bound(cat_max) - cat_val_p = _parse_datetime_bound(cat_val) - if not (cat_min_p <= cat_val_p <= cat_max_p): - continue - else: - if cat_max <= i - 0.5 or cat_min >= i + 0.5: - continue + category = cat_data[i] if i < len(cat_data) else None + if not bounds.contains_at(category, i): + continue # Value check: bar [bar_lo, bar_hi] overlaps [val_min, val_max] if val_min >= bar_hi or val_max <= bar_lo: continue @@ -2577,6 +2433,38 @@ def _extract_violin_points_from_range( return _extract_violin_points_fallback(figure, range_data) +def _sample_category_mask( + data: Any, + default: Any, + count: int, + selection: list[Any] | None, + order: dict[Any, float] | None = None, +) -> npt.NDArray[np.bool_]: + """Box and violin traces can share one category across all samples.""" + import numpy as np + + if not selection: + return np.ones(count, dtype=bool) + categories = np.asarray(default if data is None else data) + if categories.ndim == 0: + categories = np.repeat(categories, count) + elif len(categories) != count: + category = categories[0] if len(categories) else None + categories = np.asarray([category] * count) + + bounds = _AxisRange(min(selection), max(selection)) + mask = bounds.mask(categories) + if mask is not None: + return mask + + if order is None: + order = _category_position_map(categories) + positions = np.array( + [_safe_category_get(order, v, -1) for v in categories] + ) + return bounds.category_mask(positions) + + def _extract_violin_points_numpy( figure: go.Figure, range_data: dict[str, Any] ) -> list[dict[str, Any]]: @@ -2619,65 +2507,23 @@ def _extract_violin_points_numpy( if n == 0: continue - if cat_data is None: - cat_arr: list[Any] = [getattr(trace, "name", trace_idx)] * n - else: - cat_arr_raw = np.asarray(cat_data) - if cat_arr_raw.ndim == 0 or len(cat_arr_raw) != n: - cat_val = ( - cat_arr_raw.item() - if hasattr(cat_arr_raw, "item") and cat_arr_raw.ndim == 0 - else (cat_arr_raw[0] if len(cat_arr_raw) > 0 else None) - ) - cat_arr = [cat_val] * n - else: - cat_arr = cat_arr_raw.tolist() - - if cat_range: - cat_min, cat_max = min(cat_range), max(cat_range) - cat_np = np.asarray(cat_arr) - cat_is_orderable = _is_orderable_axis(cat_np, cat_min) - - if cat_is_orderable: - cat_min_p = _parse_datetime_bound(cat_min) - cat_max_p = _parse_datetime_bound(cat_max) - cat_mask = np.array( - [ - cat_min_p <= _parse_datetime_bound(v) <= cat_max_p - if _is_orderable_value(v) - else False - for v in cat_arr - ] - ) - else: - seen_order: dict[Any, float] = {} - for v in cat_arr: - try: - if v not in seen_order: - seen_order[v] = float(len(seen_order)) - except TypeError: - pass - positions = np.array( - [_safe_category_get(seen_order, v, -1) for v in cat_arr], - dtype=np.float64, - ) - cat_mask = (cat_max > positions - 0.5) & ( - cat_min < positions + 0.5 - ) - else: - cat_mask = np.ones(n, dtype=bool) + cat_mask = _sample_category_mask( + cat_data, getattr(trace, "name", trace_idx), n, cat_range + ) if val_range: - val_min_f = float(min(val_range)) - val_max_f = float(max(val_range)) - try: - val_numeric = val_arr.astype(float) - val_mask = (val_numeric >= val_min_f) & ( - val_numeric <= val_max_f - ) - cat_mask = cat_mask & val_mask - except (ValueError, TypeError): - pass # non-numeric values; skip value filtering + bounds = _AxisRange(min(val_range), max(val_range)) + val_mask = bounds.mask(val_arr) + if val_mask is not None: + cat_mask &= val_mask + else: + try: + numeric = val_arr.astype(float) + cat_mask &= (numeric >= float(bounds.lower)) & ( + numeric <= float(bounds.upper) + ) + except (ValueError, TypeError): + pass # non-numeric values; skip value filtering selected_indices = np.where(cat_mask)[0] for i in selected_indices: @@ -3013,73 +2859,20 @@ def _extract_box_points_numpy( if n == 0: continue - # Build per-sample category array. A box trace can have: - # - cat_data as an array (one category per sample, same length as val) - # - cat_data as a scalar / None (all samples share one category) - if cat_data is None: - # No explicit category; Plotly uses the trace name / index. - cat_arr: list[Any] = [getattr(trace, "name", trace_idx)] * n - else: - cat_arr_raw = np.asarray(cat_data) - if cat_arr_raw.ndim == 0 or len(cat_arr_raw) != n: - # Scalar category - cat_val = ( - cat_arr_raw.item() - if hasattr(cat_arr_raw, "item") and cat_arr_raw.ndim == 0 - else (cat_arr_raw[0] if len(cat_arr_raw) > 0 else None) - ) - cat_arr = [cat_val] * n - else: - cat_arr = cat_arr_raw.tolist() - - # --- Category filter --- - if cat_range: - cat_min, cat_max = min(cat_range), max(cat_range) - cat_np = np.asarray(cat_arr) - cat_is_orderable = _is_orderable_axis(cat_np, cat_min) - - if cat_is_orderable: - cat_min_p = _parse_datetime_bound(cat_min) - cat_max_p = _parse_datetime_bound(cat_max) - cat_mask = np.array( - [ - cat_min_p <= _parse_datetime_bound(v) <= cat_max_p - if _is_orderable_value(v) - else False - for v in cat_arr - ] - ) - else: - # Use the global order so positions are consistent across traces - positions = np.array( - [ - _safe_category_get(global_cat_order, v, -1) - for v in cat_arr - ], - dtype=np.float64, - ) - cat_mask = (cat_max > positions - 0.5) & ( - cat_min < positions + 0.5 - ) - else: - cat_mask = np.ones(n, dtype=bool) - - # --- Value filter --- - # Exclude samples whose value coordinate falls outside the selection - # rectangle (category match alone is insufficient). + cat_mask = _sample_category_mask( + cat_data, + getattr(trace, "name", trace_idx), + n, + cat_range, + global_cat_order, + ) if val_range: - val_min_p = _parse_datetime_bound(min(val_range)) - val_max_p = _parse_datetime_bound(max(val_range)) - val_mask = np.array( - [ - val_min_p <= parsed_v <= val_max_p - if _is_orderable_value(parsed_v) - else False - for parsed_v in ( - _parse_datetime_bound(v) for v in val_arr.tolist() - ) - ] - ) + bounds = _AxisRange(min(val_range), max(val_range)) + val_mask = bounds.mask(val_arr) + if val_mask is None: + val_mask = np.array( + [bool(bounds.contains(v)) for v in val_arr] + ) cat_mask = cat_mask & val_mask selected_indices = np.where(cat_mask)[0] @@ -3142,23 +2935,18 @@ def _extract_box_points_fallback( if cat_range: cat_min, cat_max = min(cat_range), max(cat_range) + cat_bounds = _AxisRange(cat_min, cat_max) if val_range: - val_min_p = _parse_datetime_bound(min(val_range)) - val_max_p = _parse_datetime_bound(max(val_range)) + val_bounds = _AxisRange(min(val_range), max(val_range)) for i, cat_val in enumerate(cat_list): # --- Category filter --- if cat_range: - if _is_orderable_value(cat_val) and _is_orderable_value( - cat_min - ): - cat_min_p = _parse_datetime_bound(cat_min) - cat_max_p = _parse_datetime_bound(cat_max) - cat_val_p = _parse_datetime_bound(cat_val) - if not (cat_min_p <= cat_val_p <= cat_max_p): - continue - else: + in_range = cat_bounds.contains(cat_val) + if in_range is False: + continue + if in_range is None: pos = _safe_category_get(global_cat_order, cat_val, -1) if pos < 0: continue @@ -3170,11 +2958,7 @@ def _extract_box_points_fallback( val_v = ( val_data[i] if hasattr(val_data, "__getitem__") else None ) - val_v_p = _parse_datetime_bound(val_v) - if val_v is None or not ( - _is_orderable_value(val_v_p) - and val_min_p <= val_v_p <= val_max_p - ): + if not val_bounds.contains(val_v): continue sample = _build_box_sample_point(trace, trace_idx, i) @@ -3285,25 +3069,18 @@ def _extract_violin_points_fallback( if cat_range: cat_min, cat_max = min(cat_range), max(cat_range) - seen_order: dict[Any, int] = {} - for v in cat_list: - try: - if v not in seen_order: - seen_order[v] = len(seen_order) - except TypeError: - pass + cat_bounds = _AxisRange(cat_min, cat_max) + seen_order = _category_position_map(cat_list) + val_bounds = ( + _AxisRange(min(val_range), max(val_range)) if val_range else None + ) for i, cat_val in enumerate(cat_list): if cat_range: - if _is_orderable_value(cat_val) and _is_orderable_value( - cat_min - ): - cat_min_p = _parse_datetime_bound(cat_min) - cat_max_p = _parse_datetime_bound(cat_max) - cat_val_p = _parse_datetime_bound(cat_val) - if not (cat_min_p <= cat_val_p <= cat_max_p): - continue - else: + in_range = cat_bounds.contains(cat_val) + if in_range is False: + continue + if in_range is None: try: pos = seen_order.get(cat_val) except TypeError: @@ -3313,15 +3090,20 @@ def _extract_violin_points_fallback( if not (cat_max > pos - 0.5 and cat_min < pos + 0.5): continue - if val_range: - val_min_f = float(min(val_range)) - val_max_f = float(max(val_range)) - try: - val_f = float(val_data[i]) - if not (val_min_f <= val_f <= val_max_f): + if val_bounds is not None: + if val_bounds.temporal: + if not val_bounds.contains(val_data[i]): continue - except (TypeError, ValueError): - pass # non-numeric value; skip value filtering + else: + try: + if ( + not float(val_bounds.lower) + <= float(val_data[i]) + <= float(val_bounds.upper) + ): + continue + except (TypeError, ValueError): + pass # non-numeric values; skip value filtering sample = _build_violin_sample_point(trace, trace_idx, i) if sample is not None: diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.py index 80d477bbe27..eb225bc0533 100644 --- a/tests/_plugins/ui/_impl/test_plotly.py +++ b/tests/_plugins/ui/_impl/test_plotly.py @@ -3,7 +3,7 @@ import os import time -from datetime import UTC, datetime, timedelta +from datetime import UTC, date, datetime, timedelta from typing import Any import pytest @@ -14,6 +14,7 @@ import plotly.express as px import plotly.graph_objects as go +from marimo._dependencies.dependencies import DependencyManager from marimo._plugins.ui._impl.plotly import ( _bar_value_in_selection_range, _compute_waterfall_bar_extents, @@ -955,6 +956,19 @@ def test_to_numeric_coord_normalizes_naive_datetimes_to_utc() -> None: time.tzset() +def test_bar_selection_numeric_object_array() -> None: + import numpy as np + + fig = go.Figure( + go.Bar(x=np.array([10, 20, 30], dtype=object), y=[1, 2, 3]) + ) + fig.add_selection(x0=15, x1=25, y0=0, y1=3) + + assert plotly(fig).value == [ + {"x": 20, "y": 2, "curveNumber": 0, "pointIndex": 1, "pointNumber": 1} + ] + + def test_bar_selection_datetime_x_axis() -> None: """Test bar chart with datetime x-axis.""" base_date = datetime(2024, 1, 1) @@ -983,6 +997,133 @@ def test_bar_selection_datetime_x_axis() -> None: assert any(bar["x"] == dates[3] and bar["y"] == 25 for bar in result) +@pytest.fixture(params=[True, False], ids=["numpy", "python"]) +def selection_backend( + request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(DependencyManager.numpy, "has", lambda: request.param) + + +@pytest.mark.usefixtures("selection_backend") +@pytest.mark.parametrize( + "numpy_dates", [True, False], ids=["datetime64[D]", "date"] +) +@pytest.mark.parametrize( + "trace_type", + [ + go.Bar, + go.Box, + go.Violin, + go.Waterfall, + go.Heatmap, + go.Histogram, + go.Scatter, + ], +) +def test_range_selection_on_date_axis( + trace_type: type, + numpy_dates: bool, +) -> None: + import numpy as np + + days = [date(2026, 1, day) for day in (5, 6, 7)] + x = np.array(days, dtype="datetime64[D]") if numpy_dates else days + if trace_type is go.Heatmap: + trace = go.Heatmap(x=x, y=[1], z=[[1, 2, 3]]) + elif trace_type is go.Histogram: + trace = go.Histogram(x=x) + elif trace_type is go.Scatter: + trace = go.Scatter(x=x, y=[1, 2, 3], mode="lines") + else: + trace = trace_type(x=x, y=[1, 2, 3]) + fig = go.Figure(trace) + fig.add_selection(x0="2026-01-05 12:00", x1="2026-01-06 12:00", y0=0, y1=4) + assert [point["x"] for point in plotly(fig).value] == [days[1]] + + +def test_bar_selection_preserves_timestamp_precision() -> None: + import pandas as pd + + start = pd.Timestamp("2026-01-05") + x = [start + pd.Timedelta(ns, unit="ns") for ns in (0, 1000, 1500)] + fig = go.Figure(go.Bar(x=x, y=[1, 2, 3])) + fig.add_selection(x0=start.isoformat(), x1=x[1].isoformat(), y0=0, y1=3) + assert [point["x"] for point in plotly(fig).value] == x[:2] + + +@pytest.mark.usefixtures("selection_backend") +@pytest.mark.parametrize("representation", ["iso", "pandas", "numpy", "date"]) +def test_bar_selection_exact_nanosecond(representation: str) -> None: + import numpy as np + import pandas as pd + + times = [f"2026-01-05T00:00:00.000000{ns}" for ns in (249, 250, 251)] + x: Any = times + if representation == "pandas": + x = [pd.Timestamp(t) for t in times] + elif representation == "numpy": + x = np.array(times, dtype="datetime64[ns]") + elif representation == "date": + x = [date(2026, 1, 5)] + fig = go.Figure(go.Bar(x=x, y=[1] * len(x))) + fig.add_selection(x0=times[1], x1=times[1], y0=0, y1=2) + expected = [] if representation == "date" else [1] + assert [point["pointIndex"] for point in plotly(fig).value] == expected + + +@pytest.mark.usefixtures("selection_backend") +def test_aware_bar_dates_with_aware_bounds() -> None: + position = datetime.fromisoformat("2026-01-05T12:00:00+02:00") + fig = go.Figure(go.Bar(x=[position], y=[1])) + fig.add_selection( + x0="2026-01-05T09:00Z", x1="2026-01-05T11:00Z", y0=0, y1=2 + ) + assert [point["x"] for point in plotly(fig).value] == [position] + + +@pytest.mark.usefixtures("selection_backend") +@pytest.mark.parametrize( + "positions", + [ + [date(2026, 1, 5), date(2026, 1, 6)], + ["2026-01-05", "2026-01-06"], + ["2026-01-05T20:00:00-05:00", "2026-01-06T20:00:00-05:00"], + ], +) +def test_bar_selection_date_positions( + positions: list[date] | list[str], +) -> None: + fig = go.Figure(go.Bar(x=positions, y=[1, 2])) + fig.add_selection(x0="2026-01-05 23:00", x1="2026-01-06 23:00", y0=0, y1=3) + assert plotly(fig).value == [ + { + "x": positions[1], + "y": 2, + "curveNumber": 0, + "pointIndex": 1, + "pointNumber": 1, + } + ] + + +@pytest.mark.usefixtures("selection_backend") +@pytest.mark.parametrize("unit", ["D", "us", "ns"]) +def test_bar_selection_numpy_date_positions(unit: str) -> None: + import numpy as np + + positions = np.array( + ["2026-01-05", "2026-01-06", "2026-01-07"], dtype=f"datetime64[{unit}]" + ) + if unit == "ns": + positions[1] += np.timedelta64(250, "ns") + positions[2] = positions[1] + np.timedelta64(1, "ns") + fig = go.Figure(go.Bar(y=positions, x=[1, 2, 3], orientation="h")) + fig.add_selection( + x0=0, x1=3, y0="2026-01-05", y1="2026-01-06T00:00:00.000000250" + ) + assert [point["pointIndex"] for point in plotly(fig).value] == [0, 1] + + def test_bar_numpy_and_fallback_datetime_x_axis() -> None: """Test that numpy and fallback produce same results for datetime bars.""" base_date = datetime(2024, 1, 1) @@ -3770,6 +3911,13 @@ def test_compute_waterfall_bar_extents_negative_relative() -> None: assert extents[1] == (250.0, 400.0) +@pytest.mark.usefixtures("selection_backend") +def test_waterfall_selection_with_missing_category() -> None: + fig = go.Figure(go.Waterfall(x=["A"], y=[1, 2])) + fig.add_selection(x0=-0.4, x1=0.4, y0=0, y1=3) + assert [point["pointIndex"] for point in plotly(fig).value] == [0] + + def test_waterfall_range_selection_partial() -> None: """Box selection extracts only bars whose visual extent overlaps the range.""" fig = go.Figure(