From 1805cb7aae2a011c546ef3ba189dc79918110d86 Mon Sep 17 00:00:00 2001 From: Kiran Gadhave Date: Thu, 3 Dec 2026 11:36:22 -0800 Subject: [PATCH 1/3] fix: compare Plotly selections in axis coordinates Plotly sends date bounds as strings, but a trace can store its positions as Python dates or NumPy timestamps. Compare date-only positions at midnight so a selection keeps its time-of-day bounds. Share the range comparison across traces while preserving each trace's category and overlap rules. Refs #11653 --- marimo/_plugins/ui/_impl/plotly.py | 552 ++++++++++--------------- tests/_plugins/ui/_impl/test_plotly.py | 126 +++++- 2 files changed, 339 insertions(+), 339 deletions(-) diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py index dc2ec4c99e4..53b5baed4fb 100644 --- a/marimo/_plugins/ui/_impl/plotly.py +++ b/marimo/_plugins/ui/_impl/plotly.py @@ -1,8 +1,10 @@ # Copyright 2026 Marimo. All rights reserved. from __future__ import annotations +import datetime import json import numbers +from functools import cached_property from typing import ( TYPE_CHECKING, Any, @@ -23,6 +25,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,94 +48,130 @@ 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) - if isinstance(value, str): - try: - datetime.datetime.fromisoformat(value) - return True - except (ValueError, AttributeError): - pass - - return False - - -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 - - if isinstance(value, (datetime.datetime, datetime.date)): - return value - +def _axis_coordinate(value: Any) -> Any: if isinstance(value, str): try: return datetime.datetime.fromisoformat(value) - except (ValueError, AttributeError): - pass - + except ValueError: + return value + if isinstance(value, datetime.date) and not isinstance( + value, datetime.datetime + ): + return datetime.datetime.combine(value, datetime.time()) return value -def _is_orderable_axis(arr: Any, bound_value: object) -> bool: - """Check if an axis contains orderable (numeric/datetime) values. +def _is_numpy_datetime(value: object) -> bool: + return getattr(getattr(value, "dtype", None), "kind", None) == "M" - 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 - Returns: - True if the axis values can be compared with the bound values - """ - import datetime +class _AxisRange: + """Inclusive coordinate bounds. A result of None requests categorical placement.""" - import numpy as np + def __init__(self, first: Any, last: Any) -> None: + self._endpoints = (first, last) + first, last = _axis_coordinate(first), _axis_coordinate(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.upper = sorted((first, last)) + self.temporal = isinstance( + first, datetime.datetime + ) or _is_numpy_datetime(first) + + @cached_property + def _numpy_bounds(self) -> tuple[np.datetime64, np.datetime64]: + import numpy as np + + def as_datetime64(value: Any) -> np.datetime64: + parsed = _axis_coordinate(value) + if isinstance(parsed, datetime.datetime): + if parsed.tzinfo is not None: + return np.datetime64(parsed.replace(tzinfo=None)) + if isinstance(value, str): + # NumPy can retain fractional seconds beyond Python's microseconds. + try: + return np.datetime64(value) + except ValueError: + pass + return np.datetime64(parsed) - # 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 + first, last = map(as_datetime64, self._endpoints) + return (first, last) if first <= last else (last, first) - # 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 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 - return False + value = _axis_coordinate(value) + if _is_numpy_datetime(value): + lower, upper = self._numpy_bounds + return bool(lower <= value <= upper) + if not isinstance(value, datetime.datetime): + return False + if _is_numpy_datetime(self.lower): + import numpy as np + + lower, upper = self._numpy_bounds + native = ( + value.to_datetime64() + if hasattr(value, "to_datetime64") + else np.datetime64(value.replace(tzinfo=None)) + ) + return bool(lower <= native <= upper) + 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 bool(lower <= value <= upper) + + def mask(self, values: npt.NDArray[Any]) -> npt.NDArray[np.bool_] | None: + import numpy as np + + 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) + ): + # Compare datetime objects directly to preserve precision and skip conversion. + 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 _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: @@ -153,17 +193,9 @@ def _to_utc_timestamp(dt: datetime.datetime) -> float: ) ) if isinstance(value, str): - parsed = _parse_datetime_bound(value) + parsed = _axis_coordinate(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, - ) - ) return None @@ -333,19 +365,21 @@ 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 +392,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,36 +689,15 @@ 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: + x_mask = _AxisRange(x_min, x_max).mask(x_arr) + if x_mask is None: # 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: + y_mask = _AxisRange(y_min, y_max).mask(y_arr) + if y_mask is None: # 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)) @@ -931,29 +936,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 +953,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( [ @@ -1056,10 +1040,8 @@ def _extract_scatter_points_fallback( 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_bounds = _AxisRange(x_min, x_max) + y_bounds = _AxisRange(y_min, y_max) if has_y_range else None x_category_positions = _category_position_map(x_data) y_category_positions = _category_position_map(y_data) @@ -1068,11 +1050,8 @@ def _extract_scatter_points_fallback( 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: + x_in_range = x_bounds.contains(x_val) + if x_in_range is None: # TypeError can occur when x_val is unhashable (e.g. a list or # dict), which dict.get() cannot accept as a key. try: @@ -1085,13 +1064,10 @@ def _extract_scatter_points_fallback( 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: + y_in_range: bool | None = True + if y_bounds is not None: + y_in_range = y_bounds.contains(y_val) + if y_in_range is None: # TypeError can occur when y_val is unhashable (e.g. a list or # dict), which dict.get() cannot accept as a key. try: @@ -1307,20 +1283,13 @@ def _extract_heatmap_cells_fallback( if x_data is None or y_data is None or z_data is None: continue + x_range = _AxisRange(x_min, x_max) + y_range = _AxisRange(y_min, y_max) # Iterate through the heatmap cells for i, y_val in enumerate(y_data): 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: + x_in_range = x_range.contains(x_val) + if x_in_range is None: # 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 @@ -1329,12 +1298,8 @@ def _extract_heatmap_cells_fallback( 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: + y_in_range = y_range.contains(y_val) + if y_in_range is None: # 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 @@ -1465,19 +1430,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 +1480,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,26 +1730,8 @@ 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: + pos_mask = _AxisRange(pos_min, pos_max).mask(position_data) + if pos_mask is None: # 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)) @@ -1884,20 +1814,10 @@ 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: + pos_in_range = position_range.contains(pos_val) + if pos_in_range is None: # 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 @@ -2211,12 +2131,8 @@ def _extract_waterfall_bars_numpy( # 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_mask = _AxisRange(cat_min, cat_max).mask(cat_arr) + if cat_mask is None: cat_positions = np.arange(n, dtype=np.float64) cat_mask = (cat_max > cat_positions - 0.5) & ( cat_min < cat_positions + 0.5 @@ -2282,18 +2198,13 @@ 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 + in_range = bounds.contains(cat_data[i]) + if in_range is None: + in_range = cat_min < i + 0.5 and cat_max > i - 0.5 + if not in_range: + continue # Value check: bar [bar_lo, bar_hi] overlaps [val_min, val_max] if val_min >= bar_hi or val_max <= bar_lo: continue @@ -2620,7 +2531,7 @@ def _extract_violin_points_numpy( continue if cat_data is None: - cat_arr: list[Any] = [getattr(trace, "name", trace_idx)] * n + cat_arr = np.full(n, getattr(trace, "name", trace_idx)) else: cat_arr_raw = np.asarray(cat_data) if cat_arr_raw.ndim == 0 or len(cat_arr_raw) != n: @@ -2629,27 +2540,14 @@ def _extract_violin_points_numpy( 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 + cat_arr = np.asarray([cat_val] * n) else: - cat_arr = cat_arr_raw.tolist() + cat_arr = cat_arr_raw 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: + cat_mask = _AxisRange(cat_min, cat_max).mask(cat_arr) + if cat_mask is None: seen_order: dict[Any, float] = {} for v in cat_arr: try: @@ -2668,16 +2566,18 @@ def _extract_violin_points_numpy( cat_mask = np.ones(n, dtype=bool) 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: @@ -3018,7 +2918,7 @@ def _extract_box_points_numpy( # - 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 + cat_arr = np.full(n, getattr(trace, "name", trace_idx)) else: cat_arr_raw = np.asarray(cat_data) if cat_arr_raw.ndim == 0 or len(cat_arr_raw) != n: @@ -3028,28 +2928,15 @@ def _extract_box_points_numpy( 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 + cat_arr = np.asarray([cat_val] * n) else: - cat_arr = cat_arr_raw.tolist() + cat_arr = cat_arr_raw # --- 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: + cat_mask = _AxisRange(cat_min, cat_max).mask(cat_arr) + if cat_mask is None: # Use the global order so positions are consistent across traces positions = np.array( [ @@ -3068,18 +2955,12 @@ def _extract_box_points_numpy( # Exclude samples whose value coordinate falls outside the selection # rectangle (category match alone is insufficient). 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 +3023,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 +3046,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,6 +3157,7 @@ def _extract_violin_points_fallback( if cat_range: cat_min, cat_max = min(cat_range), max(cat_range) + cat_bounds = _AxisRange(cat_min, cat_max) seen_order: dict[Any, int] = {} for v in cat_list: try: @@ -3293,17 +3166,15 @@ def _extract_violin_points_fallback( except TypeError: pass + 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 +3184,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..85d5a78b09b 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 @@ -955,6 +955,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 +996,117 @@ def test_bar_selection_datetime_x_axis() -> None: assert any(bar["x"] == dates[3] and bar["y"] == 25 for bar in result) +@pytest.mark.parametrize("use_numpy", [True, False]) +@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, + use_numpy: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import numpy as np + + from marimo._dependencies.dependencies import DependencyManager + + monkeypatch.setattr(DependencyManager.numpy, "has", lambda: use_numpy) + 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.parametrize("use_numpy", [True, False]) +def test_aware_bar_dates_with_aware_bounds( + use_numpy: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + from marimo._dependencies.dependencies import DependencyManager + + monkeypatch.setattr(DependencyManager.numpy, "has", lambda: use_numpy) + 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.parametrize("use_numpy", [True, False]) +@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], + use_numpy: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from marimo._dependencies.dependencies import DependencyManager + + monkeypatch.setattr(DependencyManager.numpy, "has", lambda: use_numpy) + 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.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[2] = positions[1] + np.timedelta64(500, "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-06") + 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) From 27d08bab64d46434f81290b61d425953ecfa1c4b Mon Sep 17 00:00:00 2001 From: Kiran Gadhave Date: Thu, 3 Dec 2026 14:57:15 -0800 Subject: [PATCH 2/3] refactor: share Plotly category overlap checks Box and violin plots use different category orders, but their samples follow the same selection rules. Share the overlap checks so each trace only supplies its category positions. Exercise the NumPy and pure Python paths with the same boundary cases. --- marimo/_plugins/ui/_impl/plotly.py | 334 ++++++++----------------- tests/_plugins/ui/_impl/test_plotly.py | 39 ++- 2 files changed, 129 insertions(+), 244 deletions(-) diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py index 53b5baed4fb..9435b69d1b9 100644 --- a/marimo/_plugins/ui/_impl/plotly.py +++ b/marimo/_plugins/ui/_impl/plotly.py @@ -3,6 +3,7 @@ import datetime import json +import math import numbers from functools import cached_property from typing import ( @@ -66,9 +67,14 @@ def _is_numpy_datetime(value: object) -> bool: class _AxisRange: - """Inclusive coordinate bounds. A result of None requests categorical placement.""" + """Inclusive Plotly selection bounds. + + `contains` and `mask` return `None` when the trace must supply + the position of a category on the axis. + """ def __init__(self, first: Any, last: Any) -> None: + # Keep the original strings for NumPy. Python parses only microseconds. self._endpoints = (first, last) first, last = _axis_coordinate(first), _axis_coordinate(last) if isinstance(first, datetime.datetime) and isinstance( @@ -94,7 +100,6 @@ def as_datetime64(value: Any) -> np.datetime64: if parsed.tzinfo is not None: return np.datetime64(parsed.replace(tzinfo=None)) if isinstance(value, str): - # NumPy can retain fractional seconds beyond Python's microseconds. try: return np.datetime64(value) except ValueError: @@ -113,21 +118,21 @@ def contains(self, value: Any) -> bool | None: return None value = _axis_coordinate(value) - if _is_numpy_datetime(value): - lower, upper = self._numpy_bounds - return bool(lower <= value <= upper) - if not isinstance(value, datetime.datetime): - return False - if _is_numpy_datetime(self.lower): + if isinstance(value, datetime.datetime) and _is_numpy_datetime( + self.lower + ): import numpy as np - lower, upper = self._numpy_bounds - native = ( + value = ( value.to_datetime64() if hasattr(value, "to_datetime64") else np.datetime64(value.replace(tzinfo=None)) ) - return bool(lower <= native <= upper) + 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. @@ -158,7 +163,7 @@ def mask(self, values: npt.NDArray[Any]) -> npt.NDArray[np.bool_] | None: and len(values) and isinstance(values[0], datetime.datetime) ): - # Compare datetime objects directly to preserve precision and skip conversion. + # Native comparisons preserve nanoseconds in pandas Timestamps. try: return np.asarray( (values >= self.lower) & (values <= self.upper), dtype=bool @@ -169,33 +174,45 @@ def mask(self, values: npt.NDArray[Any]) -> npt.NDArray[np.bool_] | None: (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.""" - 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 = _axis_coordinate(value) - if isinstance(parsed, datetime.datetime): - return _to_utc_timestamp(parsed) + if value.tzinfo is None: + value = value.replace(tzinfo=datetime.UTC) + return value.timestamp() return None @@ -376,7 +393,6 @@ def add_selection(selection: go.layout.Selection) -> None: for point_idx, (x, y) in enumerate( zip(x_data, y_data, strict=False) ): - # Early exit if x is not in range if not x_bounds.contains(x): continue if y_bounds.contains(y): @@ -689,21 +705,8 @@ def _extract_heatmap_cells_numpy( y_arr = np.asarray(y_data) z_arr = np.asarray(z_data) - x_mask = _AxisRange(x_min, x_max).mask(x_arr) - if x_mask is None: - # 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) - - y_mask = _AxisRange(y_min, y_max).mask(y_arr) - if y_mask is None: - # 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] @@ -1039,55 +1042,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_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 {} - x_category_positions = _category_position_map(x_data) - y_category_positions = _category_position_map(y_data) - - # 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 = x_bounds.contains(x_val) - if x_in_range is None: - # 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: - 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: bool | None = True + 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_in_range = y_bounds.contains(y_val) - if y_in_range is None: - # 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] + y_pos = _safe_category_get(y_positions, y_val, math.nan) + if not y_bounds.contains_at(y_val, y_pos): + continue point_dict = { x_field: x_val, y_field: y_val, @@ -1285,30 +1254,11 @@ def _extract_heatmap_cells_fallback( x_range = _AxisRange(x_min, x_max) y_range = _AxisRange(y_min, y_max) - # Iterate through the heatmap cells 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): - x_in_range = x_range.contains(x_val) - if x_in_range is None: - # 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 - ) - - y_in_range = y_range.contains(y_val) - if y_in_range is None: - # 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 @@ -1730,16 +1680,7 @@ def _extract_bars_numpy( pos_min, pos_max = y_min, y_max value_min, value_max = x_min, x_max - pos_mask = _AxisRange(pos_min, pos_max).mask(position_data) - if pos_mask is None: - # 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 @@ -1816,15 +1757,7 @@ def _extract_bars_fallback( position_range = _AxisRange(pos_min, pos_max) for i, pos_val in enumerate(position_data): - pos_in_range = position_range.contains(pos_val) - if pos_in_range is None: - # 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 @@ -2129,14 +2062,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_mask = _AxisRange(cat_min, cat_max).mask(cat_arr) + bounds = _AxisRange(cat_min, cat_max) + cat_mask = bounds.mask(cat_arr) if cat_mask is None: - cat_positions = np.arange(n, dtype=np.float64) - cat_mask = (cat_max > cat_positions - 0.5) & ( - cat_min < cat_positions + 0.5 - ) + 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) @@ -2200,10 +2130,7 @@ def _extract_waterfall_bars_fallback( bounds = _AxisRange(cat_min, cat_max) for i, (bar_lo, bar_hi) in enumerate(extents): - in_range = bounds.contains(cat_data[i]) - if in_range is None: - in_range = cat_min < i + 0.5 and cat_max > i - 0.5 - if not in_range: + if not bounds.contains_at(cat_data[i], i): continue # Value check: bar [bar_lo, bar_hi] overlaps [val_min, val_max] if val_min >= bar_hi or val_max <= bar_lo: @@ -2488,6 +2415,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]]: @@ -2530,40 +2489,9 @@ def _extract_violin_points_numpy( if n == 0: continue - if cat_data is None: - cat_arr = np.full(n, getattr(trace, "name", trace_idx)) - 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 = np.asarray([cat_val] * n) - else: - cat_arr = cat_arr_raw - - if cat_range: - cat_min, cat_max = min(cat_range), max(cat_range) - cat_mask = _AxisRange(cat_min, cat_max).mask(cat_arr) - if cat_mask is None: - 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: bounds = _AxisRange(min(val_range), max(val_range)) @@ -2913,47 +2841,13 @@ 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 = np.full(n, getattr(trace, "name", trace_idx)) - 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 = np.asarray([cat_val] * n) - else: - cat_arr = cat_arr_raw - - # --- Category filter --- - if cat_range: - cat_min, cat_max = min(cat_range), max(cat_range) - cat_mask = _AxisRange(cat_min, cat_max).mask(cat_arr) - if cat_mask is None: - # 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: bounds = _AxisRange(min(val_range), max(val_range)) val_mask = bounds.mask(val_arr) @@ -3158,13 +3052,7 @@ def _extract_violin_points_fallback( if cat_range: cat_min, cat_max = min(cat_range), max(cat_range) cat_bounds = _AxisRange(cat_min, cat_max) - 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 + seen_order = _category_position_map(cat_list) val_bounds = ( _AxisRange(min(val_range), max(val_range)) if val_range else None diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.py index 85d5a78b09b..c305acae49c 100644 --- a/tests/_plugins/ui/_impl/test_plotly.py +++ b/tests/_plugins/ui/_impl/test_plotly.py @@ -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, @@ -996,7 +997,14 @@ def test_bar_selection_datetime_x_axis() -> None: assert any(bar["x"] == dates[3] and bar["y"] == 25 for bar in result) -@pytest.mark.parametrize("use_numpy", [True, False]) +@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"] ) @@ -1015,14 +1023,9 @@ def test_bar_selection_datetime_x_axis() -> None: def test_range_selection_on_date_axis( trace_type: type, numpy_dates: bool, - use_numpy: bool, - monkeypatch: pytest.MonkeyPatch, ) -> None: import numpy as np - from marimo._dependencies.dependencies import DependencyManager - - monkeypatch.setattr(DependencyManager.numpy, "has", lambda: use_numpy) 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: @@ -1048,13 +1051,8 @@ def test_bar_selection_preserves_timestamp_precision() -> None: assert [point["x"] for point in plotly(fig).value] == x[:2] -@pytest.mark.parametrize("use_numpy", [True, False]) -def test_aware_bar_dates_with_aware_bounds( - use_numpy: bool, monkeypatch: pytest.MonkeyPatch -) -> None: - from marimo._dependencies.dependencies import DependencyManager - - monkeypatch.setattr(DependencyManager.numpy, "has", lambda: use_numpy) +@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( @@ -1063,7 +1061,7 @@ def test_aware_bar_dates_with_aware_bounds( assert [point["x"] for point in plotly(fig).value] == [position] -@pytest.mark.parametrize("use_numpy", [True, False]) +@pytest.mark.usefixtures("selection_backend") @pytest.mark.parametrize( "positions", [ @@ -1074,12 +1072,7 @@ def test_aware_bar_dates_with_aware_bounds( ) def test_bar_selection_date_positions( positions: list[date] | list[str], - use_numpy: bool, - monkeypatch: pytest.MonkeyPatch, ) -> None: - from marimo._dependencies.dependencies import DependencyManager - - monkeypatch.setattr(DependencyManager.numpy, "has", lambda: use_numpy) 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 == [ @@ -1093,6 +1086,7 @@ def test_bar_selection_date_positions( ] +@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 @@ -1101,9 +1095,12 @@ def test_bar_selection_numpy_date_positions(unit: str) -> None: ["2026-01-05", "2026-01-06", "2026-01-07"], dtype=f"datetime64[{unit}]" ) if unit == "ns": - positions[2] = positions[1] + np.timedelta64(500, "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-06") + 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] From d0e980635ec1197299a66209715537a3d9cc31a8 Mon Sep 17 00:00:00 2001 From: Kiran Gadhave Date: Thu, 3 Dec 2026 15:07:18 -0800 Subject: [PATCH 3/3] fix(plotly): preserve sub-microsecond ranges and guard waterfall indices Keep fractional digits when parsing selection bounds and positions so exact matches agree across timestamp representations. Check the category length before reading a waterfall label in the Python fallback. --- marimo/_plugins/ui/_impl/plotly.py | 76 ++++++++++++++++---------- tests/_plugins/ui/_impl/test_plotly.py | 27 +++++++++ 2 files changed, 74 insertions(+), 29 deletions(-) diff --git a/marimo/_plugins/ui/_impl/plotly.py b/marimo/_plugins/ui/_impl/plotly.py index 9435b69d1b9..4a340aeccff 100644 --- a/marimo/_plugins/ui/_impl/plotly.py +++ b/marimo/_plugins/ui/_impl/plotly.py @@ -5,6 +5,7 @@ import json import math import numbers +import re from functools import cached_property from typing import ( TYPE_CHECKING, @@ -66,6 +67,34 @@ def _is_numpy_datetime(value: object) -> bool: return getattr(getattr(value, "dtype", None), "kind", None) == "M" +_SUBMICROSECOND_DIGITS = re.compile(r"^[\dW-]+\D[\d:]+[.,]\d{6}(\d+)") + + +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, "" + + +def _as_datetime64(value: Any, fraction: str) -> np.datetime64: + import numpy as np + + if isinstance(value, datetime.datetime): + value = value.replace(tzinfo=None) + if fraction: + value = value.isoformat(timespec="microseconds") + fraction + return np.datetime64(value) + + class _AxisRange: """Inclusive Plotly selection bounds. @@ -74,9 +103,8 @@ class _AxisRange: """ def __init__(self, first: Any, last: Any) -> None: - # Keep the original strings for NumPy. Python parses only microseconds. - self._endpoints = (first, last) - first, last = _axis_coordinate(first), _axis_coordinate(last) + first, first_fraction = _coordinate_parts(first) + last, last_fraction = _coordinate_parts(last) if isinstance(first, datetime.datetime) and isinstance( last, datetime.datetime ): @@ -85,28 +113,18 @@ def __init__(self, first: Any, last: Any) -> None: first.replace(tzinfo=None), last.replace(tzinfo=None), ) - self.lower, self.upper = sorted((first, last)) + ( + (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]: - import numpy as np - - def as_datetime64(value: Any) -> np.datetime64: - parsed = _axis_coordinate(value) - if isinstance(parsed, datetime.datetime): - if parsed.tzinfo is not None: - return np.datetime64(parsed.replace(tzinfo=None)) - if isinstance(value, str): - try: - return np.datetime64(value) - except ValueError: - pass - return np.datetime64(parsed) - - first, last = map(as_datetime64, self._endpoints) + 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: @@ -117,17 +135,11 @@ def contains(self, value: Any) -> bool | None: return bool(self.lower <= value <= self.upper) return None - value = _axis_coordinate(value) + value, fraction = _coordinate_parts(value) if isinstance(value, datetime.datetime) and _is_numpy_datetime( self.lower ): - import numpy as np - - value = ( - value.to_datetime64() - if hasattr(value, "to_datetime64") - else np.datetime64(value.replace(tzinfo=None)) - ) + value = _as_datetime64(value, fraction) if _is_numpy_datetime(value): start, end = self._numpy_bounds return bool(start <= value <= end) @@ -141,7 +153,11 @@ def contains(self, value: Any) -> bool | None: upper.replace(tzinfo=None), ) value = value.replace(tzinfo=None) - return bool(lower <= value <= upper) + return ( + (lower, self._lower_fraction) + <= (value, fraction) + <= (upper, self._upper_fraction) + ) def mask(self, values: npt.NDArray[Any]) -> npt.NDArray[np.bool_] | None: import numpy as np @@ -162,6 +178,7 @@ def mask(self, values: npt.NDArray[Any]) -> npt.NDArray[np.bool_] | None: 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: @@ -2130,7 +2147,8 @@ def _extract_waterfall_bars_fallback( bounds = _AxisRange(cat_min, cat_max) for i, (bar_lo, bar_hi) in enumerate(extents): - if not bounds.contains_at(cat_data[i], i): + 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: diff --git a/tests/_plugins/ui/_impl/test_plotly.py b/tests/_plugins/ui/_impl/test_plotly.py index c305acae49c..eb225bc0533 100644 --- a/tests/_plugins/ui/_impl/test_plotly.py +++ b/tests/_plugins/ui/_impl/test_plotly.py @@ -1051,6 +1051,26 @@ def test_bar_selection_preserves_timestamp_precision() -> None: 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") @@ -3891,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(