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
11 changes: 11 additions & 0 deletions changelog.d/ITL-1777.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
### Added

- A boolean column is a condition on its own (ITL-1777): `stream.filter(col("flag"))`
keeps the rows where `flag` is true and `stream.filter(~col("flag"))` the rows where it
is false. They are the conditions `col("flag") == True` and `col("flag") == False`, with
the same identity, so no hash moves and the two spellings give one filter. A null is
neither true nor false, so a row with a null is kept by neither. A bare column combines
with other conditions through `&` and `|` (`col("flag") & (col("t") > 1.0)`) and is
accepted by `filter`, `Filter`, `Condition.of` and a SpiralDB source's `where`, which
sends it to SpiralDB as that equality. `col(c).is_true()` is the explicit form. A column
that is not boolean is refused when the condition meets the stream.
45 changes: 45 additions & 0 deletions docs/concepts/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,7 @@ The conditions are:
| comparison | `col(c) < v`, `<=`, `>`, `>=` | integers, floats, strings, binary, dates, timestamps |
| range | `col(c).between(low, high)`, both ends included | the same |
| null test | `col(c).is_null()`, `col(c).is_not_null()` | every type |
| boolean column | `col(c)` (true rows, `col(c) == True`), `~col(c)` (false rows, `col(c) == False`) | bool |
| struct field | `col(c).field("f")`, then any condition above | a struct column |
| two columns | `col(a) < col(b)` and the other comparisons | two columns of one Arrow type |
| combined | several arguments and keywords (all hold), `a & b`, `a \| b`, `~a` | |
Expand Down Expand Up @@ -806,6 +807,50 @@ assert (False or bounds) is bounds

Use `col(c).is_in([...])` to test membership in a list.

A boolean column is a condition on its own: `col("c")` keeps the rows where it is true and
`~col("c")` the rows where it is false. They are the conditions `col("c") == True` and
`col("c") == False`, with the same identity. A null is neither true nor false, so a row
with a null is kept by neither. A column that is not boolean is refused when the filter
meets the stream:

```python
from orcapod.errors import InputValidationError

checked = ArrowTableSource(
pa.table(
{
"unit": [3, 7, 9, 11],
"noisy": [False, True, None, False],
"sorted": [True, True, False, None],
}
),
tag_columns=["unit"],
tag_only_columns=True,
source_id="checked",
)


def units(stream):
return sorted(stream.as_table()["unit"].to_pylist())


print(units(checked.filter(col("noisy"))))
# [7]
print(units(checked.filter(~col("noisy"))))
# [3, 11]
print(units(checked.filter(~col("noisy") & col("sorted"))))
# [3]
print(units(checked.filter(col("noisy") | ~col("sorted"))))
# [7, 9]
assert checked.filter(~col("noisy")).content_hash() == checked.filter(noisy=False).content_hash()

try:
checked.filter(col("unit"))
except InputValidationError as error:
print(str(error).split(";")[0])
# Filter: column 'unit' holds int, but the value True is a bool
```

A condition that no row can satisfy is kept as written and keeps zero rows: Orcapod does not
try to tell a contradiction (there is no general way). Naming one column twice in one call
with two values is refused, as an argument error:
Expand Down
7 changes: 4 additions & 3 deletions src/orcapod/core/operators/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol
from orcapod.system_constants import constants
from orcapod.types import ColumnConfig, ContentHash, Schema
from orcapod.types.condition import Condition, check_condition_columns
from orcapod.types.condition import ColumnRef, Condition, check_condition_columns


