Skip to content
Open
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
13 changes: 7 additions & 6 deletions dataframely/_base_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,13 @@ def _get_metadata_recursively(kls: type[object]) -> Metadata:
@staticmethod
def _get_metadata(source: Mapping[str, Any]) -> Metadata:
result = Metadata()
for attr, value in {
k: v for k, v in source.items() if not k.startswith("__")
}.items():
for attr, value in source.items():
if attr.startswith("__"):
continue
if isinstance(value, Column):
if (col_name := value.alias or attr) in result.columns:
raise ImplementationError(f"Column {col_name!r} is duplicated.")
result.columns[value.alias or attr] = value
result.columns[col_name] = value
if isinstance(value, RuleFactory):
# We must ensure that custom rules do not clash with internal rules.
if attr == "primary_key":
Expand Down Expand Up @@ -284,9 +284,10 @@ def column_names(cls) -> list[str]:
def columns(cls) -> dict[str, Column]:
"""The column definitions of this schema."""
columns: dict[str, Column] = getattr(cls, _COLUMN_ATTR)
for name in columns.keys():
schema_id = f"{cls.__module__}:{cls.__name__}"
for name, column in columns.items():
# Dynamically set the name and source schema of the columns.
columns[name]._bind(f"{cls.__module__}:{cls.__name__}", name)
column._bind(schema_id, name)
return columns

