Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion marimo/_plugins/ui/_impl/charts/altair_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def sanitize_nan_infs(data: Any) -> Any:
"""Sanitize NaN and Inf values in Dataframes for JSON serialization."""
if can_narwhalify(data):
narwhals_data = nw.from_native(data)
is_prev_lazy = isinstance(narwhals_data, nw.LazyFrame)
is_prev_lazy = is_narwhals_lazyframe(narwhals_data)

# Convert to lazy for optimization if not already lazy
if not is_prev_lazy:
Expand Down
51 changes: 32 additions & 19 deletions marimo/_plugins/ui/_impl/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -952,24 +952,28 @@ def _get_column_summaries(
)

# For boolean columns, we can drop the column since we use stats
column_type = self._manager.get_field_type(column)
if column_type[0] == "boolean":
(column_type, external_type) = self._manager.get_field_type(
column
)
if column_type == "boolean":
data = data.drop_columns([column])

# Bin values are only supported for numeric and temporal columns
if column_type[0] not in [
"integer",
"number",
"date",
"datetime",
"time",
"string",
]:
continue
# Handle columns with all nulls first
# These get empty bins regardless of type
if statistic and statistic.nulls == total_rows:
try:
bin_values[column] = []
data = data.drop_columns([column])
continue
except BaseException as e:
LOGGER.warning(
"Failed to drop all-null column %s: %s", column, e
)
continue