def _user_columns(
Expand Down Expand Up @@ -67,7 +67,8 @@ class Filter(UnaryOperator):
later release.

Args:
condition: The condition, or a mapping of column equalities.
condition: The condition, a mapping of column equalities, or a bare
``col(c)`` of a boolean column (``col(c) == True``).

Raises:
ValueError: If the condition names no column.
Expand All @@ -87,7 +88,7 @@ class Filter(UnaryOperator):
PROVISIONAL: ClassVar[bool] = True

def __init__(
self, condition: Condition | Mapping[str, object], **kwargs: Any
self, condition: Condition | ColumnRef | Mapping[str, object], **kwargs: Any
) -> None:
self._condition: Condition = Condition.of(condition)
super().__init__(**kwargs)
Expand Down
9 changes: 6 additions & 3 deletions src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
require_same_process,
)
from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError
from orcapod.types import ColumnConfig, Condition
from orcapod.types import ColumnConfig, ColumnRef, Condition
from orcapod.types.condition import check_float_equalities, check_restriction
from orcapod.utils import arrow_utils
from orcapod.utils.schema_utils import _normalize_column_list
Expand Down Expand Up @@ -541,7 +541,7 @@ def table_id(self) -> str:
def where(
self,
/,
*conditions: "Mapping[str, object] | Condition | None",
*conditions: "Mapping[str, object] | Condition | ColumnRef | None",
**columns: object,
) -> "SpiralDBTableSource":
"""Return a new source on the same table that reads only the matching rows.
Expand All @@ -559,7 +559,10 @@ def where(
``limit``, the new source reads the first ``limit`` rows that match.

Two kinds of condition are taken, all of which must hold: a column equal to a
value (a keyword, a mapping, ``col(c) == v``), and a range of an integer,
value (a keyword, a mapping, ``col(c) == v``; a bare ``col(c)`` of a boolean
column is ``col(c) == True`` and ``~col(c)`` is ``col(c) == False``, sent to
SpiralDB as those equalities, so a null row is read by neither), and a range
of an integer,
timestamp or date column (``col("t") >= start``, ``col("t") < stop``,
``col("t").between(a, b)``, which includes both ends). Write a window half-open,
``>= start`` and ``< stop``: adjacent windows then neither overlap nor leave a
Expand Down
8 changes: 5 additions & 3 deletions src/orcapod/core/streams/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
)
from orcapod.protocols.core_protocols.streams import RecordBatchInput
from orcapod.system_constants import constants
from orcapod.types import ColumnConfig, Condition, ContentHash, Schema
from orcapod.types import ColumnConfig, ColumnRef, Condition, ContentHash, Schema
from orcapod.utils import arrow_utils

if TYPE_CHECKING:
Expand Down Expand Up @@ -1123,7 +1123,7 @@ def polars_filter(

def filter(
self,
*conditions: Condition | Mapping[str, object],
*conditions: Condition | ColumnRef | Mapping[str, object],
label: str | None = None,
**columns: object,
) -> StreamBase:
Expand All @@ -1137,7 +1137,9 @@ def filter(
``orcapod.core.operators.Filter``.

Args:
*conditions: Conditions (built with ``col`` or ``Condition.of``) and
*conditions: Conditions (built with ``col`` or ``Condition.of``; a bare
``col(c)`` of a boolean column keeps its true rows, ``~col(c)`` its
false rows) and
mappings of column name to value.
label: Optional node label for the pipeline graph. A column named
``label`` is written ``filter({"label": ...})`` or with ``col``.
Expand Down
4 changes: 2 additions & 2 deletions src/orcapod/protocols/core_protocols/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
IdentityChainProtocol,
PipelineElementProtocol,
)
from orcapod.types import ColumnConfig, Condition, Schema
from orcapod.types import ColumnConfig, ColumnRef, Condition, Schema

if TYPE_CHECKING:
from orcapod.types.explanation import Explanation
Expand Down Expand Up @@ -496,7 +496,7 @@ def polars_filter(

def filter(
self,
*conditions: Condition | Mapping[str, object],
*conditions: Condition | ColumnRef | Mapping[str, object],
label: str | None = None,
**columns: object,
) -> "StreamProtocol":
Expand Down
113 changes: 99 additions & 14 deletions src/orcapod/types/condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,7 @@ def check_value_for_column(
f"to {expected.__name__} (a "
"NumPy scalar with .item(), a date or time string with date.fromisoformat "
"or datetime.fromisoformat): Orcapod converts no value"
+ _bare_reference_hint(value)
)
if isinstance(value, datetime):
zoned = getattr(arrow_type, "tz", None) is not None
Expand Down Expand Up @@ -527,6 +528,21 @@ def check_value_for_column(
)


def _bare_reference_hint(value: object) -> str:
"""Return what a bool value given for a column of another type may come from.

A bare reference (``col(c)``, ``~col(c)``) is the equality to ``True`` or ``False``,
so a bare reference to a column that is not boolean meets the value check here.
"""
if type(value) is not bool:
return ""
return (
". A bare col(c) stands for col(c) == True and ~col(c) for col(c) == False: "
"both take a boolean column only; compare a column of another type with a "
"value of its own type"
)


def _literal_repr(value: object) -> str:
"""Show a rejected literal even when Python limits integer string conversion."""
if type(value) is int:
Expand Down Expand Up @@ -716,7 +732,7 @@ def check_condition_columns(
raise TypeError(
f"column {term.path.column!r} holds {getattr(column_type, '__name__', column_type)}, "
f"but the value {one!r} is a {type(one).__name__}; convert it "
"explicitly: Orcapod converts no value"
"explicitly: Orcapod converts no value" + _bare_reference_hint(one)
)


Expand Down Expand Up @@ -871,7 +887,7 @@ def _matched_by_bits(value: object) -> bool:


def check_float_equalities(
*conditions: Mapping[str, object] | Condition | None, **columns: object
*conditions: Mapping[str, object] | Condition | ColumnRef | None, **columns: object
) -> None:
"""For now, refuse equality to ``-0.0`` or NaN before merging (ITL-1480).

Expand Down Expand Up @@ -1106,6 +1122,55 @@ def __gt__(self, other: object) -> Condition:
def __ge__(self, other: object) -> Condition:
return self._term(">=", other)

def is_true(self) -> Condition:
"""Return the condition that this boolean column is true: ``col(c) == True``.

A bare reference stands for it wherever a condition is taken
(``filter(col("flag"))``, ``col("flag") & (col("t") > 1)``), so the two forms
are one condition, with one identity. A null is not true, so a row with a null
is not kept. The column must be boolean, checked when the condition meets a
stream.

Returns:
The condition.
"""
return self._term(EQUALS, True)