@classmethod
Expand Down
2 changes: 1 addition & 1 deletion dataframely/_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def all_rules_required(
"""
rules_list = [rules] if isinstance(rules, pl.Expr) else list(rules)
num_rule_columns = len(rules_list)
data_columns_list = list(data_columns) if data_columns is not None else []
data_columns_list = list(data_columns)
return register_plugin_function(
plugin_path=PLUGIN_PATH,
function_name="all_rules_required",
Expand Down
9 changes: 9 additions & 0 deletions dataframely/_polars.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ def timedelta_matches_resolution(d: dt.timedelta, resolution: str) -> bool:
return datetime_matches_resolution(EPOCH_DATETIME + d, resolution)


def read_parquet_metadata(source: Any, **kwargs: Any) -> dict[str, str]:
"""Read parquet metadata, forwarding the relevant options of a read/scan call."""
return pl.read_parquet_metadata(
source,
storage_options=kwargs.get("storage_options"),
credential_provider=kwargs.get("credential_provider"),
)


def collect_if(lf: pl.LazyFrame, condition: bool, **kwargs: Any) -> pl.LazyFrame:
"""Collect a lazy frame based on `condition`."""
if condition:
Expand Down
4 changes: 1 addition & 3 deletions dataframely/_pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,5 @@ def get_pydantic_core_schema(
def get_pydantic_json_schema(
handler: pydantic.GetJsonSchemaHandler,
) -> pydantic.json_schema.JsonSchemaValue:
from pydantic_core import core_schema

# This could be made more sophisticated by actually reflecting the schema.
return handler(core_schema.dict_schema())
return handler(pydantic_core_schema.dict_schema())
17 changes: 5 additions & 12 deletions dataframely/collection/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,18 +209,16 @@ def _get_metadata(source: dict[str, Any]) -> Metadata:
annotate_func = source["__annotate_func__"]
# __annotate_func__ can be None in Python 3.14 when a class
# has no annotations or in certain metaclass scenarios
if annotate_func is not None and callable(annotate_func):
if callable(annotate_func):
annotations = annotate_func(Format.VALUE)
for attr, kls in annotations.items():
result.members[attr] = CollectionMeta._derive_member_info(
attr, kls, CollectionMember()
)

# Get all filters by traversing the source
for attr, value in {
k: v for k, v in source.items() if not k.startswith("__")
}.items():
if isinstance(value, Filter):
for attr, value in source.items():
if not attr.startswith("__") and isinstance(value, Filter):
result.filters[attr] = value

return result
Expand Down Expand Up @@ -375,14 +373,9 @@ def _failure_propagating_members(cls) -> set[str]:
@classmethod
def common_primary_key(cls) -> list[str]:
"""The primary keys shared by non ignored members of the collection."""
schemas = cls.member_schemas()
return sorted(
_common_primary_key(
[
member.schema
for member in cls.members().values()
if not member.ignored_in_filters
]
)
_common_primary_key([schemas[name] for name in cls.non_ignored_members()])
)

@classmethod
Expand Down
50 changes: 19 additions & 31 deletions dataframely/collection/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@

import polars as pl

from dataframely._native import format_rule_failures
from dataframely._plugin import all_rules_required
from dataframely._polars import FrameType, collect_all_if
from dataframely.config import Config
from dataframely._polars import FrameType, collect_all_if, read_parquet_metadata
from dataframely.exc import ValidationError
from dataframely.filter_result import FailureInfo
from dataframely.random import Generator
Expand Down Expand Up @@ -405,19 +403,12 @@ def validate(
**kwargs,
)
if any(len(failure) > 0 for failure in failures.values()):
errors: dict[str, str] = {}
for member, failure in failures.items():
if len(failure) == 0:
continue

counts = failure.counts()
errors[member] = format_rule_failures(
list(counts.items()),
failures_from=failure._df.select(counts.keys()),
examples_from=failure.invalid(),
primary_key_columns=cls.member_schemas()[member].primary_key(),
max_examples=Config.options["max_failure_examples"],
)
member_schemas = cls.member_schemas()
errors = {
member: member_schemas[member]._format_failures(failure)
for member, failure in failures.items()
if len(failure) > 0
}

details = [
f" > Member '{member}' failed validation:\n"
Expand Down Expand Up @@ -467,8 +458,8 @@ def validate(
filter_names,
null_is_valid=False,
schema_name=name,
data_columns=cls.common_primary_key(),
primary_key_columns=cls.common_primary_key(),
data_columns=primary_key,
primary_key_columns=primary_key,
)
)
.drop(filter_names)
Expand Down Expand Up @@ -637,8 +628,6 @@ class HospitalInvoiceData(dy.Collection):
name: filter.logic(result_cls).select(primary_key)
for name, filter in filters.items()
}
keep = collect_all_if(keep, not lazy, **kwargs)

drop: dict[str, pl.LazyFrame] = {
f"{failure_propagating_member}|failure_propagation": (
failures[failure_propagating_member]
Expand All @@ -647,7 +636,10 @@ class HospitalInvoiceData(dy.Collection):
)
for failure_propagating_member in failure_propagating_members
}
drop = collect_all_if(drop, not lazy, **kwargs)
# Keep and drop frames are independent: collect them together.
collected = collect_all_if({**keep, **drop}, not lazy, **kwargs)
keep = {name: collected[name] for name in keep}
drop = {name: collected[name] for name in drop}

# Now we can iterate over the results and left-join onto each individual
# filter to obtain independent boolean indicators of whether to keep the row.
Expand All @@ -657,10 +649,10 @@ class HospitalInvoiceData(dy.Collection):
if member_info.ignored_in_filters:
continue

lf_with_eval = filtered.lazy()
lf_with_eval = filtered
for name, filter_keep in keep.items():
lf_with_eval = lf_with_eval.join(
filter_keep.lazy().with_columns(pl.lit(True).alias(name)),
filter_keep.with_columns(pl.lit(True).alias(name)),
on=primary_key,
how="left",
maintain_order="left",
Expand Down Expand Up @@ -700,7 +692,7 @@ class HospitalInvoiceData(dy.Collection):
failure = failures[member_name]
filtered_failure = lf_with_eval.filter(
~pl.all_horizontal(all_filter_columns)
).lazy()
)

# If we cast previously, `failure` and `filtered_failure` have different
# dtypes for the source data: `failure` keeps the original dtypes while
Expand Down Expand Up @@ -775,7 +767,7 @@ def join(
may fail, especially if `primary_keys` does not contain all columns
for all common primary keys.
"""
if any(member.ignored_in_filters for member in self.members().values()):
if self.ignored_members():
raise ValueError(
"The join operation is not supported for collections with members that are ignored in filters."
)
Expand Down Expand Up @@ -995,11 +987,7 @@ def scan_parquet(cls, directory: str | Path, **kwargs: Any) -> Self:
path = os.path.join(str(directory), f"{member}.parquet")
if info.is_optional:
try:
pl.read_parquet_metadata(
path,
storage_options=kwargs.get("storage_options"),
credential_provider=kwargs.get("credential_provider"),
)
read_parquet_metadata(path, **kwargs)
except FileNotFoundError:
continue
members[member] = pl.scan_parquet(path, **kwargs)
Expand All @@ -1011,7 +999,7 @@ def scan_parquet(cls, directory: str | Path, **kwargs: Any) -> Self:

@classmethod
def _validate_lazy_param(cls, lazy: bool, /) -> None:
if lazy and any(not member.is_lazy for member in cls.members().values()):
if lazy and cls.eager_members():
raise ValueError(
"Cannot use `lazy=True` on a collection with eager members."
)
Expand Down
29 changes: 28 additions & 1 deletion dataframely/columns/_mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
# SPDX-License-Identifier: BSD-3-Clause

from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, Generic, Protocol, Self, TypeVar
from copy import copy
from typing import TYPE_CHECKING, Any, Generic, Protocol, Self, TypeVar, cast

import polars as pl

Expand Down Expand Up @@ -105,3 +106,29 @@ def validation_rules(self, expr: pl.Expr) -> dict[str, pl.Expr]:
if self.is_in is not None:
result["is_in"] = expr.is_in(self.is_in)
return result


# -------------------------------- INNER COLUMN MIXIN -------------------------------- #


class InnerColumnMixin(Base):
"""Mixin for container columns with a single ``inner`` column (lists, arrays)."""

inner: "Column"

def _bind(self, schema: str, name: str) -> None:
super()._bind(schema, name)
self.inner = copy(self.inner)
self.inner._bind(schema, f"{name}.inner")

@property
def _python_type(self) -> Any:
inner_type = self.inner.pydantic_field()
return list[inner_type] # type: ignore

def _attributes_match(
self, lhs: Any, rhs: Any, name: str, column_expr: pl.Expr
) -> bool:
if name == "inner":
return cast("Column", lhs).matches(cast("Column", rhs), pl.element())
return super()._attributes_match(lhs, rhs, name, column_expr)
23 changes: 3 additions & 20 deletions dataframely/columns/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@

import math
import warnings
from copy import copy
from typing import Any, cast
from typing import Any

import polars as pl

from dataframely._compat import sa, sa_TypeEngine
from dataframely.random import Generator

from ._base import Check, Column
from ._mixins import InnerColumnMixin
from .list import _list_primary_key_check


class Array(Column):
class Array(InnerColumnMixin, Column):
"""A fixed-shape array column."""

def __init__(
Expand Down Expand Up @@ -77,11 +77,6 @@ def __init__(
self.inner = inner
self.shape = shape if isinstance(shape, tuple) else (shape,)

def _bind(self, schema: str, name: str) -> None:
super()._bind(schema, name)
self.inner = copy(self.inner)
self.inner._bind(schema, f"{name}.inner")

@property
def dtype(self) -> pl.DataType:
return pl.Array(self.inner.dtype, self.shape)
Expand Down Expand Up @@ -138,11 +133,6 @@ def _arrow_nullability(self) -> tuple[bool, list[Any]]:
nullability = (True, [nullability])
return (self.nullable, [nullability])

@property
def _python_type(self) -> Any:
inner_type = self.inner.pydantic_field()
return list[inner_type] # type: ignore

def _pydantic_field_kwargs(self) -> dict[str, Any]:
if len(self.shape) != 1:
warnings.warn(
Expand All @@ -165,10 +155,3 @@ def _sample_unchecked(self, generator: Generator, n: int) -> pl.Series:
all_elements.reshape((n, *self.shape)),
null_probability=self._null_probability,
)

def _attributes_match(
self, lhs: Any, rhs: Any, name: str, column_expr: pl.Expr
) -> bool:
if name == "inner":
return cast(Column, lhs).matches(cast(Column, rhs), pl.element())
return super()._attributes_match(lhs, rhs, name, column_expr)
2 changes: 0 additions & 2 deletions dataframely/columns/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ def __init__(
`items.inner.kind` for a field in a list of structs).
nullable: Whether this column may contain null values.
Explicitly set `nullable=True` if you want your column to be nullable.
In a future release, `nullable=False` will be the default if `nullable`
is not specified.
primary_key: Whether this column is part of the primary key of the schema.
If `True`, `nullable` is automatically set to `False`.
unique: Whether this column must contain unique values. Unlike `primary_key`,
Expand Down
Loading
Loading