# For perf, we only compute value counts for categorical columns
external_type = column_type[1].lower()
if column_type[0] == "string" and (
external_type = external_type.lower()
if column_type == "string" and (
"cat" in external_type or "enum" in external_type
):
try:
Expand All @@ -987,13 +991,22 @@ def _get_column_summaries(
e,
)

# Bin values are only supported for numeric and temporal columns
if column_type not in [
"integer",
"number",
"date",
"datetime",
"time",
]:
continue

try:
if statistic and statistic.nulls == total_rows:
bins = []
else:
bins = data.get_bin_values(column, DEFAULT_BIN_SIZE)
bins = data.get_bin_values(column, DEFAULT_BIN_SIZE)
bin_values[column] = bins
data = data.drop_columns([column])
# Only drop column if we got bins to visualize
if len(bins) > 0:
data = data.drop_columns([column])
continue
except BaseException as e:
LOGGER.warning(
Expand Down
220 changes: 20 additions & 200 deletions marimo/_plugins/ui/_impl/tables/ibis_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,19 @@

import datetime
import functools
from typing import TYPE_CHECKING, Any, Optional, Union
from typing import TYPE_CHECKING, Any, Union

import narwhals.stable.v2 as nw

from marimo import _loggers
from marimo._data.models import BinValue, ColumnStats, ExternalDataType
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.tables.format import (
FormatMapping,
)
from marimo._plugins.ui._impl.tables.pandas_table import (
PandasTableManagerFactory,
)
from marimo._plugins.ui._impl.tables.polars_table import (
PolarsTableManagerFactory,
)
from marimo._data.models import BinValue, ExternalDataType
from marimo._plugins.ui._impl.tables.narwhals_table import NarwhalsTableManager
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
FieldType,
FieldTypes,
TableCell,
TableCoordinate,
TableManager,
TableManagerFactory,
)
from marimo._utils.memoize import memoize_last_value

LOGGER = _loggers.marimo_logger()

Expand All @@ -44,127 +33,24 @@ def package_name() -> str:
def create() -> type[TableManager[Any]]:
import ibis # type: ignore

class IbisTableManager(TableManager[ibis.Table]):
class IbisTableManager(NarwhalsTableManager[ibis.Table, ibis.Table]):
type = "ibis"

def to_csv_str(
self, format_mapping: Optional[FormatMapping] = None
) -> str:
return self._as_table_manager().to_csv_str(format_mapping)

def to_json_str(
self, format_mapping: Optional[FormatMapping] = None
) -> str:
return self._as_table_manager().to_json_str(format_mapping)

def to_parquet(self) -> bytes:
return self._as_table_manager().to_parquet()

def supports_download(self) -> bool:
return False

def apply_formatting(
self, format_mapping: Optional[FormatMapping]
) -> IbisTableManager:
raise NotImplementedError("Column formatting not supported")

def supports_filters(self) -> bool:
return True

def select_rows(
self, indices: list[int]
) -> TableManager[ibis.Table]:
if not indices:
return self.take(0, 0) # Return empty table
# Select rows using Ibis API
return IbisTableManager(
self.data.filter(ibis.row_number().over().isin(indices))
)
def __init__(self, data: ibis.Table) -> None:
self._original_data = data
super().__init__(nw.from_native(data))

def select_columns(
self, columns: list[str]
) -> TableManager[ibis.Table]:
return IbisTableManager(self.data.select(columns))

def select_cells(
self, cells: list[TableCoordinate]
) -> list[TableCell]:
del cells
raise NotImplementedError("Cell selection not supported")

def drop_columns(
self, columns: list[str]
) -> TableManager[ibis.Table]:
return IbisTableManager(self.data.drop(columns))

def get_row_headers(self) -> FieldTypes:
return []
def collect(self) -> ibis.Table:
return self._original_data

@staticmethod
def is_type(value: Any) -> bool:
return isinstance(value, ibis.Table)

def take(self, count: int, offset: int) -> IbisTableManager:
if count < 0:
raise ValueError("Count must be a positive integer")
if offset < 0:
raise ValueError("Offset must be a non-negative integer")
return IbisTableManager(self.data.limit(count, offset=offset))

def search(self, query: str) -> TableManager[Any]:
query = query.lower()
predicates = []
for column in self.data.columns:
col = self.data[column]
if col.type().is_string():
predicates.append(col.lower().rlike(query))
elif col.type().is_numeric():
predicates.append(
col.cast("string").lower().contains(query)
)
elif col.type().is_boolean():
predicates.append(
col.cast("string").lower().contains(query)
)
elif col.type().is_timestamp():
predicates.append(
col.cast("string").lower().contains(query)
)
elif col.type().is_date():
predicates.append(
col.cast("string").lower().contains(query)
)
elif col.type().is_time():
predicates.append(
col.cast("string").lower().contains(query)
)

if predicates:
filtered = self.data.filter(ibis.or_(*predicates))
else:
filtered = self.data.filter(ibis.literal(False))

return IbisTableManager(filtered)

def get_stats(self, column: str) -> ColumnStats:
col = self.data[column]
total = self.data.count().execute()
nulls = col.isnull().sum().execute()

stats = ColumnStats(total=total, nulls=nulls)

if col.type().is_numeric():
stats.min = col.min().execute()
stats.max = col.max().execute()
stats.mean = col.mean().execute()
stats.median = col.median().execute()
stats.std = col.std().execute()

return stats

def _get_numeric_bin_values(
self, col: ibis.Column, num_bins: int
) -> ibis.Table:
data = self._original_data
min_val = col.min().execute()
max_val = col.max().execute()

Expand All @@ -184,7 +70,7 @@ def _get_numeric_bin_values(
bin_width = (max_val - min_val) / num_bins

# Assign bins and count occurrences
data = self.data.mutate(bin=col.histogram(nbins=num_bins))
data = data.mutate(bin=col.histogram(nbins=num_bins))
value_counts = data["bin"].value_counts(name="count")

# Fill in missing bins
Expand Down Expand Up @@ -217,11 +103,12 @@ def get_bin_values(
Returns:
list[BinValue]: The bin values.
"""
if column not in self.data.columns:
data = self._original_data
if column not in data.columns:
LOGGER.error(f"Column {column} not found in Ibis table")
return []

col = self.data[column]
col = data[column]
dtype = col.type()

if dtype.is_temporal():
Expand All @@ -246,14 +133,16 @@ def get_bin_values(
def _get_bin_values_temporal(
self, column: ColumnName, dtype: DataType, num_bins: int
) -> list[BinValue]:
data = self._original_data

def _convert_ms_to_time(ms: int) -> datetime.time:
hours = ms // 3600000
minutes = (ms % 3600000) // 60000
seconds = (ms % 60000) // 1000
microseconds = (ms % 1000) * 1000
return datetime.time(hours, minutes, seconds, microseconds)

col = self.data[column]
col = data[column]

if dtype.is_time():
col_agg = (
Expand Down Expand Up @@ -301,65 +190,10 @@ def _convert_ms_to_time(ms: int) -> datetime.time:

return bin_values

@memoize_last_value
def get_num_rows(self, force: bool = True) -> Optional[int]:
if force:
return self.data.count().execute() # type: ignore
return None

def get_num_columns(self) -> int:
return len(self.data.columns)

def get_column_names(self) -> list[str]:
return self.data.columns # type: ignore

def get_unique_column_values(
self, column: str
) -> list[str | int | float]:
result = (
self.data.distinct(on=column)
.select(column)
.execute()[column]
.tolist()
)
return result # type: ignore

def get_sample_values(self, column: str) -> list[Any]:
# Don't sample values for Ibis tables
# since it can be expensive
del column
return []

def sort_values(
self, by: ColumnName, descending: bool
) -> IbisTableManager:
sorted_data = self.data.order_by(
ibis.desc(by) if descending else ibis.asc(by)
)
return IbisTableManager(sorted_data)

@functools.lru_cache(maxsize=5) # noqa: B019
def calculate_top_k_rows(
self, column: ColumnName, k: int
) -> list[tuple[Any, int]]:
count_col_name = f"{column}_count"
result = (
self.data[[column]]
.value_counts(name=count_col_name)
.order_by(ibis.desc(count_col_name))
.limit(k)
.execute()
)

return [
(row[0], int(row[1]))
for row in result.itertuples(index=False)
]

def get_field_type(
self, column_name: str
) -> tuple[FieldType, ExternalDataType]:
column = self.data[column_name]
column = self._original_data[column_name]
dtype = column.type()
if dtype.is_string():
return ("string", str(dtype))
Expand All @@ -378,18 +212,4 @@ def get_field_type(
else:
return ("unknown", str(dtype))

def _as_table_manager(self) -> TableManager[Any]:
if DependencyManager.pandas.has():
return PandasTableManagerFactory.create()(
self.data.to_pandas()
)
if DependencyManager.polars.has():
return PolarsTableManagerFactory.create()(
self.data.to_polars()
)

raise ValueError(
"Requires at least one of pandas, polars, or pyarrow"
)

return IbisTableManager
Loading
Loading