def __invert__(self) -> Condition:
"""Return the condition that this boolean column is false: ``col(c) == False``.

``~col("flag")`` and ``col("flag") == False`` are one condition, with one
identity. A null is neither true nor false, so a row with a null is kept by
neither ``col("flag")`` nor ``~col("flag")``.
"""
return self._term(EQUALS, False)

def __and__(self, other: object) -> Condition:
"""Return ``self.is_true() & other`` (``other`` a condition or a reference)."""
right = _as_condition(other)
if right is None:
return NotImplemented
return self.is_true() & right

def __rand__(self, other: object) -> Condition:
left = _as_condition(other)
if left is None:
return NotImplemented
return left & self.is_true()

def __or__(self, other: object) -> Condition:
"""Return ``self.is_true() | other`` (``other`` a condition or a reference)."""
right = _as_condition(other)
if right is None:
return NotImplemented
return self.is_true() | right

def __ror__(self, other: object) -> Condition:
left = _as_condition(other)
if left is None:
return NotImplemented
return left | self.is_true()

__hash__ = None # pyright: ignore[reportAssignmentType] # == builds a condition, so no hash

def __bool__(self) -> Never:
Expand All @@ -1127,6 +1192,16 @@ def __repr__(self) -> str:
)


def _as_condition(value: object) -> Condition | None:
"""Return ``value`` as a condition: a bare reference is ``is_true()``; ``None`` for
anything that is neither a condition nor a reference."""
if isinstance(value, ColumnRef):
return value.is_true()
if isinstance(value, Condition):
return value
return None


def col(name: str) -> ColumnRef:
"""Return a reference to the column ``name``, to build conditions on.

Expand All @@ -1135,7 +1210,10 @@ def col(name: str) -> ColumnRef:
``not`` raise ``TypeError``. Pass separate conditions to ``filter()`` (or
separate equality keywords to ``where()``), or combine conditions with ``&``,
``|`` and ``~``, putting each comparison in parentheses. For a range, use
``col("t").between(1, 5)``, which includes both ends.
``col("t").between(1, 5)``, which includes both ends. A bare reference to a boolean
column is a condition too: ``col("flag")`` keeps the rows where it is true
(``col("flag") == True``) and ``~col("flag")`` those where it is false
(``col("flag") == False``); a null is kept by neither.

Example::

Expand Down Expand Up @@ -1249,7 +1327,7 @@ def _of_children(cls, children: tuple[Node, ...]) -> Condition:
def of(
cls,
/,
*conditions: Mapping[str, object] | Condition | None,
*conditions: Mapping[str, object] | Condition | ColumnRef | None,
**columns: object,
) -> Condition:
"""Build a condition from conditions and column values, as ``where()`` and
Expand All @@ -1258,7 +1336,8 @@ def of(
``Condition.of(unit_id=106)``, ``Condition.of({"unit_id": 106})`` and both
together are one condition: each named column must equal its value. A positional
argument is a mapping (column name to value) or a condition (built beforehand,
or with ``col``); all of them and every keyword must hold. Given one condition
or with ``col``; a bare ``col(c)`` of a boolean column is ``col(c) == True``);
all of them and every keyword must hold. Given one condition
and nothing else, it returns it unchanged.

Args:
Expand Down Expand Up @@ -1293,8 +1372,10 @@ def of(
for argument in conditions:
if argument is None:
continue
if isinstance(argument, Condition):
built.append(argument)
if isinstance(argument, (Condition, ColumnRef)):
condition_argument = _as_condition(argument)
assert condition_argument is not None
built.append(condition_argument)
elif isinstance(argument, Mapping):
for column, given in argument.items():
value = _checked_value(column, given)
Expand Down Expand Up @@ -1449,17 +1530,21 @@ def combined(self, other: Condition) -> Condition:
children.append(node)
return Condition._of_children(tuple(children))

def __and__(self, other: Condition) -> Condition:
"""Return ``self.combined(other)``: both must hold."""
if not isinstance(other, Condition):
def __and__(self, other: Condition | ColumnRef) -> Condition:
"""Return ``self.combined(other)``: both must hold (a bare reference to a
boolean column is ``is_true()``)."""
right = _as_condition(other)
if right is None:
return NotImplemented
return self.combined(other)
return self.combined(right)

def __or__(self, other: Condition) -> Condition:
def __or__(self, other: Condition | ColumnRef) -> Condition:
"""Return the condition that this one or ``other`` holds (Kleene: unknown or
true is true)."""
if not isinstance(other, Condition):
true is true; a bare reference to a boolean column is ``is_true()``)."""
converted = _as_condition(other)
if converted is None:
return NotImplemented
other = converted
if self.is_empty or other.is_empty:
raise ValueError(
"an empty condition holds for every row, so 'or' with it holds for "
Expand Down
Loading
Loading