sklink.expressions
Expressions: the shared language of relational features.
An expression describes one value per sample computed by following relationships from the entity table, such as mean(orders.amount) or count(orders[type == 'express']). Featurizers, trees, inspection and persistence all speak in expressions; the engine evaluates them.
Classes:
- Aggregate: A primitive applied to the rows reached through a
to_manypath. - Attribute: A column of the entity table, or of a table reached with
to_onehops. - Condition: Filter on the rows of the last table of a path. Conditions are and-ed.
- Expression: Base class of every expression.
- Hop: One step along a relationship.
- LeafSum: Learned weights of the rows reached through a
to_manypath, summed. - Path: Sequence of hops starting at the entity table. Empty means the entity itself.
- SampleFeature: A column of the population table
Xitself. - Window: Time window ending at the cutoff:
cutoff - duration <= time < cutoff.
Functions:
- enumerate_expressions: List the default unconditioned expressions for an entity.
- enumerate_lookups: List the lookups that conditions on the rows of
pathmay follow. - enumerate_paths: List every path from
entityallowed by the visibility rules. - expression_from_dict: Rebuild an expression from
Expression.to_dictoutput. - format_expression: Canonical name of an expression.
- make_hop: Build a hop from
currentalongrelationship, deciding its spelling. - output_type: Semantic type of the value an expression produces.
- parse: Read an expression from its canonical name.
- validate_expression: Check that an expression can be evaluated on a database with
schema.
sklink.expressions.Aggregate
Aggregate(primitive: str, path: Path, column: str | None = None, where: tuple[Condition, ...] = (), window: Window | None = None, params: tuple[tuple[str, Scalar], ...] = ()) -> NoneBases: Expression
A primitive applied to the rows reached through a to_many path.
Functions:
- columns: Return the aggregated column and the condition columns.
- relationships: Relationships of the path and of the condition lookups.
- tables: Tables of the path and of the condition lookups.
- to_dict: JSON-serializable form.
- with_where: Return the same aggregate with additional conditions.
Attributes:
- column (
str | None): - name (
str): Canonical, stable name. Seesklink.expressions.parse. - params (
tuple[tuple[str, Scalar], ...]): - path (
Path): - primitive (
str): - where (
tuple[Condition, ...]): - window (
Window | None):
sklink.expressions.Aggregate.column
column: str | None = Nonesklink.expressions.Aggregate.columns
columns(entity: str) -> frozenset[tuple[str, str]]Return the aggregated column and the condition columns.
Condition columns of a lookup belong to the table the lookup reaches.
sklink.expressions.Aggregate.name
name: strCanonical, stable name. See sklink.expressions.parse.
sklink.expressions.Aggregate.params
params: tuple[tuple[str, Scalar], ...] = field(default=(), compare=False)sklink.expressions.Aggregate.path
path: Pathsklink.expressions.Aggregate.primitive
primitive: strsklink.expressions.Aggregate.relationships
relationships() -> frozenset[str]Relationships of the path and of the condition lookups.
sklink.expressions.Aggregate.tables
tables(entity: str) -> frozenset[str]Tables of the path and of the condition lookups.
sklink.expressions.Aggregate.to_dict
to_dict() -> dict[str, Any]JSON-serializable form.
sklink.expressions.Aggregate.where
where: tuple[Condition, ...] = ()sklink.expressions.Aggregate.window
window: Window | None = Nonesklink.expressions.Aggregate.with_where
with_where(*conditions: Condition) -> AggregateReturn the same aggregate with additional conditions.
sklink.expressions.Attribute
Attribute(path: Path, column: str) -> NoneBases: Expression
A column of the entity table, or of a table reached with to_one hops.
Functions:
- columns: Return the column read.
- relationships: Relationships followed by the expression.
- tables: Tables read by the expression.
- to_dict: JSON-serializable form.
Attributes:
sklink.expressions.Attribute.column
column: strsklink.expressions.Attribute.columns
columns(entity: str) -> frozenset[tuple[str, str]]Return the column read.
sklink.expressions.Attribute.name
name: strCanonical, stable name. See sklink.expressions.parse.
sklink.expressions.Attribute.path
path: Pathsklink.expressions.Attribute.relationships
relationships() -> frozenset[str]Relationships followed by the expression.
sklink.expressions.Attribute.tables
tables(entity: str) -> frozenset[str]Tables read by the expression.
sklink.expressions.Attribute.to_dict
to_dict() -> dict[str, Any]JSON-serializable form.
sklink.expressions.Condition
Condition(column: str, op: Operator, value: Scalar | tuple[Scalar, ...] | None = None, lookup: Path = Path()) -> NoneFilter on the rows of the last table of a path. Conditions are and-ed.
The column is one of the last table itself, or, with lookup, a column of the row reached from each of its rows by following many-to-one hops (a lookup, such as the product of an order line). A row without such a parent row, or whose parent is not visible at the cutoff, has a missing value there: only is_null holds for it.
Functions:
- from_dict: Inverse of
to_dict. - sort_key: Canonical ordering: lookup, column, operator, then value.
- table: Table of the column, for rows of table
start. - to_dict: JSON-serializable form;
"lookup"only when there is one.
Attributes:
sklink.expressions.Condition.column
column: strsklink.expressions.Condition.from_dict
from_dict(data: Mapping[str, Any]) -> ConditionInverse of to_dict.
sklink.expressions.Condition.lookup
lookup: Path = Path()sklink.expressions.Condition.op
op: Operatorsklink.expressions.Condition.sort_key
sort_key() -> tuple[Any, ...]Canonical ordering: lookup, column, operator, then value.
Conditions without a lookup come first, in their usual order.
sklink.expressions.Condition.table
table(start: str) -> strTable of the column, for rows of table start.
sklink.expressions.Condition.to_dict
to_dict() -> dict[str, Any]JSON-serializable form; "lookup" only when there is one.
sklink.expressions.Condition.value
value: Scalar | tuple[Scalar, ...] | None = field(default=None, compare=False)sklink.expressions.Expression
Base class of every expression.
Expressions are immutable values: equal content means equal name and hash. They hold no data and no learned statistics, only explicit constants.
Functions:
- columns:
(table, column)pairs read by the expression (keys excluded). - relationships: Relationships followed by the expression.
- tables: Tables read by the expression.
- to_dict: JSON-serializable form; see
expression_from_dict.
Attributes:
- name (
str): Canonical, stable name. Seesklink.expressions.parse. - path (
Path): Path from the entity table.
sklink.expressions.Expression.columns
columns(entity: str) -> frozenset[tuple[str, str]](table, column) pairs read by the expression (keys excluded).
sklink.expressions.Expression.name
name: strCanonical, stable name. See sklink.expressions.parse.
sklink.expressions.Expression.path
path: PathPath from the entity table.
sklink.expressions.Expression.relationships
relationships() -> frozenset[str]Relationships followed by the expression.
sklink.expressions.Expression.tables
tables(entity: str) -> frozenset[str]Tables read by the expression.
sklink.expressions.Expression.to_dict
to_dict() -> dict[str, Any]JSON-serializable form; see expression_from_dict.
sklink.expressions.Hop
Hop(relationship: str, direction: Direction, target: str, qualified: bool = False, self_link: bool = False) -> NoneOne step along a relationship.
to_many goes from a parent row to its child rows; to_one goes from a child row to its parent row. target is the table reached and qualified tells whether the canonical name must spell the relationship because several relationships lead to the same table.
Attributes:
sklink.expressions.Hop.direction
direction: Directionsklink.expressions.Hop.qualified
qualified: bool = field(default=False, compare=False)sklink.expressions.Hop.relationship
relationship: strsklink.expressions.Hop.self_link
self_link: bool = field(default=False, compare=False)sklink.expressions.Hop.target
target: str = field(compare=False)sklink.expressions.LeafSum
LeafSum(primitive: str, path: Path, terms: tuple[tuple[Aggregate, float], ...]) -> NoneBases: Expression
Learned weights of the rows reached through a to_many path, summed.
The value of an entity is sum_l weight_l * count(path[where_l]) over the terms (an Aggregate of primitive "count" on path and its weight), divided by count(path) for the primitive "mean" (and missing without rows). The terms of a fitted model are the leaves of a small tree over the rows of the path, as in getML's Relboost: each row gets the weight of its leaf, and the entity the sum or mean of them. Its name, such as mean_weights(orders: +0.4 [type == 'pickup'] -0.1 [type in ('economy', 'express', 'standard')]), is written to be read: parse does not read it back, and expression_from_dict rebuilds it from to_dict.
Functions:
- columns: Return the condition columns of the terms.
- relationships: Relationships of the path and of the condition lookups.
- tables: Tables of the path and of the condition lookups.
- to_dict: JSON-serializable form.
Attributes:
- name (
str): Canonical, stable name. Seesklink.expressions.parse. - path (
Path): - primitive (
str): - terms (
tuple[tuple[Aggregate, float], ...]):
sklink.expressions.LeafSum.columns
columns(entity: str) -> frozenset[tuple[str, str]]Return the condition columns of the terms.
sklink.expressions.LeafSum.name
name: strCanonical, stable name. See sklink.expressions.parse.
sklink.expressions.LeafSum.path
path: Pathsklink.expressions.LeafSum.primitive
primitive: strsklink.expressions.LeafSum.relationships
relationships() -> frozenset[str]Relationships of the path and of the condition lookups.
sklink.expressions.LeafSum.tables
tables(entity: str) -> frozenset[str]Tables of the path and of the condition lookups.
sklink.expressions.LeafSum.terms
terms: tuple[tuple[Aggregate, float], ...]sklink.expressions.LeafSum.to_dict
to_dict() -> dict[str, Any]JSON-serializable form.
sklink.expressions.Path
Path(hops: tuple[Hop, ...] = ()) -> NoneSequence of hops starting at the entity table. Empty means the entity itself.
Functions:
- from_list: Inverse of
to_list. - last_table: Table reached at the end of the path.
- tables: Tables visited, starting with
entity. - to_list: JSON-serializable form.
- validate: Check that each hop starts where the previous one ended.
Attributes:
- depth (
int): Number of hops. - hops (
tuple[Hop, ...]): - is_to_one (
bool): Whether every hop is many-to-one (the path reaches at most one row).
sklink.expressions.Path.depth
depth: intNumber of hops.
sklink.expressions.Path.from_list
from_list(data: list[Mapping[str, Any]]) -> PathInverse of to_list.
sklink.expressions.Path.hops
hops: tuple[Hop, ...] = ()sklink.expressions.Path.is_to_one
is_to_one: boolWhether every hop is many-to-one (the path reaches at most one row).
sklink.expressions.Path.last_table
last_table(entity: str) -> strTable reached at the end of the path.
sklink.expressions.Path.tables
tables(entity: str) -> tuple[str, ...]Tables visited, starting with entity.
sklink.expressions.Path.to_list
to_list() -> list[dict[str, Any]]JSON-serializable form.
sklink.expressions.Path.validate
validate(schema: Schema, entity: str) -> NoneCheck that each hop starts where the previous one ended.
sklink.expressions.SampleFeature
SampleFeature(column: str) -> NoneBases: Expression
A column of the population table X itself.
Functions:
- columns: No column of the database is read.
- relationships: Relationships followed by the expression.
- tables: No table of the database is read.
- to_dict: JSON-serializable form.
Attributes:
- column (
str): - name (
str): Canonical, stable name. Seesklink.expressions.parse. - path (
Path): Empty path: the value comes fromX.
sklink.expressions.SampleFeature.column
column: strsklink.expressions.SampleFeature.columns
columns(entity: str) -> frozenset[tuple[str, str]]No column of the database is read.
sklink.expressions.SampleFeature.name
name: strCanonical, stable name. See sklink.expressions.parse.
sklink.expressions.SampleFeature.path
path: PathEmpty path: the value comes from X.
sklink.expressions.SampleFeature.relationships
relationships() -> frozenset[str]Relationships followed by the expression.
sklink.expressions.SampleFeature.tables
tables(entity: str) -> frozenset[str]No table of the database is read.
sklink.expressions.SampleFeature.to_dict
to_dict() -> dict[str, Any]JSON-serializable form.
sklink.expressions.Window
Window(duration: dt.timedelta) -> NoneTime window ending at the cutoff: cutoff - duration <= time < cutoff.
Attributes:
sklink.expressions.Window.duration
duration: dt.timedeltasklink.expressions.enumerate_expressions
enumerate_expressions(schema: Schema, *, entity: str, max_relationship_depth: int, primitives: str | Sequence[str] = 'default', allow_reverse_paths: bool = False, temporal: bool = False, max_lookup_depth: int = 0) -> list[Expression]List the default unconditioned expressions for an entity.
Attributes come from the entity table and from tables reached with many-to-one hops; aggregates from every path with a one-to-many hop, with the primitives that match each column's semantic type. Primitives that require time are used only with temporal=True and on tables with a time column.
With max_lookup_depth > 0, the columns of the tables that the rows of the longest paths look up (see enumerate_lookups) are aggregated too, such as mean(orders.order_items.products.price) at max_relationship_depth=2: a lookup reaches one row per row, so it does not count as a relationship hop. Primitives that require time are not used on them. Expressions with conditions on category values are added by estimators, because they depend on vocabularies learned from training data.
Returns:
- expressions (
list of Expression): Ordered by path depth, then canonical name. Deterministic.
sklink.expressions.enumerate_lookups
enumerate_lookups(schema: Schema, path: Path, *, entity: str, max_relationship_depth: int, max_lookup_depth: int, allow_reverse_paths: bool = False) -> list[Path]List the lookups that conditions on the rows of path may follow.
A lookup is a chain of one to max_lookup_depth many-to-one hops from the last table of path, such as from an order line to its product. It reaches at most one row per row, so it never adds rows to an aggregate and does not count as a hop of max_relationship_depth.
Lookups continue a path where max_relationship_depth stops: only paths of exactly that depth get them. A shorter path reaches the same parent tables as a longer path with to_one hops, whose conditions are on its last table, so a lookup there would repeat a question that is already asked. As in enumerate_paths, a lookup never walks back the relationship the path just followed down (the row it came from) and, unless allow_reverse_paths=True, never reaches the entity table, whose other rows are other samples.
Returns:
- lookups (
list of Path): Non-empty to_one paths relative to the last table ofpath, ordered by depth, then canonical spelling. Empty for a path without a one-to-many hop or shorter thanmax_relationship_depth.
sklink.expressions.enumerate_paths
enumerate_paths(schema: Schema, *, entity: str, max_relationship_depth: int, allow_reverse_paths: bool = False) -> list[Path]List every path from entity allowed by the visibility rules.
By default a path goes down one-to-many relationships first and then only up many-to-one relationships: it never returns to the entity table and never goes down again after going up. This keeps a sample from reading rows of other entities through a shared table (for example, the other customers who bought the same product). allow_reverse_paths=True lifts the rule except for immediately walking back the relationship just followed.
The result is ordered by depth, then canonical spelling, and includes the empty path.
sklink.expressions.expression_from_dict
expression_from_dict(data: Mapping[str, Any]) -> ExpressionRebuild an expression from Expression.to_dict output.
sklink.expressions.format_expression
format_expression(expression: Expression) -> strCanonical name of an expression.
sklink.expressions.make_hop
make_hop(schema: Schema, current: str, relationship: str, direction: str) -> HopBuild a hop from current along relationship, deciding its spelling.
sklink.expressions.output_type
output_type(expression: Expression, schema: Schema | None, entity: str | None) -> strSemantic type of the value an expression produces.
sklink.expressions.parse
parse(name: str, schema: Schema, *, entity: str) -> ExpressionRead an expression from its canonical name.
Guides: Custom primitives and expressions
Parameters:
- name (
str): Canonical name, such as"count(orders[type == 'express'])". - schema (
Schema): Schema the expression refers to. - entity (
str): Table the samples belong to.
Returns:
- expression (
Expression):
Raises:
ValueError: If the text does not follow the grammar; the message gives the position.SchemaError: If a table, column or relationship does not exist.
sklink.expressions.validate_expression
validate_expression(expression: Expression, schema: Schema, entity: str, *, temporal: bool = False) -> NoneCheck that an expression can be evaluated on a database with schema.
Raises:
SchemaError: If a relationship, table or column is missing, a column type is not accepted by the primitive, or time is used without temporal mode.